context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Management.Sync.Threading { using System; using System.Collections.Generic; using System.Threading; internal class Parallel { public readonly static int MaxParallellism = Environment.ProcessorCount; public static LoopResult ForEach<T, TA>(IEnumerable<T> source, Func<TA> argumentConstructor, Action<T,TA> body) { return ForEach(source, argumentConstructor, body, MaxParallellism); } public static LoopResult ForEach<T, TA>(IEnumerable<T> source, Func<TA> argumentConstructor, Action<T,TA> body, int parallelism) { var loopResult = new InternalLoopResult(); int numProcs = parallelism; int remainingWorkItems = numProcs; using (var enumerator = source.GetEnumerator()) { using (var mre = new ManualResetEvent(false)) { // Create each of the work items. for (int p = 0; p < numProcs; p++) { ThreadPool.QueueUserWorkItem(delegate { try { TA argument = argumentConstructor(); // Iterate until there's no more work. while (true) { // Get the next item under a lock, // then process that item. T nextItem; lock (enumerator) { if (!enumerator.MoveNext()) break; nextItem = enumerator.Current; } body(nextItem, argument); } } catch (Exception e) { loopResult.AddException(e); } if (Interlocked.Decrement(ref remainingWorkItems) == 0) mre.Set(); }); } // Wait for all threads to complete. mre.WaitOne(); loopResult.SetCompleted(); } } return loopResult; } public static LoopResult ForEach<T>(IEnumerable<T> source, Action<T> body) { return ForEach(source, body, MaxParallellism); } public static LoopResult ForEach<T>(IEnumerable<T> source, Action<T> body, int parallelism) { var loopResult = new InternalLoopResult(); int numProcs = parallelism; int remainingWorkItems = numProcs; using (var enumerator = source.GetEnumerator()) { using (var mre = new ManualResetEvent(false)) { // Create each of the work items. for (int p = 0; p < numProcs; p++) { ThreadPool.QueueUserWorkItem(delegate { // Iterate until there's no more work. try { while (true) { // Get the next item under a lock, // then process that item. T nextItem; lock (enumerator) { if (!enumerator.MoveNext()) break; nextItem = enumerator.Current; } body(nextItem); } } catch (Exception e) { loopResult.AddException(e); } if (Interlocked.Decrement(ref remainingWorkItems) == 0) mre.Set(); }); } // Wait for all threads to complete. mre.WaitOne(); loopResult.SetCompleted(); } } return loopResult; } public static LoopResult ForEach<T, TA>(IEnumerable<T> source, Func<TA> argumentConstructor, Action<T, TA> body, Action<TA> finalize, int parallelism) { var loopResult = new InternalLoopResult(); int numProcs = parallelism; int remainingWorkItems = numProcs; IList<TA> arguments = new List<TA>(); using (var enumerator = source.GetEnumerator()) { using (var mre = new ManualResetEvent(false)) { // Create each of the work items. for (int p = 0; p < numProcs; p++) { ThreadPool.QueueUserWorkItem(delegate { try { TA argument = argumentConstructor(); lock (arguments) { arguments.Add(argument); } // Iterate until there's no more work. while (true && !loopResult.IsExceptional) { // Get the next item under a lock, // then process that item. T nextItem; lock (enumerator) { if (!enumerator.MoveNext()) break; nextItem = enumerator.Current; } body(nextItem, argument); } } catch (Exception e) { loopResult.AddException(e); } if (Interlocked.Decrement(ref remainingWorkItems) == 0) mre.Set(); }); } // Wait for all threads to complete. mre.WaitOne(); foreach (var argument in arguments) { finalize(argument); } loopResult.SetCompleted(); } } return loopResult; } private class InternalLoopResult : LoopResult { private IList<Exception> exceptions; private object lockObject = new object(); public InternalLoopResult() { this.exceptions = new List<Exception>(); } public override bool IsCompleted { get; protected set; } public override IList<Exception> Exceptions { get { return new List<Exception>(exceptions); } } public override bool IsExceptional { get { lock (lockObject) { return this.exceptions.Count > 0; } } } public void SetCompleted() { this.IsCompleted = true; } public void AddException(Exception exception) { lock (lockObject) { this.exceptions.Add(exception); } } } } public abstract class LoopResult { public abstract bool IsCompleted { get; protected set; } public abstract IList<Exception> Exceptions { get; } public abstract bool IsExceptional { get; } } }
// 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.Text; using System.Runtime; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Diagnostics; using Internal.Reflection.Augments; using Internal.Runtime.Augments; using Internal.Runtime.CompilerServices; namespace System { // WARNING: Bartok hard-codes offsets to the delegate fields, so it's notion of where fields are may // differ from the runtime's notion. Bartok honors sequential and explicit layout directives, so I've // ordered the fields in such a way as to match the runtime's layout and then just tacked on this // sequential layout directive so that Bartok matches it. [StructLayout(LayoutKind.Sequential)] [DebuggerDisplay("Target method(s) = {GetTargetMethodsDescriptionForDebugger()}")] public abstract partial class Delegate : ICloneable, ISerializable { // This ctor exists solely to prevent C# from generating a protected .ctor that violates the surface area. I really want this to be a // "protected-and-internal" rather than "internal" but C# has no keyword for the former. internal Delegate() { // ! Do NOT put any code here. Delegate constructers are not guaranteed to be executed. } // V1 API: Create closed instance delegates. Method name matching is case sensitive. protected Delegate(Object target, String method) { // This constructor cannot be used by application code. To create a delegate by specifying the name of a method, an // overload of the public static CreateDelegate method is used. This will eventually end up calling into the internal // implementation of CreateDelegate below, and does not invoke this constructor. // The constructor is just for API compatibility with the public contract of the Delegate class. throw new PlatformNotSupportedException(); } // V1 API: Create open static delegates. Method name matching is case insensitive. protected Delegate(Type target, String method) { // This constructor cannot be used by application code. To create a delegate by specifying the name of a method, an // overload of the public static CreateDelegate method is used. This will eventually end up calling into the internal // implementation of CreateDelegate below, and does not invoke this constructor. // The constructor is just for API compatibility with the public contract of the Delegate class. throw new PlatformNotSupportedException(); } // New Delegate Implementation protected internal object m_firstParameter; protected internal object m_helperObject; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2111:PointersShouldNotBeVisible")] protected internal IntPtr m_extraFunctionPointerOrData; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2111:PointersShouldNotBeVisible")] protected internal IntPtr m_functionPointer; [ThreadStatic] protected static string s_DefaultValueString; // WARNING: These constants are also declared in System.Private.TypeLoader\Internal\Runtime\TypeLoader\CallConverterThunk.cs // Do not change their values without updating the values in the calling convention converter component protected const int MulticastThunk = 0; protected const int ClosedStaticThunk = 1; protected const int OpenStaticThunk = 2; protected const int ClosedInstanceThunkOverGenericMethod = 3; // This may not exist protected const int DelegateInvokeThunk = 4; protected const int OpenInstanceThunk = 5; // This may not exist protected const int ReversePinvokeThunk = 6; // This may not exist protected const int ObjectArrayThunk = 7; // This may not exist // // If the thunk does not exist, the function will return IntPtr.Zero. protected virtual IntPtr GetThunk(int whichThunk) { #if DEBUG // The GetThunk function should be overriden on all delegate types, except for universal // canonical delegates which use calling convention converter thunks to marshal arguments // for the delegate call. If we execute this version of GetThunk, we can at least assert // that the current delegate type is a generic type. Debug.Assert(this.EETypePtr.IsGeneric); #endif return TypeLoaderExports.GetDelegateThunk(this, whichThunk); } // // If there is a default value string, the overridden function should set the // s_DefaultValueString field and return true. protected virtual bool LoadDefaultValueString() { return false; } /// <summary> /// Used by various parts of the runtime as a replacement for Delegate.Method /// /// The Interop layer uses this to distinguish between different methods on a /// single type, and to get the function pointer for delegates to static functions /// /// The reflection apis use this api to figure out what MethodInfo is related /// to a delegate. /// /// </summary> /// <param name="typeOfFirstParameterIfInstanceDelegate"> /// This value indicates which type an delegate's function pointer is associated with /// This value is ONLY set for delegates where the function pointer points at an instance method /// </param> /// <param name="isOpenResolver"> /// This value indicates if the returned pointer is an open resolver structure. /// </param> /// <param name="isInterpreterEntrypoint"> /// Delegate points to an object array thunk (the delegate wraps a Func<object[], object> delegate). This /// is typically a delegate pointing to the LINQ expression interpreter. /// </param> /// <returns></returns> unsafe internal IntPtr GetFunctionPointer(out RuntimeTypeHandle typeOfFirstParameterIfInstanceDelegate, out bool isOpenResolver, out bool isInterpreterEntrypoint) { typeOfFirstParameterIfInstanceDelegate = default(RuntimeTypeHandle); isOpenResolver = false; isInterpreterEntrypoint = false; if (GetThunk(MulticastThunk) == m_functionPointer) { return IntPtr.Zero; } else if (GetThunk(ObjectArrayThunk) == m_functionPointer) { isInterpreterEntrypoint = true; return IntPtr.Zero; } else if (m_extraFunctionPointerOrData != IntPtr.Zero) { if (GetThunk(OpenInstanceThunk) == m_functionPointer) { typeOfFirstParameterIfInstanceDelegate = ((OpenMethodResolver*)m_extraFunctionPointerOrData)->DeclaringType; isOpenResolver = true; } return m_extraFunctionPointerOrData; } else { if (m_firstParameter != null) typeOfFirstParameterIfInstanceDelegate = new RuntimeTypeHandle(m_firstParameter.EETypePtr); // TODO! Implementation issue for generic invokes here ... we need another IntPtr for uniqueness. return m_functionPointer; } } // @todo: Not an api but some NativeThreadPool code still depends on it. internal IntPtr GetNativeFunctionPointer() { if (GetThunk(ReversePinvokeThunk) != m_functionPointer) { throw new InvalidOperationException("GetNativeFunctionPointer may only be used on a reverse pinvoke delegate"); } return m_extraFunctionPointerOrData; } // This function is known to the IL Transformer. protected void InitializeClosedInstance(object firstParameter, IntPtr functionPointer) { if (firstParameter == null) throw new ArgumentException(SR.Arg_DlgtNullInst); m_functionPointer = functionPointer; m_firstParameter = firstParameter; } // This function is known to the IL Transformer. protected void InitializeClosedInstanceSlow(object firstParameter, IntPtr functionPointer) { // This method is like InitializeClosedInstance, but it handles ALL cases. In particular, it handles generic method with fun function pointers. if (firstParameter == null) throw new ArgumentException(SR.Arg_DlgtNullInst); if (!FunctionPointerOps.IsGenericMethodPointer(functionPointer)) { m_functionPointer = functionPointer; m_firstParameter = firstParameter; } else { m_firstParameter = this; m_functionPointer = GetThunk(ClosedInstanceThunkOverGenericMethod); m_extraFunctionPointerOrData = functionPointer; m_helperObject = firstParameter; } } // This function is known to the compiler. protected void InitializeClosedInstanceWithGVMResolution(object firstParameter, RuntimeMethodHandle tokenOfGenericVirtualMethod) { if (firstParameter == null) throw new ArgumentException(SR.Arg_DlgtNullInst); IntPtr functionResolution = TypeLoaderExports.GVMLookupForSlot(firstParameter, tokenOfGenericVirtualMethod); if (functionResolution == IntPtr.Zero) { // TODO! What to do when GVM resolution fails. Should never happen throw new InvalidOperationException(); } if (!FunctionPointerOps.IsGenericMethodPointer(functionResolution)) { m_functionPointer = functionResolution; m_firstParameter = firstParameter; } else { m_firstParameter = this; m_functionPointer = GetThunk(ClosedInstanceThunkOverGenericMethod); m_extraFunctionPointerOrData = functionResolution; m_helperObject = firstParameter; } return; } private void InitializeClosedInstanceToInterface(object firstParameter, IntPtr dispatchCell) { if (firstParameter == null) throw new ArgumentException(SR.Arg_DlgtNullInst); m_functionPointer = RuntimeImports.RhpResolveInterfaceMethod(firstParameter, dispatchCell); m_firstParameter = firstParameter; } // This is used to implement MethodInfo.CreateDelegate() in a desktop-compatible way. Yes, the desktop really // let you use that api to invoke an instance method with a null 'this'. private void InitializeClosedInstanceWithoutNullCheck(object firstParameter, IntPtr functionPointer) { if (!FunctionPointerOps.IsGenericMethodPointer(functionPointer)) { m_functionPointer = functionPointer; m_firstParameter = firstParameter; } else { m_firstParameter = this; m_functionPointer = GetThunk(ClosedInstanceThunkOverGenericMethod); m_extraFunctionPointerOrData = functionPointer; m_helperObject = firstParameter; } } // This function is known to the compiler backend. protected void InitializeClosedStaticThunk(object firstParameter, IntPtr functionPointer, IntPtr functionPointerThunk) { m_extraFunctionPointerOrData = functionPointer; m_helperObject = firstParameter; m_functionPointer = functionPointerThunk; m_firstParameter = this; } // This function is known to the compiler backend. protected void InitializeClosedStaticWithoutThunk(object firstParameter, IntPtr functionPointer) { m_extraFunctionPointerOrData = functionPointer; m_helperObject = firstParameter; m_functionPointer = GetThunk(ClosedStaticThunk); m_firstParameter = this; } // This function is known to the compiler backend. protected void InitializeOpenStaticThunk(object firstParameter, IntPtr functionPointer, IntPtr functionPointerThunk) { // This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself. m_firstParameter = this; m_functionPointer = functionPointerThunk; m_extraFunctionPointerOrData = functionPointer; } // This function is known to the compiler backend. protected void InitializeOpenStaticWithoutThunk(object firstParameter, IntPtr functionPointer) { // This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself. m_firstParameter = this; m_functionPointer = GetThunk(OpenStaticThunk); m_extraFunctionPointerOrData = functionPointer; } // This function is known to the compiler backend. protected void InitializeReversePInvokeThunk(object firstParameter, IntPtr functionPointer, IntPtr functionPointerThunk) { // This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself. m_firstParameter = this; m_functionPointer = functionPointerThunk; m_extraFunctionPointerOrData = functionPointer; } // This function is known to the compiler backend. protected void InitializeReversePInvokeWithoutThunk(object firstParameter, IntPtr functionPointer) { // This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself. m_firstParameter = this; m_functionPointer = GetThunk(ReversePinvokeThunk); m_extraFunctionPointerOrData = functionPointer; } // This function is known to the compiler backend. protected void InitializeOpenInstanceThunk(object firstParameter, IntPtr functionPointer, IntPtr functionPointerThunk) { // This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself. m_firstParameter = this; m_functionPointer = functionPointerThunk; OpenMethodResolver instanceMethodResolver = new OpenMethodResolver(default(RuntimeTypeHandle), functionPointer, default(GCHandle), 0); m_extraFunctionPointerOrData = instanceMethodResolver.ToIntPtr(); } // This function is known to the compiler backend. protected void InitializeOpenInstanceWithoutThunk(object firstParameter, IntPtr functionPointer, IntPtr functionPointerThunk) { // This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself. m_firstParameter = this; m_functionPointer = GetThunk(OpenInstanceThunk); OpenMethodResolver instanceMethodResolver = new OpenMethodResolver(default(RuntimeTypeHandle), functionPointer, default(GCHandle), 0); m_extraFunctionPointerOrData = instanceMethodResolver.ToIntPtr(); } protected void InitializeOpenInstanceThunkDynamic(IntPtr functionPointer, IntPtr functionPointerThunk) { // This sort of delegate is invoked by calling the thunk function pointer with the arguments to the delegate + a reference to the delegate object itself. m_firstParameter = this; m_functionPointer = functionPointerThunk; m_extraFunctionPointerOrData = functionPointer; } internal void SetClosedStaticFirstParameter(object firstParameter) { // Closed static delegates place a value in m_helperObject that they pass to the target method. Debug.Assert(m_functionPointer == GetThunk(ClosedStaticThunk)); m_helperObject = firstParameter; } // This function is only ever called by the open instance method thunk, and in that case, // m_extraFunctionPointerOrData always points to an OpenMethodResolver [MethodImpl(MethodImplOptions.NoInlining)] protected IntPtr GetActualTargetFunctionPointer(object thisObject) { return OpenMethodResolver.ResolveMethod(m_extraFunctionPointerOrData, thisObject); } public override int GetHashCode() { return GetType().GetHashCode(); } private bool IsDynamicDelegate() { if (this.GetThunk(MulticastThunk) == IntPtr.Zero) { return true; } return false; } [DebuggerGuidedStepThroughAttribute] protected virtual object DynamicInvokeImpl(object[] args) { if (IsDynamicDelegate()) { // DynamicDelegate case object result = ((Func<object[], object>)m_helperObject)(args); DebugAnnotations.PreviousCallContainsDebuggerStepInCode(); return result; } else { IntPtr invokeThunk = this.GetThunk(DelegateInvokeThunk); object result = System.InvokeUtils.CallDynamicInvokeMethod(this.m_firstParameter, this.m_functionPointer, this, invokeThunk, IntPtr.Zero, this, args, binderBundle: null, wrapInTargetInvocationException: true); DebugAnnotations.PreviousCallContainsDebuggerStepInCode(); return result; } } [DebuggerGuidedStepThroughAttribute] public object DynamicInvoke(params object[] args) { object result = DynamicInvokeImpl(args); DebugAnnotations.PreviousCallContainsDebuggerStepInCode(); return result; } public static unsafe Delegate Combine(Delegate a, Delegate b) { if (a == null) return b; if (b == null) return a; return a.CombineImpl(b); } public static Delegate Remove(Delegate source, Delegate value) { if (source == null) return null; if (value == null) return source; if (!InternalEqualTypes(source, value)) throw new ArgumentException(SR.Arg_DlgtTypeMis); return source.RemoveImpl(value); } public static Delegate RemoveAll(Delegate source, Delegate value) { Delegate newDelegate = null; do { newDelegate = source; source = Remove(source, value); } while (newDelegate != source); return newDelegate; } // Used to support the C# compiler in implementing the "+" operator for delegates public static Delegate Combine(params Delegate[] delegates) { if ((delegates == null) || (delegates.Length == 0)) return null; Delegate d = delegates[0]; for (int i = 1; i < delegates.Length; i++) { d = Combine(d, delegates[i]); } return d; } private MulticastDelegate NewMulticastDelegate(Delegate[] invocationList, int invocationCount, bool thisIsMultiCastAlready) { // First, allocate a new multicast delegate just like this one, i.e. same type as the this object MulticastDelegate result = (MulticastDelegate)RuntimeImports.RhNewObject(this.EETypePtr); // Performance optimization - if this already points to a true multicast delegate, // copy _methodPtr and _methodPtrAux fields rather than calling into the EE to get them if (thisIsMultiCastAlready) { result.m_functionPointer = this.m_functionPointer; } else { result.m_functionPointer = GetThunk(MulticastThunk); } result.m_firstParameter = result; result.m_helperObject = invocationList; result.m_extraFunctionPointerOrData = (IntPtr)invocationCount; return result; } internal MulticastDelegate NewMulticastDelegate(Delegate[] invocationList, int invocationCount) { return NewMulticastDelegate(invocationList, invocationCount, false); } private bool TrySetSlot(Delegate[] a, int index, Delegate o) { if (a[index] == null && System.Threading.Interlocked.CompareExchange<Delegate>(ref a[index], o, null) == null) return true; // The slot may be already set because we have added and removed the same method before. // Optimize this case, because it's cheaper than copying the array. if (a[index] != null) { MulticastDelegate d = (MulticastDelegate)o; MulticastDelegate dd = (MulticastDelegate)a[index]; if (Object.ReferenceEquals(dd.m_firstParameter, d.m_firstParameter) && Object.ReferenceEquals(dd.m_helperObject, d.m_helperObject) && dd.m_extraFunctionPointerOrData == d.m_extraFunctionPointerOrData && dd.m_functionPointer == d.m_functionPointer) { return true; } } return false; } // This method will combine this delegate with the passed delegate // to form a new delegate. protected virtual Delegate CombineImpl(Delegate follow) { if ((Object)follow == null) // cast to object for a more efficient test return this; // Verify that the types are the same... if (!InternalEqualTypes(this, follow)) throw new ArgumentException(); if (IsDynamicDelegate() && follow.IsDynamicDelegate()) { throw new InvalidOperationException(); } MulticastDelegate dFollow = (MulticastDelegate)follow; Delegate[] resultList; int followCount = 1; Delegate[] followList = dFollow.m_helperObject as Delegate[]; if (followList != null) followCount = (int)dFollow.m_extraFunctionPointerOrData; int resultCount; Delegate[] invocationList = m_helperObject as Delegate[]; if (invocationList == null) { resultCount = 1 + followCount; resultList = new Delegate[resultCount]; resultList[0] = this; if (followList == null) { resultList[1] = dFollow; } else { for (int i = 0; i < followCount; i++) resultList[1 + i] = followList[i]; } return NewMulticastDelegate(resultList, resultCount); } else { int invocationCount = (int)m_extraFunctionPointerOrData; resultCount = invocationCount + followCount; resultList = null; if (resultCount <= invocationList.Length) { resultList = invocationList; if (followList == null) { if (!TrySetSlot(resultList, invocationCount, dFollow)) resultList = null; } else { for (int i = 0; i < followCount; i++) { if (!TrySetSlot(resultList, invocationCount + i, followList[i])) { resultList = null; break; } } } } if (resultList == null) { int allocCount = invocationList.Length; while (allocCount < resultCount) allocCount *= 2; resultList = new Delegate[allocCount]; for (int i = 0; i < invocationCount; i++) resultList[i] = invocationList[i]; if (followList == null) { resultList[invocationCount] = dFollow; } else { for (int i = 0; i < followCount; i++) resultList[invocationCount + i] = followList[i]; } } return NewMulticastDelegate(resultList, resultCount, true); } } private Delegate[] DeleteFromInvocationList(Delegate[] invocationList, int invocationCount, int deleteIndex, int deleteCount) { Delegate[] thisInvocationList = m_helperObject as Delegate[]; int allocCount = thisInvocationList.Length; while (allocCount / 2 >= invocationCount - deleteCount) allocCount /= 2; Delegate[] newInvocationList = new Delegate[allocCount]; for (int i = 0; i < deleteIndex; i++) newInvocationList[i] = invocationList[i]; for (int i = deleteIndex + deleteCount; i < invocationCount; i++) newInvocationList[i - deleteCount] = invocationList[i]; return newInvocationList; } private bool EqualInvocationLists(Delegate[] a, Delegate[] b, int start, int count) { for (int i = 0; i < count; i++) { if (!(a[start + i].Equals(b[i]))) return false; } return true; } // This method currently looks backward on the invocation list // for an element that has Delegate based equality with value. (Doesn't // look at the invocation list.) If this is found we remove it from // this list and return a new delegate. If its not found a copy of the // current list is returned. protected virtual Delegate RemoveImpl(Delegate value) { // There is a special case were we are removing using a delegate as // the value we need to check for this case // MulticastDelegate v = value as MulticastDelegate; if (v == null) return this; if (v.m_helperObject as Delegate[] == null) { Delegate[] invocationList = m_helperObject as Delegate[]; if (invocationList == null) { // they are both not real Multicast if (this.Equals(value)) return null; } else { int invocationCount = (int)m_extraFunctionPointerOrData; for (int i = invocationCount; --i >= 0;) { if (value.Equals(invocationList[i])) { if (invocationCount == 2) { // Special case - only one value left, either at the beginning or the end return invocationList[1 - i]; } else { Delegate[] list = DeleteFromInvocationList(invocationList, invocationCount, i, 1); return NewMulticastDelegate(list, invocationCount - 1, true); } } } } } else { Delegate[] invocationList = m_helperObject as Delegate[]; if (invocationList != null) { int invocationCount = (int)m_extraFunctionPointerOrData; int vInvocationCount = (int)v.m_extraFunctionPointerOrData; for (int i = invocationCount - vInvocationCount; i >= 0; i--) { if (EqualInvocationLists(invocationList, v.m_helperObject as Delegate[], i, vInvocationCount)) { if (invocationCount - vInvocationCount == 0) { // Special case - no values left return null; } else if (invocationCount - vInvocationCount == 1) { // Special case - only one value left, either at the beginning or the end return invocationList[i != 0 ? 0 : invocationCount - 1]; } else { Delegate[] list = DeleteFromInvocationList(invocationList, invocationCount, i, vInvocationCount); return NewMulticastDelegate(list, invocationCount - vInvocationCount, true); } } } } } return this; } public virtual Delegate[] GetInvocationList() { Delegate[] del; Delegate[] invocationList = m_helperObject as Delegate[]; if (invocationList == null) { del = new Delegate[1]; del[0] = this; } else { // Create an array of delegate copies and each // element into the array int invocationCount = (int)m_extraFunctionPointerOrData; del = new Delegate[invocationCount]; for (int i = 0; i < del.Length; i++) del[i] = invocationList[i]; } return del; } public MethodInfo Method { get { return GetMethodImpl(); } } protected virtual MethodInfo GetMethodImpl() { return RuntimeAugments.Callbacks.GetDelegateMethod(this); } public override bool Equals(Object obj) { // It is expected that all real uses of the Equals method will hit the MulticastDelegate.Equals logic instead of this // therefore, instead of duplicating the desktop behavior where direct calls to this Equals function do not behave // correctly, we'll just throw here. throw new PlatformNotSupportedException(); } public static bool operator ==(Delegate d1, Delegate d2) { if ((Object)d1 == null) return (Object)d2 == null; return d1.Equals(d2); } public static bool operator !=(Delegate d1, Delegate d2) { if ((Object)d1 == null) return (Object)d2 != null; return !d1.Equals(d2); } public Object Target { get { // Multi-cast delegates return the Target of the last delegate in the list if (m_functionPointer == GetThunk(MulticastThunk)) { Delegate[] invocationList = (Delegate[])m_helperObject; int invocationCount = (int)m_extraFunctionPointerOrData; return invocationList[invocationCount - 1].Target; } // Closed static delegates place a value in m_helperObject that they pass to the target method. if (m_functionPointer == GetThunk(ClosedStaticThunk) || m_functionPointer == GetThunk(ClosedInstanceThunkOverGenericMethod) || m_functionPointer == GetThunk(ObjectArrayThunk)) return m_helperObject; // Other non-closed thunks can be identified as the m_firstParameter field points at this. if (Object.ReferenceEquals(m_firstParameter, this)) { return null; } // Closed instance delegates place a value in m_firstParameter, and we've ruled out all other types of delegates return m_firstParameter; } } // V2 api: Creates open or closed delegates to static or instance methods - relaxed signature checking allowed. public static Delegate CreateDelegate(Type type, object firstArgument, MethodInfo method) => CreateDelegate(type, firstArgument, method, throwOnBindFailure: true); public static Delegate CreateDelegate(Type type, object firstArgument, MethodInfo method, bool throwOnBindFailure) => ReflectionAugments.ReflectionCoreCallbacks.CreateDelegate(type, firstArgument, method, throwOnBindFailure); // V1 api: Creates open delegates to static or instance methods - relaxed signature checking allowed. public static Delegate CreateDelegate(Type type, MethodInfo method) => CreateDelegate(type, method, throwOnBindFailure: true); public static Delegate CreateDelegate(Type type, MethodInfo method, bool throwOnBindFailure) => ReflectionAugments.ReflectionCoreCallbacks.CreateDelegate(type, method, throwOnBindFailure); // V1 api: Creates closed delegates to instance methods only, relaxed signature checking disallowed. public static Delegate CreateDelegate(Type type, object target, string method) => CreateDelegate(type, target, method, ignoreCase: false, throwOnBindFailure: true); public static Delegate CreateDelegate(Type type, object target, string method, bool ignoreCase) => CreateDelegate(type, target, method, ignoreCase, throwOnBindFailure: true); public static Delegate CreateDelegate(Type type, object target, string method, bool ignoreCase, bool throwOnBindFailure) => ReflectionAugments.ReflectionCoreCallbacks.CreateDelegate(type, target, method, ignoreCase, throwOnBindFailure); // V1 api: Creates open delegates to static methods only, relaxed signature checking disallowed. public static Delegate CreateDelegate(Type type, Type target, string method) => CreateDelegate(type, target, method, ignoreCase: false, throwOnBindFailure: true); public static Delegate CreateDelegate(Type type, Type target, string method, bool ignoreCase) => CreateDelegate(type, target, method, ignoreCase, throwOnBindFailure: true); public static Delegate CreateDelegate(Type type, Type target, string method, bool ignoreCase, bool throwOnBindFailure) => ReflectionAugments.ReflectionCoreCallbacks.CreateDelegate(type, target, method, ignoreCase, throwOnBindFailure); public virtual object Clone() { return MemberwiseClone(); } public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(SR.Serialization_DelegatesNotSupported); } internal bool IsOpenStatic { get { return GetThunk(OpenStaticThunk) == m_functionPointer; } } internal static bool InternalEqualTypes(object a, object b) { return a.EETypePtr == b.EETypePtr; } // Returns a new delegate of the specified type whose implementation is provied by the // provided delegate. internal static Delegate CreateObjectArrayDelegate(Type t, Func<object[], object> handler) { EETypePtr delegateEEType; if (!t.TryGetEEType(out delegateEEType)) { throw new InvalidOperationException(); } if (!delegateEEType.IsDefType || delegateEEType.IsGenericTypeDefinition) { throw new InvalidOperationException(); } Delegate del = (Delegate)(RuntimeImports.RhNewObject(delegateEEType)); IntPtr objArrayThunk = del.GetThunk(Delegate.ObjectArrayThunk); if (objArrayThunk == IntPtr.Zero) { throw new InvalidOperationException(); } del.m_helperObject = handler; del.m_functionPointer = objArrayThunk; del.m_firstParameter = del; return del; } // // Internal (and quite unsafe) helper to create delegates of an arbitrary type. This is used to support Reflection invoke. // // Note that delegates constructed the normal way do not come through here. The IL transformer generates the equivalent of // this code customized for each delegate type. // internal static Delegate CreateDelegate(EETypePtr delegateEEType, IntPtr ldftnResult, Object thisObject, bool isStatic, bool isOpen) { Delegate del = (Delegate)(RuntimeImports.RhNewObject(delegateEEType)); // What? No constructor call? That's right, and it's not an oversight. All "construction" work happens in // the Initialize() methods. This helper has a hard dependency on this invariant. if (isStatic) { if (isOpen) { IntPtr thunk = del.GetThunk(Delegate.OpenStaticThunk); del.InitializeOpenStaticThunk(null, ldftnResult, thunk); } else { IntPtr thunk = del.GetThunk(Delegate.ClosedStaticThunk); del.InitializeClosedStaticThunk(thisObject, ldftnResult, thunk); } } else { if (isOpen) { IntPtr thunk = del.GetThunk(Delegate.OpenInstanceThunk); del.InitializeOpenInstanceThunkDynamic(ldftnResult, thunk); } else { del.InitializeClosedInstanceWithoutNullCheck(thisObject, ldftnResult); } } return del; } private string GetTargetMethodsDescriptionForDebugger() { if (m_functionPointer == GetThunk(MulticastThunk)) { // Multi-cast delegates return the Target of the last delegate in the list Delegate[] invocationList = (Delegate[])m_helperObject; int invocationCount = (int)m_extraFunctionPointerOrData; StringBuilder builder = new StringBuilder(); for (int c = 0; c < invocationCount; c++) { if (c != 0) builder.Append(", "); builder.Append(invocationList[c].GetTargetMethodsDescriptionForDebugger()); } return builder.ToString(); } else { RuntimeTypeHandle typeOfFirstParameterIfInstanceDelegate; IntPtr functionPointer = GetFunctionPointer(out typeOfFirstParameterIfInstanceDelegate, out bool _, out bool _); if (!FunctionPointerOps.IsGenericMethodPointer(functionPointer)) { return DebuggerFunctionPointerFormattingHook(functionPointer, typeOfFirstParameterIfInstanceDelegate); } else { unsafe { GenericMethodDescriptor* pointerDef = FunctionPointerOps.ConvertToGenericDescriptor(functionPointer); return DebuggerFunctionPointerFormattingHook(pointerDef->InstantiationArgument, typeOfFirstParameterIfInstanceDelegate); } } } } private static string DebuggerFunctionPointerFormattingHook(IntPtr functionPointer, RuntimeTypeHandle typeOfFirstParameterIfInstanceDelegate) { // This method will be hooked by the debugger and the debugger will cause it to return a description for the function pointer throw new NotSupportedException(); } } }
using System; using System.IO; namespace CatLib._3rd.ICSharpCode.SharpZipLib.Zip { // TODO: Sort out wether tagged data is useful and what a good implementation might look like. // Its just a sketch of an idea at the moment. /// <summary> /// ExtraData tagged value interface. /// </summary> public interface ITaggedData { /// <summary> /// Get the ID for this tagged data value. /// </summary> short TagID { get; } /// <summary> /// Set the contents of this instance from the data passed. /// </summary> /// <param name="data">The data to extract contents from.</param> /// <param name="offset">The offset to begin extracting data from.</param> /// <param name="count">The number of bytes to extract.</param> void SetData(byte[] data, int offset, int count); /// <summary> /// Get the data representing this instance. /// </summary> /// <returns>Returns the data for this instance.</returns> byte[] GetData(); } /// <summary> /// A raw binary tagged value /// </summary> public class RawTaggedData : ITaggedData { /// <summary> /// Initialise a new instance. /// </summary> /// <param name="tag">The tag ID.</param> public RawTaggedData(short tag) { _tag = tag; } #region ITaggedData Members /// <summary> /// Get the ID for this tagged data value. /// </summary> public short TagID { get { return _tag; } set { _tag = value; } } /// <summary> /// Set the data from the raw values provided. /// </summary> /// <param name="data">The raw data to extract values from.</param> /// <param name="offset">The index to start extracting values from.</param> /// <param name="count">The number of bytes available.</param> public void SetData(byte[] data, int offset, int count) { if (data == null) { throw new ArgumentNullException("data"); } _data = new byte[count]; Array.Copy(data, offset, _data, 0, count); } /// <summary> /// Get the binary data representing this instance. /// </summary> /// <returns>The raw binary data representing this instance.</returns> public byte[] GetData() { return _data; } #endregion /// <summary> /// Get /set the binary data representing this instance. /// </summary> /// <returns>The raw binary data representing this instance.</returns> public byte[] Data { get { return _data; } set { _data = value; } } #region Instance Fields /// <summary> /// The tag ID for this instance. /// </summary> short _tag; byte[] _data; #endregion } /// <summary> /// Class representing extended unix date time values. /// </summary> public class ExtendedUnixData : ITaggedData { /// <summary> /// Flags indicate which values are included in this instance. /// </summary> [Flags] public enum Flags : byte { /// <summary> /// The modification time is included /// </summary> ModificationTime = 0x01, /// <summary> /// The access time is included /// </summary> AccessTime = 0x02, /// <summary> /// The create time is included. /// </summary> CreateTime = 0x04, } #region ITaggedData Members /// <summary> /// Get the ID /// </summary> public short TagID { get { return 0x5455; } } /// <summary> /// Set the data from the raw values provided. /// </summary> /// <param name="data">The raw data to extract values from.</param> /// <param name="index">The index to start extracting values from.</param> /// <param name="count">The number of bytes available.</param> public void SetData(byte[] data, int index, int count) { using (MemoryStream ms = new MemoryStream(data, index, count, false)) using (ZipHelperStream helperStream = new ZipHelperStream(ms)) { // bit 0 if set, modification time is present // bit 1 if set, access time is present // bit 2 if set, creation time is present _flags = (Flags)helperStream.ReadByte(); if (((_flags & Flags.ModificationTime) != 0)) { int iTime = helperStream.ReadLEInt(); _modificationTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc) + new TimeSpan(0, 0, 0, iTime, 0); // Central-header version is truncated after modification time if (count <= 5) return; } if ((_flags & Flags.AccessTime) != 0) { int iTime = helperStream.ReadLEInt(); _lastAccessTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc) + new TimeSpan(0, 0, 0, iTime, 0); } if ((_flags & Flags.CreateTime) != 0) { int iTime = helperStream.ReadLEInt(); _createTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc) + new TimeSpan(0, 0, 0, iTime, 0); } } } /// <summary> /// Get the binary data representing this instance. /// </summary> /// <returns>The raw binary data representing this instance.</returns> public byte[] GetData() { using (MemoryStream ms = new MemoryStream()) using (ZipHelperStream helperStream = new ZipHelperStream(ms)) { helperStream.IsStreamOwner = false; helperStream.WriteByte((byte)_flags); // Flags if ((_flags & Flags.ModificationTime) != 0) { TimeSpan span = _modificationTime - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); var seconds = (int)span.TotalSeconds; helperStream.WriteLEInt(seconds); } if ((_flags & Flags.AccessTime) != 0) { TimeSpan span = _lastAccessTime - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); var seconds = (int)span.TotalSeconds; helperStream.WriteLEInt(seconds); } if ((_flags & Flags.CreateTime) != 0) { TimeSpan span = _createTime - new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); var seconds = (int)span.TotalSeconds; helperStream.WriteLEInt(seconds); } return ms.ToArray(); } } #endregion /// <summary> /// Test a <see cref="DateTime"> value to see if is valid and can be represented here.</see> /// </summary> /// <param name="value">The <see cref="DateTime">value</see> to test.</param> /// <returns>Returns true if the value is valid and can be represented; false if not.</returns> /// <remarks>The standard Unix time is a signed integer data type, directly encoding the Unix time number, /// which is the number of seconds since 1970-01-01. /// Being 32 bits means the values here cover a range of about 136 years. /// The minimum representable time is 1901-12-13 20:45:52, /// and the maximum representable time is 2038-01-19 03:14:07. /// </remarks> public static bool IsValidValue(DateTime value) { return ((value >= new DateTime(1901, 12, 13, 20, 45, 52)) || (value <= new DateTime(2038, 1, 19, 03, 14, 07))); } /// <summary> /// Get /set the Modification Time /// </summary> /// <exception cref="ArgumentOutOfRangeException"></exception> /// <seealso cref="IsValidValue"></seealso> public DateTime ModificationTime { get { return _modificationTime; } set { if (!IsValidValue(value)) { throw new ArgumentOutOfRangeException("value"); } _flags |= Flags.ModificationTime; _modificationTime = value; } } /// <summary> /// Get / set the Access Time /// </summary> /// <exception cref="ArgumentOutOfRangeException"></exception> /// <seealso cref="IsValidValue"></seealso> public DateTime AccessTime { get { return _lastAccessTime; } set { if (!IsValidValue(value)) { throw new ArgumentOutOfRangeException("value"); } _flags |= Flags.AccessTime; _lastAccessTime = value; } } /// <summary> /// Get / Set the Create Time /// </summary> /// <exception cref="ArgumentOutOfRangeException"></exception> /// <seealso cref="IsValidValue"></seealso> public DateTime CreateTime { get { return _createTime; } set { if (!IsValidValue(value)) { throw new ArgumentOutOfRangeException("value"); } _flags |= Flags.CreateTime; _createTime = value; } } /// <summary> /// Get/set the <see cref="Flags">values</see> to include. /// </summary> public Flags Include { get { return _flags; } set { _flags = value; } } #region Instance Fields Flags _flags; DateTime _modificationTime = new DateTime(1970, 1, 1); DateTime _lastAccessTime = new DateTime(1970, 1, 1); DateTime _createTime = new DateTime(1970, 1, 1); #endregion } /// <summary> /// Class handling NT date time values. /// </summary> public class NTTaggedData : ITaggedData { /// <summary> /// Get the ID for this tagged data value. /// </summary> public short TagID { get { return 10; } } /// <summary> /// Set the data from the raw values provided. /// </summary> /// <param name="data">The raw data to extract values from.</param> /// <param name="index">The index to start extracting values from.</param> /// <param name="count">The number of bytes available.</param> public void SetData(byte[] data, int index, int count) { using (MemoryStream ms = new MemoryStream(data, index, count, false)) using (ZipHelperStream helperStream = new ZipHelperStream(ms)) { helperStream.ReadLEInt(); // Reserved while (helperStream.Position < helperStream.Length) { int ntfsTag = helperStream.ReadLEShort(); int ntfsLength = helperStream.ReadLEShort(); if (ntfsTag == 1) { if (ntfsLength >= 24) { long lastModificationTicks = helperStream.ReadLELong(); _lastModificationTime = DateTime.FromFileTimeUtc(lastModificationTicks); long lastAccessTicks = helperStream.ReadLELong(); _lastAccessTime = DateTime.FromFileTimeUtc(lastAccessTicks); long createTimeTicks = helperStream.ReadLELong(); _createTime = DateTime.FromFileTimeUtc(createTimeTicks); } break; } else { // An unknown NTFS tag so simply skip it. helperStream.Seek(ntfsLength, SeekOrigin.Current); } } } } /// <summary> /// Get the binary data representing this instance. /// </summary> /// <returns>The raw binary data representing this instance.</returns> public byte[] GetData() { using (MemoryStream ms = new MemoryStream()) using (ZipHelperStream helperStream = new ZipHelperStream(ms)) { helperStream.IsStreamOwner = false; helperStream.WriteLEInt(0); // Reserved helperStream.WriteLEShort(1); // Tag helperStream.WriteLEShort(24); // Length = 3 x 8. helperStream.WriteLELong(_lastModificationTime.ToFileTimeUtc()); helperStream.WriteLELong(_lastAccessTime.ToFileTimeUtc()); helperStream.WriteLELong(_createTime.ToFileTimeUtc()); return ms.ToArray(); } } /// <summary> /// Test a <see cref="DateTime"> valuie to see if is valid and can be represented here.</see> /// </summary> /// <param name="value">The <see cref="DateTime">value</see> to test.</param> /// <returns>Returns true if the value is valid and can be represented; false if not.</returns> /// <remarks> /// NTFS filetimes are 64-bit unsigned integers, stored in Intel /// (least significant byte first) byte order. They determine the /// number of 1.0E-07 seconds (1/10th microseconds!) past WinNT "epoch", /// which is "01-Jan-1601 00:00:00 UTC". 28 May 60056 is the upper limit /// </remarks> public static bool IsValidValue(DateTime value) { bool result = true; try { value.ToFileTimeUtc(); } catch { result = false; } return result; } /// <summary> /// Get/set the <see cref="DateTime">last modification time</see>. /// </summary> public DateTime LastModificationTime { get { return _lastModificationTime; } set { if (!IsValidValue(value)) { throw new ArgumentOutOfRangeException("value"); } _lastModificationTime = value; } } /// <summary> /// Get /set the <see cref="DateTime">create time</see> /// </summary> public DateTime CreateTime { get { return _createTime; } set { if (!IsValidValue(value)) { throw new ArgumentOutOfRangeException("value"); } _createTime = value; } } /// <summary> /// Get /set the <see cref="DateTime">last access time</see>. /// </summary> public DateTime LastAccessTime { get { return _lastAccessTime; } set { if (!IsValidValue(value)) { throw new ArgumentOutOfRangeException("value"); } _lastAccessTime = value; } } #region Instance Fields DateTime _lastAccessTime = DateTime.FromFileTimeUtc(0); DateTime _lastModificationTime = DateTime.FromFileTimeUtc(0); DateTime _createTime = DateTime.FromFileTimeUtc(0); #endregion } /// <summary> /// A factory that creates <see cref="ITaggedData">tagged data</see> instances. /// </summary> interface ITaggedDataFactory { /// <summary> /// Get data for a specific tag value. /// </summary> /// <param name="tag">The tag ID to find.</param> /// <param name="data">The data to search.</param> /// <param name="offset">The offset to begin extracting data from.</param> /// <param name="count">The number of bytes to extract.</param> /// <returns>The located <see cref="ITaggedData">value found</see>, or null if not found.</returns> ITaggedData Create(short tag, byte[] data, int offset, int count); } /// /// <summary> /// A class to handle the extra data field for Zip entries /// </summary> /// <remarks> /// Extra data contains 0 or more values each prefixed by a header tag and length. /// They contain zero or more bytes of actual data. /// The data is held internally using a copy on write strategy. This is more efficient but /// means that for extra data created by passing in data can have the values modified by the caller /// in some circumstances. /// </remarks> sealed public class ZipExtraData : IDisposable { #region Constructors /// <summary> /// Initialise a default instance. /// </summary> public ZipExtraData() { Clear(); } /// <summary> /// Initialise with known extra data. /// </summary> /// <param name="data">The extra data.</param> public ZipExtraData(byte[] data) { if (data == null) { _data = new byte[0]; } else { _data = data; } } #endregion /// <summary> /// Get the raw extra data value /// </summary> /// <returns>Returns the raw byte[] extra data this instance represents.</returns> public byte[] GetEntryData() { if (Length > ushort.MaxValue) { throw new ZipException("Data exceeds maximum length"); } return (byte[])_data.Clone(); } /// <summary> /// Clear the stored data. /// </summary> public void Clear() { if ((_data == null) || (_data.Length != 0)) { _data = new byte[0]; } } /// <summary> /// Gets the current extra data length. /// </summary> public int Length { get { return _data.Length; } } /// <summary> /// Get a read-only <see cref="Stream"/> for the associated tag. /// </summary> /// <param name="tag">The tag to locate data for.</param> /// <returns>Returns a <see cref="Stream"/> containing tag data or null if no tag was found.</returns> public Stream GetStreamForTag(int tag) { Stream result = null; if (Find(tag)) { result = new MemoryStream(_data, _index, _readValueLength, false); } return result; } /// <summary> /// Get the <see cref="ITaggedData">tagged data</see> for a tag. /// </summary> /// <typeparam name="T">The tag to search for.</typeparam> /// <returns>Returns a <see cref="ITaggedData">tagged value</see> or null if none found.</returns> public T GetData<T>() where T : class, ITaggedData, new() { T result = new T(); if (Find(result.TagID)) { result.SetData(_data, _readValueStart, _readValueLength); return result; } else return null; } /// <summary> /// Get the length of the last value found by <see cref="Find"/> /// </summary> /// <remarks>This is only valid if <see cref="Find"/> has previously returned true.</remarks> public int ValueLength { get { return _readValueLength; } } /// <summary> /// Get the index for the current read value. /// </summary> /// <remarks>This is only valid if <see cref="Find"/> has previously returned true. /// Initially the result will be the index of the first byte of actual data. The value is updated after calls to /// <see cref="ReadInt"/>, <see cref="ReadShort"/> and <see cref="ReadLong"/>. </remarks> public int CurrentReadIndex { get { return _index; } } /// <summary> /// Get the number of bytes remaining to be read for the current value; /// </summary> public int UnreadCount { get { if ((_readValueStart > _data.Length) || (_readValueStart < 4)) { throw new ZipException("Find must be called before calling a Read method"); } return _readValueStart + _readValueLength - _index; } } /// <summary> /// Find an extra data value /// </summary> /// <param name="headerID">The identifier for the value to find.</param> /// <returns>Returns true if the value was found; false otherwise.</returns> public bool Find(int headerID) { _readValueStart = _data.Length; _readValueLength = 0; _index = 0; int localLength = _readValueStart; int localTag = headerID - 1; // Trailing bytes that cant make up an entry (as there arent enough // bytes for a tag and length) are ignored! while ((localTag != headerID) && (_index < _data.Length - 3)) { localTag = ReadShortInternal(); localLength = ReadShortInternal(); if (localTag != headerID) { _index += localLength; } } bool result = (localTag == headerID) && ((_index + localLength) <= _data.Length); if (result) { _readValueStart = _index; _readValueLength = localLength; } return result; } /// <summary> /// Add a new entry to extra data. /// </summary> /// <param name="taggedData">The <see cref="ITaggedData"/> value to add.</param> public void AddEntry(ITaggedData taggedData) { if (taggedData == null) { throw new ArgumentNullException("taggedData"); } AddEntry(taggedData.TagID, taggedData.GetData()); } /// <summary> /// Add a new entry to extra data /// </summary> /// <param name="headerID">The ID for this entry.</param> /// <param name="fieldData">The data to add.</param> /// <remarks>If the ID already exists its contents are replaced.</remarks> public void AddEntry(int headerID, byte[] fieldData) { if ((headerID > ushort.MaxValue) || (headerID < 0)) { throw new ArgumentOutOfRangeException("headerID"); } int addLength = (fieldData == null) ? 0 : fieldData.Length; if (addLength > ushort.MaxValue) { throw new ArgumentOutOfRangeException("fieldData", "exceeds maximum length"); } // Test for new length before adjusting data. int newLength = _data.Length + addLength + 4; if (Find(headerID)) { newLength -= (ValueLength + 4); } if (newLength > ushort.MaxValue) { throw new ZipException("Data exceeds maximum length"); } Delete(headerID); byte[] newData = new byte[newLength]; _data.CopyTo(newData, 0); int index = _data.Length; _data = newData; SetShort(ref index, headerID); SetShort(ref index, addLength); if (fieldData != null) { fieldData.CopyTo(newData, index); } } /// <summary> /// Start adding a new entry. /// </summary> /// <remarks>Add data using <see cref="AddData(byte[])"/>, <see cref="AddLeShort"/>, <see cref="AddLeInt"/>, or <see cref="AddLeLong"/>. /// The new entry is completed and actually added by calling <see cref="AddNewEntry"/></remarks> /// <seealso cref="AddEntry(ITaggedData)"/> public void StartNewEntry() { _newEntry = new MemoryStream(); } /// <summary> /// Add entry data added since <see cref="StartNewEntry"/> using the ID passed. /// </summary> /// <param name="headerID">The identifier to use for this entry.</param> public void AddNewEntry(int headerID) { byte[] newData = _newEntry.ToArray(); _newEntry = null; AddEntry(headerID, newData); } /// <summary> /// Add a byte of data to the pending new entry. /// </summary> /// <param name="data">The byte to add.</param> /// <seealso cref="StartNewEntry"/> public void AddData(byte data) { _newEntry.WriteByte(data); } /// <summary> /// Add data to a pending new entry. /// </summary> /// <param name="data">The data to add.</param> /// <seealso cref="StartNewEntry"/> public void AddData(byte[] data) { if (data == null) { throw new ArgumentNullException("data"); } _newEntry.Write(data, 0, data.Length); } /// <summary> /// Add a short value in little endian order to the pending new entry. /// </summary> /// <param name="toAdd">The data to add.</param> /// <seealso cref="StartNewEntry"/> public void AddLeShort(int toAdd) { unchecked { _newEntry.WriteByte((byte)toAdd); _newEntry.WriteByte((byte)(toAdd >> 8)); } } /// <summary> /// Add an integer value in little endian order to the pending new entry. /// </summary> /// <param name="toAdd">The data to add.</param> /// <seealso cref="StartNewEntry"/> public void AddLeInt(int toAdd) { unchecked { AddLeShort((short)toAdd); AddLeShort((short)(toAdd >> 16)); } } /// <summary> /// Add a long value in little endian order to the pending new entry. /// </summary> /// <param name="toAdd">The data to add.</param> /// <seealso cref="StartNewEntry"/> public void AddLeLong(long toAdd) { unchecked { AddLeInt((int)(toAdd & 0xffffffff)); AddLeInt((int)(toAdd >> 32)); } } /// <summary> /// Delete an extra data field. /// </summary> /// <param name="headerID">The identifier of the field to delete.</param> /// <returns>Returns true if the field was found and deleted.</returns> public bool Delete(int headerID) { bool result = false; if (Find(headerID)) { result = true; int trueStart = _readValueStart - 4; byte[] newData = new byte[_data.Length - (ValueLength + 4)]; Array.Copy(_data, 0, newData, 0, trueStart); int trueEnd = trueStart + ValueLength + 4; Array.Copy(_data, trueEnd, newData, trueStart, _data.Length - trueEnd); _data = newData; } return result; } #region Reading Support /// <summary> /// Read a long in little endian form from the last <see cref="Find">found</see> data value /// </summary> /// <returns>Returns the long value read.</returns> public long ReadLong() { ReadCheck(8); return (ReadInt() & 0xffffffff) | (((long)ReadInt()) << 32); } /// <summary> /// Read an integer in little endian form from the last <see cref="Find">found</see> data value. /// </summary> /// <returns>Returns the integer read.</returns> public int ReadInt() { ReadCheck(4); int result = _data[_index] + (_data[_index + 1] << 8) + (_data[_index + 2] << 16) + (_data[_index + 3] << 24); _index += 4; return result; } /// <summary> /// Read a short value in little endian form from the last <see cref="Find">found</see> data value. /// </summary> /// <returns>Returns the short value read.</returns> public int ReadShort() { ReadCheck(2); int result = _data[_index] + (_data[_index + 1] << 8); _index += 2; return result; } /// <summary> /// Read a byte from an extra data /// </summary> /// <returns>The byte value read or -1 if the end of data has been reached.</returns> public int ReadByte() { int result = -1; if ((_index < _data.Length) && (_readValueStart + _readValueLength > _index)) { result = _data[_index]; _index += 1; } return result; } /// <summary> /// Skip data during reading. /// </summary> /// <param name="amount">The number of bytes to skip.</param> public void Skip(int amount) { ReadCheck(amount); _index += amount; } void ReadCheck(int length) { if ((_readValueStart > _data.Length) || (_readValueStart < 4)) { throw new ZipException("Find must be called before calling a Read method"); } if (_index > _readValueStart + _readValueLength - length) { throw new ZipException("End of extra data"); } if (_index + length < 4) { throw new ZipException("Cannot read before start of tag"); } } /// <summary> /// Internal form of <see cref="ReadShort"/> that reads data at any location. /// </summary> /// <returns>Returns the short value read.</returns> int ReadShortInternal() { if (_index > _data.Length - 2) { throw new ZipException("End of extra data"); } int result = _data[_index] + (_data[_index + 1] << 8); _index += 2; return result; } void SetShort(ref int index, int source) { _data[index] = (byte)source; _data[index + 1] = (byte)(source >> 8); index += 2; } #endregion #region IDisposable Members /// <summary> /// Dispose of this instance. /// </summary> public void Dispose() { if (_newEntry != null) { _newEntry.Dispose(); } } #endregion #region Instance Fields int _index; int _readValueStart; int _readValueLength; MemoryStream _newEntry; byte[] _data; #endregion } }
/************************************************************************************ Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved. Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License"); you may not use the Oculus VR Rift SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at http://www.oculusvr.com/licenses/LICENSE-3.2 Unless required by applicable law or agreed to in writing, the Oculus VR SDK distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************************/ #if !UNITY_4_6 #error Oculus Utilities require Unity 4.6. #endif using System; using System.Collections; using System.Runtime.InteropServices; using System.Linq; using System.Text.RegularExpressions; using System.Text; using UnityEngine; using Ovr; /// <summary> /// Configuration data for Oculus virtual reality. /// </summary> public class OVRManager : MonoBehaviour { /// <summary> /// Contains the valid range of antialiasing levels usable with Unity render textures. /// </summary> public enum RenderTextureAntiAliasing { _1 = 1, _2 = 2, _4 = 4, _8 = 8, } /// <summary> /// Contains the valid range of texture depth values usable with Unity render textures. /// </summary> public enum RenderTextureDepth { _0 = 0, _16 = 16, _24 = 24, } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate void LogCallback(int level, IntPtr message); /// <summary> /// Gets the singleton instance. /// </summary> public static OVRManager instance { get; private set; } /// <summary> /// Gets a reference to the active OVRDisplay /// </summary> public static OVRDisplay display { get; private set; } /// <summary> /// Gets a reference to the active OVRTracker /// </summary> public static OVRTracker tracker { get; private set; } /// <summary> /// Gets a reference to the active OVRInput /// </summary> public static OVRInput input { get; private set; } private static bool _profileIsCached = false; private static OVRProfile _profile; /// <summary> /// Gets the current profile, which contains information about the user's settings and body dimensions. /// </summary> public static OVRProfile profile { get { if (!_profileIsCached) { _profile = new OVRProfile(); _profile.TriggerLoad(); while (_profile.state == OVRProfile.State.LOADING) System.Threading.Thread.Sleep(1); if (_profile.state != OVRProfile.State.READY) Debug.LogWarning("Failed to load profile."); _profileIsCached = true; } return _profile; } } /// <summary> /// Occurs when an HMD attached. /// </summary> public static event Action HMDAcquired; /// <summary> /// Occurs when an HMD detached. /// </summary> public static event Action HMDLost; /// <summary> /// Occurs when the tracker gained tracking. /// </summary> public static event Action TrackingAcquired; /// <summary> /// Occurs when the tracker lost tracking. /// </summary> public static event Action TrackingLost; /// <summary> /// Occurs when HSW dismissed. /// </summary> public static event Action HSWDismissed; /// <summary> /// Occurs on the first Update after the OVRManager has been created, such as after a scene load. /// </summary> public static event Action Created; /// <summary> /// Occurs when the Native Texture Scale is modified. /// </summary> internal static event Action<float, float> NativeTextureScaleModified; /// <summary> /// Occurs when the Virtual Texture Scale is modified. /// </summary> internal static event Action<float, float> VirtualTextureScaleModified; /// <summary> /// Occurs when the Eye Texture AntiAliasing level is modified. /// </summary> internal static event Action<RenderTextureAntiAliasing, RenderTextureAntiAliasing> EyeTextureAntiAliasingModified; /// <summary> /// Occurs when the Eye Texture Depth is modified. /// </summary> internal static event Action<RenderTextureDepth, RenderTextureDepth> EyeTextureDepthModified; /// <summary> /// Occurs when the Eye Texture Format is modified. /// </summary> internal static event Action<RenderTextureFormat, RenderTextureFormat> EyeTextureFormatModified; /// <summary> /// Occurs when Monoscopic mode is modified. /// </summary> internal static event Action<bool, bool> MonoscopicModified; /// <summary> /// Occurs when HDR mode is modified. /// </summary> internal static event Action<bool, bool> HdrModified; /// <summary> /// If true, then the Oculus health and safety warning (HSW) is currently visible. /// </summary> public static bool isHSWDisplayed { get { #if !UNITY_ANDROID || UNITY_EDITOR return OVRPlugin.hswVisible; #else return false; #endif } } /// <summary> /// If the HSW has been visible for the necessary amount of time, this will make it disappear. /// </summary> public static void DismissHSWDisplay() { #if !UNITY_ANDROID || UNITY_EDITOR OVRPlugin.DismissHSW(); if (HSWDismissed != null) HSWDismissed(); #endif } /// <summary> /// Gets the current battery level. /// </summary> /// <returns><c>battery level in the range [0.0,1.0]</c> /// <param name="batteryLevel">Battery level.</param> public static float batteryLevel { get { #if !UNITY_ANDROID || UNITY_EDITOR return 1.0f; #else return OVR_GetBatteryLevel(); #endif } } /// <summary> /// Gets the current battery temperature. /// </summary> /// <returns><c>battery temperature in Celsius</c> /// <param name="batteryTemperature">Battery temperature.</param> public static float batteryTemperature { get { #if !UNITY_ANDROID || UNITY_EDITOR return 0.0f; #else return OVR_GetBatteryTemperature(); #endif } } /// <summary> /// Gets the current battery status. /// </summary> /// <returns><c>battery status</c> /// <param name="batteryStatus">Battery status.</param> public static int batteryStatus { get { #if !UNITY_ANDROID || UNITY_EDITOR return 0; #else return OVR_GetBatteryStatus(); #endif } } /// <summary> /// Gets the current volume level. /// </summary> /// <returns><c>volume level in the range [0,MaxVolume], or -1 for not initialized.</c> public static int volumeLevel { get { #if !UNITY_ANDROID || UNITY_EDITOR Debug.LogError( "GetVolume() is only supported on Android" ); return -1; #else return OVR_GetVolume(); #endif } } /// <summary> /// Gets the time since last volume change /// </summary> /// <returns><c>time since last volume change or -1 for not initialized.</c> public static double timeSinceLastVolumeChange { get { #if !UNITY_ANDROID || UNITY_EDITOR Debug.LogError( "GetTimeSinceLastVolumeChange() is only supported on Android" ); return -1; #else return OVR_GetTimeSinceLastVolumeChange(); #endif } } [Range(0.1f, 4.0f)] /// <summary> /// Controls the size of the eye textures. /// Values must be above 0. /// Values below 1 permit sub-sampling for improved performance. /// Values above 1 permit super-sampling for improved sharpness. /// </summary> public float nativeTextureScale = 1.0f; [Range(0.1f, 1.0f)] /// <summary> /// Controls the size of the rendering viewport. /// Values must be above 0 and less than or equal to 1. /// Values below 1 permit dynamic sub-sampling for improved performance. /// </summary> public float virtualTextureScale = 1.0f; /// <summary> /// The format of each eye texture. /// </summary> public RenderTextureFormat eyeTextureFormat = RenderTextureFormat.Default; /// <summary> /// The antialiasing level of each eye texture. /// </summary> public RenderTextureAntiAliasing eyeTextureAntiAliasing = RenderTextureAntiAliasing._2; /// <summary> /// The depth of each eye texture in bits. Valid Unity render texture depths are 0, 16, and 24. /// </summary> public RenderTextureDepth eyeTextureDepth = RenderTextureDepth._24; /// <summary> /// If true, head tracking will affect the orientation of each OVRCameraRig's cameras. /// </summary> public bool usePositionTracking = true; /// <summary> /// If true, TimeWarp will be used to correct the output of each OVRCameraRig for rotational latency. /// </summary> public bool timeWarp = true; /// <summary> /// If this is true and TimeWarp is true, each OVRCameraRig will stop tracking and only TimeWarp will respond to head motion. /// </summary> public bool freezeTimeWarp = false; /// <summary> /// If true, each scene load will cause the head pose to reset. /// </summary> public bool resetTrackerOnLoad = true; /// <summary> /// If true, the eyes see the same image, which is rendered only by the left camera. /// </summary> public bool monoscopic = false; /// <summary> /// If true, enable high dynamic range support. /// </summary> public bool hdr = false; /// <summary> /// True if the current platform supports virtual reality. /// </summary> public bool isSupportedPlatform { get; private set; } /// <summary> /// True if the runtime is installed, a VR display is present, and VR is supported in the current configuration. /// </summary> public bool isVRPresent { get { return _isVRPresent; } private set { _isVRPresent = value; } } private static bool _isVRPresent = false; private static bool usingPositionTrackingCached = false; private static bool usingPositionTracking = false; private static bool wasHmdPresent = false; private static bool wasRecreated = true; private static bool wasPositionTracked = false; private static float prevNativeTextureScale; private static float prevVirtualTextureScale; private static RenderTextureAntiAliasing prevEyeTextureAntiAliasing; private static RenderTextureDepth prevEyeTextureDepth; private static bool prevMonoscopic; private static bool prevHdr; private static RenderTextureFormat prevEyeTextureFormat; private static WaitForEndOfFrame waitForEndOfFrame = new WaitForEndOfFrame(); #if UNITY_ANDROID && !UNITY_EDITOR // Get this from Unity on startup so we can call Activity java functions. private static bool androidJavaInit = false; private static AndroidJavaObject activity; [NonSerialized] private static OVRVolumeControl volumeController = null; [NonSerialized] private Transform volumeControllerTransform = null; /// <summary> /// Occurs when the application is resumed. /// </summary> public static event Action OnApplicationResumed = null; /// <summary> /// Occurs before plugin initialized. Used to configure /// VR Mode Parms such as clock locks. /// </summary> public static event Action OnConfigureVrModeParms = null; public static void EnterVRMode() { OVRPluginEvent.Issue(RenderEventType.Resume); } public static void LeaveVRMode() { OVRPluginEvent.Issue(RenderEventType.Pause); } public delegate void VrApiEventDelegate( string eventData ); public static VrApiEventDelegate OnVrApiEvent = null; private static Int32 MaxDataSize = 4096; private static StringBuilder EventData = new StringBuilder( MaxDataSize ); // Define and set an event delegate if to handle System Activities events (for instance, // an app might handle the "reorient" event if it needs to reposition menus when the // user selects Reorient in Activities. The eventData will be a JSON string. public static void SetVrApiEventDelegate( VrApiEventDelegate d ) { OnVrApiEvent = d; } // This is just an example of an event delegate. public static void VrApiEventDefaultDelegate( string eventData ) { Debug.Log( "VrApiEventDefaultDelegate: " + eventData ); } #else private static bool ovrIsInitialized; private static bool isQuitting; #endif #region Unity Messages private void Awake() { // Only allow one instance at runtime. if (instance != null) { enabled = false; DestroyImmediate(this); return; } instance = this; System.Version netVersion = OVRPlugin.wrapperVersion; System.Version ovrVersion = OVRPlugin.version; Debug.Log("Unity v" + Application.unityVersion + ", " + "Oculus Integration v" + netVersion + ", " + "OVRPlugin v" + ovrVersion + "."); // Detect whether this platform is a supported platform RuntimePlatform currPlatform = Application.platform; isSupportedPlatform |= currPlatform == RuntimePlatform.Android; isSupportedPlatform |= currPlatform == RuntimePlatform.LinuxPlayer; isSupportedPlatform |= currPlatform == RuntimePlatform.OSXEditor; isSupportedPlatform |= currPlatform == RuntimePlatform.OSXPlayer; isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsEditor; isSupportedPlatform |= currPlatform == RuntimePlatform.WindowsPlayer; if (!isSupportedPlatform) { Debug.LogWarning("This platform is unsupported"); return; } #if !UNITY_ANDROID || UNITY_EDITOR if (OVRUnityVersionChecker.hasBuiltInVR) { Debug.LogWarning("The Oculus Unity Legacy Integration is only supported in Unity 4.x releases. For Unity 5.x, please migrate to the Oculus Utilities for Unity package and use Unity's built-in VR support (available in Unity 5.1 and later)."); isVRPresent = false; } else if (!ovrIsInitialized) { //HACK: For some reason, Unity doesn't call UnitySetGraphicsDevice until we make the first P/Invoke call. OVRPluginEvent.eventBase = OVRPluginEvent.eventBase; #if !UNITY_ANDROID || UNITY_EDITOR //Handle all log messages OVR_FlushLog(OnLogMessage); #endif // If unable to load the Oculus Runtime. if (!OVRPlugin.initialized) { bool isBadWinRenderer = ((Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer) && !SystemInfo.graphicsDeviceVersion.Contains("Direct3D 11")); if (isBadWinRenderer) Debug.LogWarning("Only D3D11 is supported on Windows."); else Debug.LogWarning("Runtime is not present or no Rift attached. Running without VR."); // Runtime is not installed if ovr_Initialize() fails. isVRPresent = false; // Go monoscopic in response. monoscopic = true; } else { OVRPluginEvent.Issue(RenderEventType.InitRenderThread); isVRPresent = true; #if UNITY_EDITOR if (!OVRUnityVersionChecker.hasEditorVRSupport) { // Only allow VR in standalones. isVRPresent = false; Debug.LogWarning("VR rendering is not supported in the editor. Please update to 4.6.7p4 or build a stand-alone player."); } #endif if (netVersion.Major > ovrVersion.Major || netVersion.Major == ovrVersion.Major && netVersion.Minor > ovrVersion.Minor) { isVRPresent = false; Debug.LogWarning("Version check failed. Please make sure you are using OVRPlugin " + Ovr.Hmd.OVR_VERSION_STRING + " or newer."); } OVRPlugin.queueAheadFraction = 0f; ovrIsInitialized = true; } } SetEditorPlay(Application.isEditor); #else // UNITY_ANDROID && !UNITY_EDITOR: Start of Android init. // Android integration does not dynamically load its runtime. isVRPresent = true; // log the unity version Debug.Log( "Unity Version: " + Application.unityVersion ); // don't allow the application to run if orientation is not landscape left. if (Screen.orientation != ScreenOrientation.LandscapeLeft) { Debug.LogError("********************************************************************************\n"); Debug.LogError("***** Default screen orientation must be set to landscape left for VR.\n" + "***** Stopping application.\n"); Debug.LogError("********************************************************************************\n"); Debug.Break(); Application.Quit(); } // don't enable gyro, it is not used and triggers expensive display calls if (Input.gyro.enabled) { Debug.LogError("*** Auto-disabling Gyroscope ***"); Input.gyro.enabled = false; } // NOTE: On Adreno Lollipop, it is an error to have antiAliasing set on the // main window surface with front buffer rendering enabled. The view will // render black. // On Adreno KitKat, some tiling control modes will cause the view to render // black. if (QualitySettings.antiAliasing > 1) { Debug.LogError("*** Antialiasing must be disabled for Gear VR ***"); } // we sync in the TimeWarp, so we don't want unity // syncing elsewhere QualitySettings.vSyncCount = 0; // try to render at 60fps Application.targetFrameRate = 60; // don't allow the app to run in the background Application.runInBackground = false; // Disable screen dimming Screen.sleepTimeout = SleepTimeout.NeverSleep; if (!androidJavaInit) { AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer"); activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity"); // Prepare for the RenderThreadInit() SetInitVariables(activity.GetRawObject(), System.IntPtr.Zero); #if USE_ENTITLEMENT_CHECK AndroidJavaObject entitlementChecker = new AndroidJavaObject("com.oculus.svclib.OVREntitlementChecker"); entitlementChecker.CallStatic("doAutomatedCheck", activity); #else Debug.Log( "Inhibiting Entitlement Check!" ); #endif androidJavaInit = true; } // We want to set up our touchpad messaging system OVRTouchpad.Create(); InitVolumeController(); // set an event delegate like this if you wish to handle events like "reorient". //SetVrApiEventDelegate( VrApiEventDefaultDelegate ); #endif // End of android init. prevEyeTextureAntiAliasing = OVRManager.instance.eyeTextureAntiAliasing; prevEyeTextureDepth = OVRManager.instance.eyeTextureDepth; prevEyeTextureFormat = OVRManager.instance.eyeTextureFormat; prevNativeTextureScale = OVRManager.instance.nativeTextureScale; prevVirtualTextureScale = OVRManager.instance.virtualTextureScale; prevMonoscopic = OVRManager.instance.monoscopic; prevHdr = OVRManager.instance.hdr; if (tracker == null) tracker = new OVRTracker(); if (display == null) display = new OVRDisplay(); else wasRecreated = true; if (input == null) input = new OVRInput(); if (resetTrackerOnLoad) display.RecenterPose(); #if !UNITY_ANDROID || UNITY_EDITOR // Except for D3D9, SDK rendering forces vsync unless you pass ovrHmdCap_NoVSync to Hmd.SetEnabledCaps(). if (timeWarp) { bool useUnityVSync = SystemInfo.graphicsDeviceVersion.Contains("Direct3D 9"); QualitySettings.vSyncCount = useUnityVSync ? 1 : 0; QualitySettings.maxQueuedFrames = 0; } #endif #if UNITY_STANDALONE_WIN if (!OVRUnityVersionChecker.hasD3D9ExclusiveModeSupport && !display.isDirectMode && SystemInfo.graphicsDeviceVersion.Contains("Direct3D 9")) { MessageBox(0, "Direct3D 9 extended mode is not supported in this configuration. " + "Please use direct display mode, a different graphics API, or rebuild the application with a newer Unity version." , "VR Configuration Warning", 0); } if (!OVRUnityVersionChecker.hasD3D11ExclusiveModeSupport && !display.isDirectMode && SystemInfo.graphicsDeviceVersion.Contains("Direct3D 11")) { MessageBox(0, "Direct3D 11 extended mode is not supported in this configuration. " + "Please use direct display mode, a different graphics API, or rebuild the application with a newer Unity version." , "VR Configuration Warning", 0); } #endif } private void OnDestroy() { #if UNITY_ANDROID && !UNITY_EDITOR RenderTexture.active = null; #endif } private void OnApplicationQuit() { #if !UNITY_ANDROID || UNITY_EDITOR isQuitting = true; #else Debug.Log( "OnApplicationQuit" ); // This will trigger the shutdown on the render thread OVRPluginEvent.Issue( RenderEventType.ShutdownRenderThread ); #endif } private void OnEnable() { if (!isVRPresent) return; bool isD3d = SystemInfo.graphicsDeviceVersion.Contains("Direct3D") || Application.platform == RuntimePlatform.WindowsEditor && SystemInfo.graphicsDeviceVersion.Contains("emulated"); display.flipInput = isD3d; StartCoroutine(CallbackCoroutine()); } private void OnDisable() { #if !UNITY_ANDROID || UNITY_EDITOR if (!isQuitting) return; if (ovrIsInitialized) { display.ReleaseEyeTextures(); OVRPluginEvent.Issue(RenderEventType.ShutdownRenderThread); ovrIsInitialized = false; } #endif // NOTE: The coroutines will also be stopped when the object is destroyed. StopAllCoroutines(); } private void Start() { #if UNITY_ANDROID && !UNITY_EDITOR if (!isVRPresent) return; // Configure app-specific vr mode parms such as clock frequencies if ( OnConfigureVrModeParms != null ) { OnConfigureVrModeParms(); } // NOTE: For Android, the resolution should be the same for both left and right eye OVRDisplay.EyeRenderDesc leftEyeDesc = OVRManager.display.GetEyeRenderDesc(OVREye.Left); Vector2 resolution = leftEyeDesc.resolution; OVR_SetEyeParms((int)resolution.x,(int)resolution.y); // This will trigger the init on the render thread InitRenderThread(); #endif } public enum VrApiEventStatus { ERROR_INTERNAL = -2, // queue isn't created, etc. ERROR_INVALID_BUFFER = -1, // the buffer passed in was invalid NOT_PENDING = 0, // no event is waiting PENDING, // an event is waiting CONSUMED, // an event was pending but was consumed internally BUFFER_OVERFLOW, // an event is being returned, but it could not fit into the buffer INVALID_JSON // there was an error parsing the JSON data } private void Update() { if (!isVRPresent) return; if (!usingPositionTrackingCached || usingPositionTracking != usePositionTracking) { tracker.isEnabled = usePositionTracking; usingPositionTracking = usePositionTracking; usingPositionTrackingCached = true; } // Dispatch any events. if (HMDLost != null && wasHmdPresent && !display.isPresent) HMDLost(); if (HMDAcquired != null && !wasHmdPresent && display.isPresent) HMDAcquired(); wasHmdPresent = display.isPresent; if (Created != null && wasRecreated) Created(); wasRecreated = false; if (TrackingLost != null && wasPositionTracked && !tracker.isPositionTracked) TrackingLost(); if (TrackingAcquired != null && !wasPositionTracked && tracker.isPositionTracked) TrackingAcquired(); wasPositionTracked = tracker.isPositionTracked; #if (!UNITY_ANDROID || UNITY_EDITOR) OVRPlugin.nativeTextureScale = nativeTextureScale; OVRPlugin.virtualTextureScale = virtualTextureScale; #endif if (NativeTextureScaleModified != null && nativeTextureScale != prevNativeTextureScale) NativeTextureScaleModified(prevNativeTextureScale, nativeTextureScale); prevNativeTextureScale = nativeTextureScale; if (VirtualTextureScaleModified != null && virtualTextureScale != prevVirtualTextureScale) VirtualTextureScaleModified(prevVirtualTextureScale, virtualTextureScale); prevVirtualTextureScale = virtualTextureScale; if (EyeTextureAntiAliasingModified != null && eyeTextureAntiAliasing != prevEyeTextureAntiAliasing) EyeTextureAntiAliasingModified(prevEyeTextureAntiAliasing, eyeTextureAntiAliasing); prevEyeTextureAntiAliasing = eyeTextureAntiAliasing; if (EyeTextureDepthModified != null && eyeTextureDepth != prevEyeTextureDepth) EyeTextureDepthModified(prevEyeTextureDepth, eyeTextureDepth); prevEyeTextureDepth = eyeTextureDepth; if (EyeTextureFormatModified != null && eyeTextureFormat != prevEyeTextureFormat) EyeTextureFormatModified(prevEyeTextureFormat, eyeTextureFormat); prevEyeTextureFormat = eyeTextureFormat; if (MonoscopicModified != null && monoscopic != prevMonoscopic) MonoscopicModified(prevMonoscopic, monoscopic); prevMonoscopic = monoscopic; if (HdrModified != null && hdr != prevHdr) HdrModified(prevHdr, hdr); prevHdr = hdr; if (isHSWDisplayed && Input.anyKeyDown) { DismissHSWDisplay(); if (HSWDismissed != null) HSWDismissed(); } display.timeWarp = timeWarp; display.Update(); input.Update(); #if UNITY_ANDROID && !UNITY_EDITOR if (volumeController != null) { if (volumeControllerTransform == null) { if (gameObject.GetComponent<OVRCameraRig>() != null) { volumeControllerTransform = gameObject.GetComponent<OVRCameraRig>().centerEyeAnchor; } } volumeController.UpdatePosition(volumeControllerTransform); } // Service VrApi events // If this code is not called, internal VrApi events will never be pushed to the internal event queue. VrApiEventStatus pendingResult = (VrApiEventStatus)OVR_GetNextPendingEvent( EventData, (uint)MaxDataSize ); while (pendingResult == VrApiEventStatus.PENDING) { if (OnVrApiEvent != null) { OnVrApiEvent(EventData.ToString()); } else { Debug.Log("No OnVrApiEvent delegate set!"); } EventData.Length = 0; pendingResult = (VrApiEventStatus)OVR_GetNextPendingEvent(EventData, (uint)MaxDataSize); } #endif } private void OnLogMessage(int l, IntPtr m) { var message = "[OVR] " + Marshal.PtrToStringAnsi(m); if (l == 2) Debug.LogWarning(message); else Debug.Log(message); } private void LateUpdate() { #if !UNITY_ANDROID || UNITY_EDITOR //Handle all log messages OVR_FlushLog(OnLogMessage); #endif if (!isVRPresent) return; display.BeginFrame(); } private IEnumerator CallbackCoroutine() { while (true) { yield return waitForEndOfFrame; if (isVRPresent) display.EndFrame(); } } #if UNITY_ANDROID && !UNITY_EDITOR private void OnPause() { LeaveVRMode(); } private IEnumerator OnResume() { yield return null; // delay 1 frame to allow Unity enough time to create the windowSurface if (OnApplicationResumed != null) { OnApplicationResumed(); } EnterVRMode(); } private void OnApplicationPause(bool pause) { Debug.Log("OnApplicationPause() " + pause); if (pause) { OnPause(); } else { StartCoroutine(OnResume()); } } void OnApplicationFocus( bool focus ) { // OnApplicationFocus() does not appear to be called // consistently while OnApplicationPause is. Moved // functionality to OnApplicationPause(). Debug.Log( "OnApplicationFocus() " + focus ); } /// <summary> /// Creates a popup dialog that shows when volume changes. /// </summary> private static void InitVolumeController() { if (volumeController == null) { Debug.Log("Creating volume controller..."); // Create the volume control popup GameObject go = GameObject.Instantiate(Resources.Load("OVRVolumeController")) as GameObject; if (go != null) { volumeController = go.GetComponent<OVRVolumeControl>(); } else { Debug.LogError("Unable to instantiate volume controller"); } } } /// <summary> /// Leaves the application/game and returns to the launcher/dashboard /// </summary> public void ReturnToLauncher() { // show the platform UI quit prompt OVRManager.PlatformUIConfirmQuit(); } #endif #endregion public static void SetEditorPlay(bool isEditor) { } public static void SetInitVariables(IntPtr activity, IntPtr vrActivityClass) { #if UNITY_ANDROID && !UNITY_EDITOR OVR_SetInitVariables(activity, vrActivityClass); #endif } public static void PlatformUIConfirmQuit() { #if UNITY_ANDROID && !UNITY_EDITOR OVRPluginEvent.Issue(RenderEventType.PlatformUIConfirmQuit); #endif } public static void PlatformUIGlobalMenu() { #if UNITY_ANDROID && !UNITY_EDITOR OVRPluginEvent.Issue(RenderEventType.PlatformUI); #endif } public static void EndEye(OVREye eye) { #if UNITY_ANDROID && !UNITY_EDITOR RenderEventType eventType = (eye == OVREye.Left) ? RenderEventType.LeftEyeEndFrame : RenderEventType.RightEyeEndFrame; int eyeTextureId = display.GetEyeTextureId(eye); OVRPluginEvent.IssueWithData(eventType, eyeTextureId); #endif } public static void InitRenderThread() { #if UNITY_ANDROID && !UNITY_EDITOR OVRPluginEvent.Issue(RenderEventType.InitRenderThread); #endif } #if !UNITY_ANDROID || UNITY_EDITOR #if UNITY_STANDALONE_WIN [DllImport("user32", EntryPoint = "MessageBoxA", CharSet = CharSet.Ansi)] public static extern bool MessageBox(int hWnd, [MarshalAs(UnmanagedType.LPStr)]string text, [MarshalAs(UnmanagedType.LPStr)]string caption, uint type); #endif [DllImport("OculusPlugin")] private static extern int OVR_FlushLog(LogCallback handler); #else [DllImport("OculusPlugin")] private static extern void OVR_SetInitVariables(IntPtr activity, IntPtr vrActivityClass); [DllImport("OculusPlugin")] private static extern void OVR_SetEyeParms( int fbWidth, int fbHeight ); [DllImport("OculusPlugin")] private static extern float OVR_GetBatteryLevel(); [DllImport("OculusPlugin")] private static extern int OVR_GetBatteryStatus(); [DllImport("OculusPlugin")] private static extern float OVR_GetBatteryTemperature(); [DllImport("OculusPlugin")] private static extern int OVR_GetVolume(); [DllImport("OculusPlugin")] private static extern double OVR_GetTimeSinceLastVolumeChange(); [DllImport("OculusPlugin")] private static extern int OVR_GetNextPendingEvent( StringBuilder sb, uint bufferSize ); #endif }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.ContainerService.Fluent { using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.ContainerService.Fluent.ContainerService.Definition; using Microsoft.Azure.Management.ContainerService.Fluent.ContainerService.Update; using Microsoft.Azure.Management.ContainerService.Fluent.ContainerServiceAgentPool.Definition; using Microsoft.Azure.Management.ContainerService.Fluent.Models; using Microsoft.Azure.Management.ResourceManager.Fluent; using System.Collections.Generic; internal partial class ContainerServiceImpl { /// <summary> /// Gets the agent pools map. /// </summary> System.Collections.Generic.IReadOnlyDictionary<string,Microsoft.Azure.Management.ContainerService.Fluent.IContainerServiceAgentPool> Microsoft.Azure.Management.ContainerService.Fluent.IContainerService.AgentPools { get { return this.AgentPools(); } } /// <summary> /// Gets true if diagnostics are enabled. /// </summary> bool Microsoft.Azure.Management.ContainerService.Fluent.IContainerService.IsDiagnosticsEnabled { get { return this.IsDiagnosticsEnabled(); } } /// <summary> /// Gets the Linux root username. /// </summary> string Microsoft.Azure.Management.ContainerService.Fluent.IContainerService.LinuxRootUsername { get { return this.LinuxRootUsername(); } } /// <summary> /// Gets the master DNS prefix which was specified at creation time. /// </summary> string Microsoft.Azure.Management.ContainerService.Fluent.IContainerService.MasterDnsPrefix { get { return this.MasterDnsPrefix(); } } /// <summary> /// Gets the master FQDN. /// </summary> string Microsoft.Azure.Management.ContainerService.Fluent.IContainerService.MasterFqdn { get { return this.MasterFqdn(); } } /// <summary> /// Gets the master node count. /// </summary> int Microsoft.Azure.Management.ContainerService.Fluent.IContainerService.MasterNodeCount { get { return this.MasterNodeCount(); } } /// <summary> /// Gets OS disk size in GB set for every machine in the master pool. /// </summary> int Microsoft.Azure.Management.ContainerService.Fluent.IContainerService.MasterOSDiskSizeInGB { get { return this.MasterOSDiskSizeInGB(); } } /// <summary> /// Gets the storage kind set for every machine in the master pool. /// </summary> StorageProfileTypes Microsoft.Azure.Management.ContainerService.Fluent.IContainerService.MasterStorageProfile { get { return this.MasterStorageProfile(); } } /// <summary> /// Gets the name of the subnet used by every machine in the master pool. /// </summary> string Microsoft.Azure.Management.ContainerService.Fluent.IContainerService.MasterSubnetName { get { return this.MasterSubnetName(); } } /// <summary> /// Gets the ID of the virtual network used by every machine in the master and agent pools. /// </summary> string Microsoft.Azure.Management.ContainerService.Fluent.IContainerService.NetworkId { get { return this.NetworkId(); } } /// <summary> /// Gets the type of the orchestrator. /// </summary> Models.ContainerServiceOrchestratorTypes Microsoft.Azure.Management.ContainerService.Fluent.IContainerService.OrchestratorType { get { return this.OrchestratorType(); } } /// <summary> /// Gets the service principal client ID. /// </summary> string Microsoft.Azure.Management.ContainerService.Fluent.IContainerService.ServicePrincipalClientId { get { return this.ServicePrincipalClientId(); } } /// <summary> /// Gets the service principal secret. /// </summary> string Microsoft.Azure.Management.ContainerService.Fluent.IContainerService.ServicePrincipalSecret { get { return this.ServicePrincipalSecret(); } } /// <summary> /// Gets the Linux SSH key. /// </summary> string Microsoft.Azure.Management.ContainerService.Fluent.IContainerService.SshKey { get { return this.SshKey(); } } /// <summary> /// Begins the definition of a agent pool profile to be attached to the container service. /// </summary> /// <param name="name">The name for the agent pool profile.</param> /// <return>The stage representing configuration for the agent pool profile.</return> ContainerServiceAgentPool.Definition.IBlank<ContainerService.Definition.IWithCreate> ContainerService.Definition.IWithAgentPool.DefineAgentPool(string name) { return this.DefineAgentPool(name); } /// <summary> /// Updates the agent pool virtual machine count. /// </summary> /// <param name="agentCount">The number of agents (virtual machines) to host docker containers.</param> /// <return>The next stage of the update.</return> ContainerService.Update.IUpdate ContainerService.Update.IWithUpdateAgentPoolCount.WithAgentVirtualMachineCount(int agentCount) { return this.WithAgentVirtualMachineCount(agentCount); } /// <summary> /// Specifies the DCOS orchestration type for the container service. /// </summary> /// <return>The next stage of the definition.</return> ContainerService.Definition.IWithLinux ContainerService.Definition.IWithOrchestrator.WithDcosOrchestration() { return this.WithDcosOrchestration(); } /// <summary> /// Enables diagnostics. /// </summary> /// <return>The next stage of the definition.</return> ContainerService.Definition.IWithCreate ContainerService.Definition.IWithDiagnostics.WithDiagnostics() { return this.WithDiagnostics(); } /// <summary> /// Enables diagnostics. /// </summary> /// <return>The next stage of the definition.</return> ContainerService.Update.IUpdate ContainerService.Update.IWithDiagnostics.WithDiagnostics() { return this.WithDiagnostics(); } /// <summary> /// Specifies the Kubernetes orchestration type for the container service. /// </summary> /// <return>The next stage of the definition.</return> ContainerService.Definition.IWithServicePrincipalProfile ContainerService.Definition.IWithOrchestrator.WithKubernetesOrchestration() { return this.WithKubernetesOrchestration(); } /// <summary> /// Begins the definition to specify Linux settings. /// </summary> /// <return>The stage representing configuration of Linux specific settings.</return> ContainerService.Definition.IWithLinuxRootUsername ContainerService.Definition.IWithLinux.WithLinux() { return this.WithLinux(); } /// <summary> /// Specifies the DNS prefix to be used to create the FQDN for the master pool. /// </summary> /// <param name="dnsPrefix">The DNS prefix to be used to create the FQDN for the master pool.</param> /// <return>The next stage of the definition.</return> ContainerService.Definition.IWithCreate ContainerService.Definition.IWithMasterDnsPrefix.WithMasterDnsPrefix(string dnsPrefix) { return this.WithMasterDnsPrefix(dnsPrefix); } /// <summary> /// Specifies the master node count. /// </summary> /// <param name="count">Master profile count (1, 3, 5).</param> /// <return>The next stage of the definition.</return> ContainerService.Definition.IWithAgentPool ContainerService.Definition.IWithMasterNodeCount.WithMasterNodeCount(ContainerServiceMasterProfileCount count) { return this.WithMasterNodeCount(count); } /// <summary> /// OS Disk Size in GB to be used for every machine in the master pool. /// If you specify 0, the default osDisk size will be used according to the vmSize specified. /// </summary> /// <param name="osDiskSizeInGB">OS Disk Size in GB to be used for every machine in the master pool.</param> /// <return>The next stage of the definition.</return> ContainerService.Definition.IWithCreate ContainerService.Definition.IWithMasterOSDiskSize.WithMasterOSDiskSizeInGB(int osDiskSizeInGB) { return this.WithMasterOSDiskSizeInGB(osDiskSizeInGB); } /// <summary> /// Specifies the storage kind to be used for every machine in master pool. /// </summary> /// <param name="storageProfile">The storage kind to be used for every machine in the master pool.</param> /// <return>The next stage of the definition.</return> ContainerService.Definition.IWithCreate ContainerService.Definition.IWithMasterStorageProfile.WithMasterStorageProfile(StorageProfileTypes storageProfile) { return this.WithMasterStorageProfile(storageProfile); } /// <summary> /// Specifies the size of the master VMs, default set to "Standard_D2_v2". /// </summary> /// <param name="vmSize">The size of the VM.</param> /// <return>The next stage of the definition.</return> ContainerService.Definition.IWithCreate ContainerService.Definition.IWithMasterVMSize.WithMasterVMSize(ContainerServiceVirtualMachineSizeTypes vmSize) { return this.WithMasterVMSize(vmSize); } /// <summary> /// Disables diagnostics. /// </summary> /// <return>The next stage of the definition.</return> ContainerService.Update.IUpdate ContainerService.Update.IWithDiagnostics.WithoutDiagnostics() { return this.WithoutDiagnostics(); } /// <summary> /// Begins the definition to specify Linux root username. /// </summary> /// <param name="rootUserName">The root username.</param> /// <return>The next stage of the definition.</return> ContainerService.Definition.IWithLinuxSshKey ContainerService.Definition.IWithLinuxRootUsername.WithRootUsername(string rootUserName) { return this.WithRootUsername(rootUserName); } /// <summary> /// Properties for cluster service principals. /// </summary> /// <param name="clientId">The ID for the service principal.</param> /// <param name="secret">The secret password associated with the service principal.</param> /// <return>The next stage.</return> ContainerService.Definition.IWithLinux ContainerService.Definition.IWithServicePrincipalProfile.WithServicePrincipal(string clientId, string secret) { return this.WithServicePrincipal(clientId, secret); } /// <summary> /// Begins the definition to specify Linux ssh key. /// </summary> /// <param name="sshKeyData">The SSH key data.</param> /// <return>The next stage of the definition.</return> ContainerService.Definition.IWithMasterNodeCount ContainerService.Definition.IWithLinuxSshKey.WithSshKey(string sshKeyData) { return this.WithSshKey(sshKeyData); } /// <summary> /// Specifies the virtual network and subnet for the virtual machines in the master and agent pools. /// </summary> /// <param name="networkId">The network ID to be used by the machines.</param> /// <param name="subnetName">The name of the subnet.</param> /// <return>The next stage of the definition.</return> ContainerService.Definition.IWithCreate ContainerService.Definition.IWithSubnet.WithSubnet(string networkId, string subnetName) { return this.WithSubnet(networkId, subnetName); } /// <summary> /// Specifies the Swarm orchestration type for the container service. /// </summary> /// <return>The next stage of the definition.</return> ContainerService.Definition.IWithLinux ContainerService.Definition.IWithOrchestrator.WithSwarmOrchestration() { return this.WithSwarmOrchestration(); } } }
namespace Xilium.CefGlue { using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using Xilium.CefGlue.Interop; /// <summary> /// Class used to represent the browser process aspects of a browser window. The /// methods of this class can only be called in the browser process. They may be /// called on any thread in that process unless otherwise indicated in the /// comments. /// </summary> public sealed unsafe partial class CefBrowserHost { /// <summary> /// Create a new browser window using the window parameters specified by /// |windowInfo|. All values will be copied internally and the actual window /// will be created on the UI thread. If |request_context| is empty the /// global request context will be used. This method can be called on any /// browser process thread and will not block. /// </summary> public static void CreateBrowser(CefWindowInfo windowInfo, CefClient client, CefBrowserSettings settings, string url, CefRequestContext requestContext) { if (windowInfo == null) throw new ArgumentNullException("windowInfo"); if (client == null) throw new ArgumentNullException("client"); if (settings == null) throw new ArgumentNullException("settings"); // TODO: [ApiUsage] if windowInfo.WindowRenderingDisabled && client doesn't provide RenderHandler implementation -> throw exception var n_windowInfo = windowInfo.ToNative(); var n_client = client.ToNative(); var n_settings = settings.ToNative(); var n_requestContext = requestContext != null ? requestContext.ToNative() : null; fixed (char* url_ptr = url) { cef_string_t n_url = new cef_string_t(url_ptr, url != null ? url.Length : 0); var n_success = cef_browser_host_t.create_browser(n_windowInfo, n_client, &n_url, n_settings, n_requestContext); if (n_success != 1) throw ExceptionBuilder.FailedToCreateBrowser(); } // TODO: free n_ structs ? } public static void CreateBrowser(CefWindowInfo windowInfo, CefClient client, CefBrowserSettings settings, string url) { CreateBrowser(windowInfo, client, settings, url, null); } public static void CreateBrowser(CefWindowInfo windowInfo, CefClient client, CefBrowserSettings settings, Uri url, CefRequestContext requestContext) { CreateBrowser(windowInfo, client, settings, url.ToString(), requestContext); } public static void CreateBrowser(CefWindowInfo windowInfo, CefClient client, CefBrowserSettings settings, Uri url) { CreateBrowser(windowInfo, client, settings, url, null); } public static void CreateBrowser(CefWindowInfo windowInfo, CefClient client, CefBrowserSettings settings, CefRequestContext requestContext) { CreateBrowser(windowInfo, client, settings, string.Empty, requestContext); } public static void CreateBrowser(CefWindowInfo windowInfo, CefClient client, CefBrowserSettings settings) { CreateBrowser(windowInfo, client, settings, string.Empty, null); } /// <summary> /// Create a new browser window using the window parameters specified by /// |windowInfo|. If |request_context| is empty the global request context /// will be used. This method can only be called on the browser process UI /// thread. /// </summary> public static CefBrowser CreateBrowserSync(CefWindowInfo windowInfo, CefClient client, CefBrowserSettings settings, string url, CefRequestContext requestContext) { if (windowInfo == null) throw new ArgumentNullException("windowInfo"); if (client == null) throw new ArgumentNullException("client"); if (settings == null) throw new ArgumentNullException("settings"); // TODO: [ApiUsage] if windowInfo.WindowRenderingDisabled && client doesn't provide RenderHandler implementation -> throw exception var n_windowInfo = windowInfo.ToNative(); var n_client = client.ToNative(); var n_settings = settings.ToNative(); var n_requestContext = requestContext != null ? requestContext.ToNative() : null; fixed (char* url_ptr = url) { cef_string_t n_url = new cef_string_t(url_ptr, url != null ? url.Length : 0); var n_browser = cef_browser_host_t.create_browser_sync(n_windowInfo, n_client, &n_url, n_settings, n_requestContext); return CefBrowser.FromNative(n_browser); } // TODO: free n_ structs ? } public static CefBrowser CreateBrowserSync(CefWindowInfo windowInfo, CefClient client, CefBrowserSettings settings, string url) { return CreateBrowserSync(windowInfo, client, settings, url, null); } public static CefBrowser CreateBrowserSync(CefWindowInfo windowInfo, CefClient client, CefBrowserSettings settings, Uri url, CefRequestContext requestContext) { return CreateBrowserSync(windowInfo, client, settings, url.ToString(), requestContext); } public static CefBrowser CreateBrowserSync(CefWindowInfo windowInfo, CefClient client, CefBrowserSettings settings, Uri url) { return CreateBrowserSync(windowInfo, client, settings, url, null); } public static CefBrowser CreateBrowserSync(CefWindowInfo windowInfo, CefClient client, CefBrowserSettings settings, CefRequestContext requestContext) { return CreateBrowserSync(windowInfo, client, settings, string.Empty, requestContext); } public static CefBrowser CreateBrowserSync(CefWindowInfo windowInfo, CefClient client, CefBrowserSettings settings) { return CreateBrowserSync(windowInfo, client, settings, string.Empty); } /// <summary> /// Returns the hosted browser object. /// </summary> public CefBrowser GetBrowser() { return CefBrowser.FromNative(cef_browser_host_t.get_browser(_self)); } /// <summary> /// Request that the browser close. The JavaScript 'onbeforeunload' event will /// be fired. If |force_close| is false the event handler, if any, will be /// allowed to prompt the user and the user can optionally cancel the close. /// If |force_close| is true the prompt will not be displayed and the close /// will proceed. Results in a call to CefLifeSpanHandler::DoClose() if the /// event handler allows the close or if |force_close| is true. See /// CefLifeSpanHandler::DoClose() documentation for additional usage /// information. /// </summary> public void CloseBrowser(bool forceClose = false) { cef_browser_host_t.close_browser(_self, forceClose ? 1 : 0); } /// <summary> /// Set whether the browser is focused. /// </summary> public void SetFocus(bool focus) { cef_browser_host_t.set_focus(_self, focus ? 1 : 0); } /// <summary> /// Set whether the window containing the browser is visible /// (minimized/unminimized, app hidden/unhidden, etc). Only used on Mac OS X. /// </summary> public void SetWindowVisibility(bool visible) { cef_browser_host_t.set_window_visibility(_self, visible ? 1 : 0); } /// <summary> /// Retrieve the window handle for this browser. /// </summary> public IntPtr GetWindowHandle() { return cef_browser_host_t.get_window_handle(_self); } /// <summary> /// Retrieve the window handle of the browser that opened this browser. Will /// return NULL for non-popup windows. This method can be used in combination /// with custom handling of modal windows. /// </summary> public IntPtr GetOpenerWindowHandle() { return cef_browser_host_t.get_opener_window_handle(_self); } /// <summary> /// Returns the client for this browser. /// </summary> public CefClient GetClient() { return CefClient.FromNative( cef_browser_host_t.get_client(_self) ); } /// <summary> /// Returns the request context for this browser. /// </summary> public CefRequestContext GetRequestContext() { return CefRequestContext.FromNative( cef_browser_host_t.get_request_context(_self) ); } /// <summary> /// Get the current zoom level. The default zoom level is 0.0. This method can /// only be called on the UI thread. /// </summary> public double GetZoomLevel() { return cef_browser_host_t.get_zoom_level(_self); } /// <summary> /// Change the zoom level to the specified value. Specify 0.0 to reset the /// zoom level. If called on the UI thread the change will be applied /// immediately. Otherwise, the change will be applied asynchronously on the /// UI thread. /// </summary> public void SetZoomLevel(double value) { cef_browser_host_t.set_zoom_level(_self, value); } /// <summary> /// Call to run a file chooser dialog. Only a single file chooser dialog may be /// pending at any given time. |mode| represents the type of dialog to display. /// |title| to the title to be used for the dialog and may be empty to show the /// default title ("Open" or "Save" depending on the mode). |default_file_name| /// is the default file name to select in the dialog. |accept_types| is a list /// of valid lower-cased MIME types or file extensions specified in an input /// element and is used to restrict selectable files to such types. |callback| /// will be executed after the dialog is dismissed or immediately if another /// dialog is already pending. The dialog will be initiated asynchronously on /// the UI thread. /// </summary> public void RunFileDialog(CefFileDialogMode mode, string title, string defaultFileName, string[] acceptTypes, CefRunFileDialogCallback callback) { fixed (char* title_ptr = title) fixed (char* defaultFileName_ptr = defaultFileName) { var n_title = new cef_string_t(title_ptr, title != null ? title.Length : 0); var n_defaultFileName = new cef_string_t(defaultFileName_ptr, defaultFileName != null ? defaultFileName.Length : 0); var n_acceptTypes = cef_string_list.From(acceptTypes); cef_browser_host_t.run_file_dialog(_self, mode, &n_title, &n_defaultFileName, n_acceptTypes, callback.ToNative()); libcef.string_list_free(n_acceptTypes); } } /// <summary> /// Download the file at |url| using CefDownloadHandler. /// </summary> public void StartDownload(string url) { if (string.IsNullOrEmpty(url)) throw new ArgumentNullException("url"); fixed (char* url_ptr = url) { var n_url = new cef_string_t(url_ptr, url.Length); cef_browser_host_t.start_download(_self, &n_url); } } /// <summary> /// Print the current browser contents. /// </summary> public void Print() { cef_browser_host_t.print(_self); } /// <summary> /// Search for |searchText|. |identifier| can be used to have multiple searches /// running simultaniously. |forward| indicates whether to search forward or /// backward within the page. |matchCase| indicates whether the search should /// be case-sensitive. |findNext| indicates whether this is the first request /// or a follow-up. /// </summary> public void Find(int identifier, string searchText, bool forward, bool matchCase, bool findNext) { fixed (char* searchText_ptr = searchText) { var n_searchText = new cef_string_t(searchText_ptr, searchText.Length); cef_browser_host_t.find(_self, identifier, &n_searchText, forward ? 1 : 0, matchCase ? 1 : 0, findNext ? 1 : 0); } } /// <summary> /// Cancel all searches that are currently going on. /// </summary> public void StopFinding(bool clearSelection) { cef_browser_host_t.stop_finding(_self, clearSelection ? 1 : 0); } /// <summary> /// Open developer tools in its own window. /// </summary> public void ShowDevTools(CefWindowInfo windowInfo, CefClient client, CefBrowserSettings browserSettings) { cef_browser_host_t.show_dev_tools(_self, windowInfo.ToNative(), client.ToNative(), browserSettings.ToNative()); } /// <summary> /// Explicitly close the developer tools window if one exists for this browser /// instance. /// </summary> public void CloseDevTools() { cef_browser_host_t.close_dev_tools(_self); } /// <summary> /// Set whether mouse cursor change is disabled. /// </summary> public void SetMouseCursorChangeDisabled(bool disabled) { cef_browser_host_t.set_mouse_cursor_change_disabled(_self, disabled ? 1 : 0); } /// <summary> /// Returns true if mouse cursor change is disabled. /// </summary> public bool IsMouseCursorChangeDisabled { get { return cef_browser_host_t.is_mouse_cursor_change_disabled(_self) != 0; } } /// <summary> /// Returns true if window rendering is disabled. /// </summary> public bool IsWindowRenderingDisabled { get { return cef_browser_host_t.is_window_rendering_disabled(_self) != 0; } } /// <summary> /// Notify the browser that the widget has been resized. The browser will first /// call CefRenderHandler::GetViewRect to get the new size and then call /// CefRenderHandler::OnPaint asynchronously with the updated regions. This /// method is only used when window rendering is disabled. /// </summary> public void WasResized() { cef_browser_host_t.was_resized(_self); } /// <summary> /// Notify the browser that it has been hidden or shown. Layouting and /// CefRenderHandler::OnPaint notification will stop when the browser is /// hidden. This method is only used when window rendering is disabled. /// </summary> public void WasHidden(bool hidden) { cef_browser_host_t.was_hidden(_self, hidden ? 1 : 0); } /// <summary> /// Send a notification to the browser that the screen info has changed. The /// browser will then call CefRenderHandler::GetScreenInfo to update the /// screen information with the new values. This simulates moving the webview /// window from one display to another, or changing the properties of the /// current display. This method is only used when window rendering is /// disabled. /// </summary> public void NotifyScreenInfoChanged() { cef_browser_host_t.notify_screen_info_changed(_self); } /// <summary> /// Invalidate the |dirtyRect| region of the view. The browser will call /// CefRenderHandler::OnPaint asynchronously with the updated regions. This /// method is only used when window rendering is disabled. /// </summary> public void Invalidate(CefRectangle dirtyRect, CefPaintElementType type) { var n_dirtyRect = new cef_rect_t(dirtyRect.X, dirtyRect.Y, dirtyRect.Width, dirtyRect.Height); cef_browser_host_t.invalidate(_self, &n_dirtyRect, type); } /// <summary> /// Send a key event to the browser. /// </summary> public void SendKeyEvent(CefKeyEvent keyEvent) { if (keyEvent == null) throw new ArgumentNullException("keyEvent"); var n_event = new cef_key_event_t(); keyEvent.ToNative(&n_event); cef_browser_host_t.send_key_event(_self, &n_event); } /// <summary> /// Send a mouse click event to the browser. The |x| and |y| coordinates are /// relative to the upper-left corner of the view. /// </summary> public void SendMouseClickEvent(CefMouseEvent @event, CefMouseButtonType type, bool mouseUp, int clickCount) { var n_event = @event.ToNative(); cef_browser_host_t.send_mouse_click_event(_self, &n_event, type, mouseUp ? 1 : 0, clickCount); } /// <summary> /// Send a mouse move event to the browser. The |x| and |y| coordinates are /// relative to the upper-left corner of the view. /// </summary> public void SendMouseMoveEvent(CefMouseEvent @event, bool mouseLeave) { var n_event = @event.ToNative(); cef_browser_host_t.send_mouse_move_event(_self, &n_event, mouseLeave ? 1 : 0); } /// <summary> /// Send a mouse wheel event to the browser. The |x| and |y| coordinates are /// relative to the upper-left corner of the view. The |deltaX| and |deltaY| /// values represent the movement delta in the X and Y directions respectively. /// In order to scroll inside select popups with window rendering disabled /// CefRenderHandler::GetScreenPoint should be implemented properly. /// </summary> public void SendMouseWheelEvent(CefMouseEvent @event, int deltaX, int deltaY) { var n_event = @event.ToNative(); cef_browser_host_t.send_mouse_wheel_event(_self, &n_event, deltaX, deltaY); } /// <summary> /// Send a focus event to the browser. /// </summary> public void SendFocusEvent(bool setFocus) { cef_browser_host_t.send_focus_event(_self, setFocus ? 1 : 0); } /// <summary> /// Send a capture lost event to the browser. /// </summary> public void SendCaptureLostEvent() { cef_browser_host_t.send_capture_lost_event(_self); } /// <summary> /// Get the NSTextInputContext implementation for enabling IME on Mac when /// window rendering is disabled. /// </summary> public IntPtr GetNSTextInputContext() { return cef_browser_host_t.get_nstext_input_context(_self); } /// <summary> /// Handles a keyDown event prior to passing it through the NSTextInputClient /// machinery. /// </summary> public void HandleKeyEventBeforeTextInputClient(IntPtr keyEvent) { cef_browser_host_t.handle_key_event_before_text_input_client(_self, keyEvent); } /// <summary> /// Performs any additional actions after NSTextInputClient handles the event. /// </summary> public void HandleKeyEventAfterTextInputClient(IntPtr keyEvent) { cef_browser_host_t.handle_key_event_after_text_input_client(_self, keyEvent); } /// <summary> /// Call this method when the user drags the mouse into the web view (before /// calling DragTargetDragOver/DragTargetLeave/DragTargetDrop). /// |drag_data| should not contain file contents as this type of data is not /// allowed to be dragged into the web view. File contents can be removed using /// CefDragData::ResetFileContents (for example, if |drag_data| comes from /// CefRenderHandler::StartDragging). /// This method is only used when window rendering is disabled. /// </summary> public void DragTargetDragEnter(CefDragData dragData, CefMouseEvent mouseEvent, CefDragOperationsMask allowedOps) { var n_mouseEvent = mouseEvent.ToNative(); cef_browser_host_t.drag_target_drag_enter(_self, dragData.ToNative(), &n_mouseEvent, allowedOps); } /// <summary> /// Call this method each time the mouse is moved across the web view during /// a drag operation (after calling DragTargetDragEnter and before calling /// DragTargetDragLeave/DragTargetDrop). /// This method is only used when window rendering is disabled. /// </summary> public void DragTargetDragOver(CefMouseEvent mouseEvent, CefDragOperationsMask allowedOps) { var n_mouseEvent = mouseEvent.ToNative(); cef_browser_host_t.drag_target_drag_over(_self, &n_mouseEvent, allowedOps); } /// <summary> /// Call this method when the user drags the mouse out of the web view (after /// calling DragTargetDragEnter). /// This method is only used when window rendering is disabled. /// </summary> public void DragTargetDragLeave() { cef_browser_host_t.drag_target_drag_leave(_self); } /// <summary> /// Call this method when the user completes the drag operation by dropping /// the object onto the web view (after calling DragTargetDragEnter). /// The object being dropped is |drag_data|, given as an argument to /// the previous DragTargetDragEnter call. /// This method is only used when window rendering is disabled. /// </summary> public void DragTargetDrop(CefMouseEvent mouseEvent) { var n_mouseEvent = mouseEvent.ToNative(); cef_browser_host_t.drag_target_drop(_self, &n_mouseEvent); } /// <summary> /// Call this method when the drag operation started by a /// CefRenderHandler::StartDragging call has ended either in a drop or /// by being cancelled. |x| and |y| are mouse coordinates relative to the /// upper-left corner of the view. If the web view is both the drag source /// and the drag target then all DragTarget* methods should be called before /// DragSource* mthods. /// This method is only used when window rendering is disabled. /// </summary> public void DragSourceEndedAt(int x, int y, CefDragOperationsMask op) { cef_browser_host_t.drag_source_ended_at(_self, x, y, op); } /// <summary> /// Call this method when the drag operation started by a /// CefRenderHandler::StartDragging call has completed. This method may be /// called immediately without first calling DragSourceEndedAt to cancel a /// drag operation. If the web view is both the drag source and the drag /// target then all DragTarget* methods should be called before DragSource* /// mthods. /// This method is only used when window rendering is disabled. /// </summary> public void DragSourceSystemDragEnded() { cef_browser_host_t.drag_source_system_drag_ended(_self); } } }
/* * Formatter.cs - Implementation of the * "System.Private.NumberFormat.Formatter" class. * * Copyright (C) 2001 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Private.NumberFormat { using System; using System.Collections; using System.Globalization; using System.Text; internal abstract class Formatter { // ---------------------------------------------------------------------- // Private static variables for formatter // private const string validformats = "CcDdEeFfGgNnPpRrXx"; static private IDictionary formats = new Hashtable(); // ---------------------------------------------------------------------- // Protected data for other methods // static protected readonly char[] decimalDigits = {'0','1','2','3','4','5','6','7','8','9'}; // ---------------------------------------------------------------------- // Protected state information // protected int precision; // ---------------------------------------------------------------------- // Protected utility methods // static protected NumberFormatInfo NumberFormatInfo(IFormatProvider provider) { if(provider == null) { return System.Globalization.NumberFormatInfo.CurrentInfo; } else { NumberFormatInfo nfi = (NumberFormatInfo) provider.GetFormat( typeof(System.Globalization.NumberFormatInfo)); if(nfi != null) { return nfi; } else { return System.Globalization.NumberFormatInfo.CurrentInfo; } } } static protected bool IsSignedInt(Object o) { return (o is SByte || o is Int16 || o is Int32 || o is Int64); } static protected bool IsUnsignedInt(Object o) { return (o is Byte || o is UInt16 || o is UInt32 || o is UInt64); } #if CONFIG_EXTENDED_NUMERICS static protected bool IsFloat(Object o) { return (o is Single || o is Double); } static protected bool IsDecimal(Object o) { return (o is Decimal); } static protected double OToDouble(Object o) { double ret; if (o is Int32) { Int32 n = (Int32)o; ret = (double)n; } else if (o is UInt32) { UInt32 n = (UInt32)o; ret = (double)n; } else if (o is SByte) { SByte n = (SByte)o; ret = (double)n; } else if (o is Byte) { Byte n = (Byte)o; ret = (double)n; } else if (o is Int16) { Int16 n = (Int16)o; ret = (double)n; } else if (o is UInt16) { UInt16 n = (UInt16)o; ret = (double)n; } else if (o is Int64) { Int64 n = (Int64)o; ret = (double)n; } else if (o is UInt64) { UInt64 n = (UInt64)o; ret = (double)n; } else if (o is Single) { Single n = (Single)o; ret = (double)n; } else if (o is Double) { ret = (double)o; } else if (o is Decimal) { Decimal n = (Decimal)o; ret = (double)n; } else { throw new FormatException(_("Format_TypeException")); } return ret; } #endif // CONFIG_EXTENDED_NUMERICS static protected ulong OToUlong(Object o) { ulong ret; if (o is Int32) { Int32 n = (Int32)o; ret = (ulong)n; } else if (o is UInt32) { UInt32 n = (UInt32)o; ret = (ulong)n; } else if (o is SByte) { SByte n = (SByte)o; ret = (ulong)n; } else if (o is Byte) { Byte n = (Byte)o; ret = (ulong)n; } else if (o is Int16) { Int16 n = (Int16)o; ret = (ulong)n; } else if (o is UInt16) { UInt16 n = (UInt16)o; ret = (ulong)n; } else if (o is Int64) { Int64 n = (Int64)o; ret = (ulong)n; } else if (o is UInt64) { ret = (ulong)o; } #if CONFIG_EXTENDED_NUMERICS else if (o is Single) { Single n = (Single)o; ret = (ulong)n; } else if (o is Double) { Double n = (Double)o; ret = (ulong)n; } else if (o is Decimal) { Decimal n = (Decimal)o; ret = (ulong)n; } #endif else { throw new FormatException(_("Format_TypeException")); } return ret; } static protected long OToLong(Object o) { long ret; if (o is Int32) { Int32 n = (Int32)o; ret = (long)n; } else if (o is UInt32) { UInt32 n = (UInt32)o; ret = (long)n; } else if (o is SByte) { SByte n = (SByte)o; ret = (long)n; } else if (o is Byte) { Byte n = (Byte)o; ret = (long)n; } else if (o is Int16) { Int16 n = (Int16)o; ret = (long)n; } else if (o is UInt16) { UInt16 n = (UInt16)o; ret = (long)n; } else if (o is Int64) { ret = (long)o; } else if (o is UInt64) { UInt64 n = (UInt64)o; ret = (long)n; } #if CONFIG_EXTENDED_NUMERICS else if (o is Single) { Single n = (Single)o; ret = (long)n; } else if (o is Double) { Double n = (Double)o; ret = (long)n; } else if (o is Decimal) { Decimal n = (Decimal)o; ret = (long)n; } #endif else { throw new FormatException(_("Format_TypeException")); } return ret; } static protected string FormatAnyRound(Object o, int precision, IFormatProvider provider) { string ret; // Type validation if (IsSignedInt(o) && (OToLong(o) < 0) ) { ulong value=(ulong) -OToLong(o); if(value==0) { // because -(Int64.MinValue) does not exist ret = "-9223372036854775808."; } else { ret = "-" + Formatter.FormatInteger(value); } } else if (IsSignedInt(o) || IsUnsignedInt(o)) { ret = Formatter.FormatInteger(OToUlong(o)); } #if CONFIG_EXTENDED_NUMERICS else if (IsDecimal(o)) { // Rounding code decimal r; int i; for (i=0, r=0.5m; i < precision; i++) { r *= 0.1m; } // Pick the call based on the inputs negativity. if ((decimal)o < 0) { ret = "-" + Formatter.FormatDecimal(-((decimal)o)+r); } else { ret = Formatter.FormatDecimal((decimal)o+r); } if (ret.Length - ret.IndexOf('.') > precision + 1) { ret = ret.Substring(0, ret.IndexOf('.')+precision+1); } } else if (IsFloat(o)) { // Beware rounding code double val = OToDouble(o); if (Double.IsNaN(val)) { return NumberFormatInfo(provider).NaNSymbol; } else if (Double.IsPositiveInfinity(val)) { return NumberFormatInfo(provider).PositiveInfinitySymbol; } else if (Double.IsNegativeInfinity(val)) { return NumberFormatInfo(provider).NegativeInfinitySymbol; } else { // do not round here, is done in Formatter.FormatFloat if (val < 0) ret = "-" + Formatter.FormatFloat( -val, precision ); else ret = Formatter.FormatFloat( val, precision ); } } #endif else { // This is a bad place to be. throw new FormatException(_("Format_TypeException")); } return ret; } static protected string FormatInteger(ulong value) { // Note: CustomFormatter counts on having the trailing decimal // point. If you're considering taking it out, think hard. if (value == 0) return "."; StringBuilder ret = new StringBuilder("."); ulong work = value; while (work > 0) { ret.Insert(0, decimalDigits[work % 10]); work /= 10; } return ret.ToString(); } #if CONFIG_EXTENDED_NUMERICS static protected string FormatDecimal(decimal value) { // Guard clause(s) if (value == 0.0m) return "."; // Variable declarations int [] bits = Decimal.GetBits(value); int scale = (bits[3] >> 16) & 0xff; decimal work = value; StringBuilder ret = new StringBuilder(); // Scale the decimal for (int i = 0; i<scale; i++) work *= 10.0m; // Pick off one digit at a time while (work > 0.0m) { ret.Insert(0, decimalDigits[ (int)(work - Decimal.Truncate(work*0.1m)*10.0m)]); work = Decimal.Truncate(work * 0.1m); } // Pad out significant digits if (ret.Length < scale) { ret.Insert(0, "0", scale - ret.Length); } // Insert a decimal point ret.Insert(ret.Length - scale, '.'); return ret.ToString(); } internal static int GetExponent( double value ) { // return (int)Math.Floor(Math.Log10(Math.Abs(value))); /* Note: if value is a value like 99.9999999999999999999999999999998 Math.Log10(value) would return 2.0 but it should return 1.0 so the exponent would be one to big. So the Method below is now used to calculate the exponent. */ if( value == 0.0 ) return 0; value = Math.Abs(value); int exponent = 0; if( value >= 1.0 ) { while( value >= 10.0 ) { exponent++; value /= 10.0; } } else { while( value <= 1.0 ) { exponent--; value *= 10.0; } } return exponent; } static protected string FormatFloat(double value, int precision) { if (value == 0.0) return "."; // Rounding code double r = 5 * Math.Pow(10, -precision - 1); if( value < 0 ) value -= r; else value += r; // //int exponent = (int)Math.Floor(Math.Log10(Math.Abs(value))); int exponent = Formatter.GetExponent( value ); double work = value * Math.Pow(10, 16 - exponent); // // Build a numeric representation, sans decimal point. // StringBuilder sb = new StringBuilder(FormatInteger((ulong)Math.Floor(work))); sb.Remove(sb.Length-1, 1); // Ditch the trailing decimal point if (sb.Length > precision + exponent + 1) { sb.Remove(precision+exponent+1, sb.Length-(precision+exponent+1)); } // // Cases for reinserting the decimal point. // if (exponent >= -1 && exponent < sb.Length) { sb.Insert(exponent+1,'.'); } else if (exponent < -1) { sb.Insert(0,new String('0',-exponent - 1)); sb.Insert(0,"."); } else { sb.Append(new String('0', exponent - sb.Length + 1)); sb.Append('.'); } // // Remove trailing zeroes. // while (sb[sb.Length-1] == '0') { sb.Remove(sb.Length-1, 1); } return sb.ToString(); } #endif // CONFIG_EXTENDED_NUMERICS static protected string GroupInteger(string value, int[] groupSizes, string separator) { if (value == String.Empty) return "0"; int vindex = value.Length; int i = 0; StringBuilder ret = new StringBuilder(); while (vindex > 0) { if (vindex - groupSizes[i] <= 0 || groupSizes[i] == 0) { ret.Insert(0, value.Substring(0, vindex)); vindex = 0; } else { vindex -= groupSizes[i]; ret.Insert(0, value.Substring(vindex, groupSizes[i])); ret.Insert(0, separator); } if (i < groupSizes.Length-1) ++i; } return ret.ToString(); } // ---------------------------------------------------------------------- // Public interface // // // Factory/Singleton method // public static Formatter CreateFormatter(String format) { return CreateFormatter(format, null); } public static Formatter CreateFormatter(String format, IFormatProvider p) { int precision; Formatter ret; if (format == null) { throw new FormatException(_("Format_StringException")); } // handle empty format if(format.Length == 0) { //return new CustomFormatter(format); return new GeneralFormatter(-1, 'G'); } // Search for cached formats if (formats[format] != null) { return (Formatter) formats[format]; } // Validate the format. // It should be of the form 'X', 'X9', or 'X99'. // If it's not, return a CustomFormatter. if (validformats.IndexOf(format[0]) == -1 || format.Length > 3) { return new CustomFormatter(format); } try { precision = (format.Length == 1) ? -1 : Byte.Parse(format.Substring(1)); } catch (FormatException) { return new CustomFormatter(format); } switch(format[0]) // There's always a yucky switch somewhere { case 'C': case 'c': ret = new CurrencyFormatter(precision); break; case 'D': case 'd': ret = new DecimalFormatter(precision); break; case 'E': case 'e': ret = new ScientificFormatter(precision, format[0]); break; case 'F': case 'f': ret = new FixedPointFormatter(precision); break; case 'G': case 'g': ret = new GeneralFormatter(precision, format[0]); break; case 'N': case 'n': ret = new System.Private.NumberFormat.NumberFormatter(precision); break; case 'P': case 'p': ret = new PercentFormatter(precision); break; case 'R': case 'r': ret = new RoundTripFormatter(precision); break; case 'X': case 'x': ret = new HexadecimalFormatter(precision, format[0]); break; default: ret = new CustomFormatter(format); break; } formats[format] = ret; return ret; } // // Public access method. // public abstract string Format(Object o, IFormatProvider provider); } // class Formatter } // namespace System.Private.Format
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Orleans.Runtime.Messaging; using Orleans.Runtime.Placement; using Orleans.Runtime.Configuration; using Orleans.Runtime.Scheduler; namespace Orleans.Runtime { internal class Dispatcher { internal OrleansTaskScheduler Scheduler { get; private set; } internal ISiloMessageCenter Transport { get; private set; } private readonly Catalog catalog; private readonly TraceLogger logger; private readonly ClusterConfiguration config; private readonly double rejectionInjectionRate; private readonly bool errorInjection; private readonly double errorInjectionRate; private readonly SafeRandom random; public Dispatcher( OrleansTaskScheduler scheduler, ISiloMessageCenter transport, Catalog catalog, ClusterConfiguration config) { Scheduler = scheduler; this.catalog = catalog; Transport = transport; this.config = config; logger = TraceLogger.GetLogger("Dispatcher", TraceLogger.LoggerType.Runtime); rejectionInjectionRate = config.Globals.RejectionInjectionRate; double messageLossInjectionRate = config.Globals.MessageLossInjectionRate; errorInjection = rejectionInjectionRate > 0.0d || messageLossInjectionRate > 0.0d; errorInjectionRate = rejectionInjectionRate + messageLossInjectionRate; random = new SafeRandom(); } #region Receive path /// <summary> /// Receive a new message: /// - validate order constraints, queue (or possibly redirect) if out of order /// - validate transactions constraints /// - invoke handler if ready, otherwise enqueue for later invocation /// </summary> /// <param name="message"></param> public void ReceiveMessage(Message message) { MessagingProcessingStatisticsGroup.OnDispatcherMessageReceive(message); // Don't process messages that have already timed out if (message.IsExpired) { logger.Warn(ErrorCode.Dispatcher_DroppingExpiredMessage, "Dropping an expired message: {0}", message); MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Expired"); message.DropExpiredMessage(MessagingStatisticsGroup.Phase.Dispatch); return; } // check if its targeted at a new activation if (message.TargetGrain.IsSystemTarget) { MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "ReceiveMessage on system target."); throw new InvalidOperationException("Dispatcher was called ReceiveMessage on system target for " + message); } if (errorInjection && ShouldInjectError(message)) { if (logger.IsVerbose) logger.Verbose(ErrorCode.Dispatcher_InjectingRejection, "Injecting a rejection"); MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "ErrorInjection"); RejectMessage(message, Message.RejectionTypes.Unrecoverable, null, "Injected rejection"); return; } try { Task ignore; ActivationData target = catalog.GetOrCreateActivation( message.TargetAddress, message.IsNewPlacement, message.NewGrainType, message.GenericGrainType, message.RequestContextData, out ignore); if (ignore != null) { ignore.Ignore(); } if (message.Direction == Message.Directions.Response) { ReceiveResponse(message, target); } else // Request or OneWay { if (target.State == ActivationState.Valid) { catalog.ActivationCollector.TryRescheduleCollection(target); } // Silo is always capable to accept a new request. It's up to the activation to handle its internal state. // If activation is shutting down, it will queue and later forward this request. ReceiveRequest(message, target); } } catch (Exception ex) { try { MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Non-existent activation"); var nea = ex as Catalog.NonExistentActivationException; if (nea == null) { var str = String.Format("Error creating activation for {0}. Message {1}", message.NewGrainType, message); logger.Error(ErrorCode.Dispatcher_ErrorCreatingActivation, str, ex); throw new OrleansException(str, ex); } if (nea.IsStatelessWorker) { if (logger.IsVerbose) logger.Verbose(ErrorCode.Dispatcher_Intermediate_GetOrCreateActivation, String.Format("Intermediate StatelessWorker NonExistentActivation for message {0}", message), ex); } else { logger.Info(ErrorCode.Dispatcher_Intermediate_GetOrCreateActivation, String.Format("Intermediate NonExistentActivation for message {0}", message), ex); } ActivationAddress nonExistentActivation = nea.NonExistentActivation; if (message.Direction != Message.Directions.Response) { // Un-register the target activation so we don't keep getting spurious messages. // The time delay (one minute, as of this writing) is to handle the unlikely but possible race where // this request snuck ahead of another request, with new placement requested, for the same activation. // If the activation registration request from the new placement somehow sneaks ahead of this un-registration, // we want to make sure that we don't un-register the activation we just created. // We would add a counter here, except that there's already a counter for this in the Catalog. // Note that this has to run in a non-null scheduler context, so we always queue it to the catalog's context if (config.Globals.DirectoryLazyDeregistrationDelay > TimeSpan.Zero) { Scheduler.QueueWorkItem(new ClosureWorkItem( // don't use message.TargetAddress, cause it may have been removed from the headers by this time! async () => { try { await Silo.CurrentSilo.LocalGrainDirectory.UnregisterConditionallyAsync( nonExistentActivation); } catch(Exception exc) { logger.Warn(ErrorCode.Dispatcher_FailedToUnregisterNonExistingAct, String.Format("Failed to un-register NonExistentActivation {0}", nonExistentActivation), exc); } }, () => "LocalGrainDirectory.UnregisterConditionallyAsync"), catalog.SchedulingContext); } ProcessRequestToInvalidActivation(message, nonExistentActivation, null, "Non-existent activation"); } else { logger.Warn(ErrorCode.Dispatcher_NoTargetActivation, "No target activation {0} for response message: {1}", nonExistentActivation, message); Silo.CurrentSilo.LocalGrainDirectory.InvalidateCacheEntry(nonExistentActivation); } } catch (Exception exc) { // Unable to create activation for this request - reject message RejectMessage(message, Message.RejectionTypes.Transient, exc); } } } public void RejectMessage( Message message, Message.RejectionTypes rejectType, Exception exc, string rejectInfo = null) { if (message.Direction == Message.Directions.Request) { var str = String.Format("{0} {1}", rejectInfo ?? "", exc == null ? "" : exc.ToString()); MessagingStatisticsGroup.OnRejectedMessage(message); Message rejection = message.CreateRejectionResponse(rejectType, str, exc as OrleansException); SendRejectionMessage(rejection); } else { logger.Warn(ErrorCode.Messaging_Dispatcher_DiscardRejection, "Discarding {0} rejection for message {1}. Exc = {2}", Enum.GetName(typeof(Message.Directions), message.Direction), message, exc == null ? "" : exc.Message); } } internal void SendRejectionMessage(Message rejection) { if (rejection.Result == Message.ResponseTypes.Rejection) { Transport.SendMessage(rejection); rejection.ReleaseBodyAndHeaderBuffers(); } else { throw new InvalidOperationException( "Attempt to invoke Dispatcher.SendRejectionMessage() for a message that isn't a rejection."); } } private void ReceiveResponse(Message message, ActivationData targetActivation) { lock (targetActivation) { if (targetActivation.State == ActivationState.Invalid) { logger.Warn(ErrorCode.Dispatcher_Receive_InvalidActivation, "Response received for invalid activation {0}", message); MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Ivalid"); return; } MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedOk(message); if (Transport.TryDeliverToProxy(message)) return; RuntimeClient.Current.ReceiveResponse(message); } } /// <summary> /// Check if we can locally accept this message. /// Redirects if it can't be accepted. /// </summary> /// <param name="message"></param> /// <param name="targetActivation"></param> private void ReceiveRequest(Message message, ActivationData targetActivation) { lock (targetActivation) { if (targetActivation.State == ActivationState.Invalid) { ProcessRequestToInvalidActivation( message, targetActivation.Address, targetActivation.ForwardingAddress, "ReceiveRequest"); } else if (!ActivationMayAcceptRequest(targetActivation, message)) { // Check for deadlock before Enqueueing. if (config.Globals.PerformDeadlockDetection && !message.TargetGrain.IsSystemTarget) { try { CheckDeadlock(message); } catch (DeadlockException exc) { // Record that this message is no longer flowing through the system MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Deadlock"); logger.Warn(ErrorCode.Dispatcher_DetectedDeadlock, "Detected Application Deadlock: {0}", exc.Message); // We want to send DeadlockException back as an application exception, rather than as a system rejection. SendResponse(message, Response.ExceptionResponse(exc)); return; } } EnqueueRequest(message, targetActivation); } else { HandleIncomingRequest(message, targetActivation); } } } /// <summary> /// Determine if the activation is able to currently accept the given message /// - always accept responses /// For other messages, require that: /// - activation is properly initialized /// - the message would not cause a reentrancy conflict /// </summary> /// <param name="targetActivation"></param> /// <param name="incoming"></param> /// <returns></returns> private bool ActivationMayAcceptRequest(ActivationData targetActivation, Message incoming) { if (!targetActivation.State.Equals(ActivationState.Valid)) return false; if (!targetActivation.IsCurrentlyExecuting) return true; return CanInterleave(targetActivation, incoming); } /// <summary> /// Whether an incoming message can interleave /// </summary> /// <param name="targetActivation"></param> /// <param name="incoming"></param> /// <returns></returns> public bool CanInterleave(ActivationData targetActivation, Message incoming) { bool canInterleave = catalog.IsReentrantGrain(targetActivation.ActivationId) || incoming.IsAlwaysInterleave || targetActivation.Running == null || (targetActivation.Running.IsReadOnly && incoming.IsReadOnly); return canInterleave; } /// <summary> /// Check if the current message will cause deadlock. /// Throw DeadlockException if yes. /// </summary> /// <param name="message">Message to analyze</param> private void CheckDeadlock(Message message) { var requestContext = message.RequestContextData; object obj; if (requestContext == null || !requestContext.TryGetValue(RequestContext.CALL_CHAIN_REQUEST_CONTEXT_HEADER, out obj) || obj == null) return; // first call in a chain var prevChain = ((IList)obj); ActivationId nextActivationId = message.TargetActivation; // check if the target activation already appears in the call chain. foreach (object invocationObj in prevChain) { var prevId = ((RequestInvocationHistory)invocationObj).ActivationId; if (!prevId.Equals(nextActivationId) || catalog.IsReentrantGrain(nextActivationId)) continue; var newChain = new List<RequestInvocationHistory>(); newChain.AddRange(prevChain.Cast<RequestInvocationHistory>()); newChain.Add(new RequestInvocationHistory(message)); throw new DeadlockException(newChain); } } /// <summary> /// Handle an incoming message and queue/invoke appropriate handler /// </summary> /// <param name="message"></param> /// <param name="targetActivation"></param> public void HandleIncomingRequest(Message message, ActivationData targetActivation) { lock (targetActivation) { if (targetActivation.State == ActivationState.Invalid) { ProcessRequestToInvalidActivation(message, targetActivation.Address, targetActivation.ForwardingAddress, "HandleIncomingRequest"); return; } // Now we can actually scheduler processing of this request targetActivation.RecordRunning(message); var context = new SchedulingContext(targetActivation); MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedOk(message); Scheduler.QueueWorkItem(new InvokeWorkItem(targetActivation, message, context), context); } } /// <summary> /// Enqueue message for local handling after transaction completes /// </summary> /// <param name="message"></param> /// <param name="targetActivation"></param> private void EnqueueRequest(Message message, ActivationData targetActivation) { var overloadException = targetActivation.CheckOverloaded(logger); if (overloadException != null) { MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "Overload2"); RejectMessage(message, Message.RejectionTypes.Overloaded, overloadException, "Target activation is overloaded " + targetActivation); return; } bool enqueuedOk = targetActivation.EnqueueMessage(message); if (!enqueuedOk) { ProcessRequestToInvalidActivation(message, targetActivation.Address, targetActivation.ForwardingAddress, "EnqueueRequest"); } // Dont count this as end of processing. The message will come back after queueing via HandleIncomingRequest. #if DEBUG // This is a hot code path, so using #if to remove diags from Release version // Note: Caller already holds lock on activation if (logger.IsVerbose2) logger.Verbose2(ErrorCode.Dispatcher_EnqueueMessage, "EnqueueMessage for {0}: targetActivation={1}", message.TargetActivation, targetActivation.DumpStatus()); #endif } internal void ProcessRequestToInvalidActivation( Message message, ActivationAddress oldAddress, ActivationAddress forwardingAddress, string failedOperation, Exception exc = null) { // Just use this opportunity to invalidate local Cache Entry as well. if (oldAddress != null) { Silo.CurrentSilo.LocalGrainDirectory.InvalidateCacheEntry(oldAddress); } // IMPORTANT: do not do anything on activation context anymore, since this activation is invalid already. Scheduler.QueueWorkItem(new ClosureWorkItem( () => TryForwardRequest(message, oldAddress, forwardingAddress, failedOperation, exc)), catalog.SchedulingContext); } internal void ProcessRequestsToInvalidActivation( List<Message> messages, ActivationAddress oldAddress, ActivationAddress forwardingAddress, string failedOperation, Exception exc = null) { // Just use this opportunity to invalidate local Cache Entry as well. if (oldAddress != null) { Silo.CurrentSilo.LocalGrainDirectory.InvalidateCacheEntry(oldAddress); } logger.Info(ErrorCode.Messaging_Dispatcher_ForwardingRequests, String.Format("Forwarding {0} requests to old address {1} after {2}.", messages.Count, oldAddress, failedOperation)); // IMPORTANT: do not do anything on activation context anymore, since this activation is invalid already. Scheduler.QueueWorkItem(new ClosureWorkItem( () => { foreach (var message in messages) { TryForwardRequest(message, oldAddress, forwardingAddress, failedOperation, exc); } } ), catalog.SchedulingContext); } internal void TryForwardRequest(Message message, ActivationAddress oldAddress, ActivationAddress forwardingAddress, string failedOperation, Exception exc = null) { bool forwardingSucceded = true; try { logger.Info(ErrorCode.Messaging_Dispatcher_TryForward, String.Format("Trying to forward after {0}, ForwardCount = {1}. Message {2}.", failedOperation, message.ForwardCount, message)); MessagingProcessingStatisticsGroup.OnDispatcherMessageReRouted(message); if (oldAddress != null) { message.AddToCacheInvalidationHeader(oldAddress); } forwardingSucceded = InsideRuntimeClient.Current.TryForwardMessage(message, forwardingAddress); } catch (Exception exc2) { forwardingSucceded = false; exc = exc2; } finally { if (!forwardingSucceded) { var str = String.Format("Forwarding failed: tried to forward message {0} for {1} times after {2} to invalid activation. Rejecting now.", message, message.ForwardCount, failedOperation); logger.Warn(ErrorCode.Messaging_Dispatcher_TryForwardFailed, str, exc); RejectMessage(message, Message.RejectionTypes.Transient, exc, str); } } } #endregion #region Send path /// <summary> /// Send an outgoing message /// - may buffer for transaction completion / commit if it ends a transaction /// - choose target placement address, maintaining send order /// - add ordering info and maintain send order /// /// </summary> /// <param name="message"></param> /// <param name="sendingActivation"></param> public async Task AsyncSendMessage(Message message, ActivationData sendingActivation = null) { try { await AddressMessage(message); TransportMessage(message); } catch (Exception ex) { if (ShouldLogError(ex)) { logger.Error(ErrorCode.Dispatcher_SelectTarget_Failed, String.Format("SelectTarget failed with {0}", ex.Message), ex); } MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(message, "SelectTarget failed"); RejectMessage(message, Message.RejectionTypes.Unrecoverable, ex); } } private bool ShouldLogError(Exception ex) { return !(ex.GetBaseException() is KeyNotFoundException) && !(ex.GetBaseException() is ClientNotAvailableException); } // this is a compatibility method for portions of the code base that don't use // async/await yet, which is almost everything. there's no liability to discarding the // Task returned by AsyncSendMessage() internal void SendMessage(Message message, ActivationData sendingActivation = null) { AsyncSendMessage(message, sendingActivation).Ignore(); } /// <summary> /// Resolve target address for a message /// - use transaction info /// - check ordering info in message and sending activation /// - use sender's placement strategy /// </summary> /// <param name="message"></param> /// <returns>Resolve when message is addressed (modifies message fields)</returns> private async Task AddressMessage(Message message) { var targetAddress = message.TargetAddress; if (targetAddress.IsComplete) return; // placement strategy is determined by searching for a specification. first, we check for a strategy associated with the grain reference, // second, we check for a strategy associated with the target's interface. third, we check for a strategy associated with the activation sending the // message. var strategy = targetAddress.Grain.IsGrain ? catalog.GetGrainPlacementStrategy(targetAddress.Grain) : null; var placementResult = await PlacementDirectorsManager.Instance.SelectOrAddActivation( message.SendingAddress, message.TargetGrain, InsideRuntimeClient.Current.Catalog, strategy); if (placementResult.IsNewPlacement && targetAddress.Grain.IsClient) { logger.Error(ErrorCode.Dispatcher_AddressMsg_UnregisteredClient, String.Format("AddressMessage could not find target for client pseudo-grain {0}", message)); throw new KeyNotFoundException(String.Format("Attempting to send a message {0} to an unregistered client pseudo-grain {1}", message, targetAddress.Grain)); } message.SetTargetPlacement(placementResult); if (placementResult.IsNewPlacement) { CounterStatistic.FindOrCreate(StatisticNames.DISPATCHER_NEW_PLACEMENT).Increment(); } if (logger.IsVerbose2) logger.Verbose2(ErrorCode.Dispatcher_AddressMsg_SelectTarget, "AddressMessage Placement SelectTarget {0}", message); } internal void SendResponse(Message request, Response response) { // create the response var message = request.CreateResponseMessage(); message.BodyObject = response; if (message.TargetGrain.IsSystemTarget) { SendSystemTargetMessage(message); } else { TransportMessage(message); } } internal void SendSystemTargetMessage(Message message) { message.Category = message.TargetGrain.Equals(Constants.MembershipOracleId) ? Message.Categories.Ping : Message.Categories.System; if (message.TargetSilo == null) { message.TargetSilo = Transport.MyAddress; } if (message.TargetActivation == null) { message.TargetActivation = ActivationId.GetSystemActivation(message.TargetGrain, message.TargetSilo); } TransportMessage(message); } /// <summary> /// Directly send a message to the transport without processing /// </summary> /// <param name="message"></param> public void TransportMessage(Message message) { if (logger.IsVerbose2) logger.Verbose2(ErrorCode.Dispatcher_Send_AddressedMessage, "Addressed message {0}", message); Transport.SendMessage(message); } #endregion #region Execution /// <summary> /// Invoked when an activation has finished a transaction and may be ready for additional transactions /// </summary> /// <param name="activation">The activation that has just completed processing this message</param> /// <param name="message">The message that has just completed processing. /// This will be <c>null</c> for the case of completion of Activate/Deactivate calls.</param> internal void OnActivationCompletedRequest(ActivationData activation, Message message) { lock (activation) { #if DEBUG // This is a hot code path, so using #if to remove diags from Release version if (logger.IsVerbose2) { logger.Verbose2(ErrorCode.Dispatcher_OnActivationCompletedRequest_Waiting, "OnActivationCompletedRequest {0}: Activation={1}", activation.ActivationId, activation.DumpStatus()); } #endif activation.ResetRunning(message); // ensure inactive callbacks get run even with transactions disabled if (!activation.IsCurrentlyExecuting) activation.RunOnInactive(); // Run message pump to see if there is a new request arrived to be processed RunMessagePump(activation); } } internal void RunMessagePump(ActivationData activation) { // Note: this method must be called while holding lock (activation) #if DEBUG // This is a hot code path, so using #if to remove diags from Release version // Note: Caller already holds lock on activation if (logger.IsVerbose2) { logger.Verbose2(ErrorCode.Dispatcher_ActivationEndedTurn_Waiting, "RunMessagePump {0}: Activation={1}", activation.ActivationId, activation.DumpStatus()); } #endif // don't run any messages if activation is not ready or deactivating if (!activation.State.Equals(ActivationState.Valid)) return; bool runLoop; do { runLoop = false; var nextMessage = activation.PeekNextWaitingMessage(); if (nextMessage == null) continue; if (!ActivationMayAcceptRequest(activation, nextMessage)) continue; activation.DequeueNextWaitingMessage(); // we might be over-writing an already running read only request. HandleIncomingRequest(nextMessage, activation); runLoop = true; } while (runLoop); } private bool ShouldInjectError(Message message) { if (!errorInjection || message.Direction != Message.Directions.Request) return false; double r = random.NextDouble() * 100; if (!(r < errorInjectionRate)) return false; if (r < rejectionInjectionRate) { return true; } if (logger.IsVerbose) logger.Verbose(ErrorCode.Dispatcher_InjectingMessageLoss, "Injecting a message loss"); // else do nothing and intentionally drop message on the floor to inject a message loss return true; } #endregion } }
// // 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.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.DataFactories.Common.Models; using Microsoft.Azure.Management.DataFactories.Core; using Microsoft.Azure.Management.DataFactories.Core.Registration.Models; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.DataFactories.Core { /// <summary> /// Operations for managing data factory ActivityTypes. /// </summary> internal partial class ActivityTypeOperations : IServiceOperations<DataFactoryManagementClient>, IActivityTypeOperations { /// <summary> /// Initializes a new instance of the ActivityTypeOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ActivityTypeOperations(DataFactoryManagementClient client) { this._client = client; } private DataFactoryManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.DataFactories.Core.DataFactoryManagementClient. /// </summary> public DataFactoryManagementClient Client { get { return this._client; } } /// <summary> /// Delete an ActivityType instance. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. The name of the data factory. /// </param> /// <param name='activityTypeName'> /// Required. The name of the activityType. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public async Task<LongRunningOperationResponse> BeginDeleteAsync(string resourceGroupName, string dataFactoryName, string activityTypeName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (dataFactoryName == null) { throw new ArgumentNullException("dataFactoryName"); } if (dataFactoryName != null && dataFactoryName.Length > 63) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (Regex.IsMatch(dataFactoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (activityTypeName == null) { throw new ArgumentNullException("activityTypeName"); } if (activityTypeName != null && activityTypeName.Length > 260) { throw new ArgumentOutOfRangeException("activityTypeName"); } if (Regex.IsMatch(activityTypeName, "^[A-Za-z0-9_][^<>*#.%&:\\\\+?/]*$") == false) { throw new ArgumentOutOfRangeException("activityTypeName"); } // 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("dataFactoryName", dataFactoryName); tracingParameters.Add("activityTypeName", activityTypeName); TracingAdapter.Enter(invocationId, this, "BeginDeleteAsync", 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/Microsoft.DataFactory/datafactories/"; url = url + Uri.EscapeDataString(dataFactoryName); url = url + "/activityTypes/"; url = url + Uri.EscapeDataString(activityTypeName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-10-01"); 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.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // 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.Accepted && 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 LongRunningOperationResponse result = null; // Deserialize Response result = new LongRunningOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("Location")) { result.OperationStatusLink = httpResponse.Headers.GetValues("Location").FirstOrDefault(); } if (httpResponse.Headers.Contains("Retry-After")) { result.RetryAfter = int.Parse(httpResponse.Headers.GetValues("Retry-After").FirstOrDefault(), CultureInfo.InvariantCulture); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (statusCode == HttpStatusCode.Conflict) { result.Status = OperationStatus.Failed; } if (statusCode == HttpStatusCode.OK) { result.Status = OperationStatus.Succeeded; } if (statusCode == HttpStatusCode.NoContent) { result.Status = OperationStatus.Succeeded; } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Create or update an ActivityType. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. The name of the data factory. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update an /// ActivityType definition. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The create or update ActivityType operation response. /// </returns> public async Task<ActivityTypeCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string dataFactoryName, ActivityTypeCreateOrUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (dataFactoryName == null) { throw new ArgumentNullException("dataFactoryName"); } if (dataFactoryName != null && dataFactoryName.Length > 63) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (Regex.IsMatch(dataFactoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.ActivityType == null) { throw new ArgumentNullException("parameters.ActivityType"); } if (parameters.ActivityType.Name == null) { throw new ArgumentNullException("parameters.ActivityType.Name"); } if (parameters.ActivityType.Name != null && parameters.ActivityType.Name.Length > 260) { throw new ArgumentOutOfRangeException("parameters.ActivityType.Name"); } if (Regex.IsMatch(parameters.ActivityType.Name, "^[A-Za-z0-9_][^<>*#.%&:\\\\+?/]*$") == false) { throw new ArgumentOutOfRangeException("parameters.ActivityType.Name"); } if (parameters.ActivityType.Properties == null) { throw new ArgumentNullException("parameters.ActivityType.Properties"); } if (parameters.ActivityType.Properties.Schema == null) { throw new ArgumentNullException("parameters.ActivityType.Properties.Schema"); } if (parameters.ActivityType.Properties.Scope == null) { throw new ArgumentNullException("parameters.ActivityType.Properties.Scope"); } // 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("dataFactoryName", dataFactoryName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", 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/Microsoft.DataFactory/datafactories/"; url = url + Uri.EscapeDataString(dataFactoryName); url = url + "/activityTypes/"; url = url + Uri.EscapeDataString(parameters.ActivityType.Name); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-10-01"); 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 httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject activityTypeCreateOrUpdateParametersValue = new JObject(); requestDoc = activityTypeCreateOrUpdateParametersValue; activityTypeCreateOrUpdateParametersValue["name"] = parameters.ActivityType.Name; JObject propertiesValue = new JObject(); activityTypeCreateOrUpdateParametersValue["properties"] = propertiesValue; propertiesValue["scope"] = parameters.ActivityType.Properties.Scope; if (parameters.ActivityType.Properties.BaseType != null) { propertiesValue["baseType"] = parameters.ActivityType.Properties.BaseType; } propertiesValue["schema"] = JObject.Parse(parameters.ActivityType.Properties.Schema); 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.Created) { 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 ActivityTypeCreateOrUpdateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ActivityTypeCreateOrUpdateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ActivityType activityTypeInstance = new ActivityType(); result.ActivityType = activityTypeInstance; JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); activityTypeInstance.Name = nameInstance; } JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { ActivityTypeProperties propertiesInstance = new ActivityTypeProperties(); activityTypeInstance.Properties = propertiesInstance; JToken scopeValue = propertiesValue2["scope"]; if (scopeValue != null && scopeValue.Type != JTokenType.Null) { string scopeInstance = ((string)scopeValue); propertiesInstance.Scope = scopeInstance; } JToken baseTypeValue = propertiesValue2["baseType"]; if (baseTypeValue != null && baseTypeValue.Type != JTokenType.Null) { string baseTypeInstance = ((string)baseTypeValue); propertiesInstance.BaseType = baseTypeInstance; } JToken schemaValue = propertiesValue2["schema"]; if (schemaValue != null && schemaValue.Type != JTokenType.Null) { string schemaInstance = schemaValue.ToString(Newtonsoft.Json.Formatting.Indented); propertiesInstance.Schema = schemaInstance; } } } } 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> /// Create or update an ActivityType. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. The name of the data factory. /// </param> /// <param name='activityTypeName'> /// Required. An ActivityType name. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update an /// ActivityType definition. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The create or update ActivityType operation response. /// </returns> public async Task<ActivityTypeCreateOrUpdateResponse> CreateOrUpdateWithRawJsonContentAsync(string resourceGroupName, string dataFactoryName, string activityTypeName, ActivityTypeCreateOrUpdateWithRawJsonContentParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (dataFactoryName == null) { throw new ArgumentNullException("dataFactoryName"); } if (dataFactoryName != null && dataFactoryName.Length > 63) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (Regex.IsMatch(dataFactoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (activityTypeName == null) { throw new ArgumentNullException("activityTypeName"); } if (activityTypeName != null && activityTypeName.Length > 260) { throw new ArgumentOutOfRangeException("activityTypeName"); } if (Regex.IsMatch(activityTypeName, "^[A-Za-z0-9_][^<>*#.%&:\\\\+?/]*$") == false) { throw new ArgumentOutOfRangeException("activityTypeName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.Content == null) { throw new ArgumentNullException("parameters.Content"); } // 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("dataFactoryName", dataFactoryName); tracingParameters.Add("activityTypeName", activityTypeName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateOrUpdateWithRawJsonContentAsync", 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/Microsoft.DataFactory/datafactories/"; url = url + Uri.EscapeDataString(dataFactoryName); url = url + "/activityTypes/"; url = url + Uri.EscapeDataString(activityTypeName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-10-01"); 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 httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = parameters.Content; 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.Created) { 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 ActivityTypeCreateOrUpdateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ActivityTypeCreateOrUpdateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ActivityType activityTypeInstance = new ActivityType(); result.ActivityType = activityTypeInstance; JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); activityTypeInstance.Name = nameInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ActivityTypeProperties propertiesInstance = new ActivityTypeProperties(); activityTypeInstance.Properties = propertiesInstance; JToken scopeValue = propertiesValue["scope"]; if (scopeValue != null && scopeValue.Type != JTokenType.Null) { string scopeInstance = ((string)scopeValue); propertiesInstance.Scope = scopeInstance; } JToken baseTypeValue = propertiesValue["baseType"]; if (baseTypeValue != null && baseTypeValue.Type != JTokenType.Null) { string baseTypeInstance = ((string)baseTypeValue); propertiesInstance.BaseType = baseTypeInstance; } JToken schemaValue = propertiesValue["schema"]; if (schemaValue != null && schemaValue.Type != JTokenType.Null) { string schemaInstance = schemaValue.ToString(Newtonsoft.Json.Formatting.Indented); propertiesInstance.Schema = schemaInstance; } } } } 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> /// Delete an ActivityType instance. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. The name of the data factory. /// </param> /// <param name='activityTypeName'> /// Required. The name of the activityType. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public async Task<LongRunningOperationResponse> DeleteAsync(string resourceGroupName, string dataFactoryName, string activityTypeName, CancellationToken cancellationToken) { DataFactoryManagementClient client = this.Client; 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("dataFactoryName", dataFactoryName); tracingParameters.Add("activityTypeName", activityTypeName); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); LongRunningOperationResponse response = await client.ActivityTypes.BeginDeleteAsync(resourceGroupName, dataFactoryName, activityTypeName, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); LongRunningOperationResponse result = await client.GetLongRunningOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); int delayInSeconds = response.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 30; } if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == OperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetLongRunningOperationStatusAsync(response.OperationStatusLink, cancellationToken).ConfigureAwait(false); delayInSeconds = result.RetryAfter; if (delayInSeconds == 0) { delayInSeconds = 15; } if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } /// <summary> /// Gets an ActivityType instance. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. The name of the data factory. /// </param> /// <param name='parameters'> /// Required. Parameters specifying how to get an ActivityType /// definition. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get ActivityType operation response. /// </returns> public async Task<ActivityTypeGetResponse> GetAsync(string resourceGroupName, string dataFactoryName, ActivityTypeGetParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (dataFactoryName == null) { throw new ArgumentNullException("dataFactoryName"); } if (dataFactoryName != null && dataFactoryName.Length > 63) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (Regex.IsMatch(dataFactoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.ActivityTypeName == null) { throw new ArgumentNullException("parameters.ActivityTypeName"); } if (parameters.ActivityTypeName != null && parameters.ActivityTypeName.Length > 260) { throw new ArgumentOutOfRangeException("parameters.ActivityTypeName"); } if (Regex.IsMatch(parameters.ActivityTypeName, "^[A-Za-z0-9_][^<>*#.%&:\\\\+?/]*$") == false) { throw new ArgumentOutOfRangeException("parameters.ActivityTypeName"); } if (parameters.RegistrationScope == null) { throw new ArgumentNullException("parameters.RegistrationScope"); } // 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("dataFactoryName", dataFactoryName); tracingParameters.Add("parameters", parameters); 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/Microsoft.DataFactory/datafactories/"; url = url + Uri.EscapeDataString(dataFactoryName); url = url + "/activityTypes/"; url = url + Uri.EscapeDataString(parameters.ActivityTypeName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-10-01"); queryParameters.Add("scope=" + Uri.EscapeDataString(parameters.RegistrationScope)); queryParameters.Add("resolved=" + Uri.EscapeDataString(parameters.Resolved.ToString().ToLower())); 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 httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // 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 ActivityTypeGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ActivityTypeGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { ActivityType activityTypeInstance = new ActivityType(); result.ActivityType = activityTypeInstance; JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); activityTypeInstance.Name = nameInstance; } JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ActivityTypeProperties propertiesInstance = new ActivityTypeProperties(); activityTypeInstance.Properties = propertiesInstance; JToken scopeValue = propertiesValue["scope"]; if (scopeValue != null && scopeValue.Type != JTokenType.Null) { string scopeInstance = ((string)scopeValue); propertiesInstance.Scope = scopeInstance; } JToken baseTypeValue = propertiesValue["baseType"]; if (baseTypeValue != null && baseTypeValue.Type != JTokenType.Null) { string baseTypeInstance = ((string)baseTypeValue); propertiesInstance.BaseType = baseTypeInstance; } JToken schemaValue = propertiesValue["schema"]; if (schemaValue != null && schemaValue.Type != JTokenType.Null) { string schemaInstance = schemaValue.ToString(Newtonsoft.Json.Formatting.Indented); propertiesInstance.Schema = schemaInstance; } } } } 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 the first page of ActivityType instances with the link to the /// next page. /// </summary> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. The name of the data factory. /// </param> /// <param name='parameters'> /// Required. Parameters specifying how to return a list of /// ActivityType definitions. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List ActivityType operation response. /// </returns> public async Task<ActivityTypeListResponse> ListAsync(string resourceGroupName, string dataFactoryName, ActivityTypeListParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (resourceGroupName != null && resourceGroupName.Length > 1000) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$") == false) { throw new ArgumentOutOfRangeException("resourceGroupName"); } if (dataFactoryName == null) { throw new ArgumentNullException("dataFactoryName"); } if (dataFactoryName != null && dataFactoryName.Length > 63) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (Regex.IsMatch(dataFactoryName, "^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$") == false) { throw new ArgumentOutOfRangeException("dataFactoryName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } // 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("dataFactoryName", dataFactoryName); tracingParameters.Add("parameters", parameters); 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/Microsoft.DataFactory/datafactories/"; url = url + Uri.EscapeDataString(dataFactoryName); url = url + "/activityTypes"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2015-10-01"); if (parameters.ActivityTypeName != null) { queryParameters.Add("name=" + Uri.EscapeDataString(parameters.ActivityTypeName)); } if (parameters.RegistrationScope != null) { queryParameters.Add("scope=" + Uri.EscapeDataString(parameters.RegistrationScope)); } queryParameters.Add("resolved=" + Uri.EscapeDataString(parameters.Resolved.ToString().ToLower())); 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 httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // 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 ActivityTypeListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ActivityTypeListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { ActivityType activityTypeInstance = new ActivityType(); result.ActivityTypes.Add(activityTypeInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); activityTypeInstance.Name = nameInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ActivityTypeProperties propertiesInstance = new ActivityTypeProperties(); activityTypeInstance.Properties = propertiesInstance; JToken scopeValue = propertiesValue["scope"]; if (scopeValue != null && scopeValue.Type != JTokenType.Null) { string scopeInstance = ((string)scopeValue); propertiesInstance.Scope = scopeInstance; } JToken baseTypeValue = propertiesValue["baseType"]; if (baseTypeValue != null && baseTypeValue.Type != JTokenType.Null) { string baseTypeInstance = ((string)baseTypeValue); propertiesInstance.BaseType = baseTypeInstance; } JToken schemaValue = propertiesValue["schema"]; if (schemaValue != null && schemaValue.Type != JTokenType.Null) { string schemaInstance = schemaValue.ToString(Newtonsoft.Json.Formatting.Indented); propertiesInstance.Schema = schemaInstance; } } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.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> /// Gets the next page of ActivityType instances with the link to the /// next page. /// </summary> /// <param name='nextLink'> /// Required. The url to the next ActivityTypes page. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The List ActivityType operation response. /// </returns> public async Task<ActivityTypeListResponse> 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 httpRequest.Headers.Add("x-ms-client-request-id", Guid.NewGuid().ToString()); // 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 ActivityTypeListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ActivityTypeListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { ActivityType activityTypeInstance = new ActivityType(); result.ActivityTypes.Add(activityTypeInstance); JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); activityTypeInstance.Name = nameInstance; } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { ActivityTypeProperties propertiesInstance = new ActivityTypeProperties(); activityTypeInstance.Properties = propertiesInstance; JToken scopeValue = propertiesValue["scope"]; if (scopeValue != null && scopeValue.Type != JTokenType.Null) { string scopeInstance = ((string)scopeValue); propertiesInstance.Scope = scopeInstance; } JToken baseTypeValue = propertiesValue["baseType"]; if (baseTypeValue != null && baseTypeValue.Type != JTokenType.Null) { string baseTypeInstance = ((string)baseTypeValue); propertiesInstance.BaseType = baseTypeInstance; } JToken schemaValue = propertiesValue["schema"]; if (schemaValue != null && schemaValue.Type != JTokenType.Null) { string schemaInstance = schemaValue.ToString(Newtonsoft.Json.Formatting.Indented); propertiesInstance.Schema = schemaInstance; } } } } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); result.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(); } } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: src/proto/grpc/testing/services.proto #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using Grpc.Core; namespace Grpc.Testing { public static class BenchmarkService { static readonly string __ServiceName = "grpc.testing.BenchmarkService"; static readonly Marshaller<global::Grpc.Testing.SimpleRequest> __Marshaller_SimpleRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.SimpleRequest.Parser.ParseFrom); static readonly Marshaller<global::Grpc.Testing.SimpleResponse> __Marshaller_SimpleResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.SimpleResponse.Parser.ParseFrom); static readonly Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse> __Method_UnaryCall = new Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse>( MethodType.Unary, __ServiceName, "UnaryCall", __Marshaller_SimpleRequest, __Marshaller_SimpleResponse); static readonly Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse> __Method_StreamingCall = new Method<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse>( MethodType.DuplexStreaming, __ServiceName, "StreamingCall", __Marshaller_SimpleRequest, __Marshaller_SimpleResponse); // service descriptor public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Grpc.Testing.ServicesReflection.Descriptor.Services[0]; } } // client interface public interface IBenchmarkServiceClient { global::Grpc.Testing.SimpleResponse UnaryCall(global::Grpc.Testing.SimpleRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); global::Grpc.Testing.SimpleResponse UnaryCall(global::Grpc.Testing.SimpleRequest request, CallOptions options); AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> UnaryCallAsync(global::Grpc.Testing.SimpleRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> UnaryCallAsync(global::Grpc.Testing.SimpleRequest request, CallOptions options); AsyncDuplexStreamingCall<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse> StreamingCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); AsyncDuplexStreamingCall<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse> StreamingCall(CallOptions options); } // server-side interface public interface IBenchmarkService { Task<global::Grpc.Testing.SimpleResponse> UnaryCall(global::Grpc.Testing.SimpleRequest request, ServerCallContext context); Task StreamingCall(IAsyncStreamReader<global::Grpc.Testing.SimpleRequest> requestStream, IServerStreamWriter<global::Grpc.Testing.SimpleResponse> responseStream, ServerCallContext context); } // client stub public class BenchmarkServiceClient : ClientBase, IBenchmarkServiceClient { public BenchmarkServiceClient(Channel channel) : base(channel) { } public global::Grpc.Testing.SimpleResponse UnaryCall(global::Grpc.Testing.SimpleRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_UnaryCall, new CallOptions(headers, deadline, cancellationToken)); return Calls.BlockingUnaryCall(call, request); } public global::Grpc.Testing.SimpleResponse UnaryCall(global::Grpc.Testing.SimpleRequest request, CallOptions options) { var call = CreateCall(__Method_UnaryCall, options); return Calls.BlockingUnaryCall(call, request); } public AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> UnaryCallAsync(global::Grpc.Testing.SimpleRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_UnaryCall, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncUnaryCall(call, request); } public AsyncUnaryCall<global::Grpc.Testing.SimpleResponse> UnaryCallAsync(global::Grpc.Testing.SimpleRequest request, CallOptions options) { var call = CreateCall(__Method_UnaryCall, options); return Calls.AsyncUnaryCall(call, request); } public AsyncDuplexStreamingCall<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse> StreamingCall(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_StreamingCall, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncDuplexStreamingCall(call); } public AsyncDuplexStreamingCall<global::Grpc.Testing.SimpleRequest, global::Grpc.Testing.SimpleResponse> StreamingCall(CallOptions options) { var call = CreateCall(__Method_StreamingCall, options); return Calls.AsyncDuplexStreamingCall(call); } } // creates service definition that can be registered with a server public static ServerServiceDefinition BindService(IBenchmarkService serviceImpl) { return ServerServiceDefinition.CreateBuilder(__ServiceName) .AddMethod(__Method_UnaryCall, serviceImpl.UnaryCall) .AddMethod(__Method_StreamingCall, serviceImpl.StreamingCall).Build(); } // creates a new client public static BenchmarkServiceClient NewClient(Channel channel) { return new BenchmarkServiceClient(channel); } } public static class WorkerService { static readonly string __ServiceName = "grpc.testing.WorkerService"; static readonly Marshaller<global::Grpc.Testing.ServerArgs> __Marshaller_ServerArgs = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ServerArgs.Parser.ParseFrom); static readonly Marshaller<global::Grpc.Testing.ServerStatus> __Marshaller_ServerStatus = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ServerStatus.Parser.ParseFrom); static readonly Marshaller<global::Grpc.Testing.ClientArgs> __Marshaller_ClientArgs = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ClientArgs.Parser.ParseFrom); static readonly Marshaller<global::Grpc.Testing.ClientStatus> __Marshaller_ClientStatus = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.ClientStatus.Parser.ParseFrom); static readonly Marshaller<global::Grpc.Testing.CoreRequest> __Marshaller_CoreRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.CoreRequest.Parser.ParseFrom); static readonly Marshaller<global::Grpc.Testing.CoreResponse> __Marshaller_CoreResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.CoreResponse.Parser.ParseFrom); static readonly Marshaller<global::Grpc.Testing.Void> __Marshaller_Void = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Grpc.Testing.Void.Parser.ParseFrom); static readonly Method<global::Grpc.Testing.ServerArgs, global::Grpc.Testing.ServerStatus> __Method_RunServer = new Method<global::Grpc.Testing.ServerArgs, global::Grpc.Testing.ServerStatus>( MethodType.DuplexStreaming, __ServiceName, "RunServer", __Marshaller_ServerArgs, __Marshaller_ServerStatus); static readonly Method<global::Grpc.Testing.ClientArgs, global::Grpc.Testing.ClientStatus> __Method_RunClient = new Method<global::Grpc.Testing.ClientArgs, global::Grpc.Testing.ClientStatus>( MethodType.DuplexStreaming, __ServiceName, "RunClient", __Marshaller_ClientArgs, __Marshaller_ClientStatus); static readonly Method<global::Grpc.Testing.CoreRequest, global::Grpc.Testing.CoreResponse> __Method_CoreCount = new Method<global::Grpc.Testing.CoreRequest, global::Grpc.Testing.CoreResponse>( MethodType.Unary, __ServiceName, "CoreCount", __Marshaller_CoreRequest, __Marshaller_CoreResponse); static readonly Method<global::Grpc.Testing.Void, global::Grpc.Testing.Void> __Method_QuitWorker = new Method<global::Grpc.Testing.Void, global::Grpc.Testing.Void>( MethodType.Unary, __ServiceName, "QuitWorker", __Marshaller_Void, __Marshaller_Void); // service descriptor public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Grpc.Testing.ServicesReflection.Descriptor.Services[1]; } } // client interface public interface IWorkerServiceClient { AsyncDuplexStreamingCall<global::Grpc.Testing.ServerArgs, global::Grpc.Testing.ServerStatus> RunServer(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); AsyncDuplexStreamingCall<global::Grpc.Testing.ServerArgs, global::Grpc.Testing.ServerStatus> RunServer(CallOptions options); AsyncDuplexStreamingCall<global::Grpc.Testing.ClientArgs, global::Grpc.Testing.ClientStatus> RunClient(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); AsyncDuplexStreamingCall<global::Grpc.Testing.ClientArgs, global::Grpc.Testing.ClientStatus> RunClient(CallOptions options); global::Grpc.Testing.CoreResponse CoreCount(global::Grpc.Testing.CoreRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); global::Grpc.Testing.CoreResponse CoreCount(global::Grpc.Testing.CoreRequest request, CallOptions options); AsyncUnaryCall<global::Grpc.Testing.CoreResponse> CoreCountAsync(global::Grpc.Testing.CoreRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); AsyncUnaryCall<global::Grpc.Testing.CoreResponse> CoreCountAsync(global::Grpc.Testing.CoreRequest request, CallOptions options); global::Grpc.Testing.Void QuitWorker(global::Grpc.Testing.Void request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); global::Grpc.Testing.Void QuitWorker(global::Grpc.Testing.Void request, CallOptions options); AsyncUnaryCall<global::Grpc.Testing.Void> QuitWorkerAsync(global::Grpc.Testing.Void request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)); AsyncUnaryCall<global::Grpc.Testing.Void> QuitWorkerAsync(global::Grpc.Testing.Void request, CallOptions options); } // server-side interface public interface IWorkerService { Task RunServer(IAsyncStreamReader<global::Grpc.Testing.ServerArgs> requestStream, IServerStreamWriter<global::Grpc.Testing.ServerStatus> responseStream, ServerCallContext context); Task RunClient(IAsyncStreamReader<global::Grpc.Testing.ClientArgs> requestStream, IServerStreamWriter<global::Grpc.Testing.ClientStatus> responseStream, ServerCallContext context); Task<global::Grpc.Testing.CoreResponse> CoreCount(global::Grpc.Testing.CoreRequest request, ServerCallContext context); Task<global::Grpc.Testing.Void> QuitWorker(global::Grpc.Testing.Void request, ServerCallContext context); } // client stub public class WorkerServiceClient : ClientBase, IWorkerServiceClient { public WorkerServiceClient(Channel channel) : base(channel) { } public AsyncDuplexStreamingCall<global::Grpc.Testing.ServerArgs, global::Grpc.Testing.ServerStatus> RunServer(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_RunServer, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncDuplexStreamingCall(call); } public AsyncDuplexStreamingCall<global::Grpc.Testing.ServerArgs, global::Grpc.Testing.ServerStatus> RunServer(CallOptions options) { var call = CreateCall(__Method_RunServer, options); return Calls.AsyncDuplexStreamingCall(call); } public AsyncDuplexStreamingCall<global::Grpc.Testing.ClientArgs, global::Grpc.Testing.ClientStatus> RunClient(Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_RunClient, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncDuplexStreamingCall(call); } public AsyncDuplexStreamingCall<global::Grpc.Testing.ClientArgs, global::Grpc.Testing.ClientStatus> RunClient(CallOptions options) { var call = CreateCall(__Method_RunClient, options); return Calls.AsyncDuplexStreamingCall(call); } public global::Grpc.Testing.CoreResponse CoreCount(global::Grpc.Testing.CoreRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_CoreCount, new CallOptions(headers, deadline, cancellationToken)); return Calls.BlockingUnaryCall(call, request); } public global::Grpc.Testing.CoreResponse CoreCount(global::Grpc.Testing.CoreRequest request, CallOptions options) { var call = CreateCall(__Method_CoreCount, options); return Calls.BlockingUnaryCall(call, request); } public AsyncUnaryCall<global::Grpc.Testing.CoreResponse> CoreCountAsync(global::Grpc.Testing.CoreRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_CoreCount, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncUnaryCall(call, request); } public AsyncUnaryCall<global::Grpc.Testing.CoreResponse> CoreCountAsync(global::Grpc.Testing.CoreRequest request, CallOptions options) { var call = CreateCall(__Method_CoreCount, options); return Calls.AsyncUnaryCall(call, request); } public global::Grpc.Testing.Void QuitWorker(global::Grpc.Testing.Void request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_QuitWorker, new CallOptions(headers, deadline, cancellationToken)); return Calls.BlockingUnaryCall(call, request); } public global::Grpc.Testing.Void QuitWorker(global::Grpc.Testing.Void request, CallOptions options) { var call = CreateCall(__Method_QuitWorker, options); return Calls.BlockingUnaryCall(call, request); } public AsyncUnaryCall<global::Grpc.Testing.Void> QuitWorkerAsync(global::Grpc.Testing.Void request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { var call = CreateCall(__Method_QuitWorker, new CallOptions(headers, deadline, cancellationToken)); return Calls.AsyncUnaryCall(call, request); } public AsyncUnaryCall<global::Grpc.Testing.Void> QuitWorkerAsync(global::Grpc.Testing.Void request, CallOptions options) { var call = CreateCall(__Method_QuitWorker, options); return Calls.AsyncUnaryCall(call, request); } } // creates service definition that can be registered with a server public static ServerServiceDefinition BindService(IWorkerService serviceImpl) { return ServerServiceDefinition.CreateBuilder(__ServiceName) .AddMethod(__Method_RunServer, serviceImpl.RunServer) .AddMethod(__Method_RunClient, serviceImpl.RunClient) .AddMethod(__Method_CoreCount, serviceImpl.CoreCount) .AddMethod(__Method_QuitWorker, serviceImpl.QuitWorker).Build(); } // creates a new client public static WorkerServiceClient NewClient(Channel channel) { return new WorkerServiceClient(channel); } } } #endregion
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Reflection; using log4net; using Nini.Config; using Mono.Addins; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using Caps = OpenSim.Framework.Capabilities.Caps; namespace OpenSim.Region.ClientStack.Linden { /// <summary> /// SimulatorFeatures capability. /// </summary> /// <remarks> /// This is required for uploading Mesh. /// Since is accepts an open-ended response, we also send more information /// for viewers that care to interpret it. /// /// NOTE: Part of this code was adapted from the Aurora project, specifically /// the normal part of the response in the capability handler. /// </remarks> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "SimulatorFeaturesModule")] public class SimulatorFeaturesModule : ISharedRegionModule, ISimulatorFeaturesModule { // private static readonly ILog m_log = // LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public event SimulatorFeaturesRequestDelegate OnSimulatorFeaturesRequest; private Scene m_scene; /// <summary> /// Simulator features /// </summary> private OSDMap m_features = new OSDMap(); private string m_MapImageServerURL = string.Empty; private string m_SearchURL = string.Empty; #region ISharedRegionModule Members public void Initialise(IConfigSource source) { IConfig config = source.Configs["SimulatorFeatures"]; if (config != null) { m_MapImageServerURL = config.GetString("MapImageServerURI", string.Empty); if (m_MapImageServerURL != string.Empty) { m_MapImageServerURL = m_MapImageServerURL.Trim(); if (!m_MapImageServerURL.EndsWith("/")) m_MapImageServerURL = m_MapImageServerURL + "/"; } m_SearchURL = config.GetString("SearchServerURI", string.Empty); } AddDefaultFeatures(); } public void AddRegion(Scene s) { m_scene = s; m_scene.EventManager.OnRegisterCaps += RegisterCaps; m_scene.RegisterModuleInterface<ISimulatorFeaturesModule>(this); } public void RemoveRegion(Scene s) { m_scene.EventManager.OnRegisterCaps -= RegisterCaps; } public void RegionLoaded(Scene s) { } public void PostInitialise() { } public void Close() { } public string Name { get { return "SimulatorFeaturesModule"; } } public Type ReplaceableInterface { get { return null; } } #endregion /// <summary> /// Add default features /// </summary> /// <remarks> /// TODO: These should be added from other modules rather than hardcoded. /// </remarks> private void AddDefaultFeatures() { lock (m_features) { m_features["MeshRezEnabled"] = true; m_features["MeshUploadEnabled"] = true; m_features["MeshXferEnabled"] = true; m_features["PhysicsMaterialsEnabled"] = true; OSDMap typesMap = new OSDMap(); typesMap["convex"] = true; typesMap["none"] = true; typesMap["prim"] = true; m_features["PhysicsShapeTypes"] = typesMap; // Extra information for viewers that want to use it OSDMap gridServicesMap = new OSDMap(); if (m_MapImageServerURL != string.Empty) gridServicesMap["map-server-url"] = m_MapImageServerURL; if (m_SearchURL != string.Empty) gridServicesMap["search"] = m_SearchURL; m_features["GridServices"] = gridServicesMap; } } public void RegisterCaps(UUID agentID, Caps caps) { IRequestHandler reqHandler = new RestHTTPHandler( "GET", "/CAPS/" + UUID.Random(), x => { return HandleSimulatorFeaturesRequest(x, agentID); }, "SimulatorFeatures", agentID.ToString()); caps.RegisterHandler("SimulatorFeatures", reqHandler); } public void AddFeature(string name, OSD value) { lock (m_features) m_features[name] = value; } public bool RemoveFeature(string name) { lock (m_features) return m_features.Remove(name); } public bool TryGetFeature(string name, out OSD value) { lock (m_features) return m_features.TryGetValue(name, out value); } public OSDMap GetFeatures() { lock (m_features) return new OSDMap(m_features); } private OSDMap DeepCopy() { // This isn't the cheapest way of doing this but the rate // of occurrence is low (on sim entry only) and it's a sure // way to get a true deep copy. OSD copy = OSDParser.DeserializeLLSDXml(OSDParser.SerializeLLSDXmlString(m_features)); return (OSDMap)copy; } private Hashtable HandleSimulatorFeaturesRequest(Hashtable mDhttpMethod, UUID agentID) { // m_log.DebugFormat("[SIMULATOR FEATURES MODULE]: SimulatorFeatures request"); OSDMap copy = DeepCopy(); SimulatorFeaturesRequestDelegate handlerOnSimulatorFeaturesRequest = OnSimulatorFeaturesRequest; if (handlerOnSimulatorFeaturesRequest != null) handlerOnSimulatorFeaturesRequest(agentID, ref copy); //Send back data Hashtable responsedata = new Hashtable(); responsedata["int_response_code"] = 200; responsedata["content_type"] = "text/plain"; responsedata["keepalive"] = false; responsedata["str_response_string"] = OSDParser.SerializeLLSDXmlString(copy); return responsedata; } } }
/* * MindTouch Core - open source enterprise collaborative networking * Copyright (c) 2006-2010 MindTouch Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit www.opengarden.org; * please review the licensing section. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * http://www.gnu.org/copyleft/gpl.html */ using System; using System.Collections.Generic; using System.Data; using System.Linq; using MindTouch.Data; namespace MindTouch.Deki.Data.MySql { public partial class MySqlDekiDataSession { //--- Methods --- public IList<NavBE> Nav_GetTree(PageBE page, bool includeAllChildren) { ulong homepageId = Head.Pages_HomePageId; // determine if we need to exclude child pages (if requested page is a child page of Special:) bool includeChildren = (page.Title.Namespace != NS.SPECIAL && page.Title.Namespace != NS.SPECIAL_TALK); // create queries string query = @" /* Nav_GetTree */ SELECT page_id, page_namespace, page_title, page_display_name, pages.page_parent as page_parent, restriction_perm_flags, ({1}) AS page_children FROM pages LEFT JOIN restrictions ON page_restriction_id = restriction_id WHERE {0}"; string subquery = includeChildren ? "SELECT count(C.page_id) FROM pages C WHERE C.page_parent = pages.page_id AND C.page_id != ?HOMEPAGEID AND C.page_parent != ?HOMEPAGEID AND C.page_namespace = ?PAGENS AND C.page_is_redirect = 0 GROUP BY C.page_parent" : "0"; // always include the homepage List<string> where = new List<string>(); where.Add("pages.page_id = ?HOMEPAGEID"); // determine what pages need to be included if(page.ID == homepageId) { // include all children of the homepage in the main namespace where.Add("(pages.page_is_redirect = 0 AND pages.page_parent = 0 AND pages.page_id != ?HOMEPAGEID AND pages.page_namespace = 0)"); } else { // build list of all parent pages, including the current page, but exclusing the homepage, which needs special consideration List<string> pageIdsTextList = DbUtils.ConvertArrayToStringArray(Head.Pages_GetParentIds(page).Where(x => (x != homepageId) && (x != 0)).Union(new[] { page.ID })); string parentIdsList = string.Join(",", pageIdsTextList.ToArray()); // include all parents with the requested page where.Add(string.Format("pages.page_id IN ({0})", parentIdsList)); // check if the parent pages should also contain all their children pages if(includeAllChildren) { if(includeChildren) { // include the children pages of all parents, including the requested page, but excluding the homepage, which needs to be handled differently where.Add(string.Format("(pages.page_is_redirect = 0 AND pages.page_parent IN ({0}) AND pages.page_namespace = ?PAGENS)", parentIdsList)); } // check if for the current namespace, we need to show the children of the homepage if(page.Title.ShowHomepageChildren) { where.Add("(pages.page_is_redirect = 0 AND pages.page_parent = 0 AND pages.page_id != ?HOMEPAGEID AND pages.page_namespace = ?PAGENS)"); } } else { if(includeChildren) { // include only the children of the requested page in the requested namespace where.Add("(pages.page_is_redirect = 0 AND pages.page_parent = ?PAGEID AND pages.page_namespace = ?PAGENS)"); } // check if the requested page is not a child of the homepage; otherwise, we need to be careful about including sibling pages if(page.ParentID != 0) { // include all siblings of the requested page since it's not a child of the homepage where.Add("(pages.page_is_redirect = 0 AND pages.page_parent = ?PAGEPARENT AND pages.page_id != ?PAGEID AND pages.page_namespace = ?PAGENS)"); } else if(page.Title.ShowHomepageChildren) { // include all siblings of the requested page since the requested namespace includes all homepage children pages where.Add("(pages.page_is_redirect = 0 AND pages.page_parent = 0 AND pages.page_id != ?HOMEPAGEID AND pages.page_namespace = ?PAGENS)"); } } } // compose query and execute it query = string.Format(query, string.Join(" OR ", where.ToArray()), subquery); DataCommand cmd = Catalog.NewQuery(query) .With("HOMEPAGEID", Head.Pages_HomePageId) .With("PAGEID", page.ID) .With("PAGENS", (int)page.Title.Namespace) .With("PAGEPARENT", page.ParentID); return Nav_GetInternal(cmd); } public IList<NavBE> Nav_GetSiblings(PageBE page) { string query = @" /* Nav_GetSiblings */ SELECT page_id, page_namespace, page_title, page_display_name, pages.page_parent as page_parent, restriction_perm_flags, ( SELECT count(C.page_id) FROM pages C WHERE C.page_parent = pages.page_id AND C.page_id != ?HOMEPAGEID AND C.page_parent != ?HOMEPAGEID AND C.page_namespace = ?PAGENS AND C.page_is_redirect = 0 GROUP BY C.page_parent ) AS page_children FROM pages LEFT JOIN restrictions ON page_restriction_id = restriction_id WHERE pages.page_is_redirect = 0 AND ( ( ?HOMEPAGEID != ?PAGEID AND pages.page_parent = ?PAGEPARENT AND pages.page_id != ?HOMEPAGEID AND pages.page_namespace = ?PAGENS ) OR pages.page_id = ?PAGEID ) "; DataCommand cmd = Catalog.NewQuery(query) .With("HOMEPAGEID", Head.Pages_HomePageId) .With("PAGEID", page.ID) .With("PAGENS", (int) page.Title.Namespace) .With("PAGEPARENT", page.ParentID); return Nav_GetInternal(cmd); } public IList<NavBE> Nav_GetChildren(PageBE page) { string query = @" /* Nav_GetChildren */ SELECT page_id, page_namespace, page_title, page_display_name, pages.page_parent as page_parent, restriction_perm_flags, ( SELECT count(C.page_id) FROM pages C WHERE C.page_parent = pages.page_id AND C.page_id != ?HOMEPAGEID AND C.page_parent != ?HOMEPAGEID AND C.page_namespace = ?PAGENS AND C.page_is_redirect = 0 GROUP BY C.page_parent ) AS page_children FROM pages LEFT JOIN restrictions ON page_restriction_id = restriction_id WHERE pages.page_is_redirect = 0 AND ( ( ?HOMEPAGEID != ?PAGEID AND pages.page_parent = ?PAGEID AND pages.page_namespace = ?PAGENS ) OR ( ?HOMEPAGEID = ?PAGEID AND pages.page_parent = 0 AND pages.page_id != ?HOMEPAGEID AND pages.page_namespace = ?PAGENS ) ) "; DataCommand cmd = Catalog.NewQuery(query) .With("HOMEPAGEID", Head.Pages_HomePageId) .With("PAGEID", page.ID) .With("PAGENS", (int) page.Title.Namespace); return Nav_GetInternal(cmd); } public IList<NavBE> Nav_GetSiblingsAndChildren(PageBE page) { string query = @" /* Nav_GetSiblingsAndChildren */ SELECT page_id, page_namespace, page_title, page_display_name, pages.page_parent as page_parent, restriction_perm_flags, ( SELECT count(C.page_id) FROM pages C WHERE C.page_parent = pages.page_id AND C.page_id != ?HOMEPAGEID AND C.page_parent != ?HOMEPAGEID AND C.page_namespace = ?PAGENS AND C.page_is_redirect = 0 GROUP BY C.page_parent ) AS page_children FROM pages LEFT JOIN restrictions ON page_restriction_id = restriction_id WHERE ( ( pages.page_is_redirect = 0 AND ?HOMEPAGEID != ?PAGEID AND pages.page_parent = ?PAGEPARENT AND pages.page_namespace = ?PAGENS AND pages.page_id != ?HOMEPAGEID ) OR ( pages.page_is_redirect = 0 AND ?HOMEPAGEID = ?PAGEID AND pages.page_parent = 0 AND pages.page_namespace = ?PAGENS ) OR ( ?HOMEPAGEID != ?PAGEID AND pages.page_parent = ?PAGEID AND pages.page_namespace=?PAGENS AND pages.page_is_redirect=0 ) OR pages.page_id = ?PAGEID ) "; DataCommand cmd = Catalog.NewQuery(query) .With("HOMEPAGEID", Head.Pages_HomePageId) .With("PAGEID", page.ID) .With("PAGENS", (int) page.Title.Namespace) .With("PAGEPARENT", page.ParentID); return Nav_GetInternal(cmd); } public ulong Nav_GetNearestParent(Title title) { string query = @"/* Nav_GetNearestParent */ SELECT page_id FROM pages WHERE page_namespace={0} AND STRCMP(SUBSTRING('{1}', 1, CHAR_LENGTH(page_title) + 1), CONCAT(page_title, '/'))=0 ORDER BY CHAR_LENGTH(page_title) DESC LIMIT 1"; return Catalog.NewQuery(string.Format(query, (int)title.Namespace, DataCommand.MakeSqlSafe(title.AsUnprefixedDbPath()))).ReadAsULong() ?? Head.Pages_HomePageId; } private RC[] Nav_RecentChangeFeedExcludeList { get { string[] list = _settings.GetValue("feed/recent-changes-type-exclude-list", string.Empty).Split(new char[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries); List<RC> rcList = new List<RC>(); foreach (string item in list) { RC type; if(SysUtil.TryParseEnum(item, out type)) { rcList.Add(type); } } return rcList.ToArray(); } } private string Nav_GetChangeTypeLimitQuery(bool createOnly) { if (createOnly) { return "AND rc_type = " + (uint)RC.NEW; } string query = string.Empty; RC[] recentChangeFeedExcludeList = Nav_RecentChangeFeedExcludeList; if (recentChangeFeedExcludeList.Length > 0) { query = "AND rc_type NOT IN({0})"; string ids = string.Empty; for (int i = 0; i < recentChangeFeedExcludeList.Length; i++) { if (ids != string.Empty) ids += ","; ids += string.Format("{0}", (uint)recentChangeFeedExcludeList[i]); } query = string.Format(query, ids); } return query; } private string Nav_GetTimestampQuery(DateTime since) { string timestampFilter = string.Empty; if (since > DateTime.MinValue) timestampFilter = string.Format(" AND rc_timestamp > '{0}' ", DbUtils.ToString(since)); return timestampFilter; } private string Nav_GetLanguageQuery(string language) { string languageFilter = string.Empty; if (language != null) { //Note MaxM: Since this is getting embedded in the WHERE clause instead of an ON clause, allow for null in case the left join doesn't match a row in pages so the entire row doesn't get removed languageFilter = string.Format(" AND (page_language = '{0}' OR page_language = '' OR page_language is null ) ", MindTouch.Data.DataCommand.MakeSqlSafe(language)); } return languageFilter; } private IList<NavBE> Nav_GetInternal(DataCommand queryCommand) { List<NavBE> navPages = new List<NavBE>(); queryCommand.Execute(delegate(IDataReader dr) { while (dr.Read()) { NavBE np = Nav_Populate(dr); navPages.Add(np); } }); return navPages; } private NavBE Nav_Populate(IDataReader dr) { return new NavBE { ChildCount = dr.Read<int?>("page_children"), DisplayName = dr.Read<string>("page_display_name"), Id = dr.Read<uint>("page_id"), NameSpace = dr.Read<ushort>("page_namespace"), ParentId = dr.Read<uint>("page_parent"), RestrictionFlags = dr.Read<ulong?>("restriction_perm_flags"), Title = dr.Read<string>("page_title") }; } } }
// 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. ////////////////////////////////////////////////////////// // L-1-5-1.cs - Beta1 Layout Test - RDawson // // Tests layout of classes using 1-deep nesting in // the same assembly and module (checking access from an // unrelated class). // // See ReadMe.txt in the same project as this source for // further details about these tests. // using System; class Test { public static int Main() { int mi_RetCode; mi_RetCode = B.Test(); if(mi_RetCode == 100) Console.WriteLine("Pass"); else Console.WriteLine("FAIL"); return mi_RetCode; } } class B { public static int Test() { int mi_RetCode = 100; A.Cls ac = new A.Cls(); A a = new A(); if(Test_Nested(ac) != 100) mi_RetCode = 0; //@csharp - C# simply won't compile non-related private/family/protected access if(Test_Nested(a.ClsPubInst) != 100) mi_RetCode = 0; if(Test_Nested(a.ClsAsmInst) != 100) mi_RetCode = 0; if(Test_Nested(a.ClsFoaInst) != 100) mi_RetCode = 0; if(Test_Nested(A.ClsPubStat) != 100) mi_RetCode = 0; return mi_RetCode; } public static int Test_Nested(A.Cls ac) { int mi_RetCode = 100; ///////////////////////////////// // Test instance field access ac.NestFldPubInst = 100; if(ac.NestFldPubInst != 100) mi_RetCode = 0; ac.NestFldAsmInst = 100; if(ac.NestFldAsmInst != 100) mi_RetCode = 0; ac.NestFldFoaInst = 100; if(ac.NestFldFoaInst != 100) mi_RetCode = 0; ///////////////////////////////// // Test static field access A.Cls.NestFldPubStat = 100; if(A.Cls.NestFldPubStat != 100) mi_RetCode = 0; A.Cls.NestFldAsmStat = 100; if(A.Cls.NestFldAsmStat != 100) mi_RetCode = 0; A.Cls.NestFldFoaStat = 100; if(A.Cls.NestFldFoaStat != 100) mi_RetCode = 0; ///////////////////////////////// // Test instance method access if(ac.NestMethPubInst() != 100) mi_RetCode = 0; if(ac.NestMethAsmInst() != 100) mi_RetCode = 0; if(ac.NestMethFoaInst() != 100) mi_RetCode = 0; ///////////////////////////////// // Test static method access if(A.Cls.NestMethPubStat() != 100) mi_RetCode = 0; if(A.Cls.NestMethAsmStat() != 100) mi_RetCode = 0; if(A.Cls.NestMethFoaStat() != 100) mi_RetCode = 0; ///////////////////////////////// // Test virtual method access if(ac.NestMethPubVirt() != 100) mi_RetCode = 0; if(ac.NestMethAsmVirt() != 100) mi_RetCode = 0; if(ac.NestMethFoaVirt() != 100) mi_RetCode = 0; //////////////////////////////////////////// // Test access from within the nested class if(ac.Test() != 100) mi_RetCode = 0; return mi_RetCode; } } class A { // TODO: CHECK IF THIS IS TESTED ////////////////////////////// // Instance Fields // public int FldPubInst; // private int FldPrivInst; // protected int FldFamInst; //Translates to "family" // internal int FldAsmInst; //Translates to "assembly" // protected internal int FldFoaInst; //Translates to "famorassem" ////////////////////////////// // Static Fields public static int FldPubStat; private static int FldPrivStat; protected static int FldFamStat; //family internal static int FldAsmStat; //assembly protected internal static int FldFoaStat; //famorassem ////////////////////////////////////// // Instance fields for nested classes public Cls ClsPubInst = new Cls(); // not used //private Cls ClsPrivInst = new Cls(); //protected Cls ClsFamInst = new Cls(); internal Cls ClsAsmInst = new Cls(); protected internal Cls ClsFoaInst = new Cls(); ///////////////////////////////////// // Static fields of nested classes public static Cls ClsPubStat = new Cls(); // not used // private static Cls ClsPrivStat = new Cls(); ////////////////////////////// // Instance Methods public int MethPubInst(){ Console.WriteLine("A::MethPubInst()"); return 100; } private int MethPrivInst(){ Console.WriteLine("A::MethPrivInst()"); return 100; } protected int MethFamInst(){ Console.WriteLine("A::MethFamInst()"); return 100; } internal int MethAsmInst(){ Console.WriteLine("A::MethAsmInst()"); return 100; } protected internal int MethFoaInst(){ Console.WriteLine("A::MethFoaInst()"); return 100; } ////////////////////////////// // Static Methods public static int MethPubStat(){ Console.WriteLine("A::MethPubStat()"); return 100; } private static int MethPrivStat(){ Console.WriteLine("A::MethPrivStat()"); return 100; } protected static int MethFamStat(){ Console.WriteLine("A::MethFamStat()"); return 100; } internal static int MethAsmStat(){ Console.WriteLine("A::MethAsmStat()"); return 100; } protected internal static int MethFoaStat(){ Console.WriteLine("A::MethFoaStat()"); return 100; } ////////////////////////////// // Virtual Instance Methods public virtual int MethPubVirt(){ Console.WriteLine("A::MethPubVirt()"); return 100; } //@csharp - Note that C# won't compile an illegal private virtual function //So there is no negative testing MethPrivVirt() here. protected virtual int MethFamVirt(){ Console.WriteLine("A::MethFamVirt()"); return 100; } internal virtual int MethAsmVirt(){ Console.WriteLine("A::MethAsmVirt()"); return 100; } protected internal virtual int MethFoaVirt(){ Console.WriteLine("A::MethFoaVirt()"); return 100; } public class Cls{ public int Test(){ int mi_RetCode = 100; ///////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// // ACCESS ENCLOSING FIELDS/MEMBERS ///////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// //@csharp - C# will not allow nested classes to access non-static members of their enclosing classes ///////////////////////////////// // Test static field access FldPubStat = 100; if(FldPubStat != 100) mi_RetCode = 0; FldPrivStat = 100; if(FldPrivStat != 100) mi_RetCode = 0; FldFamStat = 100; if(FldFamStat != 100) mi_RetCode = 0; FldAsmStat = 100; if(FldAsmStat != 100) mi_RetCode = 0; FldFoaStat = 100; if(FldFoaStat != 100) mi_RetCode = 0; ///////////////////////////////// // Test static method access if(MethPubStat() != 100) mi_RetCode = 0; if(MethFamStat() != 100) mi_RetCode = 0; if(MethAsmStat() != 100) mi_RetCode = 0; if(MethFoaStat() != 100) mi_RetCode = 0; //////////////////////////////////////////// // Test access from within the nested class //@todo - Look at testing accessing one nested class from another, @bugug - NEED TO ADD SUCH TESTING, access the public nested class fields from here, etc... return mi_RetCode; } ////////////////////////////// // Instance Fields public int NestFldPubInst; // TODO: Check if this is covered in IL // private int NestFldPrivInst; // TODO: Check if this is covered in IL // protected int NestFldFamInst; //Translates to "family" internal int NestFldAsmInst; //Translates to "assembly" protected internal int NestFldFoaInst; //Translates to "famorassem" ////////////////////////////// // Static Fields public static int NestFldPubStat; // TODO: Check if this is covered in IL // private static int NestFldPrivStat; // TODO: Check if this is covered in IL // protected static int NestFldFamStat; //family internal static int NestFldAsmStat; //assembly protected internal static int NestFldFoaStat; //famorassem ////////////////////////////// // Instance NestMethods public int NestMethPubInst(){ Console.WriteLine("A::NestMethPubInst()"); return 100; } private int NestMethPrivInst(){ Console.WriteLine("A::NestMethPrivInst()"); return 100; } protected int NestMethFamInst(){ Console.WriteLine("A::NestMethFamInst()"); return 100; } internal int NestMethAsmInst(){ Console.WriteLine("A::NestMethAsmInst()"); return 100; } protected internal int NestMethFoaInst(){ Console.WriteLine("A::NestMethFoaInst()"); return 100; } ////////////////////////////// // Static NestMethods public static int NestMethPubStat(){ Console.WriteLine("A::NestMethPubStat()"); return 100; } private static int NestMethPrivStat(){ Console.WriteLine("A::NestMethPrivStat()"); return 100; } protected static int NestMethFamStat(){ Console.WriteLine("A::NestMethFamStat()"); return 100; } internal static int NestMethAsmStat(){ Console.WriteLine("A::NestMethAsmStat()"); return 100; } protected internal static int NestMethFoaStat(){ Console.WriteLine("A::NestMethFoaStat()"); return 100; } ////////////////////////////// // Virtual Instance NestMethods public virtual int NestMethPubVirt(){ Console.WriteLine("A::NestMethPubVirt()"); return 100; } //@csharp - Note that C# won't compile an illegal private virtual function //So there is no negative testing NestMethPrivVirt() here. protected virtual int NestMethFamVirt(){ Console.WriteLine("A::NestMethFamVirt()"); return 100; } internal virtual int NestMethAsmVirt(){ Console.WriteLine("A::NestMethAsmVirt()"); return 100; } protected internal virtual int NestMethFoaVirt(){ Console.WriteLine("A::NestMethFoaVirt()"); return 100; } } }
// 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.Diagnostics; using System.Text.Utf8; using Newtonsoft.Json; using JsonReader = System.Text.Json.JsonReader; using JsonWriter = System.Text.Json.JsonWriter; using JsonParser = System.Text.Json.JsonParser; using System.Text.Formatting; using System.Text; using System.IO; using Newtonsoft.Json.Linq; namespace Json.Net.Tests { internal class JsonNetComparison { private const int NumberOfIterations = 10; private const int NumberOfSamples = 10; private const bool OutputResults = true; private const bool OutputJsonData = false; private static readonly Stopwatch Timer = new Stopwatch(); private static readonly List<long> TimingResultsJsonNet = new List<long>(); private static readonly List<long> TimingResultsJsonReader = new List<long>(); private static void Main() { RunParserTest(); RunWriterTest(); RunReaderTest(); //Console.Read(); } private static void RunReaderTest() { Output("====== TEST Read ======"); // Do not test first iteration ReaderTestJsonNet(TestJson.Json3KB, false); ReaderTestJsonNet(TestJson.Json30KB, false); ReaderTestJsonNet(TestJson.Json300KB, false); ReaderTestJsonNet(TestJson.Json3MB, false); Output("Json.NET Timing Results"); for (int i = 0; i < NumberOfSamples; i++) { ReaderTestJsonNet(TestJson.Json3KB, OutputResults); ReaderTestJsonNet(TestJson.Json30KB, OutputResults); ReaderTestJsonNet(TestJson.Json300KB, OutputResults); ReaderTestJsonNet(TestJson.Json3MB, OutputResults); } // Do not test first iteration ReaderTestSystemTextJson(TestJson.Json3KB, false); ReaderTestSystemTextJson(TestJson.Json30KB, false); ReaderTestSystemTextJson(TestJson.Json300KB, false); ReaderTestSystemTextJson(TestJson.Json3MB, false); Output("System.Text.Json Timing Results"); for (int i = 0; i < NumberOfSamples; i++) { ReaderTestSystemTextJson(TestJson.Json3KB, OutputResults); ReaderTestSystemTextJson(TestJson.Json30KB, OutputResults); ReaderTestSystemTextJson(TestJson.Json300KB, OutputResults); ReaderTestSystemTextJson(TestJson.Json3MB, OutputResults); } } private static void ReaderTestJsonNet(string str, bool output) { Timer.Restart(); for (var i = 0; i < NumberOfIterations; i++) { JsonNetReaderHelper(new StringReader(str), OutputJsonData); } if (output) Console.WriteLine(Timer.ElapsedTicks); } private static void JsonNetReaderHelper(TextReader str, bool output) { var reader = new JsonTextReader(str); while (reader.Read()) { if (reader.Value != null) { // ReSharper disable once UnusedVariable var x = reader.TokenType; // ReSharper disable once UnusedVariable var y = reader.Value; if (output) Console.WriteLine(y); } else { // ReSharper disable once UnusedVariable var z = reader.TokenType; if (output) Console.WriteLine(z); } } } private static void ReaderTestSystemTextJson(string str, bool output) { var utf8Str = new Utf8String(str); Timer.Restart(); for (var i = 0; i < NumberOfIterations; i++) { JsonReaderHelper(utf8Str, OutputJsonData); } if (output) Console.WriteLine(Timer.ElapsedTicks); } private static void JsonReaderHelper(Utf8String str, bool output) { var reader = new JsonReader(str); while (reader.Read()) { var tokenType = reader.TokenType; switch (tokenType) { case JsonReader.JsonTokenType.ObjectStart: case JsonReader.JsonTokenType.ObjectEnd: case JsonReader.JsonTokenType.ArrayStart: case JsonReader.JsonTokenType.ArrayEnd: if (output) Console.WriteLine(tokenType); break; case JsonReader.JsonTokenType.Property: var name = reader.GetName(); if (output) Console.WriteLine(name); var value = reader.GetValue(); if (output) Console.WriteLine(value); break; case JsonReader.JsonTokenType.Value: value = reader.GetValue(); if (output) Console.WriteLine(value); break; default: throw new ArgumentOutOfRangeException(); } } } private static void RunParserTest() { Output("====== TEST Parse ======"); // Do not test first iteration ParserTestJsonNet(TestJson.Json3KB, false); ParserTestJsonNet(TestJson.Json30KB, false); ParserTestJsonNet(TestJson.Json300KB, false); ParserTestJsonNet(TestJson.Json3MB, false); Output("Json.NET Timing Results"); for (int i = 0; i < NumberOfSamples; i++) { ParserTestJsonNet(TestJson.Json3KB, OutputResults); ParserTestJsonNet(TestJson.Json30KB, OutputResults); ParserTestJsonNet(TestJson.Json300KB, OutputResults); ParserTestJsonNet(TestJson.Json3MB, OutputResults); } // Do not test first iteration ParserTestSystemTextJson(TestJson.Json3KB, 3, false); ParserTestSystemTextJson(TestJson.Json30KB, 30, false); ParserTestSystemTextJson(TestJson.Json300KB, 300, false); ParserTestSystemTextJson(TestJson.Json3MB, 3000, false); Output("System.Text.Json Timing Results"); for (int i = 0; i < NumberOfSamples; i++) { ParserTestSystemTextJson(TestJson.Json3KB, 3, OutputResults); ParserTestSystemTextJson(TestJson.Json30KB, 30, OutputResults); ParserTestSystemTextJson(TestJson.Json300KB, 300, OutputResults); ParserTestSystemTextJson(TestJson.Json3MB, 3000, OutputResults); } } private static void ParserTestSystemTextJson(string str, int numElements, bool timeResults) { int strLength = str.Length; int byteLength = strLength * 2; var buffer = new byte[byteLength]; for (var j = 0; j < strLength; j++) { buffer[j] = (byte)str[j]; } SystemTextParserHelper(buffer, strLength, numElements, timeResults); } private static void SystemTextParserHelper(byte[] buffer, int strLength, int numElements, bool timeResults) { if (timeResults) Timer.Restart(); var json = new JsonParser(buffer, strLength); var parseObject = json.Parse(); if (timeResults) Console.WriteLine("Parse: " + Timer.ElapsedTicks); if (timeResults) Timer.Restart(); for (int i = 0; i < numElements; i++) { var xElement = parseObject[i]; var id = (Utf8String)xElement["_id"]; var index = (int)xElement["index"]; var guid = (Utf8String)xElement["guid"]; var isActive = (bool)xElement["isActive"]; var balance = (Utf8String)xElement["balance"]; var picture = (Utf8String)xElement["picture"]; var age = (int)xElement["age"]; var eyeColor = (Utf8String)xElement["eyeColor"]; var name = (Utf8String)xElement["name"]; var gender = (Utf8String)xElement["gender"]; var company = (Utf8String)xElement["company"]; var email = (Utf8String)xElement["email"]; var phone = (Utf8String)xElement["phone"]; var address = (Utf8String)xElement["address"]; var about = (Utf8String)xElement["about"]; var registered = (Utf8String)xElement["registered"]; var latitude = (double)xElement["latitude"]; var longitude = (double)xElement["longitude"]; var tags = xElement["tags"]; var tags1 = (Utf8String)tags[0]; var tags2 = (Utf8String)tags[1]; var tags3 = (Utf8String)tags[2]; var tags4 = (Utf8String)tags[3]; var tags5 = (Utf8String)tags[4]; var tags6 = (Utf8String)tags[5]; var tags7 = (Utf8String)tags[6]; var friends = xElement["friends"]; var friend1 = friends[0]; var friend2 = friends[1]; var friend3 = friends[2]; var id1 = (int)friend1["id"]; var friendName1 = (Utf8String)friend1["name"]; var id2 = (int)friend2["id"]; var friendName2 = (Utf8String)friend2["name"]; var id3 = (int)friend3["id"]; var friendName3 = (Utf8String)friend3["name"]; var greeting = (Utf8String)xElement["greeting"]; var favoriteFruit = (Utf8String)xElement["favoriteFruit"]; } if (timeResults) Console.WriteLine("Access: " + Timer.ElapsedTicks); } private static void ParserTestJsonNet(string str, bool timeResults) { if (timeResults) Timer.Restart(); JArray parseObject = JArray.Parse(str); if (timeResults) Console.WriteLine("Parse: " + Timer.ElapsedTicks); if (timeResults) Timer.Restart(); for (int i = 0; i < parseObject.Count; i++) { var xElement = parseObject[i]; var id = (string)xElement["_id"]; var index = (int)xElement["index"]; var guid = (string)xElement["guid"]; var isActive = (bool)xElement["isActive"]; var balance = (string)xElement["balance"]; var picture = (string)xElement["picture"]; var age = (int)xElement["age"]; var eyeColor = (string)xElement["eyeColor"]; var name = (string)xElement["name"]; var gender = (string)xElement["gender"]; var company = (string)xElement["company"]; var email = (string)xElement["email"]; var phone = (string)xElement["phone"]; var address = (string)xElement["address"]; var about = (string)xElement["about"]; var registered = (string)xElement["registered"]; var latitude = (double)xElement["latitude"]; var longitude = (double)xElement["longitude"]; var tags = xElement["tags"]; var tags1 = (string)tags[0]; var tags2 = (string)tags[1]; var tags3 = (string)tags[2]; var tags4 = (string)tags[3]; var tags5 = (string)tags[4]; var tags6 = (string)tags[5]; var tags7 = (string)tags[6]; var friends = xElement["friends"]; var friend1 = friends[0]; var friend2 = friends[1]; var friend3 = friends[2]; var id1 = (int)friend1["id"]; var friendName1 = (string)friend1["name"]; var id2 = (int)friend2["id"]; var friendName2 = (string)friend2["name"]; var id3 = (int)friend3["id"]; var friendName3 = (string)friend3["name"]; var greeting = (string)xElement["greeting"]; var favoriteFruit = (string)xElement["favoriteFruit"]; } if (timeResults) Console.WriteLine("Access: " + Timer.ElapsedTicks); } private static void ParsingAccess3MBBreakdown(string str, bool timeResults) { int strLength = str.Length; int byteLength = strLength * 2; var buffer = new byte[byteLength]; for (var j = 0; j < strLength; j++) { buffer[j] = (byte)str[j]; } int iter = 10; var json = new JsonParser(buffer, strLength); var parseObject = json.Parse(); var xElement = parseObject[1500]; if (timeResults) Timer.Restart(); for (int i = 0; i < iter; i++) { xElement = parseObject[1500]; } if (timeResults) Console.WriteLine(Timer.ElapsedTicks); if (timeResults) Timer.Restart(); var email = xElement["email"]; if (timeResults) Timer.Restart(); for (int i = 0; i < iter; i++) { email = xElement["email"]; } if (timeResults) Console.WriteLine(Timer.ElapsedTicks); if (timeResults) Timer.Restart(); var emailString = (Utf8String)email; if (timeResults) Timer.Restart(); for (int i = 0; i < iter; i++) { emailString = (Utf8String)email; } if (timeResults) Console.WriteLine(Timer.ElapsedTicks); if (timeResults) Timer.Restart(); var about = xElement["about"]; if (timeResults) Timer.Restart(); for (int i = 0; i < iter; i++) { about = xElement["about"]; } if (timeResults) Console.WriteLine(Timer.ElapsedTicks); if (timeResults) Timer.Restart(); var aboutString = (Utf8String)about; if (timeResults) Timer.Restart(); for (int i = 0; i < iter; i++) { aboutString = (Utf8String)about; } if (timeResults) Console.WriteLine(Timer.ElapsedTicks); if (timeResults) Timer.Restart(); var age = xElement["age"]; if (timeResults) Timer.Restart(); for (int i = 0; i < iter; i++) { age = xElement["age"]; } if (timeResults) Console.WriteLine(Timer.ElapsedTicks); if (timeResults) Timer.Restart(); var ageInt = (int)age; if (timeResults) Timer.Restart(); for (int i = 0; i < iter; i++) { ageInt = (int)age; } if (timeResults) Console.WriteLine(Timer.ElapsedTicks); if (timeResults) Timer.Restart(); var latitude = xElement["latitude"]; if (timeResults) Timer.Restart(); for (int i = 0; i < iter; i++) { latitude = xElement["latitude"]; } if (timeResults) Console.WriteLine(Timer.ElapsedTicks); if (timeResults) Timer.Restart(); var latitudeDouble = (double)latitude; if (timeResults) Timer.Restart(); for (int i = 0; i < iter; i++) { latitudeDouble = (double)latitude; } if (timeResults) Console.WriteLine(Timer.ElapsedTicks); if (timeResults) Timer.Restart(); var isActive = xElement["isActive"]; if (timeResults) Timer.Restart(); for (int i = 0; i < iter; i++) { isActive = xElement["isActive"]; } if (timeResults) Console.WriteLine(Timer.ElapsedTicks); if (timeResults) Timer.Restart(); var isActiveBool = (bool)isActive; if (timeResults) Timer.Restart(); for (int i = 0; i < iter; i++) { isActiveBool = (bool)isActive; } if (timeResults) Console.WriteLine(Timer.ElapsedTicks); } private static void RunWriterTest() { Output("====== TEST Write ======"); for (var i = 0; i < NumberOfSamples; i++) { JsonNetWriterHelper(OutputJsonData); // Do not test first iteration RunWriterTestJsonNet(); JsonWriterHelper(OutputJsonData); // Do not test first iteration RunWriterTestJson(); } Output("Json.NET Timing Results"); foreach (var res in TimingResultsJsonNet) { Output(res.ToString()); } Output("System.Text.Json Timing Results"); foreach (var res in TimingResultsJsonReader) { Output(res.ToString()); } TimingResultsJsonNet.Clear(); TimingResultsJsonReader.Clear(); } private static void RunWriterTestJsonNet() { Timer.Restart(); for (var i = 0; i < NumberOfIterations*NumberOfIterations; i++) { JsonNetWriterHelper(OutputJsonData); } TimingResultsJsonNet.Add(Timer.ElapsedMilliseconds); } private static void JsonNetWriterHelper(bool output) { StringBuilder sb = new StringBuilder(); StringWriter sw = new StringWriter(sb); var writer = new JsonTextWriter(sw); writer.Formatting = Formatting.Indented; writer.WriteStartObject(); writer.WritePropertyName("CPU"); writer.WriteValue("Intel"); writer.WritePropertyName("PSU"); writer.WriteValue("500W"); writer.WritePropertyName("Drives"); writer.WriteStartArray(); writer.WriteValue("DVD read/writer"); writer.WriteValue("500 gigabyte hard drive"); writer.WriteValue("200 gigabype hard drive"); writer.WriteEnd(); writer.WriteEndObject(); if (output) Console.WriteLine(sw.ToString()); } private static void RunWriterTestJson() { Timer.Restart(); for (var i = 0; i < NumberOfIterations*NumberOfIterations; i++) { JsonWriterHelper(OutputJsonData); } TimingResultsJsonReader.Add(Timer.ElapsedMilliseconds); } private static void JsonWriterHelper(bool output) { var buffer = new byte[1024]; var stream = new MemoryStream(buffer); var writer = new JsonWriter(stream, TextEncoder.Encoding.Utf8, prettyPrint: true); writer.WriteObjectStart(); writer.WriteAttribute("CPU", "Intel"); writer.WriteAttribute("PSU", "500W"); writer.WriteMember("Drives"); writer.WriteArrayStart(); writer.WriteString("DVD read/writer"); writer.WriteString("500 gigabyte hard drive"); writer.WriteString("200 gigabype hard drive"); writer.WriteArrayEnd(); writer.WriteObjectEnd(); if (output) Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, (int)stream.Position)); } private static void Output(string str) { if (!OutputResults) return; Console.WriteLine(str); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Cache.Store { using System.Collections; using System.Diagnostics; using Apache.Ignite.Core.Cache.Store; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl.Handle; using Apache.Ignite.Core.Impl.Portable; using Apache.Ignite.Core.Impl.Portable.IO; using Apache.Ignite.Core.Impl.Resource; using Apache.Ignite.Core.Impl.Unmanaged; using Apache.Ignite.Core.Portable; /// <summary> /// Interop cache store. /// </summary> internal class CacheStore { /** */ private const byte OpLoadCache = 0; /** */ private const byte OpLoad = 1; /** */ private const byte OpLoadAll = 2; /** */ private const byte OpPut = 3; /** */ private const byte OpPutAll = 4; /** */ private const byte OpRmv = 5; /** */ private const byte OpRmvAll = 6; /** */ private const byte OpSesEnd = 7; /** */ private readonly bool _convertPortable; /** Store. */ private readonly ICacheStore _store; /** Session. */ private readonly CacheStoreSessionProxy _sesProxy; /** */ private readonly long _handle; /// <summary> /// Initializes a new instance of the <see cref="CacheStore" /> class. /// </summary> /// <param name="store">Store.</param> /// <param name="convertPortable">Whether to convert portable objects.</param> /// <param name="registry">The handle registry.</param> private CacheStore(ICacheStore store, bool convertPortable, HandleRegistry registry) { Debug.Assert(store != null); _store = store; _convertPortable = convertPortable; _sesProxy = new CacheStoreSessionProxy(); ResourceProcessor.InjectStoreSession(store, _sesProxy); _handle = registry.AllocateCritical(this); } /// <summary> /// Creates interop cache store from a stream. /// </summary> /// <param name="memPtr">Memory pointer.</param> /// <param name="registry">The handle registry.</param> /// <returns> /// Interop cache store. /// </returns> internal static CacheStore CreateInstance(long memPtr, HandleRegistry registry) { using (var stream = IgniteManager.Memory.Get(memPtr).Stream()) { var reader = PortableUtils.Marshaller.StartUnmarshal(stream, PortableMode.KeepPortable); var assemblyName = reader.ReadString(); var className = reader.ReadString(); var convertPortable = reader.ReadBoolean(); var propertyMap = reader.ReadGenericDictionary<string, object>(); var store = (ICacheStore) IgniteUtils.CreateInstance(assemblyName, className); IgniteUtils.SetProperties(store, propertyMap); return new CacheStore(store, convertPortable, registry); } } /// <summary> /// Gets the handle. /// </summary> public long Handle { get { return _handle; } } /// <summary> /// Initializes this instance with a grid. /// </summary> /// <param name="grid">Grid.</param> public void Init(Ignite grid) { ResourceProcessor.Inject(_store, grid); } /// <summary> /// Invokes a store operation. /// </summary> /// <param name="input">Input stream.</param> /// <param name="cb">Callback.</param> /// <param name="grid">Grid.</param> /// <returns>Invocation result.</returns> /// <exception cref="IgniteException">Invalid operation type: + opType</exception> public int Invoke(IPortableStream input, IUnmanagedTarget cb, Ignite grid) { IPortableReader reader = grid.Marshaller.StartUnmarshal(input, _convertPortable ? PortableMode.Deserialize : PortableMode.ForcePortable); IPortableRawReader rawReader = reader.RawReader(); int opType = rawReader.ReadByte(); // Setup cache sessoin for this invocation. long sesId = rawReader.ReadLong(); CacheStoreSession ses = grid.HandleRegistry.Get<CacheStoreSession>(sesId, true); ses.CacheName = rawReader.ReadString(); _sesProxy.SetSession(ses); try { // Perform operation. switch (opType) { case OpLoadCache: _store.LoadCache((k, v) => WriteObjects(cb, grid, k, v), rawReader.ReadObjectArray<object>()); break; case OpLoad: object val = _store.Load(rawReader.ReadObject<object>()); if (val != null) WriteObjects(cb, grid, val); break; case OpLoadAll: var keys = rawReader.ReadCollection(); var result = _store.LoadAll(keys); foreach (DictionaryEntry entry in result) WriteObjects(cb, grid, entry.Key, entry.Value); break; case OpPut: _store.Write(rawReader.ReadObject<object>(), rawReader.ReadObject<object>()); break; case OpPutAll: _store.WriteAll(rawReader.ReadDictionary()); break; case OpRmv: _store.Delete(rawReader.ReadObject<object>()); break; case OpRmvAll: _store.DeleteAll(rawReader.ReadCollection()); break; case OpSesEnd: grid.HandleRegistry.Release(sesId); _store.SessionEnd(rawReader.ReadBoolean()); break; default: throw new IgniteException("Invalid operation type: " + opType); } return 0; } finally { _sesProxy.ClearSession(); } } /// <summary> /// Writes objects to the marshaller. /// </summary> /// <param name="cb">Optional callback.</param> /// <param name="grid">Grid.</param> /// <param name="objects">Objects.</param> private static void WriteObjects(IUnmanagedTarget cb, Ignite grid, params object[] objects) { using (var stream = IgniteManager.Memory.Allocate().Stream()) { PortableWriterImpl writer = grid.Marshaller.StartMarshal(stream); try { foreach (var obj in objects) { writer.DetachNext(); writer.WriteObject(obj); } } finally { grid.Marshaller.FinishMarshal(writer); } if (cb != null) { stream.SynchronizeOutput(); UnmanagedUtils.CacheStoreCallbackInvoke(cb, stream.MemoryPointer); } } } } }
using UnityEngine; using System.Collections; using Ecosim; using Ecosim.SceneData; using Ecosim.GameCtrl.GameButtons; using System; using System.IO; using Ecosim.SceneEditor; public class QuestionnaireWindow : ReportBaseWindow { private Questionnaire questionnaire; private Progression.QuestionnaireState questionnaireState; private Vector2 messageScrollPos; private Answer selectedAnswer; private System.Action <Answer, bool> onMessageContinueClick; private string messageTitle; private string message; private int messageXOffset; private int messageYOffset; private int messageLines; private int messageTitleLines; private bool messageIsDragging; private Vector2 messageMouseDragPosition; public QuestionnaireWindow (Questionnaire questionnaire, System.Action onFinished, Texture2D icon) : base (onFinished, icon) { this.questionnaire = questionnaire; questionnaireState = new Progression.QuestionnaireState (this.questionnaire.id); EditorCtrl.self.scene.progression.questionnaireStates.Add (questionnaireState); messageXOffset = -1; messageYOffset = -1; message = null; } public override void Render () { base.Render (); // Check for introduction if (this.questionnaire.useIntroduction && !this.questionnaire.introShown) { // We'll (mis)use the message for this for now if (this.message == null) { this.message = questionnaire.introduction; this.messageTitle = "Introduction"; this.messageLines = this.message.Split (new string[] { "&#xA;" }, System.StringSplitOptions.RemoveEmptyEntries).Length; this.messageTitleLines = 1; this.onMessageContinueClick = delegate (Answer arg1, bool arg2) { this.message = null; this.questionnaire.introShown = true; }; } RenderMessage (); return; } // Check for question if (questionnaire.currentQuestionIndex < questionnaire.questions.Count) { Question question = questionnaire.questions [questionnaire.currentQuestionIndex]; GUI.enabled = (this.message == null); if (question is MPCQuestion) { RenderMPCQuestion (question as MPCQuestion); } else if (question is OpenQuestion) { RenderOpenQuestion (question as OpenQuestion); } GUI.enabled = true; RenderMessage (); return; } // Check for conclusion if (this.questionnaire.useConclusion && !this.questionnaire.conclusionShown) { // We'll (mis)use the message for this for now if (this.message == null) { this.message = questionnaire.conclusion; this.messageTitle = "Final Remark"; this.messageLines = this.message.Split (new string[] { "&#xA;" }, System.StringSplitOptions.RemoveEmptyEntries).Length; this.messageTitleLines = 1; this.onMessageContinueClick = delegate (Answer arg1, bool arg2) { this.message = null; this.questionnaire.conclusionShown = true; // Check if we can go to the results page CheckForResultsPage (); }; } RenderMessage (); return; } try { if (this.questionnaire.useResultsPage) { // Then the results RenderResults (); } } catch { } } #region Questionnaire private void RenderMPCQuestion (MPCQuestion question) { Questionnaire q = questionnaire; RenderQuestionStart (question); { GUILayout.Space (1f); GUILayout.Label (question.body, headerDark, GUILayout.Width (width), defaultOption); //GUILayout.Space (1); GUILayout.Label ("Choose your answer:", headerLight, GUILayout.Width (width), defaultOption); GUILayout.Space (1); // Answers GUILayout.BeginVertical ( GUILayout.Width (width)); { //GUILayout.Space (5); foreach (MPCQuestion.MPCAnswer a in question.answers) { if (GUILayout.Button (a.body, button, GUILayout.Width (width), defaultOption)) { if (selectedAnswer == null) { HandleMPCAnswer (a, true); } } GUILayout.Space (1); } //GUILayout.Space (4); } GUILayout.EndVertical (); } RenderQuestionEnd (question); } private void HandleMPCAnswer (Answer answer, bool checkForFeedback) { MPCQuestion.MPCAnswer a = (MPCQuestion.MPCAnswer)answer; if (checkForFeedback && a.useFeedback) { this.message = a.feedback; this.messageTitle = "Selected answer: " + a.body; this.selectedAnswer = a; this.onMessageContinueClick = HandleMPCAnswer; this.messageLines = this.message.Split (new string[] { "&#xA;" }, System.StringSplitOptions.RemoveEmptyEntries).Length; this.messageTitleLines = this.messageTitle.Split (new string[] { "&#xA;" }, System.StringSplitOptions.RemoveEmptyEntries).Length; return; } if (!a.allowRetry && a.startFromBeginning) { // Start over this.questionnaire.currentQuestionIndex = 0; this.questionnaireState.Reset (); } else if (a.allowRetry) { // Just remove the feedback } else { // Create question state Question q = this.questionnaire.questions [this.questionnaire.currentQuestionIndex]; Progression.QuestionnaireState.QuestionState questionState = questionnaireState.GetQuestionState (this.questionnaire.currentQuestionIndex); questionState.questionName = q.body; questionState.questionAnswer = a.body; questionState.moneyGained = 0; if (this.questionnaire.useBudget) { questionState.moneyGained = a.moneyGained; } questionState.score = 0; if (this.questionnaire.useRequiredScore) { questionState.score = a.score; } // Next question NextQuestion (); } this.selectedAnswer = null; this.message = null; this.scrollPosition = Vector2.zero; this.messageScrollPos = Vector2.zero; } private void RenderOpenQuestion (OpenQuestion question) { Questionnaire q = questionnaire; RenderQuestionStart (question); { GUILayout.Space (1); OpenQuestion.OpenAnswer a = question.answers[0] as OpenQuestion.OpenAnswer; GUILayout.Label (question.body, headerDark, GUILayout.Width (width), defaultOption); //GUILayout.Space (1); GUILayout.Label ("Write your answer:", headerLight, GUILayout.Width (width), defaultOption); GUILayout.Space (1); if (a.useMaxChars) a.body = GUILayout.TextArea (a.body, a.maxChars, textArea, GUILayout.Width (width), defaultOption); else a.body = GUILayout.TextArea (a.body, textArea, GUILayout.Width (width), defaultOption); GUILayout.Space (1); GUILayout.BeginHorizontal (); { string label = (a.useMaxChars) ? string.Format("<size=10>Characters {0}/{1}</size>", a.body.Length, a.maxChars) : ""; GUILayout.Label (label, headerLight, GUILayout.Width (width - 52), GUILayout.Height (30), defaultOption); GUILayout.Space (1); if (GUILayout.Button ("Done", button, GUILayout.Width (51), defaultOption)) { if (this.selectedAnswer == null) { HandleOpenAnswer (question.answers[0], true); } } } GUILayout.EndHorizontal (); } RenderQuestionEnd (question); } private void HandleOpenAnswer (Answer a, bool checkForFeedback) { // Check if the feedback was "can't be empty" and we clicked "Continue" if (!checkForFeedback && a.body.Length == 0) { this.message = null; return; } // Check for empty body if (a.body.Length == 0) { this.message = "Your answer can't be empty."; this.selectedAnswer = a; this.messageTitle = "Oops..."; this.onMessageContinueClick = HandleOpenAnswer; this.messageLines = 1; this.messageTitleLines = 1; return; } // Check for feedback if (checkForFeedback && a.useFeedback) { this.message = a.feedback; this.selectedAnswer = a; this.messageTitle = null; this.onMessageContinueClick = HandleOpenAnswer; this.messageLines = this.message.Split (new string[] { "&#xA;" }, System.StringSplitOptions.RemoveEmptyEntries).Length; this.messageTitleLines = 0; return; } // Create question state Question q = this.questionnaire.questions [this.questionnaire.currentQuestionIndex]; Progression.QuestionnaireState qs = EditorCtrl.self.scene.progression.GetQuestionnaireState (this.questionnaire.id); Progression.QuestionnaireState.QuestionState questionState = qs.GetQuestionState (this.questionnaire.currentQuestionIndex); questionState.questionName = q.body; questionState.questionAnswer = a.body; // Next question NextQuestion (); this.selectedAnswer = null; this.message = null; this.scrollPosition = Vector2.zero; this.messageScrollPos = Vector2.zero; } private void RenderQuestionStart (Question question) { Questionnaire q = questionnaire; Rect areaRect = new Rect (left + 32, top, width, height); GUILayout.BeginArea (areaRect); CameraControl.MouseOverGUI |= areaRect.Contains (Input.mousePosition); scrollPosition = GUILayout.BeginScrollView (scrollPosition); // Header if (q.showHeader) { GUILayout.BeginHorizontal (); { GUILayout.Label ("Questionnaire: " + q.name, headerDark, GUILayout.Width (width - 40), defaultOption); GUILayout.Space (1); GUILayout.Label (string.Format ("{0}/{1}", (q.currentQuestionIndex + 1), q.questions.Count), headerDark, GUILayout.Width (39), defaultOption); } GUILayout.EndHorizontal (); } //GUILayout.Space (1); } private void RenderQuestionEnd (Question question) { GUILayout.EndScrollView (); GUILayout.EndArea (); } private void NextQuestion () { // Up the current index this.questionnaire.currentQuestionIndex++; // Check if we can go to the results page CheckForResultsPage (); } private void CheckForResultsPage () { // Exception: if we don't show the results page and we've // answered our last question we fire the onFinished event // for some reason we can do it instead of RenderResultsPage... if (this.questionnaire.currentQuestionIndex >= this.questionnaire.questions.Count) { // Check if we have a conclusion and if it's shown already if (this.questionnaire.useConclusion && !this.questionnaire.conclusionShown) return; // Check if we have a results page if (this.questionnaire.useResultsPage) return; // Fire onFinished event if (this.onFinished != null) onFinished (); } } #endregion #region Results private void RenderResults () { Questionnaire q = questionnaire; Progression.QuestionnaireState qs = questionnaireState;//EditorCtrl.self.scene.progression.GetQuestionnaireState (q.id); Rect areaRect = new Rect (left, top, width + 20, height); GUILayout.BeginArea (areaRect); { CameraControl.MouseOverGUI |= areaRect.Contains (Input.mousePosition); // Check if we passed bool passed = true; if (q.useRequiredScore) { passed = (qs.totalScore >= q.requiredScore); } GUILayout.Label ("Questionnaire results:\n" + q.name, headerDark, GUILayout.Width (width), defaultOption); GUILayout.Space (5); this.scrollPosition = GUILayout.BeginScrollView (this.scrollPosition); { // Questions int qidx = 1; foreach (Progression.QuestionnaireState.QuestionState qState in qs.questionStates) { EcoGUI.SplitLabel (qidx + ". " + qState.questionName, headerDark, GUILayout.Width (width)); //GUILayout.Space (1); //GUILayout.Label ("Your answer:", headerLight, GUILayout.Width (width)); EcoGUI.SplitLabel (qState.questionAnswer, textArea, GUILayout.Width (width)); GUILayout.Space (5); qidx++; } // Money gained if (passed && q.useBudget) { GUILayout.Label ("Money earned: " + qs.totalMoneyEarned, headerDark, GUILayout.Width (width), defaultOption); //GUILayout.Space (1); if (q.useBudgetFeedback) { EcoGUI.SplitLabel (q.budgetFeedback, headerLight, GUILayout.Width (width)); } GUILayout.Space (5); } } GUILayout.EndScrollView (); // Score if (q.useRequiredScore) { GUILayout.Label ("Total score: " + qs.totalScore + "\nScore required to pass: " + q.requiredScore, headerDark, GUILayout.Width (width), defaultOption); //GUILayout.Space (1); if (q.useReqScoreFeedback) { EcoGUI.SplitLabel (q.reqScoreFeedback, headerLight, GUILayout.Width (width), defaultOption); GUILayout.Space (1); } GUILayout.Label ("Result: " + ((passed) ? "Passed" : "Failed"), headerDark, GUILayout.Width (width), defaultOption); } // Continue button if (passed) { if (q.usePassedFeedback) { EcoGUI.SplitLabel (q.passedFeedback, headerLight, GUILayout.Width (width), defaultOption); } GUILayout.Space (1); GUILayout.BeginHorizontal (); { int saveWidth = (SaveFileDialog.SystemDialogAvailable ()) ? 80 : 135; GUILayout.Label ("", headerLight, GUILayout.Width (width - (2 + 80 + saveWidth)), defaultOption); GUILayout.Space (1); RenderSaveButton (qs, passed); GUILayout.Space (1); if (GUILayout.Button ("Continue", button, GUILayout.Width (80), defaultOption)) { if (onFinished != null) { onFinished (); onFinished = null; } } } GUILayout.EndHorizontal (); } else { if (q.useFailedFeedback) { EcoGUI.SplitLabel (q.failedFeedback, headerLight, GUILayout.Width (width), defaultOption); } GUILayout.Space (1); GUILayout.BeginHorizontal (); { GUILayout.Label ("", headerLight, GUILayout.Width (width - 162), defaultOption); GUILayout.Space (1); RenderSaveButton (qs, passed); GUILayout.Space (1); string btnLabel = (q.startOverOnFailed) ? "Retry" : "Continue"; if (GUILayout.Button (btnLabel, button, GUILayout.Width (80), defaultOption)) { if (q.startOverOnFailed) { q.currentQuestionIndex = 0; this.questionnaireState.Reset (); } else { if (onFinished != null) { onFinished (); onFinished = null; } } } } GUILayout.EndHorizontal (); } } GUILayout.EndArea (); } private void RenderSaveButton (Progression.QuestionnaireState qs, bool passed) { string saveName = (SaveFileDialog.SystemDialogAvailable ()) ? "Save" : "Save to Desktop"; int saveWidth = (SaveFileDialog.SystemDialogAvailable ()) ? 80 : 135; if (GUILayout.Button (saveName, button, GUILayout.Width (saveWidth), defaultOption)) { GameControl.self.StartCoroutine (SaveFileDialog.Show ("questionnaire_" + this.questionnaire.id, "txt files (*.txt)|*.txt", delegate(bool ok, string url) { if (!ok) return; // Create new file System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding (); FileStream fs = File.Create (url); System.Text.StringBuilder sb = new System.Text.StringBuilder (); Scene scene = EditorCtrl.self.scene; sb.AppendFormat ("Name: {0} {1}\n", scene.playerInfo.firstName, scene.playerInfo.familyName); sb.AppendFormat ("Date: {0}\n", System.DateTime.Today.ToString ("dd\\/MM\\/yyyy")); sb.AppendLine (); sb.AppendFormat ("Results Questionnaire {0}:\n", this.questionnaire.id); sb.AppendFormat ("{0}\n", this.questionnaire.name); sb.AppendLine (); int qIdx = 1; foreach (Progression.QuestionnaireState.QuestionState qState in qs.questionStates) { sb.AppendFormat ("{0}. {1}:\n", qIdx.ToString (), qState.questionName); sb.AppendFormat ("{0}\n", qState.questionAnswer); sb.AppendLine (); qIdx++; } if (passed && this.questionnaire.useBudget) { sb.AppendFormat ("Money earned: {0}\n", qs.totalMoneyEarned); sb.AppendLine (); } if (this.questionnaire.useRequiredScore) { sb.AppendFormat ("Total score: {0}\n", qs.totalScore); sb.AppendFormat ("Required score: {0}\n", this.questionnaire.requiredScore); sb.AppendFormat ("Result: {0}\n", ((passed) ? "Passed" : "Failed")); sb.AppendLine (); } // Stringify and save string txt = sb.ToString (); fs.Write (enc.GetBytes (txt), 0, enc.GetByteCount (txt)); // Close and dispose the stream fs.Close (); fs.Dispose (); fs = null; })); } } #endregion #region Message private void RenderMessage () { if (string.IsNullOrEmpty (this.message)) return; float editorWidth = 0f; if (EditorCtrl.self.isOpen) { editorWidth = 400; } width = Screen.width * 0.5f; height = (messageLines + messageTitleLines + 1) * 60f; height = Mathf.Clamp (height, 0f, Screen.height * 0.75f); // Check x y offsets if (messageXOffset == -1) { messageXOffset = (int)(((Screen.width - width) * 0.5f) + editorWidth); } if (messageYOffset == -1) { messageYOffset = (int)((Screen.height * 0.5f) - (height * 0.5f)); } //left = ((Screen.width - width) * 0.5f) + editorWidth; //top = (Screen.height * 0.5f) - (height * 0.5f); left = messageXOffset; top = messageYOffset; Rect areaRect = new Rect (left, top, width, height); GUILayout.BeginArea (areaRect); { CameraControl.MouseOverGUI |= areaRect.Contains (Input.mousePosition); GUILayout.Label (messageTitle ?? "", headerDark, GUILayout.Width (width), defaultOption); Vector2 mousePos = Input.mousePosition; Vector2 guiMousePos = new Vector2 (mousePos.x, Screen.height - mousePos.y); // Check for drag if (Event.current.type == EventType.MouseUp) { // Cancel drag messageIsDragging = false; } else if (messageIsDragging) { // Do drag messageXOffset += (int)(guiMousePos.x - messageMouseDragPosition.x); messageYOffset += (int)(guiMousePos.y - messageMouseDragPosition.y); messageMouseDragPosition = guiMousePos; } else if (Event.current.type == EventType.MouseDown) { // Start drag if (GUILayoutUtility.GetLastRect ().Contains (Event.current.mousePosition)) { messageIsDragging = true; messageMouseDragPosition = guiMousePos; Event.current.Use (); this.SetWindowOnTop (); } } GUILayout.Space (1); this.messageScrollPos = GUILayout.BeginScrollView (this.messageScrollPos); { GUILayout.Label (this.message, textArea, GUILayout.Width (width), GUILayout.ExpandHeight (true), defaultOption); GUILayout.Space (1); } GUILayout.EndScrollView (); GUILayout.Space (1); GUILayout.BeginHorizontal (); { GUILayout.Label ("", headerLight, GUILayout.Width (width - 90), defaultOption); if (GUILayout.Button ("Continue", button, GUILayout.Width (90), defaultOption)) { this.message = null; if (onMessageContinueClick != null) onMessageContinueClick (this.selectedAnswer, false); } } GUILayout.EndHorizontal (); } GUILayout.EndArea (); } #endregion public override void Dispose () { base.Dispose (); this.questionnaire = null; this.selectedAnswer = null; this.onMessageContinueClick = null; } }
using System; using System.Threading; using System.Collections.Generic; using System.Collections.Specialized; using System.Collections.ObjectModel; using System.Workflow.Runtime; using System.Diagnostics; using System.Globalization; namespace System.Workflow.Runtime.Hosting { [Obsolete("The System.Workflow.* types are deprecated. Instead, please use the new types from System.Activities.*")] public class ManualWorkflowSchedulerService : WorkflowSchedulerService { private class CallbackInfo { WaitCallback callback; Guid instanceId; Guid timerId; DateTime when; public CallbackInfo(WaitCallback callback, Guid instanceId, Guid timerId, DateTime when) { this.callback = callback; this.when = when; this.instanceId = instanceId; this.timerId = timerId; } public DateTime When { get { return when; } } public bool IsExpired { get { return DateTime.UtcNow >= when; } } public Guid InstanceId { get { return instanceId; } } public Guid TimerId { get { return timerId; } } public WaitCallback Callback { get { return callback; } } } private KeyedPriorityQueue<Guid, CallbackInfo, DateTime> pendingScheduleRequests = new KeyedPriorityQueue<Guid, CallbackInfo, DateTime>(); private Dictionary<Guid, DefaultWorkflowSchedulerService.WorkItem> scheduleRequests = new Dictionary<Guid, DefaultWorkflowSchedulerService.WorkItem>(); private object locker = new Object(); private Timer callbackTimer; private readonly TimerCallback timerCallback; // non-null indicates that active timers are enabled private volatile bool threadRunning; // indicates that the timer thread is running private static TimeSpan infinite = new TimeSpan(Timeout.Infinite); private IList<PerformanceCounter> queueCounters; private static TimeSpan fiveMinutes = new TimeSpan(0, 5, 0); private const string USE_ACTIVE_TIMERS_KEY = "UseActiveTimers"; // Note that pendingScheduleRequests are keyed by instance ID under the assertion that there is at most one outstanding // timer for any given instance ID. To support cancellation, and additional map is kept of timerID-to-instanceID so that // we can find the appropriate pending given a timer ID public ManualWorkflowSchedulerService() { } public ManualWorkflowSchedulerService(bool useActiveTimers) { if (useActiveTimers) { timerCallback = new TimerCallback(OnTimerCallback); pendingScheduleRequests.FirstElementChanged += OnFirstElementChanged; WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "ManualWorkflowSchedulerService: started with active timers"); } } public ManualWorkflowSchedulerService(NameValueCollection parameters) { if (parameters == null) throw new ArgumentNullException("parameters"); foreach (string key in parameters.Keys) { if (key == null) throw new ArgumentException(String.Format(Thread.CurrentThread.CurrentCulture, ExecutionStringManager.UnknownConfigurationParameter, "null")); string p = parameters[key]; if (!key.Equals(USE_ACTIVE_TIMERS_KEY, StringComparison.OrdinalIgnoreCase)) throw new ArgumentException(String.Format(Thread.CurrentThread.CurrentCulture, ExecutionStringManager.UnknownConfigurationParameter, key)); bool useActiveTimers; if (!bool.TryParse(p, out useActiveTimers)) throw new FormatException(USE_ACTIVE_TIMERS_KEY); if (useActiveTimers) { timerCallback = new TimerCallback(OnTimerCallback); pendingScheduleRequests.FirstElementChanged += OnFirstElementChanged; WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "ManualWorkflowSchedulerService: Started with active timers"); } } } internal protected override void Schedule(WaitCallback callback, Guid workflowInstanceId) { if (callback == null) throw new ArgumentNullException("callback"); if (workflowInstanceId.Equals(Guid.Empty)) throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, ExecutionStringManager.CantBeEmptyGuid, "workflowInstanceId")); lock (locker) { WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "ManualWorkflowSchedulerService: Schedule workflow {0}", workflowInstanceId); if (!scheduleRequests.ContainsKey(workflowInstanceId)) scheduleRequests.Add(workflowInstanceId, new DefaultWorkflowSchedulerService.WorkItem(callback, workflowInstanceId)); } if (queueCounters != null) { foreach (PerformanceCounter p in queueCounters) { p.RawValue = scheduleRequests.Count; } } } internal protected override void Schedule(WaitCallback callback, Guid workflowInstanceId, DateTime whenUtc, Guid timerId) { if (callback == null) throw new ArgumentNullException("callback"); if (workflowInstanceId.Equals(Guid.Empty)) throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, ExecutionStringManager.CantBeEmptyGuid, "workflowInstanceId")); if (timerId.Equals(Guid.Empty)) throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, ExecutionStringManager.CantBeEmptyGuid, "timerId")); lock (locker) { WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "ManualWorkflowSchedulerService: Schedule timer {0} for workflow {1} at {2}", timerId, workflowInstanceId, whenUtc); pendingScheduleRequests.Enqueue(timerId, new CallbackInfo(callback, workflowInstanceId, timerId, whenUtc), whenUtc); } } internal protected override void Cancel(Guid timerId) { if (timerId.Equals(Guid.Empty)) throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, ExecutionStringManager.CantBeEmptyGuid, "timerId")); lock (locker) { WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "ManualWorkflowSchedulerService: Cancel timer {0}", timerId); pendingScheduleRequests.Remove(timerId); } } private bool RunOne(Guid workflowInstanceId) { bool retval = false; DefaultWorkflowSchedulerService.WorkItem cs = null; lock (locker) { if (scheduleRequests.ContainsKey(workflowInstanceId)) { cs = scheduleRequests[workflowInstanceId]; scheduleRequests.Remove(workflowInstanceId); } } try { if (cs != null) { WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "ManualWorkflowSchedulerService: Executing {0}", workflowInstanceId); if (queueCounters != null) { foreach (PerformanceCounter p in queueCounters) { p.RawValue = scheduleRequests.Count; } } cs.Invoke(this); retval = true; } } catch (Exception e) { RaiseServicesExceptionNotHandledEvent(e, workflowInstanceId); } return retval; } private bool HasExpiredTimer(Guid workflowInstanceId, out Guid timerId) { lock (locker) { CallbackInfo ci = pendingScheduleRequests.FindByPriority(DateTime.UtcNow, delegate(CallbackInfo c) { return c.InstanceId == workflowInstanceId; }); if (ci != null) { timerId = ci.TimerId; return true; } } timerId = Guid.Empty; return false; } private bool ProcessTimer(Guid workflowInstanceId) { bool retval = false; CallbackInfo cs = null; Guid timerId = Guid.Empty; lock (locker) { Guid expTimerId; if (HasExpiredTimer(workflowInstanceId, out expTimerId)) { cs = pendingScheduleRequests.Remove(expTimerId); } } try { if (cs != null) { WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "ManualWorkflowSchedulerService: Processing timer {0}", timerId); cs.Callback(cs.InstanceId); retval = true; } } catch (Exception e) { RaiseServicesExceptionNotHandledEvent(e, workflowInstanceId); } return retval; } private bool CanRun(Guid workflowInstanceId) { bool retval = false; lock (locker) { Guid timerId; retval = scheduleRequests.ContainsKey(workflowInstanceId) || HasExpiredTimer(workflowInstanceId, out timerId); WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "ManualWorkflowSchedulerService: CanRun is {0}", retval); } return retval; } public bool RunWorkflow(Guid workflowInstanceId) { if (workflowInstanceId.Equals(Guid.Empty)) throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, ExecutionStringManager.CantBeEmptyGuid, "workflowInstanceId")); WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "ManualWorkflowSchedulerService: Running workflow {0}", workflowInstanceId); bool retval = false; // return true if we do any work at all while (CanRun(workflowInstanceId)) { if (RunOne(workflowInstanceId) || ProcessTimer(workflowInstanceId)) retval = true; // did some work, try again else break; // no work done this iteration } return retval; } private Timer CreateTimerCallback(CallbackInfo info) { DateTime now = DateTime.UtcNow; TimeSpan span = (info.When > now) ? info.When - now : TimeSpan.Zero; // never let more than five minutes go by without checking if (span > fiveMinutes) { span = fiveMinutes; } return new Timer(timerCallback, info.InstanceId, span, infinite); } override protected void OnStarted() { base.OnStarted(); if (this.timerCallback != null) { lock (locker) { CallbackInfo ci = pendingScheduleRequests.Peek(); if (ci != null) callbackTimer = CreateTimerCallback(ci); } } lock (locker) { if (queueCounters == null && this.Runtime.PerformanceCounterManager != null) { queueCounters = this.Runtime.PerformanceCounterManager.CreateCounters(ExecutionStringManager.PerformanceCounterWorkflowsWaitingName); } } } protected internal override void Stop() { base.Stop(); if (this.timerCallback != null) { lock (locker) { if (callbackTimer != null) { callbackTimer.Dispose(); callbackTimer = null; } } } } private void OnTimerCallback(object ignored) { CallbackInfo ci = null; try { lock (locker) { if (State.Equals(WorkflowRuntimeServiceState.Started)) { ci = pendingScheduleRequests.Peek(); if (ci != null) { if (ci.IsExpired) { WorkflowTrace.Host.TraceEvent(TraceEventType.Information, 0, "Timeout occured for timer for instance {0}", ci.InstanceId); threadRunning = true; pendingScheduleRequests.Dequeue(); } else { callbackTimer = CreateTimerCallback(ci); } } } } if (threadRunning) { ci.Callback(ci.InstanceId); // delivers the timer message RunWorkflow(ci.InstanceId); } } catch (ThreadAbortException e) { WorkflowTrace.Host.TraceEvent(TraceEventType.Error, 0, "Timeout for instance, {0} threw exception {1}", ci == null ? Guid.Empty : ci.InstanceId, e.Message); RaiseServicesExceptionNotHandledEvent(e, ci.InstanceId); throw; } catch (Exception e) { WorkflowTrace.Host.TraceEvent(TraceEventType.Error, 0, "Timeout for instance, {0} threw exception {1}", ci == null ? Guid.Empty : ci.InstanceId, e.Message); RaiseServicesExceptionNotHandledEvent(e, ci.InstanceId); } finally { lock (locker) { if (threadRunning) { threadRunning = false; ci = pendingScheduleRequests.Peek(); if (ci != null) callbackTimer = CreateTimerCallback(ci); } } } } private void OnFirstElementChanged(object source, KeyedPriorityQueueHeadChangedEventArgs<CallbackInfo> e) { lock (locker) { if (threadRunning) return; // ignore when a timer thread is already processing a timer request if (callbackTimer != null) { callbackTimer.Dispose(); callbackTimer = null; } if (e.NewFirstElement != null && this.State == WorkflowRuntimeServiceState.Started) { callbackTimer = CreateTimerCallback(e.NewFirstElement); } } } } }
// Transport Security Layer (TLS) // Copyright (c) 2003-2004 Carlos Guzman Alvarez // // 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.Security.Cryptography.X509Certificates; using System.Security.Cryptography; using Mono.Security.Cryptography; namespace Mono.Security.Protocol.Tls.Handshake.Client { internal class TlsClientCertificateVerify : HandshakeMessage { #region Constructors public TlsClientCertificateVerify(Context context) : base(context, HandshakeType.CertificateVerify) { } #endregion #region Methods public override void Update() { base.Update(); this.Reset(); } #endregion #region Protected Methods protected override void ProcessAsSsl3() { AsymmetricAlgorithm privKey = null; ClientContext context = (ClientContext)this.Context; privKey = context.SslStream.RaisePrivateKeySelection( context.ClientSettings.ClientCertificate, context.ClientSettings.TargetHost); if (privKey == null) { throw new TlsException(AlertDescription.UserCancelled, "Client certificate Private Key unavailable."); } else { SslHandshakeHash hash = new SslHandshakeHash(context.MasterSecret); hash.TransformFinalBlock( context.HandshakeMessages.ToArray(), 0, (int)context.HandshakeMessages.Length); // CreateSignature uses ((RSA)privKey).DecryptValue which is not implemented // in RSACryptoServiceProvider. Other implementations likely implement DecryptValue // so we will try the CreateSignature method. byte[] signature = null; #if !MOONLIGHT if (!(privKey is RSACryptoServiceProvider)) #endif { try { signature = hash.CreateSignature((RSA)privKey); } catch (NotImplementedException) { } } // If DecryptValue is not implemented, then try to export the private // key and let the RSAManaged class do the DecryptValue if (signature == null) { // RSAManaged of the selected ClientCertificate // (at this moment the first one) RSA rsa = this.getClientCertRSA((RSA)privKey); // Write message signature = hash.CreateSignature(rsa); } this.Write((short)signature.Length); this.Write(signature, 0, signature.Length); } } protected override void ProcessAsTls1() { AsymmetricAlgorithm privKey = null; ClientContext context = (ClientContext)this.Context; privKey = context.SslStream.RaisePrivateKeySelection( context.ClientSettings.ClientCertificate, context.ClientSettings.TargetHost); if (privKey == null) { throw new TlsException(AlertDescription.UserCancelled, "Client certificate Private Key unavailable."); } else { // Compute handshake messages hash MD5SHA1 hash = new MD5SHA1(); hash.ComputeHash( context.HandshakeMessages.ToArray(), 0, (int)context.HandshakeMessages.Length); // CreateSignature uses ((RSA)privKey).DecryptValue which is not implemented // in RSACryptoServiceProvider. Other implementations likely implement DecryptValue // so we will try the CreateSignature method. byte[] signature = null; #if !MOONLIGHT if (!(privKey is RSACryptoServiceProvider)) #endif { try { signature = hash.CreateSignature((RSA)privKey); } catch (NotImplementedException) { } } // If DecryptValue is not implemented, then try to export the private // key and let the RSAManaged class do the DecryptValue if (signature == null) { // RSAManaged of the selected ClientCertificate // (at this moment the first one) RSA rsa = this.getClientCertRSA((RSA)privKey); // Write message signature = hash.CreateSignature(rsa); } this.Write((short)signature.Length); this.Write(signature, 0, signature.Length); } } #endregion #region Private methods private RSA getClientCertRSA(RSA privKey) { RSAParameters rsaParams = new RSAParameters(); RSAParameters privateParams = privKey.ExportParameters(true); // for RSA m_publickey contains 2 ASN.1 integers // the modulus and the public exponent ASN1 pubkey = new ASN1 (this.Context.ClientSettings.Certificates[0].GetPublicKey()); ASN1 modulus = pubkey [0]; if ((modulus == null) || (modulus.Tag != 0x02)) { return null; } ASN1 exponent = pubkey [1]; if (exponent.Tag != 0x02) { return null; } rsaParams.Modulus = this.getUnsignedBigInteger(modulus.Value); rsaParams.Exponent = exponent.Value; // Set private key parameters rsaParams.D = privateParams.D; rsaParams.DP = privateParams.DP; rsaParams.DQ = privateParams.DQ; rsaParams.InverseQ = privateParams.InverseQ; rsaParams.P = privateParams.P; rsaParams.Q = privateParams.Q; // BUG: MS BCL 1.0 can't import a key which // isn't the same size as the one present in // the container. int keySize = (rsaParams.Modulus.Length << 3); RSAManaged rsa = new RSAManaged(keySize); rsa.ImportParameters (rsaParams); return (RSA)rsa; } private byte[] getUnsignedBigInteger(byte[] integer) { if (integer [0] == 0x00) { // this first byte is added so we're sure it's an unsigned integer // however we can't feed it into RSAParameters or DSAParameters int length = integer.Length - 1; byte[] uinteger = new byte [length]; Buffer.BlockCopy (integer, 1, uinteger, 0, length); return uinteger; } else { return integer; } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Expressions.Shortcuts; using HandlebarsDotNet.Decorators; using HandlebarsDotNet.Helpers; using HandlebarsDotNet.Helpers.BlockHelpers; using HandlebarsDotNet.PathStructure; using HandlebarsDotNet.Polyfills; using HandlebarsDotNet.Runtime; using static Expressions.Shortcuts.ExpressionShortcuts; namespace HandlebarsDotNet.Compiler { internal enum BlockHelperDirection { Direct, Inverse } internal class BlockHelperFunctionBinder : HandlebarsExpressionVisitor { private readonly List<DecoratorDefinition> _decorators; private CompilationContext CompilationContext { get; } public BlockHelperFunctionBinder(CompilationContext compilationContext, List<DecoratorDefinition> decorators) { _decorators = decorators; CompilationContext = compilationContext; } protected override Expression VisitStatementExpression(StatementExpression sex) { return sex.Body is BlockHelperExpression ? Visit(sex.Body) : sex; } protected override Expression VisitBlockHelperExpression(BlockHelperExpression bhex) { var pathInfo = PathInfoStore.Current.GetOrAdd(bhex.HelperName); var bindingContext = CompilationContext.Args.BindingContext; var direction = bhex.IsRaw || pathInfo.IsBlockHelper ? BlockHelperDirection.Direct : BlockHelperDirection.Inverse; var isDecorator = direction switch { BlockHelperDirection.Direct => bhex.HelperName.StartsWith("#*"), BlockHelperDirection.Inverse => bhex.HelperName.StartsWith("^*"), _ => throw new ArgumentOutOfRangeException() }; if (isDecorator) { _decorators.AddRange(VisitDecoratorBlockExpression(bhex)); return Expression.Empty(); } var readerContext = bhex.Context; var direct = Compile(bhex.Body, out var directDecorators); var inverse = Compile(bhex.Inversion, out var inverseDecorators); var args = FunctionBinderHelpers.CreateArguments(bhex.Arguments, CompilationContext); var context = bindingContext.Property(o => o.Value); var blockParams = CreateBlockParams(); var blockHelpers = CompilationContext.Configuration.BlockHelpers; if (blockHelpers.TryGetValue(pathInfo, out var descriptor)) { return BindByRef(pathInfo, descriptor); } var helperResolvers = CompilationContext.Configuration.HelperResolvers; for (var index = 0; index < helperResolvers.Count; index++) { var resolver = helperResolvers[index]; if (!resolver.TryResolveBlockHelper(pathInfo, out var resolvedDescriptor)) continue; descriptor = new Ref<IHelperDescriptor<BlockHelperOptions>>(resolvedDescriptor); blockHelpers.AddOrReplace(pathInfo, descriptor); return BindByRef(pathInfo, descriptor); } var lateBindBlockHelperDescriptor = new LateBindBlockHelperDescriptor(pathInfo); var lateBindBlockHelperRef = new Ref<IHelperDescriptor<BlockHelperOptions>>(lateBindBlockHelperDescriptor); blockHelpers.AddOrReplace(pathInfo, lateBindBlockHelperRef); return BindByRef(pathInfo, lateBindBlockHelperRef); ExpressionContainer<ChainSegment[]> CreateBlockParams() { var parameters = bhex.BlockParams?.BlockParam?.Parameters; parameters ??= ArrayEx.Empty<ChainSegment>(); return Arg(parameters); } TemplateDelegate Compile(Expression expression, out IReadOnlyList<DecoratorDefinition> decorators) { var blockExpression = (BlockExpression) expression; return FunctionBuilder.Compile(blockExpression.Expressions, CompilationContext, out decorators); } Expression BindByRef(PathInfo name, Ref<IHelperDescriptor<BlockHelperOptions>> helperBox) { switch (direction) { case BlockHelperDirection.Direct when directDecorators.Count > 0: { var helperOptions = direction switch { BlockHelperDirection.Direct => New(() => new BlockHelperOptions(name, direct, inverse, blockParams, bindingContext)), BlockHelperDirection.Inverse => New(() => new BlockHelperOptions(name, inverse, direct, blockParams, bindingContext)), _ => throw new HandlebarsCompilerException("Helper referenced with unknown prefix", readerContext) }; var callContext = New(() => new Context(bindingContext, context)); var writer = CompilationContext.Args.EncodedWriter; var directDecorator = directDecorators.Compile(CompilationContext); var templateDelegate = FunctionBuilder.Compile( new [] { Call(() => helperBox.Value.Invoke(writer, helperOptions, callContext, args)).Expression }, CompilationContext, out _ ); return Call(() => directDecorator.Invoke(writer, bindingContext, templateDelegate)) .Call(f => f.Invoke(writer, bindingContext)); } case BlockHelperDirection.Inverse when inverseDecorators.Count > 0: { var helperOptions = direction switch { BlockHelperDirection.Direct => New(() => new BlockHelperOptions(name, direct, inverse, blockParams, bindingContext)), BlockHelperDirection.Inverse => New(() => new BlockHelperOptions(name, inverse, direct, blockParams, bindingContext)), _ => throw new HandlebarsCompilerException("Helper referenced with unknown prefix", readerContext) }; var callContext = New(() => new Context(bindingContext, context)); var writer = CompilationContext.Args.EncodedWriter; var inverseDecorator = inverseDecorators.Compile(CompilationContext); var templateDelegate = FunctionBuilder.Compile( new [] { Call(() => helperBox.Value.Invoke(writer, helperOptions, callContext, args)).Expression }, CompilationContext, out _ ); return Call(() => inverseDecorator.Invoke(writer, bindingContext, templateDelegate)) .Call(f => f.Invoke(writer, bindingContext)); } default: { var helperOptions = direction switch { BlockHelperDirection.Direct => New(() => new BlockHelperOptions(name, direct, inverse, blockParams, bindingContext)), BlockHelperDirection.Inverse => New(() => new BlockHelperOptions(name, inverse, direct, blockParams, bindingContext)), _ => throw new HandlebarsCompilerException("Helper referenced with unknown prefix", readerContext) }; var callContext = New(() => new Context(bindingContext, context)); var writer = CompilationContext.Args.EncodedWriter; return Call(() => helperBox.Value.Invoke(writer, helperOptions, callContext, args)); } } } } private IEnumerable<DecoratorDefinition> VisitDecoratorBlockExpression(BlockHelperExpression bhex) { var pathInfo = PathInfoStore.Current.GetOrAdd(bhex.HelperName); var bindingContext = CompilationContext.Args.BindingContext; var direction = bhex.IsRaw || pathInfo.IsBlockHelper ? BlockHelperDirection.Direct : BlockHelperDirection.Inverse; if (direction == BlockHelperDirection.Inverse) { throw new HandlebarsCompilerException("^ is not supported for decorators", bhex.Context); } var direct = Compile(bhex.Body, out var decorators); for (var index = 0; index < decorators.Count; index++) { yield return decorators[index]; } var args = FunctionBinderHelpers.CreateArguments(bhex.Arguments, CompilationContext); var context = bindingContext.Property(o => o.Value); var blockParams = CreateBlockParams(); var blockDecorators = CompilationContext.Configuration.BlockDecorators; if (blockDecorators.TryGetValue(pathInfo, out var descriptor)) { var binding = BindDecoratorByRef(pathInfo, descriptor, out var f1); yield return new DecoratorDefinition(binding, f1); yield break; } var emptyBlockDecorator = new EmptyBlockDecorator(pathInfo); var emptyBlockDecoratorRef = new Ref<IDecoratorDescriptor<BlockDecoratorOptions>>(emptyBlockDecorator); blockDecorators.AddOrReplace(pathInfo, emptyBlockDecoratorRef); var emptyBinding = BindDecoratorByRef(pathInfo, emptyBlockDecoratorRef, out var f2); yield return new DecoratorDefinition(emptyBinding, f2); ExpressionContainer<ChainSegment[]> CreateBlockParams() { var parameters = bhex.BlockParams?.BlockParam?.Parameters; parameters ??= ArrayEx.Empty<ChainSegment>(); return Arg(parameters); } TemplateDelegate Compile(Expression expression, out IReadOnlyList<DecoratorDefinition> decorators) { var blockExpression = (BlockExpression) expression; return FunctionBuilder.Compile(blockExpression.Expressions, CompilationContext, out decorators); } Expression BindDecoratorByRef(PathInfo name, Ref<IDecoratorDescriptor<BlockDecoratorOptions>> helperBox, out ExpressionContainer<TemplateDelegate> function) { function = Parameter<TemplateDelegate>(); var f = function; var helperOptions = New(() => new BlockDecoratorOptions(name, direct, blockParams, bindingContext)); var callContext = New(() => new Context(bindingContext, context)); return Call(() => helperBox.Value.Invoke(f, helperOptions, callContext, args)); } } } }
using System.Windows.Forms; namespace SPD.GUI { /// <summary> /// /// </summary> partial class MainForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm)); this.menuStrip = new System.Windows.Forms.MenuStrip(); this.neuerPatientToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.patientSuchenToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.nextActionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.overviewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.printToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.topMostToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.statisticsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.patientsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.sexToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.yearOfBirthToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.weightToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.visitsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.dateOfMissionToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.operationsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.dateOfMissionToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.backupToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.settingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.databaseSettingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemGeneralSettings = new System.Windows.Forms.ToolStripMenuItem(); this.diagnoseGroupSettingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.clearCachesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.importToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.shortcutsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.statusStrip = new System.Windows.Forms.StatusStrip(); this.menuStrip.SuspendLayout(); this.SuspendLayout(); // // menuStrip // this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.neuerPatientToolStripMenuItem, this.patientSuchenToolStripMenuItem, this.nextActionsToolStripMenuItem, this.overviewToolStripMenuItem, this.printToolStripMenuItem, this.topMostToolStripMenuItem, this.statisticsToolStripMenuItem, this.backupToolStripMenuItem, this.settingsToolStripMenuItem, this.importToolStripMenuItem, this.helpToolStripMenuItem}); this.menuStrip.Location = new System.Drawing.Point(0, 0); this.menuStrip.Name = "menuStrip"; this.menuStrip.Size = new System.Drawing.Size(994, 24); this.menuStrip.TabIndex = 0; this.menuStrip.Text = "menuStrip1"; // // neuerPatientToolStripMenuItem // this.neuerPatientToolStripMenuItem.Name = "neuerPatientToolStripMenuItem"; this.neuerPatientToolStripMenuItem.Size = new System.Drawing.Size(77, 20); this.neuerPatientToolStripMenuItem.Text = "&New patient"; this.neuerPatientToolStripMenuItem.Click += new System.EventHandler(this.newPatientToolStripMenuItem_Click); // // patientSuchenToolStripMenuItem // this.patientSuchenToolStripMenuItem.Name = "patientSuchenToolStripMenuItem"; this.patientSuchenToolStripMenuItem.Size = new System.Drawing.Size(76, 20); this.patientSuchenToolStripMenuItem.Text = "&Find Patient"; this.patientSuchenToolStripMenuItem.Click += new System.EventHandler(this.findPatientToolStripMenuItem_Click); // // nextActionsToolStripMenuItem // this.nextActionsToolStripMenuItem.Name = "nextActionsToolStripMenuItem"; this.nextActionsToolStripMenuItem.Size = new System.Drawing.Size(80, 20); this.nextActionsToolStripMenuItem.Text = "Next Actions"; this.nextActionsToolStripMenuItem.Click += new System.EventHandler(this.nextActionsToolStripMenuItem_Click); // // overviewToolStripMenuItem // this.overviewToolStripMenuItem.Name = "overviewToolStripMenuItem"; this.overviewToolStripMenuItem.Size = new System.Drawing.Size(65, 20); this.overviewToolStripMenuItem.Text = "Overview"; this.overviewToolStripMenuItem.Click += new System.EventHandler(this.overviewToolStripMenuItem_Click); // // printToolStripMenuItem // this.printToolStripMenuItem.Name = "printToolStripMenuItem"; this.printToolStripMenuItem.Size = new System.Drawing.Size(41, 20); this.printToolStripMenuItem.Text = "&Print"; this.printToolStripMenuItem.Click += new System.EventHandler(this.printToolStripMenuItem_Click); // // topMostToolStripMenuItem // this.topMostToolStripMenuItem.Name = "topMostToolStripMenuItem"; this.topMostToolStripMenuItem.Size = new System.Drawing.Size(63, 20); this.topMostToolStripMenuItem.Text = "Top &Most"; this.topMostToolStripMenuItem.Click += new System.EventHandler(this.topMostToolStripMenuItem_Click); // // statisticsToolStripMenuItem // this.statisticsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.patientsToolStripMenuItem, this.visitsToolStripMenuItem, this.operationsToolStripMenuItem}); this.statisticsToolStripMenuItem.Name = "statisticsToolStripMenuItem"; this.statisticsToolStripMenuItem.Size = new System.Drawing.Size(62, 20); this.statisticsToolStripMenuItem.Text = "&Statistics"; // // patientsToolStripMenuItem // this.patientsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.sexToolStripMenuItem, this.yearOfBirthToolStripMenuItem, this.weightToolStripMenuItem}); this.patientsToolStripMenuItem.Name = "patientsToolStripMenuItem"; this.patientsToolStripMenuItem.Size = new System.Drawing.Size(127, 22); this.patientsToolStripMenuItem.Text = "&Patients"; // // sexToolStripMenuItem // this.sexToolStripMenuItem.Name = "sexToolStripMenuItem"; this.sexToolStripMenuItem.Size = new System.Drawing.Size(134, 22); this.sexToolStripMenuItem.Text = "Sex"; this.sexToolStripMenuItem.Click += new System.EventHandler(this.sexToolStripMenuItem_Click); // // yearOfBirthToolStripMenuItem // this.yearOfBirthToolStripMenuItem.Name = "yearOfBirthToolStripMenuItem"; this.yearOfBirthToolStripMenuItem.Size = new System.Drawing.Size(134, 22); this.yearOfBirthToolStripMenuItem.Text = "Year of Birth"; this.yearOfBirthToolStripMenuItem.Click += new System.EventHandler(this.yearOfBirthToolStripMenuItem_Click); // // weightToolStripMenuItem // this.weightToolStripMenuItem.Name = "weightToolStripMenuItem"; this.weightToolStripMenuItem.Size = new System.Drawing.Size(134, 22); this.weightToolStripMenuItem.Text = "Weight"; this.weightToolStripMenuItem.Click += new System.EventHandler(this.weightToolStripMenuItem_Click); // // visitsToolStripMenuItem // this.visitsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.dateOfMissionToolStripMenuItem}); this.visitsToolStripMenuItem.Name = "visitsToolStripMenuItem"; this.visitsToolStripMenuItem.Size = new System.Drawing.Size(127, 22); this.visitsToolStripMenuItem.Text = "&Visits"; // // dateOfMissionToolStripMenuItem // this.dateOfMissionToolStripMenuItem.Name = "dateOfMissionToolStripMenuItem"; this.dateOfMissionToolStripMenuItem.Size = new System.Drawing.Size(147, 22); this.dateOfMissionToolStripMenuItem.Text = "Date of mission"; this.dateOfMissionToolStripMenuItem.Click += new System.EventHandler(this.dateOfMissionToolStripMenuItem_Click); // // operationsToolStripMenuItem // this.operationsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.dateOfMissionToolStripMenuItem1}); this.operationsToolStripMenuItem.Name = "operationsToolStripMenuItem"; this.operationsToolStripMenuItem.Size = new System.Drawing.Size(127, 22); this.operationsToolStripMenuItem.Text = "&Operations"; // // dateOfMissionToolStripMenuItem1 // this.dateOfMissionToolStripMenuItem1.Name = "dateOfMissionToolStripMenuItem1"; this.dateOfMissionToolStripMenuItem1.Size = new System.Drawing.Size(147, 22); this.dateOfMissionToolStripMenuItem1.Text = "Date of mission"; this.dateOfMissionToolStripMenuItem1.Click += new System.EventHandler(this.dateOfMissionToolStripMenuItem1_Click); // // backupToolStripMenuItem // this.backupToolStripMenuItem.Name = "backupToolStripMenuItem"; this.backupToolStripMenuItem.Size = new System.Drawing.Size(53, 20); this.backupToolStripMenuItem.Text = "&Backup"; this.backupToolStripMenuItem.Click += new System.EventHandler(this.backupToolStripMenuItem_Click); // // settingsToolStripMenuItem // this.settingsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.databaseSettingsToolStripMenuItem, this.toolStripMenuItemGeneralSettings, this.diagnoseGroupSettingsToolStripMenuItem, this.clearCachesToolStripMenuItem}); this.settingsToolStripMenuItem.Name = "settingsToolStripMenuItem"; this.settingsToolStripMenuItem.Size = new System.Drawing.Size(58, 20); this.settingsToolStripMenuItem.Text = "Settings"; // // databaseSettingsToolStripMenuItem // this.databaseSettingsToolStripMenuItem.Name = "databaseSettingsToolStripMenuItem"; this.databaseSettingsToolStripMenuItem.Size = new System.Drawing.Size(192, 22); this.databaseSettingsToolStripMenuItem.Text = "Database Settings"; this.databaseSettingsToolStripMenuItem.Click += new System.EventHandler(this.databaseSettingsToolStripMenuItem_Click); // // toolStripMenuItemGeneralSettings // this.toolStripMenuItemGeneralSettings.Name = "toolStripMenuItemGeneralSettings"; this.toolStripMenuItemGeneralSettings.Size = new System.Drawing.Size(192, 22); this.toolStripMenuItemGeneralSettings.Text = "General Settings"; this.toolStripMenuItemGeneralSettings.Click += new System.EventHandler(this.toolStripMenuItemGeneralSettings_Click); // // diagnoseGroupSettingsToolStripMenuItem // this.diagnoseGroupSettingsToolStripMenuItem.Name = "diagnoseGroupSettingsToolStripMenuItem"; this.diagnoseGroupSettingsToolStripMenuItem.Size = new System.Drawing.Size(192, 22); this.diagnoseGroupSettingsToolStripMenuItem.Text = "Diagnose Group Settings"; this.diagnoseGroupSettingsToolStripMenuItem.Click += new System.EventHandler(this.diagnoseGroupSettingsToolStripMenuItem_Click); // // clearCachesToolStripMenuItem // this.clearCachesToolStripMenuItem.Name = "clearCachesToolStripMenuItem"; this.clearCachesToolStripMenuItem.Size = new System.Drawing.Size(192, 22); this.clearCachesToolStripMenuItem.Text = "Clear Caches"; this.clearCachesToolStripMenuItem.Click += new System.EventHandler(this.clearCachesToolStripMenuItem_Click); // // importToolStripMenuItem // this.importToolStripMenuItem.Name = "importToolStripMenuItem"; this.importToolStripMenuItem.Size = new System.Drawing.Size(51, 20); this.importToolStripMenuItem.Text = "Import"; this.importToolStripMenuItem.Click += new System.EventHandler(this.importToolStripMenuItem_Click); // // helpToolStripMenuItem // this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.shortcutsToolStripMenuItem, this.aboutToolStripMenuItem}); this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; this.helpToolStripMenuItem.Size = new System.Drawing.Size(24, 20); this.helpToolStripMenuItem.Text = "&?"; // // shortcutsToolStripMenuItem // this.shortcutsToolStripMenuItem.Name = "shortcutsToolStripMenuItem"; this.shortcutsToolStripMenuItem.Size = new System.Drawing.Size(120, 22); this.shortcutsToolStripMenuItem.Text = "&Shortcuts"; this.shortcutsToolStripMenuItem.Click += new System.EventHandler(this.shortcutsToolStripMenuItem_Click); // // aboutToolStripMenuItem // this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem"; this.aboutToolStripMenuItem.Size = new System.Drawing.Size(120, 22); this.aboutToolStripMenuItem.Text = "&About"; this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click); // // statusStrip // this.statusStrip.Location = new System.Drawing.Point(0, 739); this.statusStrip.Name = "statusStrip"; this.statusStrip.Size = new System.Drawing.Size(735, 22); this.statusStrip.TabIndex = 1; this.statusStrip.Text = "statusStrip1"; this.statusStrip.Visible = false; // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(994, 761); this.Controls.Add(this.statusStrip); this.Controls.Add(this.menuStrip); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MainMenuStrip = this.menuStrip; this.Name = "MainForm"; this.Text = "SPD Patient Documentation"; this.menuStrip.ResumeLayout(false); this.menuStrip.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private MenuStrip menuStrip; private ToolStripMenuItem neuerPatientToolStripMenuItem; private ToolStripMenuItem patientSuchenToolStripMenuItem; private ToolStripMenuItem helpToolStripMenuItem; private ToolStripMenuItem aboutToolStripMenuItem; private ToolStripMenuItem topMostToolStripMenuItem; private ToolStripMenuItem printToolStripMenuItem; private ToolStripMenuItem shortcutsToolStripMenuItem; private ToolStripMenuItem statisticsToolStripMenuItem; private ToolStripMenuItem patientsToolStripMenuItem; private ToolStripMenuItem sexToolStripMenuItem; private ToolStripMenuItem yearOfBirthToolStripMenuItem; private ToolStripMenuItem weightToolStripMenuItem; private ToolStripMenuItem visitsToolStripMenuItem; private ToolStripMenuItem operationsToolStripMenuItem; private ToolStripMenuItem dateOfMissionToolStripMenuItem; private ToolStripMenuItem dateOfMissionToolStripMenuItem1; private ToolStripMenuItem backupToolStripMenuItem; private ToolStripMenuItem nextActionsToolStripMenuItem; private ToolStripMenuItem settingsToolStripMenuItem; private ToolStripMenuItem databaseSettingsToolStripMenuItem; private System.Windows.Forms.StatusStrip statusStrip; private ToolStripMenuItem toolStripMenuItemGeneralSettings; private ToolStripMenuItem importToolStripMenuItem; private ToolStripMenuItem diagnoseGroupSettingsToolStripMenuItem; private ToolStripMenuItem clearCachesToolStripMenuItem; private ToolStripMenuItem overviewToolStripMenuItem; } }
// Generated by ProtoGen, Version=2.4.1.555, Culture=neutral, PublicKeyToken=55f7125234beb589. DO NOT EDIT! #pragma warning disable 1591, 0612, 3021 #region Designer generated code <<<<<<< Updated upstream // Generated from: ManagementCommand.proto namespace Alachisoft.NosDB.Common.Protobuf.ManagementCommands { [global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"ManagementCommand")] public partial class ManagementCommand : global::ProtoBuf.IExtensible { public ManagementCommand() {} ======= using pb = global::Google.ProtocolBuffers; using pbc = global::Google.ProtocolBuffers.Collections; using pbd = global::Google.ProtocolBuffers.Descriptors; using scg = global::System.Collections.Generic; namespace Alachisoft.NoSDB.Common.Protobuf.ManagementCommands { namespace Proto { >>>>>>> Stashed changes [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class ManagementCommand { #region Extension registration public static void RegisterAllExtensions(pb::ExtensionRegistry registry) { } #endregion #region Static variables internal static pbd::MessageDescriptor internal__static_Alachisoft_NoSDB_Common_Protobuf_ManagementCommands_ManagementCommand__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementCommand, global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementCommand.Builder> internal__static_Alachisoft_NoSDB_Common_Protobuf_ManagementCommands_ManagementCommand__FieldAccessorTable; #endregion #region Descriptor public static pbd::FileDescriptor Descriptor { get { return descriptor; } } private static pbd::FileDescriptor descriptor; static ManagementCommand() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "ChdNYW5hZ2VtZW50Q29tbWFuZC5wcm90bxIzQWxhY2hpc29mdC5Ob1NEQi5D", "b21tb24uUHJvdG9idWYuTWFuYWdlbWVudENvbW1hbmRzIqMCChFNYW5hZ2Vt", "ZW50Q29tbWFuZBIRCglyZXF1ZXN0SWQYASABKAMSGQoOY29tbWFuZFZlcnNp", "b24YAiABKAU6ATASEgoKbWV0aG9kTmFtZRgDIAEoCRIQCghvdmVybG9hZBgE", "IAEoBRIRCglhcmd1bWVudHMYBSABKAwSEgoKb2JqZWN0TmFtZRgGIAEoCRJh", "CgZzb3VyY2UYByABKA4yUS5BbGFjaGlzb2Z0Lk5vU0RCLkNvbW1vbi5Qcm90", "b2J1Zi5NYW5hZ2VtZW50Q29tbWFuZHMuTWFuYWdlbWVudENvbW1hbmQuU291", "cmNlVHlwZSIwCgpTb3VyY2VUeXBlEgoKBkNMSUVOVBABEgkKBVNIQVJEEAIS", "CwoHTU9OSVRPUhADQkMKJGNvbS5hbGFjaGlzb2Z0Lm5vc2RiLmNvbW1vbi5w", "cm90b2J1ZkIbTkNNYW5hZ2VtZW50Q29tbWFuZFByb3RvY29s")); pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) { descriptor = root; internal__static_Alachisoft_NoSDB_Common_Protobuf_ManagementCommands_ManagementCommand__Descriptor = Descriptor.MessageTypes[0]; internal__static_Alachisoft_NoSDB_Common_Protobuf_ManagementCommands_ManagementCommand__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementCommand, global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementCommand.Builder>(internal__static_Alachisoft_NoSDB_Common_Protobuf_ManagementCommands_ManagementCommand__Descriptor, new string[] { "RequestId", "CommandVersion", "MethodName", "Overload", "Arguments", "ObjectName", "Source", }); return null; }; pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbd::FileDescriptor[] { }, assigner); } #endregion } } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class ManagementCommand : pb::GeneratedMessage<ManagementCommand, ManagementCommand.Builder> { private ManagementCommand() { } private static readonly ManagementCommand defaultInstance = new ManagementCommand().MakeReadOnly(); private static readonly string[] _managementCommandFieldNames = new string[] { "arguments", "commandVersion", "methodName", "objectName", "overload", "requestId", "source" }; private static readonly uint[] _managementCommandFieldTags = new uint[] { 42, 16, 26, 50, 32, 8, 56 }; public static ManagementCommand DefaultInstance { get { return defaultInstance; } } public override ManagementCommand DefaultInstanceForType { get { return DefaultInstance; } } protected override ManagementCommand ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.Proto.ManagementCommand.internal__static_Alachisoft_NoSDB_Common_Protobuf_ManagementCommands_ManagementCommand__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<ManagementCommand, ManagementCommand.Builder> InternalFieldAccessors { get { return global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.Proto.ManagementCommand.internal__static_Alachisoft_NoSDB_Common_Protobuf_ManagementCommands_ManagementCommand__FieldAccessorTable; } } <<<<<<< Updated upstream private Alachisoft.NosDB.Common.Protobuf.ManagementCommands.ManagementCommand.SourceType _source = Alachisoft.NosDB.Common.Protobuf.ManagementCommands.ManagementCommand.SourceType.CLIENT; [global::ProtoBuf.ProtoMember(7, IsRequired = false, Name=@"source", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)] [global::System.ComponentModel.DefaultValue(Alachisoft.NosDB.Common.Protobuf.ManagementCommands.ManagementCommand.SourceType.CLIENT)] public Alachisoft.NosDB.Common.Protobuf.ManagementCommands.ManagementCommand.SourceType source { get { return _source; } set { _source = value; } } [global::ProtoBuf.ProtoContract(Name=@"SourceType")] public enum SourceType { [global::ProtoBuf.ProtoEnum(Name=@"CLIENT", Value=1)] CLIENT = 1, [global::ProtoBuf.ProtoEnum(Name=@"SHARD", Value=2)] SHARD = 2, [global::ProtoBuf.ProtoEnum(Name=@"MONITOR", Value=3)] MONITOR = 3 ======= #region Nested types [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Types { public enum SourceType { CLIENT = 1, SHARD = 2, MONITOR = 3, } } #endregion public const int RequestIdFieldNumber = 1; private bool hasRequestId; private long requestId_; public bool HasRequestId { get { return hasRequestId; } } public long RequestId { get { return requestId_; } } public const int CommandVersionFieldNumber = 2; private bool hasCommandVersion; private int commandVersion_; public bool HasCommandVersion { get { return hasCommandVersion; } } public int CommandVersion { get { return commandVersion_; } } public const int MethodNameFieldNumber = 3; private bool hasMethodName; private string methodName_ = ""; public bool HasMethodName { get { return hasMethodName; } } public string MethodName { get { return methodName_; } } public const int OverloadFieldNumber = 4; private bool hasOverload; private int overload_; public bool HasOverload { get { return hasOverload; } } public int Overload { get { return overload_; } } public const int ArgumentsFieldNumber = 5; private bool hasArguments; private pb::ByteString arguments_ = pb::ByteString.Empty; public bool HasArguments { get { return hasArguments; } } public pb::ByteString Arguments { get { return arguments_; } } public const int ObjectNameFieldNumber = 6; private bool hasObjectName; private string objectName_ = ""; public bool HasObjectName { get { return hasObjectName; } } public string ObjectName { get { return objectName_; } } public const int SourceFieldNumber = 7; private bool hasSource; private global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementCommand.Types.SourceType source_ = global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementCommand.Types.SourceType.CLIENT; public bool HasSource { get { return hasSource; } } public global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementCommand.Types.SourceType Source { get { return source_; } } public override bool IsInitialized { get { return true; } } public override void WriteTo(pb::ICodedOutputStream output) { CalcSerializedSize(); string[] field_names = _managementCommandFieldNames; if (hasRequestId) { output.WriteInt64(1, field_names[5], RequestId); } if (hasCommandVersion) { output.WriteInt32(2, field_names[1], CommandVersion); } if (hasMethodName) { output.WriteString(3, field_names[2], MethodName); } if (hasOverload) { output.WriteInt32(4, field_names[4], Overload); } if (hasArguments) { output.WriteBytes(5, field_names[0], Arguments); } if (hasObjectName) { output.WriteString(6, field_names[3], ObjectName); } if (hasSource) { output.WriteEnum(7, field_names[6], (int) Source, Source); } UnknownFields.WriteTo(output); } private int memoizedSerializedSize = -1; public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; return CalcSerializedSize(); } } private int CalcSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasRequestId) { size += pb::CodedOutputStream.ComputeInt64Size(1, RequestId); } if (hasCommandVersion) { size += pb::CodedOutputStream.ComputeInt32Size(2, CommandVersion); } if (hasMethodName) { size += pb::CodedOutputStream.ComputeStringSize(3, MethodName); } if (hasOverload) { size += pb::CodedOutputStream.ComputeInt32Size(4, Overload); } if (hasArguments) { size += pb::CodedOutputStream.ComputeBytesSize(5, Arguments); } if (hasObjectName) { size += pb::CodedOutputStream.ComputeStringSize(6, ObjectName); } if (hasSource) { size += pb::CodedOutputStream.ComputeEnumSize(7, (int) Source); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } public static ManagementCommand ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static ManagementCommand ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static ManagementCommand ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static ManagementCommand ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static ManagementCommand ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static ManagementCommand ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static ManagementCommand ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static ManagementCommand ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static ManagementCommand ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static ManagementCommand ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private ManagementCommand MakeReadOnly() { return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(ManagementCommand prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<ManagementCommand, Builder> { protected override Builder ThisBuilder { get { return this; } } public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(ManagementCommand cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } private bool resultIsReadOnly; private ManagementCommand result; private ManagementCommand PrepareBuilder() { if (resultIsReadOnly) { ManagementCommand original = result; result = new ManagementCommand(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override bool IsInitialized { get { return result.IsInitialized; } } protected override ManagementCommand MessageBeingBuilt { get { return PrepareBuilder(); } } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override pbd::MessageDescriptor DescriptorForType { get { return global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementCommand.Descriptor; } } public override ManagementCommand DefaultInstanceForType { get { return global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementCommand.DefaultInstance; } } public override ManagementCommand BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is ManagementCommand) { return MergeFrom((ManagementCommand) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(ManagementCommand other) { if (other == global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementCommand.DefaultInstance) return this; PrepareBuilder(); if (other.HasRequestId) { RequestId = other.RequestId; } if (other.HasCommandVersion) { CommandVersion = other.CommandVersion; } if (other.HasMethodName) { MethodName = other.MethodName; } if (other.HasOverload) { Overload = other.Overload; } if (other.HasArguments) { Arguments = other.Arguments; } if (other.HasObjectName) { ObjectName = other.ObjectName; } if (other.HasSource) { Source = other.Source; } this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if(tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_managementCommandFieldNames, field_name, global::System.StringComparer.Ordinal); if(field_ordinal >= 0) tag = _managementCommandFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } case 8: { result.hasRequestId = input.ReadInt64(ref result.requestId_); break; } case 16: { result.hasCommandVersion = input.ReadInt32(ref result.commandVersion_); break; } case 26: { result.hasMethodName = input.ReadString(ref result.methodName_); break; } case 32: { result.hasOverload = input.ReadInt32(ref result.overload_); break; } case 42: { result.hasArguments = input.ReadBytes(ref result.arguments_); break; } case 50: { result.hasObjectName = input.ReadString(ref result.objectName_); break; } case 56: { object unknown; if(input.ReadEnum(ref result.source_, out unknown)) { result.hasSource = true; } else if(unknown is int) { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } unknownFields.MergeVarintField(7, (ulong)(int)unknown); } break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public bool HasRequestId { get { return result.hasRequestId; } } public long RequestId { get { return result.RequestId; } set { SetRequestId(value); } } public Builder SetRequestId(long value) { PrepareBuilder(); result.hasRequestId = true; result.requestId_ = value; return this; } public Builder ClearRequestId() { PrepareBuilder(); result.hasRequestId = false; result.requestId_ = 0L; return this; } public bool HasCommandVersion { get { return result.hasCommandVersion; } } public int CommandVersion { get { return result.CommandVersion; } set { SetCommandVersion(value); } } public Builder SetCommandVersion(int value) { PrepareBuilder(); result.hasCommandVersion = true; result.commandVersion_ = value; return this; } public Builder ClearCommandVersion() { PrepareBuilder(); result.hasCommandVersion = false; result.commandVersion_ = 0; return this; } public bool HasMethodName { get { return result.hasMethodName; } } public string MethodName { get { return result.MethodName; } set { SetMethodName(value); } } public Builder SetMethodName(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasMethodName = true; result.methodName_ = value; return this; } public Builder ClearMethodName() { PrepareBuilder(); result.hasMethodName = false; result.methodName_ = ""; return this; } public bool HasOverload { get { return result.hasOverload; } } public int Overload { get { return result.Overload; } set { SetOverload(value); } } public Builder SetOverload(int value) { PrepareBuilder(); result.hasOverload = true; result.overload_ = value; return this; } public Builder ClearOverload() { PrepareBuilder(); result.hasOverload = false; result.overload_ = 0; return this; } public bool HasArguments { get { return result.hasArguments; } } public pb::ByteString Arguments { get { return result.Arguments; } set { SetArguments(value); } } public Builder SetArguments(pb::ByteString value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasArguments = true; result.arguments_ = value; return this; } public Builder ClearArguments() { PrepareBuilder(); result.hasArguments = false; result.arguments_ = pb::ByteString.Empty; return this; } public bool HasObjectName { get { return result.hasObjectName; } } public string ObjectName { get { return result.ObjectName; } set { SetObjectName(value); } } public Builder SetObjectName(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasObjectName = true; result.objectName_ = value; return this; } public Builder ClearObjectName() { PrepareBuilder(); result.hasObjectName = false; result.objectName_ = ""; return this; } public bool HasSource { get { return result.hasSource; } } public global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementCommand.Types.SourceType Source { get { return result.Source; } set { SetSource(value); } } public Builder SetSource(global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementCommand.Types.SourceType value) { PrepareBuilder(); result.hasSource = true; result.source_ = value; return this; } public Builder ClearSource() { PrepareBuilder(); result.hasSource = false; result.source_ = global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.ManagementCommand.Types.SourceType.CLIENT; return this; } } static ManagementCommand() { object.ReferenceEquals(global::Alachisoft.NoSDB.Common.Protobuf.ManagementCommands.Proto.ManagementCommand.Descriptor, null); >>>>>>> Stashed changes } } #endregion } #endregion Designer generated code
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Azure.Messaging.EventHubs.Diagnostics; using Azure.Messaging.EventHubs.Tests; using Moq; using NUnit.Framework; namespace Azure.Messaging.EventHubs.Primitives.Tests { /// <summary> /// The suite of tests for the <see cref="PartitionLoadBalancer" /> /// class. /// </summary> /// [TestFixture] public class PartitionLoadBalancerTests { private const string FullyQualifiedNamespace = "fqns"; private const string EventHubName = "name"; private const string ConsumerGroup = "consumerGroup"; /// <summary> /// Verifies that partitions owned by a <see cref="PartitionLoadBalancer" /> are immediately available to be claimed by another loadbalancer /// after StopAsync is called. /// </summary> /// [Test] public async Task RelinquishOwnershipAsyncRelinquishesPartitionOwnershipOtherClientsConsiderThemClaimableImmediately() { const int NumberOfPartitions = 3; var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); var loadbalancer1 = new PartitionLoadBalancer( storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1)); var loadbalancer2 = new PartitionLoadBalancer( storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1)); // Ownership should start empty. var completeOwnership = await storageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); Assert.That(completeOwnership.Count(), Is.EqualTo(0)); // Start the load balancer so that it claims a random partition until none are left. for (int i = 0; i < NumberOfPartitions; i++) { await loadbalancer1.RunLoadBalancingAsync(partitionIds, CancellationToken.None); } completeOwnership = await storageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); // All partitions are owned by loadbalancer1. Assert.That(completeOwnership.Count(p => p.OwnerIdentifier.Equals(loadbalancer1.OwnerIdentifier)), Is.EqualTo(NumberOfPartitions)); // Stopping the load balancer should relinquish all partition ownership. await loadbalancer1.RelinquishOwnershipAsync(CancellationToken.None); completeOwnership = await storageManager.ListOwnershipAsync(loadbalancer1.FullyQualifiedNamespace, loadbalancer1.EventHubName, loadbalancer1.ConsumerGroup); // No partitions are owned by loadbalancer1. Assert.That(completeOwnership.Count(p => p.OwnerIdentifier.Equals(loadbalancer1.OwnerIdentifier)), Is.EqualTo(0)); // Start loadbalancer2 so that the load balancer claims a random partition until none are left. // All partitions should be immediately claimable even though they were just claimed by the loadbalancer1. for (int i = 0; i < NumberOfPartitions; i++) { await loadbalancer2.RunLoadBalancingAsync(partitionIds, CancellationToken.None); } completeOwnership = await storageManager.ListOwnershipAsync(loadbalancer1.FullyQualifiedNamespace, loadbalancer1.EventHubName, loadbalancer1.ConsumerGroup); // All partitions are owned by loadbalancer2. Assert.That(completeOwnership.Count(p => p.OwnerIdentifier.Equals(loadbalancer2.OwnerIdentifier)), Is.EqualTo(NumberOfPartitions)); } /// <summary> /// Verifies that claimable partitions are claimed by a <see cref="PartitionLoadBalancer" /> after RunAsync is called. /// </summary> /// [Test] public async Task RunLoadBalancingAsyncClaimsAllClaimablePartitions() { const int NumberOfPartitions = 3; var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); var loadbalancer = new PartitionLoadBalancer( storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1)); // Ownership should start empty. var completeOwnership = await storageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); Assert.That(completeOwnership.Count(), Is.EqualTo(0)); // Start the load balancer so that it claims a random partition until none are left. for (int i = 0; i < NumberOfPartitions; i++) { await loadbalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); } completeOwnership = await storageManager.ListOwnershipAsync(FullyQualifiedNamespace, EventHubName, ConsumerGroup); // All partitions are owned by load balancer. Assert.That(completeOwnership.Count(), Is.EqualTo(NumberOfPartitions)); } /// <summary> /// Verifies that partitions ownership load balancing will direct a <see cref="PartitionLoadBalancer" /> to claim ownership of a claimable partition /// when it owns exactly the calculated MinimumOwnedPartitionsCount. /// </summary> /// [Test] public async Task RunLoadBalancingAsyncClaimsPartitionsWhenOwnedEqualsMinimumOwnedPartitionsCount() { const int MinimumpartitionCount = 4; const int NumberOfPartitions = 13; var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); var loadbalancer = new PartitionLoadBalancer( storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1)); // Create partitions owned by this load balancer. var loadbalancer1PartitionIds = Enumerable.Range(1, MinimumpartitionCount); var completeOwnership = CreatePartitionOwnership(loadbalancer1PartitionIds.Select(i => i.ToString()), loadbalancer.OwnerIdentifier); // Create partitions owned by a different load balancer. var loadbalancer2Id = Guid.NewGuid().ToString(); var loadbalancer2PartitionIds = Enumerable.Range(loadbalancer1PartitionIds.Max() + 1, MinimumpartitionCount); completeOwnership = completeOwnership .Concat(CreatePartitionOwnership(loadbalancer2PartitionIds.Select(i => i.ToString()), loadbalancer2Id)); // Create partitions owned by a different load balancer. var loadbalancer3Id = Guid.NewGuid().ToString(); var loadbalancer3PartitionIds = Enumerable.Range(loadbalancer2PartitionIds.Max() + 1, MinimumpartitionCount); completeOwnership = completeOwnership .Concat(CreatePartitionOwnership(loadbalancer3PartitionIds.Select(i => i.ToString()), loadbalancer3Id)); // Seed the storageManager with all partitions. await storageManager.ClaimOwnershipAsync(completeOwnership); var claimablePartitionIds = partitionIds.Except(completeOwnership.Select(p => p.PartitionId)); // Get owned partitions. var totalOwnedPartitions = await storageManager.ListOwnershipAsync(loadbalancer.FullyQualifiedNamespace, loadbalancer.EventHubName, loadbalancer.ConsumerGroup); var ownedByloadbalancer1 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer.OwnerIdentifier); // Verify owned partitionIds match the owned partitions. Assert.That(ownedByloadbalancer1.Count(), Is.EqualTo(MinimumpartitionCount)); Assert.That(ownedByloadbalancer1.Any(owned => claimablePartitionIds.Contains(owned.PartitionId)), Is.False); // Start the load balancer to claim ownership from of a Partition even though ownedPartitionCount == MinimumOwnedPartitionsCount. await loadbalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); // Get owned partitions. totalOwnedPartitions = await storageManager.ListOwnershipAsync(loadbalancer.FullyQualifiedNamespace, loadbalancer.EventHubName, loadbalancer.ConsumerGroup); ownedByloadbalancer1 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer.OwnerIdentifier); // Verify that we took ownership of the additional partition. Assert.That(ownedByloadbalancer1.Count(), Is.GreaterThan(MinimumpartitionCount)); Assert.That(ownedByloadbalancer1.Any(owned => claimablePartitionIds.Contains(owned.PartitionId)), Is.True); } /// <summary> /// Verifies that partitions ownership load balancing will direct a <see cref="PartitionLoadBalancer" /> steal ownership of a partition /// from another <see cref="PartitionLoadBalancer" /> the other load balancer owns greater than the calculated MaximumOwnedPartitionsCount. /// </summary> /// [Test] public async Task RunLoadBalancingAsyncStealsPartitionsWhenThisLoadbalancerOwnsMinPartitionsAndOtherLoadbalancerOwnsGreatherThanMaxPartitions() { const int MinimumpartitionCount = 4; const int MaximumpartitionCount = 5; const int NumberOfPartitions = 14; var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); var loadbalancer = new PartitionLoadBalancer( storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1)); // Create partitions owned by this load balancer. var loadbalancer1PartitionIds = Enumerable.Range(1, MinimumpartitionCount); var completeOwnership = CreatePartitionOwnership(loadbalancer1PartitionIds.Select(i => i.ToString()), loadbalancer.OwnerIdentifier); // Create partitions owned by a different load balancer. var loadbalancer2Id = Guid.NewGuid().ToString(); var loadbalancer2PartitionIds = Enumerable.Range(loadbalancer1PartitionIds.Max() + 1, MinimumpartitionCount); completeOwnership = completeOwnership .Concat(CreatePartitionOwnership(loadbalancer2PartitionIds.Select(i => i.ToString()), loadbalancer2Id)); // Create partitions owned by a different load balancer above the MaximumPartitionCount. var loadbalancer3Id = Guid.NewGuid().ToString(); var stealablePartitionIds = Enumerable.Range(loadbalancer2PartitionIds.Max() + 1, MaximumpartitionCount + 1); completeOwnership = completeOwnership .Concat(CreatePartitionOwnership(stealablePartitionIds.Select(i => i.ToString()), loadbalancer3Id)); // Seed the storageManager with the owned partitions. await storageManager.ClaimOwnershipAsync(completeOwnership); // Get owned partitions. var totalOwnedPartitions = await storageManager.ListOwnershipAsync(loadbalancer.FullyQualifiedNamespace, loadbalancer.EventHubName, loadbalancer.ConsumerGroup); var ownedByloadbalancer1 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer.OwnerIdentifier); var ownedByloadbalancer3 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer3Id); // Verify owned partitionIds match the owned partitions. Assert.That(ownedByloadbalancer1.Any(owned => stealablePartitionIds.Contains(int.Parse(owned.PartitionId))), Is.False); // Verify load balancer 3 has stealable partitions. Assert.That(ownedByloadbalancer3.Count(), Is.GreaterThan(MaximumpartitionCount)); // Start the load balancer to steal ownership from of a when ownedPartitionCount == MinimumOwnedPartitionsCount but a loadbalancer owns > MaximumPartitionCount. await loadbalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); // Get owned partitions. totalOwnedPartitions = await storageManager.ListOwnershipAsync(loadbalancer.FullyQualifiedNamespace, loadbalancer.EventHubName, loadbalancer.ConsumerGroup); ownedByloadbalancer1 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer.OwnerIdentifier); ownedByloadbalancer3 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer3Id); // Verify that we took ownership of the additional partition. Assert.That(ownedByloadbalancer1.Any(owned => stealablePartitionIds.Contains(int.Parse(owned.PartitionId))), Is.True); // Verify load balancer 3 now does not own > MaximumPartitionCount. Assert.That(ownedByloadbalancer3.Count(), Is.EqualTo(MaximumpartitionCount)); } /// <summary> /// Verifies that partitions ownership load balancing will direct a <see cref="PartitionLoadBalancer" /> steal ownership of a partition /// from another <see cref="PartitionLoadBalancer" /> the other load balancer owns exactly the calculated MaximumOwnedPartitionsCount. /// </summary> /// [Test] public async Task RunLoadBalancingAsyncStealsPartitionsWhenThisLoadbalancerOwnsLessThanMinPartitionsAndOtherLoadbalancerOwnsMaxPartitions() { const int MinimumpartitionCount = 4; const int MaximumpartitionCount = 5; const int NumberOfPartitions = 12; var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); var loadbalancer = new PartitionLoadBalancer( storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1)); // Create more partitions owned by this load balancer. var loadbalancer1PartitionIds = Enumerable.Range(1, MinimumpartitionCount - 1); var completeOwnership = CreatePartitionOwnership(loadbalancer1PartitionIds.Select(i => i.ToString()), loadbalancer.OwnerIdentifier); // Create more partitions owned by a different load balancer. var loadbalancer2Id = Guid.NewGuid().ToString(); var loadbalancer2PartitionIds = Enumerable.Range(loadbalancer1PartitionIds.Max() + 1, MinimumpartitionCount); completeOwnership = completeOwnership .Concat(CreatePartitionOwnership(loadbalancer2PartitionIds.Select(i => i.ToString()), loadbalancer2Id)); // Create more partitions owned by a different load balancer above the MaximumPartitionCount. var loadbalancer3Id = Guid.NewGuid().ToString(); var stealablePartitionIds = Enumerable.Range(loadbalancer2PartitionIds.Max() + 1, MaximumpartitionCount); completeOwnership = completeOwnership .Concat(CreatePartitionOwnership(stealablePartitionIds.Select(i => i.ToString()), loadbalancer3Id)); // Seed the storageManager with the owned partitions. await storageManager.ClaimOwnershipAsync(completeOwnership); // Get owned partitions. var totalOwnedPartitions = await storageManager.ListOwnershipAsync(loadbalancer.FullyQualifiedNamespace, loadbalancer.EventHubName, loadbalancer.ConsumerGroup); var ownedByloadbalancer1 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer.OwnerIdentifier); var ownedByloadbalancer3 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer3Id); // Verify owned partitionIds match the owned partitions. Assert.That(ownedByloadbalancer1.Any(owned => stealablePartitionIds.Contains(int.Parse(owned.PartitionId))), Is.False); // Verify load balancer 3 has stealable partitions. Assert.That(ownedByloadbalancer3.Count(), Is.EqualTo(MaximumpartitionCount)); // Start the load balancer to steal ownership from of a when ownedPartitionCount == MinimumOwnedPartitionsCount but a load balancer owns > MaximumPartitionCount. await loadbalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); // Get owned partitions. totalOwnedPartitions = await storageManager.ListOwnershipAsync(loadbalancer.FullyQualifiedNamespace, loadbalancer.EventHubName, loadbalancer.ConsumerGroup); ownedByloadbalancer1 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer.OwnerIdentifier); ownedByloadbalancer3 = totalOwnedPartitions.Where(p => p.OwnerIdentifier == loadbalancer3Id); // Verify that we took ownership of the additional partition. Assert.That(ownedByloadbalancer1.Any(owned => stealablePartitionIds.Contains(int.Parse(owned.PartitionId))), Is.True); // Verify load balancer 3 now does not own > MaximumPartitionCount. Assert.That(ownedByloadbalancer3.Count(), Is.LessThan(MaximumpartitionCount)); } /// <summary> /// Verify logs for the <see cref="PartitionLoadBalancer" />. /// </summary> /// [Test] public async Task VerifiesEventProcessorLogs() { const int NumberOfPartitions = 4; const int MinimumpartitionCount = NumberOfPartitions / 2; var partitionIds = Enumerable.Range(1, NumberOfPartitions).Select(p => p.ToString()).ToArray(); var storageManager = new InMemoryStorageManager((s) => Console.WriteLine(s)); var loadbalancer = new PartitionLoadBalancer( storageManager, Guid.NewGuid().ToString(), ConsumerGroup, FullyQualifiedNamespace, EventHubName, TimeSpan.FromMinutes(1)); // Create more partitions owned by a different load balancer. var loadbalancer2Id = Guid.NewGuid().ToString(); var completeOwnership = CreatePartitionOwnership(partitionIds.Skip(1), loadbalancer2Id); // Seed the storageManager with the owned partitions. await storageManager.ClaimOwnershipAsync(completeOwnership); var mockLog = new Mock<PartitionLoadBalancerEventSource>(); loadbalancer.Logger = mockLog.Object; for (int i = 0; i < NumberOfPartitions; i++) { await loadbalancer.RunLoadBalancingAsync(partitionIds, CancellationToken.None); } await loadbalancer.RelinquishOwnershipAsync(CancellationToken.None); mockLog.Verify(m => m.RenewOwnershipStart(loadbalancer.OwnerIdentifier)); mockLog.Verify(m => m.RenewOwnershipComplete(loadbalancer.OwnerIdentifier)); mockLog.Verify(m => m.ClaimOwnershipStart(It.Is<string>(p => partitionIds.Contains(p)))); mockLog.Verify(m => m.MinimumPartitionsPerEventProcessor(MinimumpartitionCount)); mockLog.Verify(m => m.CurrentOwnershipCount(MinimumpartitionCount, loadbalancer.OwnerIdentifier)); mockLog.Verify(m => m.StealPartition(loadbalancer.OwnerIdentifier)); mockLog.Verify(m => m.ShouldStealPartition(loadbalancer.OwnerIdentifier)); mockLog.Verify(m => m.UnclaimedPartitions(It.Is<HashSet<string>>(p => p.Overlaps(partitionIds)))); } /// <summary> /// Creates a collection of <see cref="PartitionOwnership" /> based on the specified arguments. /// </summary> /// /// <param name="partitionIds">A collection of partition identifiers that the collection will be associated with.</param> /// <param name="identifier">The owner identifier of the EventProcessorClient owning the collection.</param> /// /// <returns>A collection of <see cref="PartitionOwnership" />.</returns> /// private IEnumerable<EventProcessorPartitionOwnership> CreatePartitionOwnership(IEnumerable<string> partitionIds, string identifier) { return partitionIds .Select(partitionId => new EventProcessorPartitionOwnership { FullyQualifiedNamespace = FullyQualifiedNamespace, EventHubName = EventHubName, ConsumerGroup = ConsumerGroup, OwnerIdentifier = identifier, PartitionId = partitionId, LastModifiedTime = DateTimeOffset.UtcNow, Version = Guid.NewGuid().ToString() }).ToList(); } } }
using System.Net.Mime; using System.Text; namespace System.Net.Mail { public enum MailPriority { Normal = 0, Low = 1, High = 2 } internal class Message { #region Fields MailAddress from; MailAddress sender; MailAddressCollection replyToList; MailAddress replyTo; MailAddressCollection to; MailAddressCollection cc; MailAddressCollection bcc; MimeBasePart content; HeaderCollection headers; HeaderCollection envelopeHeaders; string subject; Encoding subjectEncoding; Encoding headersEncoding; MailPriority priority = (MailPriority)(-1); #endregion Fields #region Constructors internal Message() { } internal Message(string from, string to):this() { if (from == null) throw new ArgumentNullException("from"); if (to == null) throw new ArgumentNullException("to"); if (from == String.Empty) throw new ArgumentException(SR.GetString(SR.net_emptystringcall,"from"), "from"); if (to == String.Empty) throw new ArgumentException(SR.GetString(SR.net_emptystringcall,"to"), "to"); this.from = new MailAddress(from); MailAddressCollection collection = new MailAddressCollection(); collection.Add(to); this.to = collection; } internal Message(MailAddress from, MailAddress to):this() { this.from = from; this.To.Add(to); } #endregion Constructors #region Properties public MailPriority Priority{ get { return (((int)priority == -1)?MailPriority.Normal:priority); } set{ priority = value; } } internal MailAddress From { get { return from; } set { if (value == null) { throw new ArgumentNullException("value"); } from = value; } } internal MailAddress Sender { get { return sender; } set { sender = value; } } internal MailAddress ReplyTo { get { return replyTo; } set { replyTo = value; } } internal MailAddressCollection ReplyToList { get { if (replyToList == null) replyToList = new MailAddressCollection(); return replyToList; } } internal MailAddressCollection To { get { if (to == null) to = new MailAddressCollection(); return to; } } internal MailAddressCollection Bcc { get { if (bcc == null) bcc = new MailAddressCollection(); return bcc; } } internal MailAddressCollection CC { get { if (cc == null) cc = new MailAddressCollection(); return cc; } } internal string Subject { get { return subject; } set { Encoding inputEncoding = null; try { // extract the encoding from =?encoding?BorQ?blablalba?= inputEncoding = MimeBasePart.DecodeEncoding(value); } catch (ArgumentException) { }; if (inputEncoding != null && value != null) { try { // Store the decoded value, we'll re-encode before sending value = MimeBasePart.DecodeHeaderValue(value); subjectEncoding = subjectEncoding ?? inputEncoding; } // Failed to decode, just pass it through as ascii (legacy) catch (FormatException) { } } if (value != null && MailBnfHelper.HasCROrLF(value)) { throw new ArgumentException(SR.GetString(SR.MailSubjectInvalidFormat)); } subject = value; if (subject != null) { subject = subject.Normalize(NormalizationForm.FormC); if (subjectEncoding == null && !MimeBasePart.IsAscii(subject, false)) { subjectEncoding = Encoding.GetEncoding(MimeBasePart.defaultCharSet); } } } } internal Encoding SubjectEncoding { get { return subjectEncoding; } set { subjectEncoding = value; } } internal HeaderCollection Headers { get { if (headers == null) { headers = new HeaderCollection(); if(Logging.On)Logging.Associate(Logging.Web, this, headers); } return headers; } } internal Encoding HeadersEncoding { get { return headersEncoding; } set { headersEncoding = value; } } internal HeaderCollection EnvelopeHeaders { get { if (envelopeHeaders == null) { envelopeHeaders = new HeaderCollection(); if(Logging.On)Logging.Associate(Logging.Web, this, envelopeHeaders); } return envelopeHeaders; } } internal virtual MimeBasePart Content { get { return content; } set { if (value == null) { throw new ArgumentNullException("value"); } content = value; } } #endregion Properties #region Sending internal void EmptySendCallback(IAsyncResult result) { Exception e = null; if(result.CompletedSynchronously){ return; } EmptySendContext context = (EmptySendContext)result.AsyncState; try{ context.writer.EndGetContentStream(result).Close(); } catch(Exception ex){ e = ex; } context.result.InvokeCallback(e); } internal class EmptySendContext { internal EmptySendContext(BaseWriter writer, LazyAsyncResult result) { this.writer = writer; this.result = result; } internal LazyAsyncResult result; internal BaseWriter writer; } internal virtual IAsyncResult BeginSend(BaseWriter writer, bool sendEnvelope, bool allowUnicode, AsyncCallback callback, object state) { PrepareHeaders(sendEnvelope, allowUnicode); writer.WriteHeaders(Headers, allowUnicode); if (Content != null) { return Content.BeginSend(writer, callback, allowUnicode, state); } else{ LazyAsyncResult result = new LazyAsyncResult(this,state,callback); IAsyncResult newResult = writer.BeginGetContentStream(EmptySendCallback, new EmptySendContext(writer,result)); if(newResult.CompletedSynchronously){ writer.EndGetContentStream(newResult).Close(); } return result; } } internal virtual void EndSend(IAsyncResult asyncResult){ if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } if (Content != null) { Content.EndSend(asyncResult); } else{ LazyAsyncResult castedAsyncResult = asyncResult as LazyAsyncResult; if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException(SR.GetString(SR.net_io_invalidasyncresult)); } if (castedAsyncResult.EndCalled) { throw new InvalidOperationException(SR.GetString(SR.net_io_invalidendcall, "EndSend")); } castedAsyncResult.InternalWaitForCompletion(); castedAsyncResult.EndCalled = true; if (castedAsyncResult.Result is Exception) { throw (Exception)castedAsyncResult.Result; } } } internal virtual void Send(BaseWriter writer, bool sendEnvelope, bool allowUnicode) { if (sendEnvelope) { PrepareEnvelopeHeaders(sendEnvelope, allowUnicode); writer.WriteHeaders(EnvelopeHeaders, allowUnicode); } PrepareHeaders(sendEnvelope, allowUnicode); writer.WriteHeaders(Headers, allowUnicode); if (Content != null) { Content.Send(writer, allowUnicode); } else{ writer.GetContentStream().Close(); } } internal void PrepareEnvelopeHeaders(bool sendEnvelope, bool allowUnicode) { if (this.headersEncoding == null) { this.headersEncoding = Encoding.GetEncoding(MimeBasePart.defaultCharSet); } EncodeHeaders(this.EnvelopeHeaders, allowUnicode); // Dev10 #430372: only add X-Sender header if it wasn't already set by the user string xSenderHeader = MailHeaderInfo.GetString(MailHeaderID.XSender); if (!IsHeaderSet(xSenderHeader)) { MailAddress sender = Sender ?? From; EnvelopeHeaders.InternalSet(xSenderHeader, sender.Encode(xSenderHeader.Length, allowUnicode)); } string headerName = MailHeaderInfo.GetString(MailHeaderID.XReceiver); EnvelopeHeaders.Remove(headerName); foreach (MailAddress address in To) { EnvelopeHeaders.InternalAdd(headerName, address.Encode(headerName.Length, allowUnicode)); } foreach (MailAddress address in CC) { EnvelopeHeaders.InternalAdd(headerName, address.Encode(headerName.Length, allowUnicode)); } foreach (MailAddress address in Bcc) { EnvelopeHeaders.InternalAdd(headerName, address.Encode(headerName.Length, allowUnicode)); } } internal void PrepareHeaders(bool sendEnvelope, bool allowUnicode) { string headerName; if (this.headersEncoding == null) { this.headersEncoding = Encoding.GetEncoding(MimeBasePart.defaultCharSet); } //ContentType is written directly to the stream so remove potential user duplicate Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.ContentType)); Headers[MailHeaderInfo.GetString(MailHeaderID.MimeVersion)] = "1.0"; // add sender to headers first so that it is written first to allow the IIS smtp svc to // send MAIL FROM with the sender if both sender and from are present headerName = MailHeaderInfo.GetString(MailHeaderID.Sender); if(Sender != null) { Headers.InternalAdd(headerName, Sender.Encode(headerName.Length, allowUnicode)); } else { Headers.Remove(headerName); } headerName = MailHeaderInfo.GetString(MailHeaderID.From); Headers.InternalAdd(headerName, From.Encode(headerName.Length, allowUnicode)); headerName = MailHeaderInfo.GetString(MailHeaderID.To); if (To.Count > 0) { Headers.InternalAdd(headerName, To.Encode(headerName.Length, allowUnicode)); } else { Headers.Remove(headerName); } headerName = MailHeaderInfo.GetString(MailHeaderID.Cc); if (CC.Count > 0) { Headers.InternalAdd(headerName, CC.Encode(headerName.Length, allowUnicode)); } else { Headers.Remove(headerName); } headerName = MailHeaderInfo.GetString(MailHeaderID.ReplyTo); if (ReplyTo != null) { Headers.InternalAdd(headerName, ReplyTo.Encode(headerName.Length, allowUnicode)); } else if (ReplyToList.Count > 0) { Headers.InternalAdd(headerName, ReplyToList.Encode(headerName.Length, allowUnicode)); } else { Headers.Remove(headerName); } Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Bcc)); if (priority == MailPriority.High){ Headers[MailHeaderInfo.GetString(MailHeaderID.XPriority)] = "1"; Headers[MailHeaderInfo.GetString(MailHeaderID.Priority)] = "urgent"; Headers[MailHeaderInfo.GetString(MailHeaderID.Importance)] = "high"; } else if (priority == MailPriority.Low){ Headers[MailHeaderInfo.GetString(MailHeaderID.XPriority)] = "5"; Headers[MailHeaderInfo.GetString(MailHeaderID.Priority)] = "non-urgent"; Headers[MailHeaderInfo.GetString(MailHeaderID.Importance)] = "low"; } //if the priority was never set, allow the app to set the headers directly. else if (((int)priority) != -1){ Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.XPriority)); Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Priority)); Headers.Remove(MailHeaderInfo.GetString(MailHeaderID.Importance)); } Headers.InternalAdd(MailHeaderInfo.GetString(MailHeaderID.Date), MailBnfHelper.GetDateTimeString(DateTime.Now, null)); headerName = MailHeaderInfo.GetString(MailHeaderID.Subject); if (!string.IsNullOrEmpty(subject)){ if (allowUnicode) { Headers.InternalAdd(headerName, subject); } else { Headers.InternalAdd(headerName, MimeBasePart.EncodeHeaderValue(subject, subjectEncoding, MimeBasePart.ShouldUseBase64Encoding(subjectEncoding), headerName.Length)); } } else{ Headers.Remove(headerName); } EncodeHeaders(this.headers, allowUnicode); } internal void EncodeHeaders(HeaderCollection headers, bool allowUnicode) { if (this.headersEncoding == null) { this.headersEncoding = Encoding.GetEncoding(MimeBasePart.defaultCharSet); } System.Diagnostics.Debug.Assert(this.headersEncoding != null); for (int i = 0; i < headers.Count; i++) { string headerName = headers.GetKey(i); //certain well-known values are encoded by PrepareHeaders and PrepareEnvelopeHeaders //so we can ignore them because either we encoded them already or there is no //way for the user to have set them. If a header is well known and user settable then //we should encode it here, otherwise we have already encoded it if necessary if (!MailHeaderInfo.IsUserSettable(headerName)) { continue; } string[] values = headers.GetValues(headerName); string encodedValue = String.Empty; for (int j = 0; j < values.Length; j++) { //encode if we need to if (MimeBasePart.IsAscii(values[j], false) || (allowUnicode && MailHeaderInfo.AllowsUnicode(headerName) // EAI && !MailBnfHelper.HasCROrLF(values[j]))) { encodedValue = values[j]; } else { encodedValue = MimeBasePart.EncodeHeaderValue(values[j], this.headersEncoding, MimeBasePart.ShouldUseBase64Encoding(this.headersEncoding), headerName.Length); } //potentially there are multiple values per key if (j == 0) { //if it's the first or only value, set will overwrite all the values assigned to that key //which is fine since we have them stored in values[] headers.Set(headerName, encodedValue); } else { //this is a subsequent key, so we must Add it since the first key will have overwritten the //other values headers.Add(headerName, encodedValue); } } } } private bool IsHeaderSet(string headerName) { for (int i = 0; i < Headers.Count; i++) { if (string.Compare(Headers.GetKey(i), headerName, StringComparison.InvariantCultureIgnoreCase) == 0) { return true; } } return false; } #endregion Sending } }
using System; 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 IBits = Lucene.Net.Util.IBits; using FixedBitSet = Lucene.Net.Util.FixedBitSet; using OpenBitSet = Lucene.Net.Util.OpenBitSet; /// <summary> /// Base class for <see cref="DocIdSet"/> to be used with <see cref="IFieldCache"/>. The implementation /// of its iterator is very stupid and slow if the implementation of the /// <see cref="MatchDoc(int)"/> method is not optimized, as iterators simply increment /// the document id until <see cref="MatchDoc(int)"/> returns <c>true</c>. Because of this /// <see cref="MatchDoc(int)"/> must be as fast as possible and in no case do any /// I/O. /// <para/> /// @lucene.internal /// </summary> public class FieldCacheDocIdSet : DocIdSet { protected readonly int m_maxDoc; protected readonly IBits m_acceptDocs; private readonly Predicate<int> matchDoc; private readonly bool hasMatchDoc; // LUCENENET specific - added constructor to allow the class to be used without hand-coding // a subclass by passing a predicate. public FieldCacheDocIdSet(int maxDoc, IBits acceptDocs, Predicate<int> matchDoc) { this.matchDoc = matchDoc ?? throw new ArgumentNullException(nameof(matchDoc)); this.hasMatchDoc = true; this.m_maxDoc = maxDoc; this.m_acceptDocs = acceptDocs; } protected FieldCacheDocIdSet(int maxDoc, IBits acceptDocs) { this.m_maxDoc = maxDoc; this.m_acceptDocs = acceptDocs; } /// <summary> /// This method checks, if a doc is a hit /// </summary> protected internal virtual bool MatchDoc(int doc) => hasMatchDoc && matchDoc(doc); /// <summary> /// This DocIdSet is always cacheable (does not go back /// to the reader for iteration) /// </summary> public override sealed bool IsCacheable => true; public override sealed IBits Bits => (m_acceptDocs is null) ? (IBits)new BitsAnonymousClass(this) : new BitsAnonymousClass2(this); private class BitsAnonymousClass : IBits { private readonly FieldCacheDocIdSet outerInstance; public BitsAnonymousClass(FieldCacheDocIdSet outerInstance) { this.outerInstance = outerInstance; } public virtual bool Get(int docid) { return outerInstance.MatchDoc(docid); } public virtual int Length => outerInstance.m_maxDoc; } private class BitsAnonymousClass2 : IBits { private readonly FieldCacheDocIdSet outerInstance; public BitsAnonymousClass2(FieldCacheDocIdSet outerInstance) { this.outerInstance = outerInstance; } public virtual bool Get(int docid) { return outerInstance.MatchDoc(docid) && outerInstance.m_acceptDocs.Get(docid); } public virtual int Length => outerInstance.m_maxDoc; } public override sealed DocIdSetIterator GetIterator() { if (m_acceptDocs is null) { // Specialization optimization disregard acceptDocs return new DocIdSetIteratorAnonymousClass(this); } else if (m_acceptDocs is FixedBitSet || m_acceptDocs is OpenBitSet) { // special case for FixedBitSet / OpenBitSet: use the iterator and filter it // (used e.g. when Filters are chained by FilteredQuery) return new FilteredDocIdSetIteratorAnonymousClass(this, ((DocIdSet)m_acceptDocs).GetIterator()); } else { // Stupid consultation of acceptDocs and matchDoc() return new DocIdSetIteratorAnonymousClass2(this); } } private class DocIdSetIteratorAnonymousClass : DocIdSetIterator { private readonly FieldCacheDocIdSet outerInstance; public DocIdSetIteratorAnonymousClass(FieldCacheDocIdSet outerInstance) { this.outerInstance = outerInstance; doc = -1; } private int doc; public override int DocID => doc; public override int NextDoc() { do { doc++; if (doc >= outerInstance.m_maxDoc) { return doc = NO_MORE_DOCS; } } while (!outerInstance.MatchDoc(doc)); return doc; } public override int Advance(int target) { for (doc = target; doc < outerInstance.m_maxDoc; doc++) { if (outerInstance.MatchDoc(doc)) { return doc; } } return doc = NO_MORE_DOCS; } public override long GetCost() { return outerInstance.m_maxDoc; } } private class FilteredDocIdSetIteratorAnonymousClass : FilteredDocIdSetIterator { private readonly FieldCacheDocIdSet outerInstance; public FilteredDocIdSetIteratorAnonymousClass(FieldCacheDocIdSet outerInstance, Lucene.Net.Search.DocIdSetIterator iterator) : base(iterator) { this.outerInstance = outerInstance; } protected override bool Match(int doc) { return outerInstance.MatchDoc(doc); } } private class DocIdSetIteratorAnonymousClass2 : DocIdSetIterator { private readonly FieldCacheDocIdSet outerInstance; public DocIdSetIteratorAnonymousClass2(FieldCacheDocIdSet outerInstance) { this.outerInstance = outerInstance; doc = -1; } private int doc; public override int DocID => doc; public override int NextDoc() { do { doc++; if (doc >= outerInstance.m_maxDoc) { return doc = NO_MORE_DOCS; } } while (!(outerInstance.MatchDoc(doc) && outerInstance.m_acceptDocs.Get(doc))); return doc; } public override int Advance(int target) { for (doc = target; doc < outerInstance.m_maxDoc; doc++) { if (outerInstance.MatchDoc(doc) && outerInstance.m_acceptDocs.Get(doc)) { return doc; } } return doc = NO_MORE_DOCS; } public override long GetCost() { return outerInstance.m_maxDoc; } } } }
// // SimpleWebServer.cs // // Author: // Anton Keks <anton@azib.net> // // Copyright (C) 2009 Novell, Inc. // Copyright (C) 2009 Anton Keks // // 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.IO; using System.Net; using System.Net.Sockets; using System.Collections.Generic; using System.Text; using System.Threading; using FSpot.Extensions; using Hyena; namespace FSpot.Tools.LiveWebGallery { public class SimpleWebServer : IService { private Thread server_thread; private TcpListener listener; private Dictionary<string, RequestHandler> handlers = new Dictionary<string, RequestHandler> (); private IWebStats stats; public IWebStats Stats { set { stats = value; } } public bool Active { get { return server_thread != null && server_thread.IsAlive; } } public string HostPort { get { string host = Dns.GetHostName (); // TODO: add support for .local hostnames foreach (IPAddress addr in Dns.GetHostAddresses(host)) { if (!IPAddress.IsLoopback (addr)) { host = addr.ToString (); } } return host + ":" + (listener.LocalEndpoint as IPEndPoint).Port; } } public void RegisterHandler (string request_prefix, RequestHandler handler) { handlers.Add (request_prefix, handler); } public bool Start () { try { listener = new TcpListener (IPAddress.Any, 8080); listener.Start (); } catch (SocketException) { // address already in use? choose a random port then listener = new TcpListener (IPAddress.Any, 0); listener.Start (); } server_thread = new Thread (new ThreadStart(ServerLoop)); server_thread.Start (); return true; } public bool Stop () { server_thread.Abort (); server_thread.Join (); listener.Stop (); return true; } public void ServerLoop () { Log.Information ("Listening on " + listener.LocalEndpoint); while (true) { TcpClient client = listener.AcceptTcpClient (); if (client.Connected) { if (stats != null) stats.IncomingRequest ((client.Client.RemoteEndPoint as IPEndPoint).Address); RequestProcessor parser = new RequestProcessor (client, handlers); new Thread (new ThreadStart (parser.Process)).Start (); } } } class RequestProcessor { private TcpClient client; private Dictionary<string, RequestHandler> handlers; public RequestProcessor (TcpClient client, Dictionary<string, RequestHandler> handlers) { this.client = client; this.handlers = handlers; } public void Process () { using (client) { NetworkStream stream = client.GetStream (); TextReader reader = new StreamReader (stream, Encoding.UTF8); string line = reader.ReadLine (); if (line == null) return; Log.Debug ("Incoming request from " + (client.Client.RemoteEndPoint as IPEndPoint).Address + ": " + line); string request_method = null, request_string = null; int space_pos = line.IndexOf (' '); if (space_pos > 0) { request_method = line.Substring (0, space_pos); request_string = line.Substring (space_pos + 1, line.LastIndexOf (' ') - space_pos - 1); } while (!string.IsNullOrEmpty(line = reader.ReadLine ())) { // process other request headers here if needed } using (stream) { if (!"GET".Equals (request_method)) { RequestHandler.SendError (stream, "400 Bad Request"); return; } if (request_string.StartsWith ("/")) request_string = request_string.Substring (1); string request_prefix = request_string; int slash_pos = request_string.IndexOf ("/"); if (slash_pos >= 0) request_prefix = request_string.Substring (0, slash_pos); if (!handlers.ContainsKey (request_prefix)) { RequestHandler.SendError (stream, "404 No handler for \"" + request_string + "\""); return; } try { handlers[request_prefix].Handle (request_string.Substring (slash_pos+1), stream); } catch (Exception e) { Log.Exception (e); try { RequestHandler.SendError (stream, "500 " + e.Message); } catch (IOException) { // ignore already closed connections } } } } } } } public abstract class RequestHandler { public abstract void Handle (string requested, Stream stream); public static void SendLine (Stream stream, string header) { byte[] buf = Encoding.UTF8.GetBytes (header + "\r\n"); stream.Write (buf, 0, buf.Length); } public static void SendStatus (Stream stream, string status) { SendLine (stream, "HTTP/1.0 " + status + "\r\nServer: F-Spot"); } public static void SendError (Stream stream, string error) { SendStatus (stream, error); StartContent (stream); SendLine (stream, error); } public static void StartContent (Stream stream) { // sends the last empty newline after headers SendLine (stream, ""); } public static void SendHeadersAndStartContent (Stream stream, params string[] headers) { SendStatus (stream, "200 OK"); foreach (string header in headers) { SendLine (stream, header); } StartContent (stream); } public string MimeTypeForExt (string ext) { switch (ext.ToLower ()) { case ".jpg": case ".jpeg": return "image/jpeg"; case ".png": return "image/png"; case ".gif": return "image/gif"; case ".js": return "text/javascript"; case ".css": return "text/css"; default: throw new Exception ("Unknown file type: " + ext); } } } public interface IWebStats { void IncomingRequest (IPAddress addr); } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using SDKTemplate; using System; using Windows.Networking.NetworkOperators; using System.Collections.Generic; using Windows.Networking.Connectivity; namespace MobileBroadband { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class GetConnectionProfiles : Page { // A pointer back to the main page. This is needed if you want to call methods in MainPage such // as NotifyUser() MainPage rootPage = MainPage.Current; private IReadOnlyList<string> deviceAccountId = null; public GetConnectionProfiles() { this.InitializeComponent(); } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { PrepareScenario(); } /// <summary> /// This is the click handler for the 'Default' button. You would replace this with your own handler /// if you have a button or buttons on this page. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void GetConnectionProfilesButton_Click(object sender, RoutedEventArgs e) { Button b = sender as Button; if (b != null) { try { // For the sake of simplicity, we only get the ConnectionProfiles from the first NetworkAccountId var mobileBroadbandAccount = MobileBroadbandAccount.CreateFromNetworkAccountId(deviceAccountId[0]); PrintConnectionProfiles(mobileBroadbandAccount.GetConnectionProfiles()); } catch (Exception ex) { rootPage.NotifyUser("Error:" + ex.Message, NotifyType.ErrorMessage); } } } void PrepareScenario() { rootPage.NotifyUser("", NotifyType.StatusMessage); try { deviceAccountId = MobileBroadbandAccount.AvailableNetworkAccountIds; if (deviceAccountId.Count != 0) { GetConnectionProfilesButton.Content = "Get Connection Profiles"; GetConnectionProfilesButton.IsEnabled = true; } else { GetConnectionProfilesButton.Content = "No available accounts detected"; GetConnectionProfilesButton.IsEnabled = false; } } catch (Exception ex) { rootPage.NotifyUser("Error:" + ex.Message, NotifyType.ErrorMessage); } } private void PrintConnectionProfiles(IReadOnlyList<ConnectionProfile> connectionProfiles) { string connectionProfileList = string.Empty; try { foreach (var connectionProfile in connectionProfiles) { //Display Profile information for each of the connection profiles connectionProfileList += GetConnectionProfile(connectionProfile); connectionProfileList += "--------------------------------------------------------------------\n"; } if (connectionProfiles.Count == 0) { connectionProfileList += "No Connection Profiles found.\n"; } rootPage.NotifyUser(connectionProfileList, NotifyType.StatusMessage); } catch (Exception ex) { rootPage.NotifyUser("Unexpected exception occurred: " + ex.ToString(), NotifyType.ErrorMessage); } } // //Get Connection Profile name and cost information // string GetConnectionProfile(ConnectionProfile connectionProfile) { string connectionProfileInfo = string.Empty; if (connectionProfile != null) { connectionProfileInfo = "Profile Name : " + connectionProfile.ProfileName + "\n"; switch (connectionProfile.GetNetworkConnectivityLevel()) { case NetworkConnectivityLevel.None: connectionProfileInfo += "Connectivity Level : None\n"; break; case NetworkConnectivityLevel.LocalAccess: connectionProfileInfo += "Connectivity Level : Local Access\n"; break; case NetworkConnectivityLevel.ConstrainedInternetAccess: connectionProfileInfo += "Connectivity Level : Constrained Internet Access\n"; break; case NetworkConnectivityLevel.InternetAccess: connectionProfileInfo += "Connectivity Level : Internet Access\n"; break; } switch (connectionProfile.GetDomainConnectivityLevel()) { case DomainConnectivityLevel.None: connectionProfileInfo += "Domain Connectivity Level : None\n"; break; case DomainConnectivityLevel.Unauthenticated: connectionProfileInfo += "Domain Connectivity Level : Unauthenticated\n"; break; case DomainConnectivityLevel.Authenticated: connectionProfileInfo += "Domain Connectivity Level : Authenticated\n"; break; } //Get Connection Cost information ConnectionCost connectionCost = connectionProfile.GetConnectionCost(); connectionProfileInfo += GetConnectionCostInfo(connectionCost); //Get Dataplan Status information DataPlanStatus dataPlanStatus = connectionProfile.GetDataPlanStatus(); connectionProfileInfo += GetDataPlanStatusInfo(dataPlanStatus); //Get Network Security Settings NetworkSecuritySettings netSecuritySettings = connectionProfile.NetworkSecuritySettings; connectionProfileInfo += GetNetworkSecuritySettingsInfo(netSecuritySettings); //Get Wlan Connection Profile Details if this is a Wlan ConnectionProfile if (connectionProfile.IsWlanConnectionProfile) { WlanConnectionProfileDetails wlanConnectionProfileDetails = connectionProfile.WlanConnectionProfileDetails; connectionProfileInfo += GetWlanConnectionProfileDetailsInfo(wlanConnectionProfileDetails); } //Get Wwan Connection Profile Details if this is a Wwan ConnectionProfile if (connectionProfile.IsWwanConnectionProfile) { WwanConnectionProfileDetails wwanConnectionProfileDetails = connectionProfile.WwanConnectionProfileDetails; connectionProfileInfo += GetWwanConnectionProfileDetailsInfo(wwanConnectionProfileDetails); } //Get the Service Provider GUID if (connectionProfile.ServiceProviderGuid.HasValue) { connectionProfileInfo += "====================\n"; connectionProfileInfo += "Service Provider GUID: " + connectionProfile.ServiceProviderGuid + "\n"; } //Get the number of signal bars if (connectionProfile.GetSignalBars().HasValue) { connectionProfileInfo += "====================\n"; connectionProfileInfo += "Signal Bars: " + connectionProfile.GetSignalBars() + "\n"; } } return connectionProfileInfo; } // //Get Profile Connection cost // string GetConnectionCostInfo(ConnectionCost connectionCost) { string cost = string.Empty; cost += "Connection Cost Information: \n"; cost += "====================\n"; if (connectionCost == null) { cost += "Connection Cost not available\n"; return cost; } switch (connectionCost.NetworkCostType) { case NetworkCostType.Unrestricted: cost += "Cost: Unrestricted"; break; case NetworkCostType.Fixed: cost += "Cost: Fixed"; break; case NetworkCostType.Variable: cost += "Cost: Variable"; break; case NetworkCostType.Unknown: cost += "Cost: Unknown"; break; default: cost += "Cost: Error"; break; } cost += "\n"; cost += "Roaming: " + connectionCost.Roaming + "\n"; cost += "Over Data Limit: " + connectionCost.OverDataLimit + "\n"; cost += "Approaching Data Limit : " + connectionCost.ApproachingDataLimit + "\n"; //Display cost based suggestions to the user cost += CostBasedSuggestions(connectionCost); return cost; } // //Display Cost based suggestions to the user // string CostBasedSuggestions(ConnectionCost connectionCost) { string costBasedSuggestions = string.Empty; costBasedSuggestions += "Cost Based Suggestions: \n"; costBasedSuggestions += "====================\n"; if (connectionCost.Roaming) { costBasedSuggestions += "Connection is out of MNO's network, using the connection may result in additional charge. Application can implement High Cost behavior in this scenario\n"; } else if (connectionCost.NetworkCostType == NetworkCostType.Variable) { costBasedSuggestions += "Connection cost is variable, and the connection is charged based on usage, so application can implement the Conservative behavior\n"; } else if (connectionCost.NetworkCostType == NetworkCostType.Fixed) { if (connectionCost.OverDataLimit || connectionCost.ApproachingDataLimit) { costBasedSuggestions += "Connection has exceeded the usage cap limit or is approaching the datalimit, and the application can implement High Cost behavior in this scenario\n"; } else { costBasedSuggestions += "Application can implemement the Conservative behavior\n"; } } else { costBasedSuggestions += "Application can implement the Standard behavior\n"; } return costBasedSuggestions; } // //Display Profile Dataplan Status information // string GetDataPlanStatusInfo(DataPlanStatus dataPlan) { string dataplanStatusInfo = string.Empty; dataplanStatusInfo = "Dataplan Status Information:\n"; dataplanStatusInfo += "====================\n"; if (dataPlan == null) { dataplanStatusInfo += "Dataplan Status not available\n"; return dataplanStatusInfo; } if (dataPlan.DataPlanUsage != null) { dataplanStatusInfo += "Usage In Megabytes : " + dataPlan.DataPlanUsage.MegabytesUsed + "\n"; dataplanStatusInfo += "Last Sync Time : " + dataPlan.DataPlanUsage.LastSyncTime + "\n"; } else { dataplanStatusInfo += "Usage In Megabytes : Not Defined\n"; } ulong? inboundBandwidth = dataPlan.InboundBitsPerSecond; if (inboundBandwidth.HasValue) { dataplanStatusInfo += "InboundBitsPerSecond : " + inboundBandwidth + "\n"; } else { dataplanStatusInfo += "InboundBitsPerSecond : Not Defined\n"; } ulong? outboundBandwidth = dataPlan.OutboundBitsPerSecond; if (outboundBandwidth.HasValue) { dataplanStatusInfo += "OutboundBitsPerSecond : " + outboundBandwidth + "\n"; } else { dataplanStatusInfo += "OutboundBitsPerSecond : Not Defined\n"; } uint? dataLimit = dataPlan.DataLimitInMegabytes; if (dataLimit.HasValue) { dataplanStatusInfo += "DataLimitInMegabytes : " + dataLimit + "\n"; } else { dataplanStatusInfo += "DataLimitInMegabytes : Not Defined\n"; } System.DateTimeOffset? nextBillingCycle = dataPlan.NextBillingCycle; if (nextBillingCycle.HasValue) { dataplanStatusInfo += "NextBillingCycle : " + nextBillingCycle + "\n"; } else { dataplanStatusInfo += "NextBillingCycle : Not Defined\n"; } uint? maxTransferSize = dataPlan.MaxTransferSizeInMegabytes; if (maxTransferSize.HasValue) { dataplanStatusInfo += "MaxTransferSizeInMegabytes : " + maxTransferSize + "\n"; } else { dataplanStatusInfo += "MaxTransferSizeInMegabytes : Not Defined\n"; } return dataplanStatusInfo; } // //Get Network Security Settings information // string GetNetworkSecuritySettingsInfo(NetworkSecuritySettings netSecuritySettings) { string networkSecurity = string.Empty; networkSecurity += "Network Security Settings: \n"; networkSecurity += "====================\n"; if (netSecuritySettings == null) { networkSecurity += "Network Security Settings not available\n"; return networkSecurity; } //NetworkAuthenticationType switch (netSecuritySettings.NetworkAuthenticationType) { case NetworkAuthenticationType.None: networkSecurity += "NetworkAuthenticationType: None"; break; case NetworkAuthenticationType.Unknown: networkSecurity += "NetworkAuthenticationType: Unknown"; break; case NetworkAuthenticationType.Open80211: networkSecurity += "NetworkAuthenticationType: Open80211"; break; case NetworkAuthenticationType.SharedKey80211: networkSecurity += "NetworkAuthenticationType: SharedKey80211"; break; case NetworkAuthenticationType.Wpa: networkSecurity += "NetworkAuthenticationType: Wpa"; break; case NetworkAuthenticationType.WpaPsk: networkSecurity += "NetworkAuthenticationType: WpaPsk"; break; case NetworkAuthenticationType.WpaNone: networkSecurity += "NetworkAuthenticationType: WpaNone"; break; case NetworkAuthenticationType.Rsna: networkSecurity += "NetworkAuthenticationType: Rsna"; break; case NetworkAuthenticationType.RsnaPsk: networkSecurity += "NetworkAuthenticationType: RsnaPsk"; break; default: networkSecurity += "NetworkAuthenticationType: Error"; break; } networkSecurity += "\n"; //NetworkEncryptionType switch (netSecuritySettings.NetworkEncryptionType) { case NetworkEncryptionType.None: networkSecurity += "NetworkEncryptionType: None"; break; case NetworkEncryptionType.Unknown: networkSecurity += "NetworkEncryptionType: Unknown"; break; case NetworkEncryptionType.Wep: networkSecurity += "NetworkEncryptionType: Wep"; break; case NetworkEncryptionType.Wep40: networkSecurity += "NetworkEncryptionType: Wep40"; break; case NetworkEncryptionType.Wep104: networkSecurity += "NetworkEncryptionType: Wep104"; break; case NetworkEncryptionType.Tkip: networkSecurity += "NetworkEncryptionType: Tkip"; break; case NetworkEncryptionType.Ccmp: networkSecurity += "NetworkEncryptionType: Ccmp"; break; case NetworkEncryptionType.WpaUseGroup: networkSecurity += "NetworkEncryptionType: WpaUseGroup"; break; case NetworkEncryptionType.RsnUseGroup: networkSecurity += "NetworkEncryptionType: RsnUseGroup"; break; default: networkSecurity += "NetworkEncryptionType: Error"; break; } networkSecurity += "\n"; return networkSecurity; } string GetWlanConnectionProfileDetailsInfo(WlanConnectionProfileDetails wlanConnectionProfileDetails) { string wlanDetails = string.Empty; wlanDetails += "Wireless LAN Connection Profile Details:\n"; wlanDetails += "====================\n"; if (wlanConnectionProfileDetails == null) { wlanDetails += "Wireless LAN connection profile details unavailable.\n"; return wlanDetails; } wlanDetails += "Connected SSID: " + wlanConnectionProfileDetails.GetConnectedSsid() + "\n"; return wlanDetails; } string GetWwanConnectionProfileDetailsInfo(WwanConnectionProfileDetails wwanConnectionProfileDetails) { string wwanDetails = string.Empty; wwanDetails += "Wireless WAN Connection Profile Details:\n"; wwanDetails += "====================\n"; if (wwanConnectionProfileDetails == null) { wwanDetails += "Wireless WAN connection profile details unavailable.\n"; return wwanDetails; } wwanDetails += "Home Provider ID: " + wwanConnectionProfileDetails.HomeProviderId + "\n"; wwanDetails += "Access Point Name: " + wwanConnectionProfileDetails.AccessPointName + "\n"; wwanDetails += "Network Registration State: " + wwanConnectionProfileDetails.GetNetworkRegistrationState() + "\n"; wwanDetails += "Current Data Class: " + wwanConnectionProfileDetails.GetCurrentDataClass() + "\n"; return wwanDetails; } } }
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ // // 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. namespace Castle.Facilities.WcfIntegration { using System; #if DOTNET40 using System.Collections.Concurrent; #endif using System.Linq; using System.Reflection; using System.ServiceModel; using Castle.Core; using Castle.Facilities.WcfIntegration.Internal; using Castle.Facilities.WcfIntegration.Proxy; using Castle.MicroKernel; using Castle.MicroKernel.ComponentActivator; using Castle.MicroKernel.Context; using Castle.MicroKernel.Facilities; using System.ServiceModel.Channels; public class WcfClientActivator : DefaultComponentActivator { private readonly WcfClientExtension clients; private readonly WcfProxyFactory proxyFactory; private IWcfBurden channelBurden; private ChannelCreator createChannel; public WcfClientActivator(ComponentModel model, IKernel kernel, ComponentInstanceDelegate onCreation, ComponentInstanceDelegate onDestruction) : base(model, kernel, onCreation, onDestruction) { clients = kernel.Resolve<WcfClientExtension>(); proxyFactory = new WcfProxyFactory(clients.ProxyGenerator, clients); } protected override object Instantiate(CreationContext context) { IWcfBurden burden; var channelCreator = GetChannelCreator(context, out burden); try { var channelHolder = new WcfChannelHolder(channelCreator, burden, clients.CloseTimeout); var channel = (IChannel)proxyFactory.Create(Kernel, channelHolder, Model, context); NotifyChannelCreatedOrAvailable(channel, burden, false); return channel; } catch (CommunicationException) { throw; } catch (Exception ex) { throw new ComponentActivatorException("WcfClientActivator: could not proxy component " + Model.Name, ex, Model); } } protected override void SetUpProperties(object instance, CreationContext context) { //we don't... there should be no properties on WCF clients } /// <summary> /// Creates the channel creator. /// </summary> /// <param name = "context">The context for the creator.</param> /// <param name = "burden">Receives the channel burden.</param> /// <returns>The channel creator.</returns> /// <remarks> /// Always Open the channel before being used to prevent serialization of requests. /// http://blogs.msdn.com/wenlong/archive/2007/10/26/best-practice-always-open-wcf-client-proxy-explicitly-when-it-is-shared.aspx /// </remarks> private ChannelCreator GetChannelCreator(CreationContext context, out IWcfBurden burden) { burden = channelBurden; var creator = createChannel; var clientModel = ObtainClientModel(Model, context); if (clientModel != null) { var inner = CreateChannelCreator(Kernel, Model, clientModel, out burden); var scopedBurden = burden; creator = () => { var client = (IChannel)inner(); if (client is IContextChannel) { ((IContextChannel)client).Extensions.Add(new WcfBurdenExtension<IContextChannel>(scopedBurden)); } else { var parameters = client.GetProperty<ChannelParameterCollection>(); if (parameters != null) { parameters.Add(scopedBurden); } } NotifyChannelCreatedOrAvailable(client, scopedBurden, true); client.Open(); return client; }; } else if (createChannel == null) { clientModel = ObtainClientModel(Model); var inner = CreateChannelCreator(Kernel, Model, clientModel, out channelBurden); creator = createChannel = () => { var client = (IChannel)inner(); NotifyChannelCreatedOrAvailable(client, channelBurden, true); client.Open(); return client; }; burden = channelBurden; clients.TrackBurden(burden); } return creator; } private static ChannelCreator CreateChannelCreator(IKernel kernel, ComponentModel model, IWcfClientModel clientModel, out IWcfBurden burden) { ValidateClientModel(clientModel, model); var createChannelDelegate = createChannelCache.GetOrAdd(clientModel.GetType(), clientModelType => { return (CreateChannelDelegate)Delegate.CreateDelegate(typeof(CreateChannelDelegate), createChannelMethod.MakeGenericMethod(clientModelType)); }); var channelCreator = createChannelDelegate(kernel, clientModel, model, out burden); if (channelCreator == null) { throw new CommunicationException("Unable to generate the channel creator. " + "Either the endpoint could be be created or it's a bug so please report it."); } return channelCreator; } private static ChannelCreator CreateChannelCreatorInternal<TModel>( IKernel kernel, IWcfClientModel clientModel, ComponentModel model, out IWcfBurden burden) where TModel : IWcfClientModel { var channelBuilder = kernel.Resolve<IChannelBuilder<TModel>>(); return channelBuilder.GetChannelCreator((TModel)clientModel, model.GetServiceContract(), out burden); } private static void NotifyChannelCreatedOrAvailable(IChannel channel, IWcfBurden burden, bool created) { var channelFactory = burden.Dependencies.OfType<ChannelFactoryHolder>() .Select(holder => holder.ChannelFactory).FirstOrDefault(); if (channelFactory != null) { foreach (var observer in burden.Dependencies.OfType<IChannelFactoryAware>()) { if (created) { observer.ChannelCreated(channelFactory, channel); } else { observer.ChannelAvailable(channelFactory, channel); } } } } private static IWcfClientModel ObtainClientModel(ComponentModel model) { return (IWcfClientModel)model.ExtendedProperties[WcfConstants.ClientModelKey]; } private static IWcfClientModel ObtainClientModel(ComponentModel model, CreationContext context) { var clientModel = WcfUtils.FindDependencies<IWcfClientModel>(context.AdditionalArguments).FirstOrDefault(); var endpoint = WcfUtils.FindDependencies<IWcfEndpoint>(context.AdditionalArguments).FirstOrDefault(); if (endpoint != null) { if (clientModel == null) { clientModel = ObtainClientModel(model); } clientModel = clientModel.ForEndpoint(endpoint); } return clientModel; } private static void ValidateClientModel(IWcfClientModel clientModel, ComponentModel model) { if (clientModel.Endpoint == null) { throw new FacilityException("The client model requires an endpoint."); } var contract = clientModel.Contract ?? model.GetServiceContract(); if (contract == null) { throw new FacilityException("The service contract for the client endpoint could not be determined."); } if (model.Services.Contains(contract) == false) { throw new FacilityException(string.Format( "The service contract {0} is not supported by the component {0} or any of its services.", clientModel.Contract.FullName, model.Implementation.FullName)); } } private delegate ChannelCreator CreateChannelDelegate(IKernel kernel, IWcfClientModel clientModel, ComponentModel model, out IWcfBurden burden); private static readonly ConcurrentDictionary<Type, CreateChannelDelegate> createChannelCache = new ConcurrentDictionary<Type, CreateChannelDelegate>(); private static readonly MethodInfo createChannelMethod = typeof(WcfClientActivator).GetMethod("CreateChannelCreatorInternal", BindingFlags.NonPublic | BindingFlags.Static, null, new[] { typeof(IKernel), typeof(IWcfClientModel), typeof(ComponentModel), typeof(IWcfBurden).MakeByRefType() }, null ); } }
// Prexonite // // Copyright (c) 2014, Christian Klauser // 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. // The names of the 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING // IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #region using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using System.Text; using Prexonite.Compiler.Cil; #endregion namespace Prexonite.Types { [PTypeLiteral("List")] public class ListPType : PType, ICilCompilerAware { private ListPType() { } private static readonly ListPType _instance = new ListPType(); public static ListPType Instance { get { return _instance; } } public override PValue CreatePValue(object value) { var listOfPValue = value as List<PValue>; var enumerableOfPValue = value as IEnumerable<PValue>; var enumerable = value as IEnumerable; if (listOfPValue != null) return new PValue(listOfPValue, this); if (enumerableOfPValue != null) return new PValue(new List<PValue>(enumerableOfPValue), this); if (enumerable != null) { var lst = new List<PValue>(); foreach (var v in enumerable) { var pv = v as PValue; if (pv != null) lst.Add(pv); else throw new PrexoniteException( "Cannot create List from IEnumerable that contains elements of any type other than PValue. Use List.CreateFromList for this purpose."); } return new PValue(lst, this); } throw new PrexoniteException( "Cannot create a PValue from the supplied " + value + "."); } public override bool TryDynamicCall( StackContext sctx, PValue subject, PValue[] args, PCall call, string id, out PValue result) { result = null; var lst = subject.Value as List<PValue>; if (lst == null) throw new PrexoniteException(subject + " is not a List."); if (id.Length == 0) { if (call == PCall.Get) { switch (args.Length) { case 0: result = lst.Count == 0 ? Null.CreatePValue() : lst[lst.Count - 1]; break; case 1: result = lst[(int)args[0].ConvertTo(sctx, Int).Value]; break; default: //Multi-index lookup var n_lst = new List<PValue>(args.Length); foreach (var index in args) n_lst.Add(lst[(int)index.ConvertTo(sctx, Int).Value]); result = new PValue(n_lst, this); break; } } else { if (args.Length == 1) lst.Add(args[0] ?? Null.CreatePValue()); else //Multi index set { var v = args[args.Length - 1] ?? Null.CreatePValue(); for (var i = 0; i < args.Length - 1; i++) lst[(int)args[i].ConvertTo(sctx, Int).Value] = v; } result = Null.CreatePValue(); } } else { int index; switch (id.ToLowerInvariant()) { case "length": case "count": result = lst.Count; break; case "getenumerator": result = sctx.CreateNativePValue(new PValueEnumeratorWrapper(lst.GetEnumerator())); break; case "add": lst.AddRange(args); result = Null.CreatePValue(); break; case "clear": lst.Clear(); result = Null.CreatePValue(); break; case "contains": var r = true; foreach (var arg in args) if (!lst.Contains(arg)) { r = false; break; } result = r; break; case "copyto": index = 0; if (args.Length > 1) index = (int)args[1].ConvertTo(sctx, Int).Value; else if (args.Length == 0) throw new PrexoniteException("List.CopyTo requires a target array."); var targetAsArray = args[0].Value as PValue[]; if (targetAsArray == null) throw new PrexoniteException( "List.CopyTo requires it's first argument to be of type Object(\"" + typeof(PValue[]) + "\")"); lst.CopyTo(targetAsArray, index); result = Null.CreatePValue(); break; case "remove": var cnt = 0; foreach (var arg in args) { if (lst.Remove(arg)) cnt++; } result = cnt; break; case "removeat": var toRemove = new List<bool>(lst.Count); for (var i = 0; i < lst.Count; i++) toRemove.Add(false); foreach (var arg in args) { var li = (int)arg.ConvertTo(sctx, Int).Value; if (li > lst.Count - 1 || li < 0) throw new ArgumentOutOfRangeException( "The index " + li + " is out of the range of the supplied list."); toRemove[li] = true; } for (var i = 0; i < toRemove.Count; i++) { if (toRemove[i]) { toRemove.RemoveAt(i); lst.RemoveAt(i); i--; } } result = Null.CreatePValue(); break; case "indexof": if (args.Length == 0) result = -1; else if (args.Length == 1) result = lst.IndexOf(args[0]); else { var indices = new List<PValue>(args.Length); foreach (var arg in args) indices.Add(lst.IndexOf(arg)); result = new PValue(indices, this); } break; case "insert": case "insertat": if (args.Length < 1) throw new PrexoniteException( "List.InsertAt requires at least an index."); index = (int)args[0].ConvertTo(sctx, Int).Value; for (var i = 1; i < args.Length; i++) lst.Insert(index, args[i]); result = Null.CreatePValue(); break; case "sort": if (args.Length < 1) { lst.Sort(new PValueComparer(sctx)); break; } if (args.Length == 1 && args[0].Type is ObjectPType) { //Maybe: comparison using IComparer or Comparison var icmp = args[0].Value as IComparer<PValue>; if (icmp != null) { lst.Sort(icmp); result = Null.CreatePValue(); break; } var cmp = args[0].Value as Comparer<PValue>; if (cmp != null) { lst.Sort(icmp); result = Null.CreatePValue(); break; } } //else //Comparison using lambda expressions lst.Sort( delegate(PValue a, PValue b) { foreach (var f in args) { var pdec = f.IndirectCall(sctx, new[] { a, b }); if (!(pdec.Type is IntPType)) pdec = pdec.ConvertTo(sctx, Int); var dec = (int)pdec.Value; if (dec != 0) return dec; } return 0; }); result = Null.CreatePValue(); break; case "tostring": result = _getStringRepresentation(lst, sctx); break; case @"\implements": foreach (var arg in args) { Type T; if (arg.Type is ObjectPType && typeof(Type).IsAssignableFrom(((ObjectPType)arg.Type).ClrType)) T = (Type)arg.Value; else { var typeName = arg.CallToString(sctx); switch (typeName.ToUpperInvariant()) { case "IENUMERABLE": case "ILIST": case "ICOLLECTION": result = true; return true; default: T = ObjectPType.GetType(sctx, typeName); break; } } if (!T.IsAssignableFrom(typeof(List<PValue>))) { result = false; return true; } } result = true; return true; default: if ( Object[subject.ClrType].TryDynamicCall( sctx, subject, args, call, id, out result)) { if (call == PCall.Get) if (result == null) result = Null.CreatePValue(); else if (result.Value is PValue) result = (PValue)result.Value; else result = Null.CreatePValue(); } break; } } return result != null; } private static string _getStringRepresentation(IEnumerable<PValue> lst, StackContext sctx) { var sb = new StringBuilder("[ "); foreach (var v in lst) { sb.Append(v.CallToString(sctx)); sb.Append(", "); } if (sb.Length > 2) sb.Remove(sb.Length - 2, 2); sb.Append(" ]"); return sb.ToString(); } public override bool TryStaticCall( StackContext sctx, PValue[] args, PCall call, string id, out PValue result) { result = null; if (Engine.StringsAreEqual(id, "Create")) { result = new PValue(new List<PValue>(args), this); } else if (Engine.StringsAreEqual(id, "CreateFromSize") && args.Length >= 1) { result = new PValue(new List<PValue>((int)args[0].ConvertTo(sctx, Int).Value), this); } else if (Engine.StringsAreEqual(id, "CreateFromList")) { var lst = new List<PValue>(); foreach (var arg in args) { var enumerableP = arg.Value as IEnumerable<PValue>; var enumerable = arg.Value as IEnumerable; if (enumerableP != null) lst.AddRange(enumerableP); else if (enumerable != null) { foreach (var e in enumerable) lst.Add(e as PValue ?? sctx.CreateNativePValue(e)); } } result = new PValue(lst, this); } return result != null; } public override bool TryConstruct(StackContext sctx, PValue[] args, out PValue result) { result = new PValue(new List<PValue>(args), this); return true; } protected override bool InternalConvertTo( StackContext sctx, PValue subject, PType target, bool useExplicit, out PValue result) { var objT = target as ObjectPType; result = null; if ((object)objT != null) { var clrType = objT.ClrType; var genericTypeTemplate = clrType.IsGenericType ? clrType.GetGenericTypeDefinition() : null; if (clrType == typeof(IEnumerable<PValue>) || clrType == typeof(List<PValue>) || clrType == typeof(ICollection<PValue>) || clrType == typeof(IList<PValue>) || clrType == typeof(IEnumerable) || clrType == typeof(ICollection) || clrType == typeof(IList)) result = target.CreatePValue(subject); else if (clrType == typeof(PValue[]) && useExplicit) result = target.CreatePValue(((List<PValue>)subject.Value).ToArray()); else if (clrType == typeof(PValueKeyValuePair)) { var lst = (List<PValue>)subject.Value; var key = lst.Count > 0 ? lst[0] : Null.CreatePValue(); var valueList = new List<PValue>(lst.Count > 0 ? lst.Count - 1 : 0); for (var i = 1; i < lst.Count; i++) valueList.Add(lst[i]); var value = List.CreatePValue(valueList); result = target.CreatePValue(new PValueKeyValuePair(key, value)); } else if (clrType.IsArray) { //Convert each element in the list to the element type of the array. var et = clrType.GetElementType(); var lst = (List<PValue>)subject.Value; var array = Array.CreateInstance(et, lst.Count); var success = true; for (var i = 0; i < lst.Count; i++) { PValue converted; if (lst[i].TryConvertTo(sctx, et, useExplicit, out converted)) { array.SetValue(converted.Value, i); } else { success = false; break; } } if (success) result = sctx.CreateNativePValue(array); } else if (genericTypeTemplate == typeof (IEnumerable<>) || genericTypeTemplate == typeof(ICollection<>) || genericTypeTemplate == typeof(IReadOnlyCollection<>) || genericTypeTemplate == typeof(IReadOnlyList<>) || genericTypeTemplate == typeof(IList<>)) { // Convert each element in the list to the element type of the sequence var elementT = clrType.GetGenericArguments()[0]; var listT = typeof (List<>).MakeGenericType(elementT); // ReSharper disable once PossibleNullReferenceException var list = (IList) listT.GetConstructor(new Type[0]).Invoke(new object[0]); var success = true; foreach (var pv in (List<PValue>)subject.Value) { PValue converted; if (pv.TryConvertTo(sctx, elementT, useExplicit, out converted)) { list.Add(converted.Value); } else { success = false; break; } } if (success) { if (genericTypeTemplate == typeof (IReadOnlyCollection<>) || genericTypeTemplate == typeof (IReadOnlyList<>)) { // Wrap in readonly list view var readonlyListT = typeof (ReadOnlyCollection<>).MakeGenericType(elementT); var readonlyList = // ReSharper disable once PossibleNullReferenceException readonlyListT.GetConstructor(new[] {typeof (IList<>).MakeGenericType(elementT)}) .Invoke(new object[]{list}); result = sctx.CreateNativePValue(readonlyList); } else { result = sctx.CreateNativePValue(list); } } } } return result != null; } protected override bool InternalConvertFrom( StackContext sctx, PValue subject, bool useExplicit, out PValue result) { //TODO: Create to List conversions (KeyValuePair) result = null; return false; } protected override bool InternalIsEqual(PType otherType) { return otherType is ListPType; } public override bool IndirectCall( StackContext sctx, PValue subject, PValue[] args, out PValue result) { var lst = new List<PValue>(); result = List.CreatePValue(lst); PValue r; foreach (var e in ((IEnumerable<PValue>)subject.Value)) if (e.TryIndirectCall(sctx, args, out r)) lst.Add(r); else lst.Add(Null.CreatePValue()); return true; } /// <summary> /// Concatenates lists. /// </summary> /// <param name = "sctx">The stack context in which to concatenate the lists.</param> /// <param name = "leftOperand">Any PValue.</param> /// <param name = "rightOperand">Any PValue.</param> /// <param name = "result">The resulting list, wrapped in a PValue object.</param> /// <returns>Always true</returns> /// <exception cref = "ArgumentNullException">either <paramref name = "leftOperand" /> or <paramref name = "rightOperand" /> is null.</exception> /// <remarks> /// <para> /// The operator does not modify it's arguments but instead creates a new list. /// </para> /// <para> /// Lists passed as operands are unfolded; the lists contents are added, not the list itself.<br /> /// <code>~List.Create(1,2,3) + 4 == ~List.Create(1,2,3,4)</code> /// </para> /// </remarks> public override bool Addition( StackContext sctx, PValue leftOperand, PValue rightOperand, out PValue result) { if (leftOperand == null) throw new ArgumentNullException("leftOperand"); if (rightOperand == null) throw new ArgumentNullException("rightOperand"); var nlst = new List<PValue>(); var npv = List.CreatePValue(nlst); if (leftOperand.Type is ListPType) nlst.AddRange((List<PValue>)leftOperand.Value); else nlst.Add(leftOperand); if (rightOperand.Type is ListPType) nlst.AddRange((List<PValue>)rightOperand.Value); else nlst.Add(rightOperand); result = npv; return true; } public const string Literal = "List"; public override string ToString() { return Literal; } private const int _code = 86312339; public override int GetHashCode() { return _code; } #region ICilCompilerAware Members /// <summary> /// Asses qualification and preferences for a certain instruction. /// </summary> /// <param name = "ins">The instruction that is about to be compiled.</param> /// <returns>A set of <see cref = "CompilationFlags" />.</returns> CompilationFlags ICilCompilerAware.CheckQualification(Instruction ins) { return CompilationFlags.PrefersCustomImplementation; } private static readonly MethodInfo GetListPType = typeof(PType).GetProperty("List").GetGetMethod(); /// <summary> /// Provides a custom compiler routine for emitting CIL byte code for a specific instruction. /// </summary> /// <param name = "state">The compiler state.</param> /// <param name = "ins">The instruction to compile.</param> void ICilCompilerAware.ImplementInCil(CompilerState state, Instruction ins) { state.EmitCall(GetListPType); } #endregion } }
#region License // Copyright (c) 2010-2019, Mark Final // 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 BuildAMation 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 HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // License using System.Linq; namespace MakeFileBuilder { // Notes: // A rule is target + prerequisities + receipe // A recipe is a collection of commands /// <summary> /// Shared metadata for all objects in MakeFiles /// </summary> sealed class MakeFileCommonMetaData { /// <summary> /// Is NMAKE the MakeFile chosen format? /// </summary> public static bool IsNMAKE = ("NMAKE".Equals(Bam.Core.CommandLineProcessor.Evaluate(new Options.ChooseFormat()), System.StringComparison.Ordinal)); /// <summary> /// A fake Target for order only dependencies /// </summary> public static Target DIRSTarget = new Target( Bam.Core.TokenizedString.CreateVerbatim("$(DIRS)"), false, null, null, 0, string.Empty, false ); public MakeFileCommonMetaData() { this.Directories = new Bam.Core.StringArray(); this.Environment = new System.Collections.Generic.Dictionary<string, Bam.Core.StringArray>(); this.PackageVariables = new System.Collections.Generic.Dictionary<string, string>(); if (Bam.Core.OSUtilities.IsLinuxHosting) { // for system utilities, e.g. mkdir, cp, echo this.Environment.Add("PATH", new Bam.Core.StringArray("/bin")); // for some tools, e.g. as this.Environment["PATH"].Add("/usr/bin"); } } private Bam.Core.StringArray Directories { get; set; } private System.Collections.Generic.Dictionary<string, Bam.Core.StringArray> Environment { get; set; } private System.Collections.Generic.Dictionary<string, string> PackageVariables { get; set; } /// <summary> /// Add key-value pairs (using strings and TokenizedStringArrays) which represent /// an environment variable name, and its value (usually multiple paths), to be used /// when the MakeFile is executed. /// Duplicates values are not added. /// </summary> /// <param name="import">The dictionary of key-value pairs to add.</param> public void ExtendEnvironmentVariables( System.Collections.Generic.Dictionary<string, Bam.Core.TokenizedStringArray> import) { if (null == import) { return; } lock (this.Environment) { foreach (var env in import) { if (!this.Environment.ContainsKey(env.Key)) { this.Environment.Add(env.Key, new Bam.Core.StringArray()); } foreach (var path in env.Value) { this.Environment[env.Key].AddUnique(path.ToString()); } } } } /// <summary> /// Add a directory to those to be created when running the MakeFile. /// Duplicates are not added. /// </summary> /// <param name="path">Path to the directory to be added.</param> public void AddDirectory( string path) { lock (this.Directories) { // at least mingw32-make does not like trailing slashes this.Directories.AddUnique(path.TrimEnd(System.IO.Path.DirectorySeparatorChar)); } } /// <summary> /// Write the environment variables to be exported to the MakeFile. /// </summary> /// <param name="output">Where to write the environment variables to.</param> public void ExportEnvironment( System.Text.StringBuilder output) { System.Diagnostics.Debug.Assert(!MakeFileCommonMetaData.IsNMAKE); foreach (var env in this.Environment) { output.AppendLine( $"{env.Key}:={this.UseMacrosInPath(env.Value.ToString(System.IO.Path.PathSeparator))}" ); } } /// <summary> /// Write a phony target that sets the environment variables. /// Required for NMAKE since macros are not exported as environment variables. /// </summary> /// <param name="output"></param> public void ExportEnvironmentAsPhonyTarget( System.Text.StringBuilder output) { System.Diagnostics.Debug.Assert(MakeFileCommonMetaData.IsNMAKE); output.AppendLine(".PHONY: nmakesetenv"); output.AppendLine("nmakesetenv:"); foreach (var env in this.Environment) { // trim the end of 'continuation" characters output.AppendLine($"\t@set {env.Key}={env.Value.ToString(System.IO.Path.PathSeparator).TrimEnd(new[] { System.IO.Path.DirectorySeparatorChar })}"); } output.AppendLine(); } /// <summary> /// Write the directories to be created when running the MakeFile. /// </summary> /// <param name="output">Where to write the directories to.</param> /// <param name="explicitlyCreateHierarchy">Optional bool indicating that the entire directory hierarchy needs to be make. Defaults to false.</param> /// <returns>True if directories were exported, false if none were.</returns> public bool ExportDirectories( System.Text.StringBuilder output, bool explicitlyCreateHierarchy = false) { if (!this.Directories.Any()) { return false; } if (this.Directories.Any(item => item.Contains(" "))) { // http://savannah.gnu.org/bugs/?712 // https://stackoverflow.com/questions/9838384/can-gnu-make-handle-filenames-with-spaces Bam.Core.Log.ErrorMessage("WARNING: MakeFiles do not support spaces in pathnames."); } if (explicitlyCreateHierarchy) { var extraDirs = new Bam.Core.StringArray(); foreach (var dir in this.Directories) { var current_dir = dir; for (;;) { var parent = System.IO.Path.GetDirectoryName(current_dir); if (null == parent) { break; } if (!System.IO.Directory.Exists(parent) && !this.Directories.Contains(parent)) { extraDirs.AddUnique(parent); current_dir = parent; continue; } break; } } this.Directories.AddRange(extraDirs); this.Directories = new Bam.Core.StringArray(this.Directories.OrderBy(item => item.Length)); } if (IsNMAKE) { output.Append("DIRS = "); } else { output.Append("DIRS:="); } foreach (var dir in this.Directories) { output.Append($"{this.UseMacrosInPath(dir)} "); } output.AppendLine(); if (IsNMAKE) { output.AppendLine(); } return true; } /// <summary> /// Get the variable name for a package's directory /// </summary> /// <param name="packageName">Name of package</param> /// <returns>Variable name</returns> public static string VariableForPackageDir( string packageName) { return $"{packageName}_DIR"; } private void AppendVariable( System.Text.StringBuilder output, string path, string variableName) { if (this.PackageVariables.ContainsKey(path)) { if (this.PackageVariables[path].Equals(variableName, System.StringComparison.Ordinal)) { return; } if (variableName.EndsWith(".tests_DIR", System.StringComparison.Ordinal)) { // this is a package test namespace return; } // unexpectedly, due to paths being the primary lookup, there is no need to add an alias here // as it's always resolved to the original variable Bam.Core.Log.DebugMessage($"Path '{path}' is already registered with macro '{this.PackageVariables[path]}'. Ignoring the alias '{variableName}'"); return; } if (IsNMAKE) { output.Append($"{variableName} = {path}"); } else { output.Append( $"{variableName} := {path}" ); } output.AppendLine(); this.PackageVariables.Add(path, $"$({variableName})"); } /// <summary> /// Export all package directories /// </summary> /// <param name="output">StringBuilder to write to</param> /// <param name="packageMap">Map of packages</param> public void ExportPackageDirectories( System.Text.StringBuilder output, System.Collections.Generic.Dictionary<string, string> packageMap) { this.AppendVariable(output, Bam.Core.Graph.Instance.Macros[Bam.Core.GraphMacroNames.BuildRoot].ToString(), "BUILDROOT"); foreach (var pkg in packageMap) { var packageVar = VariableForPackageDir(pkg.Key); this.AppendVariable(output, pkg.Value, packageVar); } } /// <summary> /// Replace a Make string with macros that are appropriate /// </summary> /// <param name="path">Path to replace</param> /// <returns>Make macroised path</returns> public string UseMacrosInPath( string path) { foreach (var pkg in this.PackageVariables) { if (!path.Contains(pkg.Key)) { continue; } path = path.Replace(pkg.Key, pkg.Value); } return path; } } }
using System.Collections.Generic; using System.Collections.Immutable; using System.Data.Entity; using System.Data.Entity.Core.Objects; using System.Data.Entity.Infrastructure; using System.Linq; using System.Threading.Tasks; using Abp.Dependency; using Abp.Domain.Uow; using Abp.EntityFramework.Utils; using Abp.Extensions; using Abp.MultiTenancy; using Abp.Timing; using Castle.Core.Internal; namespace Abp.EntityFramework.Uow { /// <summary> /// Implements Unit of work for Entity Framework. /// </summary> public class EfUnitOfWork : UnitOfWorkBase, ITransientDependency { protected IDictionary<string, DbContext> ActiveDbContexts { get; } protected IIocResolver IocResolver { get; } private readonly IDbContextResolver _dbContextResolver; private readonly IDbContextTypeMatcher _dbContextTypeMatcher; private readonly IEfTransactionStrategy _transactionStrategy; /// <summary> /// Creates a new <see cref="EfUnitOfWork"/>. /// </summary> public EfUnitOfWork( IIocResolver iocResolver, IConnectionStringResolver connectionStringResolver, IDbContextResolver dbContextResolver, IEfUnitOfWorkFilterExecuter filterExecuter, IUnitOfWorkDefaultOptions defaultOptions, IDbContextTypeMatcher dbContextTypeMatcher, IEfTransactionStrategy transactionStrategy) : base( connectionStringResolver, defaultOptions, filterExecuter) { IocResolver = iocResolver; _dbContextResolver = dbContextResolver; _dbContextTypeMatcher = dbContextTypeMatcher; _transactionStrategy = transactionStrategy; ActiveDbContexts = new Dictionary<string, DbContext>(System.StringComparer.OrdinalIgnoreCase); } protected override void BeginUow() { if (Options.IsTransactional == true) { _transactionStrategy.InitOptions(Options); } } public override void SaveChanges() { foreach (var dbContext in GetAllActiveDbContexts()) { SaveChangesInDbContext(dbContext); } } public override async Task SaveChangesAsync() { foreach (var dbContext in GetAllActiveDbContexts()) { await SaveChangesInDbContextAsync(dbContext); } } public IReadOnlyList<DbContext> GetAllActiveDbContexts() { return ActiveDbContexts.Values.ToImmutableList(); } protected override void CompleteUow() { SaveChanges(); if (Options.IsTransactional == true) { _transactionStrategy.Commit(); } } protected override async Task CompleteUowAsync() { await SaveChangesAsync(); if (Options.IsTransactional == true) { _transactionStrategy.Commit(); } } public virtual TDbContext GetOrCreateDbContext<TDbContext>(MultiTenancySides? multiTenancySide = null, string name = null) where TDbContext : DbContext { var concreteDbContextType = _dbContextTypeMatcher.GetConcreteType(typeof(TDbContext)); var connectionStringResolveArgs = new ConnectionStringResolveArgs(multiTenancySide) { ["DbContextType"] = typeof(TDbContext), ["DbContextConcreteType"] = concreteDbContextType }; var connectionString = ResolveConnectionString(connectionStringResolveArgs); var dbContextKey = concreteDbContextType.FullName + "#" + connectionString; if (name != null) { dbContextKey += "#" + name; } if (ActiveDbContexts.TryGetValue(dbContextKey, out var dbContext)) { return (TDbContext) dbContext; } if (Options.IsTransactional == true) { dbContext = _transactionStrategy.CreateDbContext<TDbContext>(connectionString, _dbContextResolver); } else { dbContext = _dbContextResolver.Resolve<TDbContext>(connectionString); } if (dbContext is IShouldInitializeDcontext abpDbContext) { abpDbContext.Initialize(new AbpEfDbContextInitializationContext(this)); } FilterExecuter.As<IEfUnitOfWorkFilterExecuter>().ApplyCurrentFilters(this, dbContext); ActiveDbContexts[dbContextKey] = dbContext; return (TDbContext) dbContext; } public virtual async Task<TDbContext> GetOrCreateDbContextAsync<TDbContext>( MultiTenancySides? multiTenancySide = null, string name = null) where TDbContext : DbContext { var concreteDbContextType = _dbContextTypeMatcher.GetConcreteType(typeof(TDbContext)); var connectionStringResolveArgs = new ConnectionStringResolveArgs(multiTenancySide) { ["DbContextType"] = typeof(TDbContext), ["DbContextConcreteType"] = concreteDbContextType }; var connectionString = await ResolveConnectionStringAsync(connectionStringResolveArgs); var dbContextKey = concreteDbContextType.FullName + "#" + connectionString; if (name != null) { dbContextKey += "#" + name; } if (ActiveDbContexts.TryGetValue(dbContextKey, out var dbContext)) { return (TDbContext) dbContext; } if (Options.IsTransactional == true) { dbContext = await _transactionStrategy .CreateDbContextAsync<TDbContext>(connectionString, _dbContextResolver); } else { dbContext = _dbContextResolver.Resolve<TDbContext>(connectionString); } if (dbContext is IShouldInitializeDcontext abpDbContext) { abpDbContext.Initialize(new AbpEfDbContextInitializationContext(this)); } FilterExecuter.As<IEfUnitOfWorkFilterExecuter>().ApplyCurrentFilters(this, dbContext); ActiveDbContexts[dbContextKey] = dbContext; return (TDbContext) dbContext; } protected override void DisposeUow() { if (Options.IsTransactional == true) { _transactionStrategy.Dispose(IocResolver); } else { foreach (var activeDbContext in GetAllActiveDbContexts()) { Release(activeDbContext); } } ActiveDbContexts.Clear(); } protected virtual void SaveChangesInDbContext(DbContext dbContext) { dbContext.SaveChanges(); } protected virtual Task SaveChangesInDbContextAsync(DbContext dbContext) { return dbContext.SaveChangesAsync(); } protected virtual void Release(DbContext dbContext) { dbContext.Dispose(); IocResolver.Release(dbContext); } } }
/** * JsonMapper.cs * JSON to .Net object and object to JSON conversions. * * The authors disclaim copyright to this source code. For more details, see * the COPYING file included with this distribution. **/ #if !UNITY_WP8 using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; namespace OuyaSDK_LitJson { internal struct PropertyMetadata { public MemberInfo Info; public bool IsField; public Type Type; } internal struct ArrayMetadata { private Type element_type; private bool is_array; private bool is_list; public Type ElementType { get { if (element_type == null) return typeof (JsonData); return element_type; } set { element_type = value; } } public bool IsArray { get { return is_array; } set { is_array = value; } } public bool IsList { get { return is_list; } set { is_list = value; } } } internal struct ObjectMetadata { private Type element_type; private bool is_dictionary; private IDictionary<string, PropertyMetadata> properties; public Type ElementType { get { if (element_type == null) return typeof (JsonData); return element_type; } set { element_type = value; } } public bool IsDictionary { get { return is_dictionary; } set { is_dictionary = value; } } public IDictionary<string, PropertyMetadata> Properties { get { return properties; } set { properties = value; } } } internal delegate void ExporterFunc (object obj, JsonWriter writer); public delegate void ExporterFunc<T> (T obj, JsonWriter writer); internal delegate object ImporterFunc (object input); public delegate TValue ImporterFunc<TJson, TValue> (TJson input); public delegate IJsonWrapper WrapperFactory (); public class JsonMapper { #region Fields private static int max_nesting_depth; private static IFormatProvider datetime_format; private static IDictionary<Type, ExporterFunc> base_exporters_table; private static IDictionary<Type, ExporterFunc> custom_exporters_table; private static IDictionary<Type, IDictionary<Type, ImporterFunc>> base_importers_table; private static IDictionary<Type, IDictionary<Type, ImporterFunc>> custom_importers_table; private static IDictionary<Type, ArrayMetadata> array_metadata; private static readonly object array_metadata_lock = new Object (); private static IDictionary<Type, IDictionary<Type, MethodInfo>> conv_ops; private static readonly object conv_ops_lock = new Object (); private static IDictionary<Type, ObjectMetadata> object_metadata; private static readonly object object_metadata_lock = new Object (); private static IDictionary<Type, IList<PropertyMetadata>> type_properties; private static readonly object type_properties_lock = new Object (); private static JsonWriter static_writer; private static readonly object static_writer_lock = new Object (); #endregion #region Constructors static JsonMapper () { max_nesting_depth = 100; array_metadata = new Dictionary<Type, ArrayMetadata> (); conv_ops = new Dictionary<Type, IDictionary<Type, MethodInfo>> (); object_metadata = new Dictionary<Type, ObjectMetadata> (); type_properties = new Dictionary<Type, IList<PropertyMetadata>> (); static_writer = new JsonWriter (); datetime_format = DateTimeFormatInfo.InvariantInfo; base_exporters_table = new Dictionary<Type, ExporterFunc> (); custom_exporters_table = new Dictionary<Type, ExporterFunc> (); base_importers_table = new Dictionary<Type, IDictionary<Type, ImporterFunc>> (); custom_importers_table = new Dictionary<Type, IDictionary<Type, ImporterFunc>> (); RegisterBaseExporters (); RegisterBaseImporters (); } #endregion #region Private Methods private static void AddArrayMetadata (Type type) { if (array_metadata.ContainsKey (type)) return; ArrayMetadata data = new ArrayMetadata (); data.IsArray = type.IsArray; if (type.GetInterface ("System.Collections.IList") != null) data.IsList = true; foreach (PropertyInfo p_info in type.GetProperties ()) { if (p_info.Name != "Item") continue; ParameterInfo[] parameters = p_info.GetIndexParameters (); if (parameters.Length != 1) continue; if (parameters[0].ParameterType == typeof (int)) data.ElementType = p_info.PropertyType; } lock (array_metadata_lock) { try { array_metadata.Add (type, data); } catch (ArgumentException) { return; } } } private static void AddObjectMetadata (Type type) { if (object_metadata.ContainsKey (type)) return; ObjectMetadata data = new ObjectMetadata (); if (type.GetInterface ("System.Collections.IDictionary") != null) data.IsDictionary = true; data.Properties = new Dictionary<string, PropertyMetadata> (); foreach (PropertyInfo p_info in type.GetProperties ()) { if (p_info.Name == "Item") { ParameterInfo[] parameters = p_info.GetIndexParameters (); if (parameters.Length != 1) continue; if (parameters[0].ParameterType == typeof (string)) data.ElementType = p_info.PropertyType; continue; } PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = p_info; p_data.Type = p_info.PropertyType; data.Properties.Add (p_info.Name, p_data); } foreach (FieldInfo f_info in type.GetFields ()) { PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = f_info; p_data.IsField = true; p_data.Type = f_info.FieldType; data.Properties.Add (f_info.Name, p_data); } lock (object_metadata_lock) { try { object_metadata.Add (type, data); } catch (ArgumentException) { return; } } } private static void AddTypeProperties (Type type) { if (type_properties.ContainsKey (type)) return; IList<PropertyMetadata> props = new List<PropertyMetadata> (); foreach (PropertyInfo p_info in type.GetProperties ()) { if (p_info.Name == "Item") continue; PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = p_info; p_data.IsField = false; props.Add (p_data); } foreach (FieldInfo f_info in type.GetFields ()) { PropertyMetadata p_data = new PropertyMetadata (); p_data.Info = f_info; p_data.IsField = true; props.Add (p_data); } lock (type_properties_lock) { try { type_properties.Add (type, props); } catch (ArgumentException) { return; } } } private static MethodInfo GetConvOp (Type t1, Type t2) { lock (conv_ops_lock) { if (! conv_ops.ContainsKey (t1)) conv_ops.Add (t1, new Dictionary<Type, MethodInfo> ()); } if (conv_ops[t1].ContainsKey (t2)) return conv_ops[t1][t2]; MethodInfo op = t1.GetMethod ( "op_Implicit", new Type[] { t2 }); lock (conv_ops_lock) { try { conv_ops[t1].Add (t2, op); } catch (ArgumentException) { return conv_ops[t1][t2]; } } return op; } private static object ReadValue (Type inst_type, JsonReader reader) { reader.Read (); if (reader.Token == JsonToken.ArrayEnd) return null; if (reader.Token == JsonToken.Null) { if (! inst_type.IsClass) throw new JsonException (String.Format ( "Can't assign null to an instance of type {0}", inst_type)); return null; } if (reader.Token == JsonToken.Single || reader.Token == JsonToken.Double || reader.Token == JsonToken.Int || reader.Token == JsonToken.Long || reader.Token == JsonToken.String || reader.Token == JsonToken.Boolean) { Type json_type = reader.Value.GetType (); if (inst_type.IsAssignableFrom (json_type)) return reader.Value; // If there's a custom importer that fits, use it if (custom_importers_table.ContainsKey (json_type) && custom_importers_table[json_type].ContainsKey ( inst_type)) { ImporterFunc importer = custom_importers_table[json_type][inst_type]; return importer (reader.Value); } // Maybe there's a base importer that works if (base_importers_table.ContainsKey (json_type) && base_importers_table[json_type].ContainsKey ( inst_type)) { ImporterFunc importer = base_importers_table[json_type][inst_type]; return importer (reader.Value); } // Maybe it's an enum if (inst_type.IsEnum) return Enum.ToObject (inst_type, reader.Value); // Try using an implicit conversion operator MethodInfo conv_op = GetConvOp (inst_type, json_type); if (conv_op != null) return conv_op.Invoke (null, new object[] { reader.Value }); // No luck throw new JsonException (String.Format ( "Can't assign value '{0}' (type {1}) to type {2}", reader.Value, json_type, inst_type)); } object instance = null; if (reader.Token == JsonToken.ArrayStart) { AddArrayMetadata (inst_type); ArrayMetadata t_data = array_metadata[inst_type]; if (! t_data.IsArray && ! t_data.IsList) throw new JsonException (String.Format ( "Type {0} can't act as an array", inst_type)); IList list; Type elem_type; if (! t_data.IsArray) { list = (IList) Activator.CreateInstance (inst_type); elem_type = t_data.ElementType; } else { list = new ArrayList (); elem_type = inst_type.GetElementType (); } while (true) { object item = ReadValue (elem_type, reader); if (reader.Token == JsonToken.ArrayEnd) break; list.Add (item); } if (t_data.IsArray) { int n = list.Count; instance = Array.CreateInstance (elem_type, n); for (int i = 0; i < n; i++) ((Array) instance).SetValue (list[i], i); } else instance = list; } else if (reader.Token == JsonToken.ObjectStart) { AddObjectMetadata (inst_type); ObjectMetadata t_data = object_metadata[inst_type]; instance = Activator.CreateInstance (inst_type); while (true) { reader.Read (); if (reader.Token == JsonToken.ObjectEnd) break; string property = (string) reader.Value; if (t_data.Properties.ContainsKey (property)) { PropertyMetadata prop_data = t_data.Properties[property]; if (prop_data.IsField) { if (((FieldInfo) prop_data.Info).IsLiteral) { reader.Read(); continue; } ((FieldInfo) prop_data.Info).SetValue ( instance, ReadValue (prop_data.Type, reader)); } else { PropertyInfo p_info = (PropertyInfo) prop_data.Info; if (p_info.CanWrite) p_info.SetValue ( instance, ReadValue (prop_data.Type, reader), null); else ReadValue (prop_data.Type, reader); } } else { if (! t_data.IsDictionary) throw new JsonException (String.Format ( "The type {0} doesn't have the " + "property '{1}'", inst_type, property)); ((IDictionary) instance).Add ( property, ReadValue ( t_data.ElementType, reader)); } } } return instance; } private static IJsonWrapper ReadValue (WrapperFactory factory, JsonReader reader) { reader.Read (); if (reader.Token == JsonToken.ArrayEnd || reader.Token == JsonToken.Null) return null; IJsonWrapper instance = factory (); if (reader.Token == JsonToken.String) { instance.SetString ((string) reader.Value); return instance; } if (reader.Token == JsonToken.Single) { instance.SetSingle((float)reader.Value); return instance; } if (reader.Token == JsonToken.Double) { instance.SetDouble ((double) reader.Value); return instance; } if (reader.Token == JsonToken.Int) { instance.SetInt ((int) reader.Value); return instance; } if (reader.Token == JsonToken.Long) { instance.SetLong ((long) reader.Value); return instance; } if (reader.Token == JsonToken.Boolean) { instance.SetBoolean ((bool) reader.Value); return instance; } if (reader.Token == JsonToken.ArrayStart) { instance.SetJsonType (JsonType.Array); while (true) { IJsonWrapper item = ReadValue (factory, reader); if (reader.Token == JsonToken.ArrayEnd) break; ((IList) instance).Add (item); } } else if (reader.Token == JsonToken.ObjectStart) { instance.SetJsonType (JsonType.Object); while (true) { reader.Read (); if (reader.Token == JsonToken.ObjectEnd) break; string property = (string) reader.Value; ((IDictionary) instance)[property] = ReadValue ( factory, reader); } } return instance; } private static void RegisterBaseExporters () { base_exporters_table[typeof (byte)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((byte) obj)); }; base_exporters_table[typeof (char)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToString ((char) obj)); }; base_exporters_table[typeof (DateTime)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToString ((DateTime) obj, datetime_format)); }; base_exporters_table[typeof (decimal)] = delegate (object obj, JsonWriter writer) { writer.Write ((decimal) obj); }; base_exporters_table[typeof (sbyte)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((sbyte) obj)); }; base_exporters_table[typeof (short)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((short) obj)); }; base_exporters_table[typeof (ushort)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToInt32 ((ushort) obj)); }; base_exporters_table[typeof (uint)] = delegate (object obj, JsonWriter writer) { writer.Write (Convert.ToUInt64 ((uint) obj)); }; base_exporters_table[typeof (ulong)] = delegate (object obj, JsonWriter writer) { writer.Write ((ulong) obj); }; } private static void RegisterBaseImporters () { ImporterFunc importer; importer = delegate (object input) { return Convert.ToByte ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (byte), importer); importer = delegate (object input) { return Convert.ToUInt64 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (ulong), importer); importer = delegate (object input) { return Convert.ToSByte ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (sbyte), importer); importer = delegate (object input) { return Convert.ToInt16 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (short), importer); importer = delegate (object input) { return Convert.ToUInt16 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (ushort), importer); importer = delegate (object input) { return Convert.ToUInt32 ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (uint), importer); importer = delegate (object input) { return Convert.ToSingle ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (float), importer); importer = delegate(object input) { return Convert.ToSingle((int)input); }; RegisterImporter(base_importers_table, typeof(int), typeof(float), importer); importer = delegate(object input) { return Convert.ToDecimal((float)input); }; RegisterImporter(base_importers_table, typeof(float), typeof(decimal), importer); importer = delegate(object input) { return Convert.ToDouble((float)input); }; RegisterImporter(base_importers_table, typeof(float), typeof(double), importer); importer = delegate (object input) { return Convert.ToDouble ((int) input); }; RegisterImporter (base_importers_table, typeof (int), typeof (double), importer); importer = delegate (object input) { return Convert.ToDecimal ((double) input); }; RegisterImporter (base_importers_table, typeof (double), typeof (decimal), importer); importer = delegate(object input) { return Convert.ToSingle((double)input); }; RegisterImporter(base_importers_table, typeof(double), typeof(float), importer); importer = delegate (object input) { return Convert.ToUInt32 ((long) input); }; RegisterImporter (base_importers_table, typeof (long), typeof (uint), importer); importer = delegate (object input) { return Convert.ToChar ((string) input); }; RegisterImporter (base_importers_table, typeof (string), typeof (char), importer); importer = delegate (object input) { return Convert.ToDateTime ((string) input, datetime_format); }; RegisterImporter (base_importers_table, typeof (string), typeof (DateTime), importer); } private static void RegisterImporter ( IDictionary<Type, IDictionary<Type, ImporterFunc>> table, Type json_type, Type value_type, ImporterFunc importer) { if (! table.ContainsKey (json_type)) table.Add (json_type, new Dictionary<Type, ImporterFunc> ()); table[json_type][value_type] = importer; } private static void WriteValue (object obj, JsonWriter writer, bool writer_is_private, int depth) { if (depth > max_nesting_depth) throw new JsonException ( String.Format ("Max allowed object depth reached while " + "trying to export from type {0}", obj.GetType ())); if (obj == null) { writer.Write (null); return; } if (obj is IJsonWrapper) { if (writer_is_private) writer.TextWriter.Write (((IJsonWrapper) obj).ToJson ()); else ((IJsonWrapper) obj).ToJson (writer); return; } if (obj is String) { writer.Write ((string) obj); return; } if (obj is Single) { writer.Write((float)obj); return; } if (obj is Double) { writer.Write ((double) obj); return; } if (obj is Int32) { writer.Write ((int) obj); return; } if (obj is Boolean) { writer.Write ((bool) obj); return; } if (obj is Int64) { writer.Write ((long) obj); return; } if (obj is Array) { writer.WriteArrayStart (); foreach (object elem in (Array) obj) WriteValue (elem, writer, writer_is_private, depth + 1); writer.WriteArrayEnd (); return; } if (obj is IList) { writer.WriteArrayStart (); foreach (object elem in (IList) obj) WriteValue (elem, writer, writer_is_private, depth + 1); writer.WriteArrayEnd (); return; } if (obj is IDictionary) { writer.WriteObjectStart (); foreach (DictionaryEntry entry in (IDictionary) obj) { writer.WritePropertyName ((string) entry.Key); WriteValue (entry.Value, writer, writer_is_private, depth + 1); } writer.WriteObjectEnd (); return; } Type obj_type = obj.GetType (); // See if there's a custom exporter for the object if (custom_exporters_table.ContainsKey (obj_type)) { ExporterFunc exporter = custom_exporters_table[obj_type]; exporter (obj, writer); return; } // If not, maybe there's a base exporter if (base_exporters_table.ContainsKey (obj_type)) { ExporterFunc exporter = base_exporters_table[obj_type]; exporter (obj, writer); return; } // Last option, let's see if it's an enum if (obj is Enum) { Type e_type = Enum.GetUnderlyingType (obj_type); if (e_type == typeof (long) || e_type == typeof (uint) || e_type == typeof (ulong)) writer.Write ((ulong) obj); else writer.Write ((int) obj); return; } // Okay, so it looks like the input should be exported as an // object AddTypeProperties (obj_type); IList<PropertyMetadata> props = type_properties[obj_type]; writer.WriteObjectStart (); foreach (PropertyMetadata p_data in props) { if (p_data.IsField) { if (((FieldInfo) p_data.Info).IsLiteral) { continue; } writer.WritePropertyName (p_data.Info.Name); WriteValue (((FieldInfo) p_data.Info).GetValue (obj), writer, writer_is_private, depth + 1); } else { PropertyInfo p_info = (PropertyInfo) p_data.Info; if (p_info.CanRead) { writer.WritePropertyName (p_data.Info.Name); WriteValue (p_info.GetValue (obj, null), writer, writer_is_private, depth + 1); } } } writer.WriteObjectEnd (); } #endregion public static string ToJson (object obj) { lock (static_writer_lock) { static_writer.Reset (); WriteValue (obj, static_writer, true, 0); return static_writer.ToString (); } } public static void ToJson (object obj, JsonWriter writer) { WriteValue (obj, writer, false, 0); } public static JsonData ToObject (JsonReader reader) { return (JsonData) ToWrapper ( delegate { return new JsonData (); }, reader); } public static JsonData ToObject (TextReader reader) { JsonReader json_reader = new JsonReader (reader); return (JsonData) ToWrapper ( delegate { return new JsonData (); }, json_reader); } public static JsonData ToObject (string json) { return (JsonData) ToWrapper ( delegate { return new JsonData (); }, json); } public static T ToObject<T> (JsonReader reader) { return (T) ReadValue (typeof (T), reader); } public static T ToObject<T> (TextReader reader) { JsonReader json_reader = new JsonReader (reader); return (T) ReadValue (typeof (T), json_reader); } public static T ToObject<T> (string json) { JsonReader reader = new JsonReader (json); return (T) ReadValue (typeof (T), reader); } public static IJsonWrapper ToWrapper (WrapperFactory factory, JsonReader reader) { return ReadValue (factory, reader); } public static IJsonWrapper ToWrapper (WrapperFactory factory, string json) { JsonReader reader = new JsonReader (json); return ReadValue (factory, reader); } public static void RegisterExporter<T> (ExporterFunc<T> exporter) { ExporterFunc exporter_wrapper = delegate (object obj, JsonWriter writer) { exporter ((T) obj, writer); }; custom_exporters_table[typeof (T)] = exporter_wrapper; } public static void RegisterImporter<TJson, TValue> ( ImporterFunc<TJson, TValue> importer) { ImporterFunc importer_wrapper = delegate (object input) { return importer ((TJson) input); }; RegisterImporter (custom_importers_table, typeof (TJson), typeof (TValue), importer_wrapper); } public static void UnregisterExporters () { custom_exporters_table.Clear (); } public static void UnregisterImporters () { custom_importers_table.Clear (); } } } #endif
using System; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Security; namespace Org.BouncyCastle.Crypto.Paddings { /** * A wrapper class that allows block ciphers to be used to process data in * a piecemeal fashion with padding. The PaddedBufferedBlockCipher * outputs a block only when the buffer is full and more data is being added, * or on a doFinal (unless the current block in the buffer is a pad block). * The default padding mechanism used is the one outlined in Pkcs5/Pkcs7. */ public class PaddedBufferedBlockCipher : BufferedBlockCipher { private readonly IBlockCipherPadding padding; /** * Create a buffered block cipher with the desired padding. * * @param cipher the underlying block cipher this buffering object wraps. * @param padding the padding type. */ public PaddedBufferedBlockCipher( IBlockCipher cipher, IBlockCipherPadding padding) { this.Cipher = cipher; this.padding = padding; Buffer = new byte[cipher.GetBlockSize()]; BufferOffset = 0; } /** * Create a buffered block cipher Pkcs7 padding * * @param cipher the underlying block cipher this buffering object wraps. */ public PaddedBufferedBlockCipher( IBlockCipher cipher) : this(cipher, new Pkcs7Padding()) { } /** * initialise the cipher. * * @param forEncryption if true the cipher is initialised for * encryption, if false for decryption. * @param param the key and other data required by the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ public override void Init( bool forEncryption, ICipherParameters parameters) { this.ForEncryption = forEncryption; ISecureRandom initRandom = null; if (parameters is ParametersWithRandom) { ParametersWithRandom p = (ParametersWithRandom)parameters; initRandom = p.Random; parameters = p.Parameters; } Reset(); padding.Init(initRandom); Cipher.Init(forEncryption, parameters); } /** * return the minimum size of the output buffer required for an update * plus a doFinal with an input of len bytes. * * @param len the length of the input. * @return the space required to accommodate a call to update and doFinal * with len bytes of input. */ public override int GetOutputSize( int length) { int total = length + BufferOffset; int leftOver = total % Buffer.Length; if (leftOver == 0) { if (ForEncryption) { return total + Buffer.Length; } return total; } return total - leftOver + Buffer.Length; } /** * return the size of the output buffer required for an update * an input of len bytes. * * @param len the length of the input. * @return the space required to accommodate a call to update * with len bytes of input. */ public override int GetUpdateOutputSize( int length) { int total = length + BufferOffset; int leftOver = total % Buffer.Length; if (leftOver == 0) { return total - Buffer.Length; } return total - leftOver; } /** * process a single byte, producing an output block if neccessary. * * @param in the input byte. * @param out the space for any output that might be produced. * @param outOff the offset from which the output will be copied. * @return the number of output bytes copied to out. * @exception DataLengthException if there isn't enough space in out. * @exception InvalidOperationException if the cipher isn't initialised. */ public override int ProcessByte( byte input, byte[] output, int outOff) { int resultLen = 0; if (BufferOffset == Buffer.Length) { resultLen = Cipher.ProcessBlock(Buffer, 0, output, outOff); BufferOffset = 0; } Buffer[BufferOffset++] = input; return resultLen; } /** * process an array of bytes, producing output if necessary. * * @param in the input byte array. * @param inOff the offset at which the input data starts. * @param len the number of bytes to be copied out of the input array. * @param out the space for any output that might be produced. * @param outOff the offset from which the output will be copied. * @return the number of output bytes copied to out. * @exception DataLengthException if there isn't enough space in out. * @exception InvalidOperationException if the cipher isn't initialised. */ public override int ProcessBytes( byte[] input, int inOff, int length, byte[] output, int outOff) { if (length < 0) { throw new ArgumentException("Can't have a negative input length!"); } int blockSize = GetBlockSize(); int outLength = GetUpdateOutputSize(length); if (outLength > 0) { if ((outOff + outLength) > output.Length) { throw new DataLengthException("output buffer too short"); } } int resultLen = 0; int gapLen = Buffer.Length - BufferOffset; if (length > gapLen) { Array.Copy(input, inOff, Buffer, BufferOffset, gapLen); resultLen += Cipher.ProcessBlock(Buffer, 0, output, outOff); BufferOffset = 0; length -= gapLen; inOff += gapLen; while (length > Buffer.Length) { resultLen += Cipher.ProcessBlock(input, inOff, output, outOff + resultLen); length -= blockSize; inOff += blockSize; } } Array.Copy(input, inOff, Buffer, BufferOffset, length); BufferOffset += length; return resultLen; } /** * Process the last block in the buffer. If the buffer is currently * full and padding needs to be added a call to doFinal will produce * 2 * GetBlockSize() bytes. * * @param out the array the block currently being held is copied into. * @param outOff the offset at which the copying starts. * @return the number of output bytes copied to out. * @exception DataLengthException if there is insufficient space in out for * the output or we are decrypting and the input is not block size aligned. * @exception InvalidOperationException if the underlying cipher is not * initialised. * @exception InvalidCipherTextException if padding is expected and not found. */ public override int DoFinal( byte[] output, int outOff) { int blockSize = Cipher.GetBlockSize(); int resultLen = 0; if (ForEncryption) { if (BufferOffset == blockSize) { if ((outOff + 2 * blockSize) > output.Length) { Reset(); throw new DataLengthException("output buffer too short"); } resultLen = Cipher.ProcessBlock(Buffer, 0, output, outOff); BufferOffset = 0; } padding.AddPadding(Buffer, BufferOffset); resultLen += Cipher.ProcessBlock(Buffer, 0, output, outOff + resultLen); Reset(); } else { if (BufferOffset == blockSize) { resultLen = Cipher.ProcessBlock(Buffer, 0, Buffer, 0); BufferOffset = 0; } else { Reset(); throw new DataLengthException("last block incomplete in decryption"); } try { resultLen -= padding.PadCount(Buffer); Array.Copy(Buffer, 0, output, outOff, resultLen); } finally { Reset(); } } return resultLen; } } }
using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; using System.Linq; namespace HTLib2 { public partial class LCS { public class OLcs<T> { public IList<object> _seq1; public IList<object> _seq2; public Func<object,object,bool> _equals; public Tuple<int,int,int>[,] LCS_src1_src2_leng; public void BackTrack ( int curr1, int curr2 , int max_llcs_length , out List<T> lcs , List<int> lcsidx1 = null , List<int> lcsidx2 = null ) { List<object> llcs; List<int> llcsidx1; List<int> llcsidx2; List<Tuple<Oper, object>> loper1to2; List<Tuple<Oper, object>> loper2to1; LongestCommonSubsequence_BackTrack ( _seq1, _seq2, _equals, LCS_src1_src2_leng , curr1, curr2, max_llcs_length , out llcs, out llcsidx1, out llcsidx2, out loper1to2, out loper2to1 ); lcs = llcs.OfType<T>().ToList(); if(lcsidx1 != null) { lcsidx1.Clear(); lcsidx1.AddRange(llcsidx1); } if(lcsidx2 != null) { lcsidx2.Clear(); lcsidx2.AddRange(llcsidx2); } } public T[] lcs; public int[] lcsidx1; public int[] lcsidx2; public Tuple<Oper, T>[] oper1to2; public Tuple<Oper, T>[] oper2to1; public int Length { get { return lcs.Length; } } } static bool LongestCommonSubsequence_selftest = true; public static OLcs<T> LongestCommonSubsequence<T>( IList<T> seq1, IList<T> seq2 , Func<T,T,bool> equals ) { Func<object, object, bool> objequals = delegate(object v1, object v2) { return equals((T)v1,(T)v2); }; Tuple<int,int,int>[,] LCS_src1_src2_leng; object[] lcs ; int[] lcsidx1; int[] lcsidx2; Tuple<Oper, object>[] oper1to2; Tuple<Oper, object>[] oper2to1; object[] objseq1 = seq1.OfType<object>().ToArray(); object[] objseq2 = seq2.OfType<object>().ToArray(); bool succ = LongestCommonSubsequenceImpl ( objseq1, objseq2 , objequals , out LCS_src1_src2_leng , out lcs , out lcsidx1 , out lcsidx2 , out oper1to2 , out oper2to1 ); if(succ == false) return null; return new OLcs<T> { _seq1 = objseq1, _seq2 = objseq2, _equals = objequals, LCS_src1_src2_leng = LCS_src1_src2_leng, lcs = lcs .OfType<T>().ToArray(), lcsidx1 = lcsidx1 , lcsidx2 = lcsidx2 , oper1to2 = oper1to2 .Select(delegate(Tuple<Oper, object> op) { return new Tuple<Oper,T>(op.Item1, (T)op.Item2); }) .ToArray(), oper2to1 = oper2to1 .Select(delegate(Tuple<Oper, object> op) { return new Tuple<Oper,T>(op.Item1, (T)op.Item2); }) .ToArray(), }; } public enum Oper { Match, Delete, Insert, }; public static T[] DoOper<T>(IList<T> seq1, IList<Tuple<Oper, T>> oper1to2, Func<T, T, bool> equals) { seq1 = new List<T>(seq1); List<T> seq2 = new List<T>(); foreach(var oper in oper1to2) { switch(oper.Item1) { case Oper.Match : HDebug.Assert(equals(seq1[0], oper.Item2)); seq1.RemoveAt(0); seq2.Add(oper.Item2); break; case Oper.Insert: seq2.Add(oper.Item2); break; case Oper.Delete: HDebug.Assert(equals(seq1[0], oper.Item2)); seq1.RemoveAt(0); break; default: throw new Exception(); } } return seq2.ToArray(); } static bool LongestCommonSubsequenceImpl ( IList<object> seq1, IList<object> seq2 , Func<object,object,bool> equals , out Tuple<int,int,int>[,] LCS_src1_src2_leng , out object[] lcs , out int[] lcsidx1 , out int[] lcsidx2 , out Tuple<Oper, object>[] oper1to2 , out Tuple<Oper, object>[] oper2to1 ) { /// LCS(X[i],Y[j]) = | empty if i = 0 or j = 0 /// | (LCS(X[i-1],Y[j-1],xi) if xi = yi /// | longest(LCS(X[i], Y[j-1]), LCS(X[i-1],Y[j])) if xi != yj if(LongestCommonSubsequence_selftest) { LongestCommonSubsequence_selftest = false; Func<char,char,bool> charcomp = delegate(char a, char b) { return (a==b); }; OLcs<char> tlcs; char[] tseq1; char[] tseq2; { /// AGCAT /// | | /// G AR tseq1 = "AGCAT".ToArray(); tseq2 = "GAR" .ToArray(); tlcs = LongestCommonSubsequence(tseq1, tseq2, charcomp); HDebug.Assert(tlcs.lcs.HToString() == "GA"); HDebug.Assert(tseq1.HSelectByIndex(tlcs.lcsidx1).HToString() == "GA"); HDebug.Assert(tseq2.HSelectByIndex(tlcs.lcsidx2).HToString() == "GA"); HDebug.Assert(DoOper(tseq1, tlcs.oper1to2, charcomp).HToString() == tseq2.HToString()); HDebug.Assert(DoOper(tseq2, tlcs.oper2to1, charcomp).HToString() == tseq1.HToString()); } { /// XYG AR /// | | | /// AX GCAT tseq1 = "XYGAR" .ToArray(); tseq2 = "AXGCAT".ToArray(); tlcs = LongestCommonSubsequence(tseq1, tseq2, charcomp); HDebug.Assert(tlcs.lcs.HToString() == "XGA"); HDebug.Assert(tseq1.HSelectByIndex(tlcs.lcsidx1).HToString() == "XGA"); HDebug.Assert(tseq2.HSelectByIndex(tlcs.lcsidx2).HToString() == "XGA"); HDebug.Assert(DoOper(tseq1, tlcs.oper1to2, charcomp).HToString() == tseq2.HToString()); HDebug.Assert(DoOper(tseq2, tlcs.oper2to1, charcomp).HToString() == tseq1.HToString()); } } int size1 = seq1.Count; int size2 = seq2.Count; Tuple<int,int,int>[,] LCS = new Tuple<int, int, int>[size1+1, size2+1]; for(int i=0; i<size1+1; i++) { for(int j=0; j<size2+1; j++) { if(i==0 || j==0) { if (i==0 && j==0) LCS[i, j] = new Tuple<int, int, int>( -1, -1, 0); else if(i==0 && j!=0) LCS[i, j] = new Tuple<int, int, int>( 0, j-1, 0); else if(i!=0 && j==0) LCS[i, j] = new Tuple<int, int, int>(i-1, 0, 0); else throw new HException("HTLib2.LCS.LongestCommonSubsequenceImpl - 1"); } else if(equals(seq1[i-1], seq2[j-1]) == true) //else if(seq1[i-1] == seq2[j-1]) { LCS[i, j] = new Tuple<int, int, int>(i-1, j-1, LCS[i-1, j-1].Item3+1); } else { if(LCS[i, j-1].Item3 >= LCS[i-1, j].Item3) { LCS[i, j] = new Tuple<int, int, int>(i, j-1, LCS[i, j-1].Item3); } else { LCS[i, j] = new Tuple<int, int, int>(i-1, j, LCS[i-1, j].Item3); } } } } List<object> llcs ; List<int> llcsidx1 ; List<int> llcsidx2 ; List<Tuple<Oper, object>> loper1to2; List<Tuple<Oper, object>> loper2to1; //List<Tuple<T,int,int>> lcs = new List<Tuple<T, int, int>>(); int curr1 = size1; int curr2 = size2; int max_llcs_length = int.MaxValue; LongestCommonSubsequence_BackTrack ( seq1, seq2, equals , LCS , curr1, curr2, max_llcs_length , out llcs, out llcsidx1, out llcsidx2, out loper1to2, out loper2to1 ); LCS_src1_src2_leng = LCS; lcs = llcs .ToArray(); lcsidx1 = llcsidx1 .ToArray(); lcsidx2 = llcsidx2 .ToArray(); oper1to2 = loper1to2.ToArray(); oper2to1 = loper2to1.ToArray(); return true; } public class OTrack { public List<object> llcs ; public List<int> llcsidx1 ; public List<int> llcsidx2 ; public List<Tuple<Oper, object>> loper1to2; public List<Tuple<Oper, object>> loper2to1; } public static void LongestCommonSubsequence_BackTrack ( IList<object> seq1, IList<object> seq2 , Func<object,object,bool> equals , Tuple<int,int,int>[,] LCS , int curr1 , int curr2 , int max_llcs_length , out List<object> llcs , out List<int> llcsidx1 , out List<int> llcsidx2 , out List<Tuple<Oper, object>> loper1to2 , out List<Tuple<Oper, object>> loper2to1 ) { llcs = new List<object>(); llcsidx1 = new List<int> (); llcsidx2 = new List<int> (); loper1to2 = new List<Tuple<Oper, object>>(); loper2to1 = new List<Tuple<Oper, object>>(); //List<Tuple<T,int,int>> lcs = new List<Tuple<T, int, int>>(); while(!(curr1 == 0 && curr2 == 0)) { if(llcs.Count >= max_llcs_length) break; int prev1 = LCS[curr1, curr2].Item1; int prev2 = LCS[curr1, curr2].Item2; if(prev1+1==curr1 && prev2+1==curr2) { HDebug.Assert(equals(seq1[curr1-1], seq2[curr2-1]) == true); //Debug.Assert(seq1[curr1-1] == seq2[curr2-1]); //lcs.Insert(0, new Tuple<object, int, int>( // seq1[curr1-1], // curr1-1, // curr2-1 // )); llcs .Insert(0, seq1[prev1]); llcsidx1 .Insert(0, prev1 ); llcsidx2 .Insert(0, prev2 ); loper1to2.Insert(0, new Tuple<Oper, object>(Oper.Match, seq1[prev1])); loper2to1.Insert(0, new Tuple<Oper, object>(Oper.Match, seq1[prev1])); } else if(prev1+1==curr1 && prev2 ==curr2) { loper1to2.Insert(0, new Tuple<Oper, object>(Oper.Delete, seq1[prev1])); loper2to1.Insert(0, new Tuple<Oper, object>(Oper.Insert, seq1[prev1])); } else if(prev1 ==curr1 && prev2+1==curr2) { loper1to2.Insert(0, new Tuple<Oper, object>(Oper.Insert, seq2[prev2])); loper2to1.Insert(0, new Tuple<Oper, object>(Oper.Delete, seq2[prev2])); } else { throw new HException("HTLib2.LCS.LongestCommonSubsequenceImpl - 2"); } curr1 = prev1; curr2 = prev2; } } } }
// Copyright 2015 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. using Google.Apis.Download; using Google.Apis.Services; using Google.Apis.Storage.v1; using Google.Cloud.ClientTesting; using System; using System.IO; using System.Linq; using System.Net; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; using Object = Google.Apis.Storage.v1.Data.Object; namespace Google.Cloud.Storage.V1.IntegrationTests { [Collection(nameof(StorageFixture))] public class DownloadObjectTest { private readonly StorageFixture _fixture; public DownloadObjectTest(StorageFixture fixture) { _fixture = fixture; } [Fact] public async Task SimpleDownload() { using (var stream = new MemoryStream()) { await _fixture.Client.DownloadObjectAsync(_fixture.ReadBucket, _fixture.SmallObject, stream); Assert.Equal(_fixture.SmallContent, stream.ToArray()); } } [Fact] public void WrongObjectName() => ValidateNotFound(_fixture.ReadBucket, "doesntexist"); [Fact] public Task WrongObjectName_Async() => ValidateNotFoundAsync(_fixture.ReadBucket, "doesntexist"); [Fact] public void WrongBucketName() => ValidateNotFound(_fixture.BucketPrefix + "doesntexist", "doesntexist"); [Fact] public Task WrongBucketName_Async() => ValidateNotFoundAsync(_fixture.BucketPrefix + "doesntexist", "doesntexist"); private void ValidateNotFound(string bucket, string objectName) { var stream = new MemoryStream(); var exception = Assert.Throws<GoogleApiException>(() => _fixture.Client.DownloadObject(bucket, objectName, stream)); Assert.Equal(HttpStatusCode.NotFound, exception.HttpStatusCode); } private async Task ValidateNotFoundAsync(string bucket, string objectName) { var stream = new MemoryStream(); var exception = await Assert.ThrowsAsync<GoogleApiException>(() => _fixture.Client.DownloadObjectAsync(bucket, objectName, stream)); Assert.Equal(HttpStatusCode.NotFound, exception.HttpStatusCode); } [Fact] public async Task ChunkSize() { int chunks = 0; var progress = new Progress<IDownloadProgress> (p => chunks++); using (var stream = new MemoryStream()) { await _fixture.Client.DownloadObjectAsync( _fixture.ReadBucket, _fixture.LargeObject, stream, new DownloadObjectOptions { ChunkSize = 2 * 1024 }, CancellationToken.None, progress); Assert.Equal(_fixture.LargeContent, stream.ToArray()); Assert.True(chunks >= 5); } } [Fact] public void DownloadObjectFromInvalidBucket() { Assert.Throws<ArgumentException>(() => _fixture.Client.DownloadObject("!!!", _fixture.LargeObject, new MemoryStream())); } [Fact] public void DownloadObjectWrongGeneration() { var existing = GetLatestVersionOfMultiversionObject(); var stream = new MemoryStream(); var exception = Assert.Throws<GoogleApiException>(() => _fixture.Client.DownloadObject(existing, stream, new DownloadObjectOptions { Generation = existing.Generation + 1 }, null)); Assert.Equal(HttpStatusCode.NotFound, exception.HttpStatusCode); Assert.Equal(0, stream.Length); } [Fact] public void DownloadDifferentGenerations() { var bucket = _fixture.ReadBucket; var name = _fixture.SmallThenLargeObject; var objects = _fixture.Client.ListObjects(bucket, name, new ListObjectsOptions { Versions = true }).ToList(); Assert.Equal(2, objects.Count); // Fetch them by generation and check size matches foreach (var obj in objects) { var stream = new MemoryStream(); _fixture.Client.DownloadObject(bucket, name, stream, new DownloadObjectOptions { Generation = obj.Generation }, null); Assert.Equal((long) obj.Size, stream.Length); } } [Fact] public void SpecifyingObjectSourceIgnoredGeneration() { var bucket = _fixture.ReadBucket; var name = _fixture.SmallThenLargeObject; var objects = _fixture.Client.ListObjects(bucket, name, new ListObjectsOptions { Versions = true }) .OrderBy(x => x.Generation) .ToList(); Assert.Equal(2, objects.Count); Assert.NotEqual(objects[0].Size, objects[1].Size); var stream = new MemoryStream(); _fixture.Client.DownloadObject(objects[0], stream); Assert.Equal((long) objects[1].Size, stream.Length); } [Fact] public void DownloadObjectIfGenerationMatch_Matching() { var existing = GetLatestVersionOfMultiversionObject(); var stream = new MemoryStream(); _fixture.Client.DownloadObject(existing, stream, new DownloadObjectOptions { IfGenerationMatch = existing.Generation}, null); Assert.NotEqual(0, stream.Length); } [Fact] public void DownloadObjectIfGenerationMatch_NotMatching() { var existing = GetLatestVersionOfMultiversionObject(); var stream = new MemoryStream(); var exception = Assert.Throws<GoogleApiException>(() => _fixture.Client.DownloadObject(existing, stream, new DownloadObjectOptions { IfGenerationMatch = existing.Generation + 1 }, null)); Assert.Equal(HttpStatusCode.PreconditionFailed, exception.HttpStatusCode); Assert.Equal(0, stream.Length); } [Fact] public void DownloadObjectIfGenerationNotMatch_Matching() { var existing = GetLatestVersionOfMultiversionObject(); var stream = new MemoryStream(); var exception = Assert.Throws<GoogleApiException>(() => _fixture.Client.DownloadObject(existing, stream, new DownloadObjectOptions { IfGenerationNotMatch = existing.Generation }, null)); Assert.Equal(HttpStatusCode.NotModified, exception.HttpStatusCode); Assert.Equal(0, stream.Length); } [Fact] public void DownloadObjectIfGenerationNotMatch_NotMatching() { var existing = GetLatestVersionOfMultiversionObject(); var stream = new MemoryStream(); _fixture.Client.DownloadObject(existing, stream, new DownloadObjectOptions { IfGenerationNotMatch = existing.Generation + 1 }, null); Assert.NotEqual(0, stream.Length); } [Fact] public void DownloadObject_IfGenerationMatchAndNotMatch() { Assert.Throws<ArgumentException>(() => _fixture.Client.DownloadObject( _fixture.ReadBucket, _fixture.SmallThenLargeObject, new MemoryStream(), new DownloadObjectOptions { IfGenerationMatch = 1, IfGenerationNotMatch = 2 }, null)); } [Fact] public void DownloadObjectIfMetagenerationMatch_Matching() { var existing = GetLatestVersionOfMultiversionObject(); var stream = new MemoryStream(); _fixture.Client.DownloadObject(existing, stream, new DownloadObjectOptions { IfMetagenerationMatch = existing.Metageneration}, null); Assert.NotEqual(0, stream.Length); } [Fact] public void DownloadObjectIfMetagenerationMatch_NotMatching() { var existing = GetLatestVersionOfMultiversionObject(); var stream = new MemoryStream(); var exception = Assert.Throws<GoogleApiException>(() => _fixture.Client.DownloadObject(existing, stream, new DownloadObjectOptions { IfMetagenerationMatch = existing.Metageneration + 1 }, null)); Assert.Equal(HttpStatusCode.PreconditionFailed, exception.HttpStatusCode); Assert.Equal(0, stream.Length); } [Fact] public void DownloadObjectIfMetagenerationNotMatch_Matching() { var existing = GetLatestVersionOfMultiversionObject(); var stream = new MemoryStream(); var exception = Assert.Throws<GoogleApiException>(() => _fixture.Client.DownloadObject(existing, stream, new DownloadObjectOptions { IfMetagenerationNotMatch = existing.Metageneration }, null)); Assert.Equal(HttpStatusCode.NotModified, exception.HttpStatusCode); Assert.Equal(0, stream.Length); } [Fact] public void DownloadObjectIfMetagenerationNotMatch_NotMatching() { var existing = GetLatestVersionOfMultiversionObject(); var stream = new MemoryStream(); _fixture.Client.DownloadObject(existing, stream, new DownloadObjectOptions { IfMetagenerationNotMatch = existing.Metageneration + 1 }, null); Assert.NotEqual(0, stream.Length); } [Fact] public void DownloadObject_IfMetagenerationMatchAndNotMatch() { Assert.Throws<ArgumentException>(() => _fixture.Client.DownloadObject( _fixture.ReadBucket, _fixture.SmallThenLargeObject, new MemoryStream(), new DownloadObjectOptions { IfMetagenerationMatch = 1, IfMetagenerationNotMatch = 2 }, null)); } [Fact] public void DownloadObject_Range() { var stream = new MemoryStream(); _fixture.Client.DownloadObject(_fixture.ReadBucket, _fixture.LargeObject, stream, new DownloadObjectOptions { Range = new RangeHeaderValue(2000, 2999) }); var expected = _fixture.LargeContent.Skip(2000).Take(1000).ToArray(); var actual = stream.ToArray(); Assert.Equal(expected, actual); } [SkippableFact] public void DownloadGzippedFile() { TestEnvironment.SkipIfVpcSc(); // The file has a Content-Encoding of gzip, and it's stored compressed. // We should still be able to download it, and the result should be the original plain text. var stream = new MemoryStream(); _fixture.Client.DownloadObject(StorageFixture.CrossLanguageTestBucket, "gzipped-text.txt", stream); var expected = Encoding.UTF8.GetBytes("hello world"); var actual = stream.ToArray(); Assert.Equal(expected, actual); } // See https://github.com/googleapis/google-cloud-dotnet/issues/1784 for the background to // the following two tests. [SkippableFact(Skip = "https://github.com/googleapis/google-cloud-dotnet/issues/1784")] public void DownloadGzippedFile_NoClientDecompression() { TestEnvironment.SkipIfVpcSc(); var service = new StorageService(new BaseClientService.Initializer { HttpClientInitializer = _fixture.Client.Service.HttpClientInitializer, GZipEnabled = false }); var client = new StorageClientImpl(service); var stream = new MemoryStream(); client.DownloadObject(StorageFixture.CrossLanguageTestBucket, "gzipped-text.txt", stream); var expected = Encoding.UTF8.GetBytes("hello world"); var actual = stream.ToArray(); Assert.Equal(expected, actual); } [SkippableFact] public void DownloadGzippedFile_NoClientDecompression_IgnoreHash() { TestEnvironment.SkipIfVpcSc(); var service = new StorageService(new BaseClientService.Initializer { HttpClientInitializer = _fixture.Client.Service.HttpClientInitializer, GZipEnabled = false }); var client = new StorageClientImpl(service); var stream = new MemoryStream(); client.DownloadObject(StorageFixture.CrossLanguageTestBucket, "gzipped-text.txt", stream, new DownloadObjectOptions { DownloadValidationMode = DownloadValidationMode.Never }); var expected = Encoding.UTF8.GetBytes("hello world"); var actual = stream.ToArray(); Assert.Equal(expected, actual); } [Fact] public void InvalidDownloadValidationMode() { var options = new DownloadObjectOptions { DownloadValidationMode = (DownloadValidationMode) 12345 }; Assert.Throws<ArgumentException>(() => _fixture.Client.DownloadObject(_fixture.ReadBucket, "irrelevant.txt", new MemoryStream(), options)); } private Object GetLatestVersionOfMultiversionObject() { var service = _fixture.Client.Service; return service.Objects.Get(_fixture.ReadBucket, _fixture.SmallThenLargeObject).Execute(); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using LibGit2Sharp.Core; using LibGit2Sharp.Core.Handles; namespace LibGit2Sharp { /// <summary> /// Show changes between the working tree and the index or a tree, changes between the index and a tree, changes between two trees, or changes between two files on disk. /// <para> /// Copied and renamed files currently cannot be detected, as the feature is not supported by libgit2 yet. /// These files will be shown as a pair of Deleted/Added files.</para> /// </summary> public class Diff { private readonly Repository repo; private static GitDiffOptions BuildOptions(DiffModifiers diffOptions, FilePath[] filePaths = null, MatchedPathsAggregator matchedPathsAggregator = null, CompareOptions compareOptions = null) { var options = new GitDiffOptions(); options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_TYPECHANGE; compareOptions = compareOptions ?? new CompareOptions(); options.ContextLines = (ushort)compareOptions.ContextLines; options.InterhunkLines = (ushort)compareOptions.InterhunkLines; if (diffOptions.HasFlag(DiffModifiers.IncludeUntracked)) { options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_UNTRACKED | GitDiffOptionFlags.GIT_DIFF_RECURSE_UNTRACKED_DIRS | GitDiffOptionFlags.GIT_DIFF_SHOW_UNTRACKED_CONTENT; } if (diffOptions.HasFlag(DiffModifiers.IncludeIgnored)) { options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_IGNORED | GitDiffOptionFlags.GIT_DIFF_RECURSE_IGNORED_DIRS; } if (diffOptions.HasFlag(DiffModifiers.IncludeUnmodified) || compareOptions.IncludeUnmodified || (compareOptions.Similarity != null && (compareOptions.Similarity.RenameDetectionMode == RenameDetectionMode.CopiesHarder || compareOptions.Similarity.RenameDetectionMode == RenameDetectionMode.Exact))) { options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_UNMODIFIED; } if (diffOptions.HasFlag(DiffModifiers.DisablePathspecMatch)) { options.Flags |= GitDiffOptionFlags.GIT_DIFF_DISABLE_PATHSPEC_MATCH; } if (matchedPathsAggregator != null) { options.NotifyCallback = matchedPathsAggregator.OnGitDiffNotify; } if (filePaths != null) { options.PathSpec = GitStrArrayManaged.BuildFrom(filePaths); } return options; } /// <summary> /// Needed for mocking purposes. /// </summary> protected Diff() { } internal Diff(Repository repo) { this.repo = repo; } private static readonly IDictionary<DiffTargets, Func<Repository, TreeComparisonHandleRetriever>> HandleRetrieverDispatcher = BuildHandleRetrieverDispatcher(); private static IDictionary<DiffTargets, Func<Repository, TreeComparisonHandleRetriever>> BuildHandleRetrieverDispatcher() { return new Dictionary<DiffTargets, Func<Repository, TreeComparisonHandleRetriever>> { { DiffTargets.Index, IndexToTree }, { DiffTargets.WorkingDirectory, WorkdirToTree }, { DiffTargets.Index | DiffTargets.WorkingDirectory, WorkdirAndIndexToTree }, }; } private static readonly IDictionary<Type, Func<DiffSafeHandle, object>> ChangesBuilders = new Dictionary<Type, Func<DiffSafeHandle, object>> { { typeof(Patch), diff => new Patch(diff) }, { typeof(TreeChanges), diff => new TreeChanges(diff) }, { typeof(PatchStats), diff => new PatchStats(diff) }, }; /// <summary> /// Show changes between two <see cref="Blob"/>s. /// </summary> /// <param name="oldBlob">The <see cref="Blob"/> you want to compare from.</param> /// <param name="newBlob">The <see cref="Blob"/> you want to compare to.</param> /// <param name="compareOptions">Additional options to define comparison behavior.</param> /// <returns>A <see cref="ContentChanges"/> containing the changes between the <paramref name="oldBlob"/> and the <paramref name="newBlob"/>.</returns> public virtual ContentChanges Compare(Blob oldBlob, Blob newBlob, CompareOptions compareOptions = null) { using (GitDiffOptions options = BuildOptions(DiffModifiers.None, compareOptions: compareOptions)) { return new ContentChanges(repo, oldBlob, newBlob, options); } } /// <summary> /// Show changes between two <see cref="Tree"/>s. /// </summary> /// <param name="oldTree">The <see cref="Tree"/> you want to compare from.</param> /// <param name="newTree">The <see cref="Tree"/> you want to compare to.</param> /// <param name="paths">The list of paths (either files or directories) that should be compared.</param> /// <param name="explicitPathsOptions"> /// If set, the passed <paramref name="paths"/> will be treated as explicit paths. /// Use these options to determine how unmatched explicit paths should be handled. /// </param> /// <param name="compareOptions">Additional options to define patch generation behavior.</param> /// <returns>A <see cref="TreeChanges"/> containing the changes between the <paramref name="oldTree"/> and the <paramref name="newTree"/>.</returns> public virtual T Compare<T>(Tree oldTree, Tree newTree, IEnumerable<string> paths = null, ExplicitPathsOptions explicitPathsOptions = null, CompareOptions compareOptions = null) where T : class { Func<DiffSafeHandle, object> builder; if (!ChangesBuilders.TryGetValue(typeof (T), out builder)) { throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture, "Unexpected type '{0}' passed to Compare. Supported values are either '{1}' or '{2}'.", typeof (T), typeof (TreeChanges), typeof (Patch))); } var comparer = TreeToTree(repo); ObjectId oldTreeId = oldTree != null ? oldTree.Id : null; ObjectId newTreeId = newTree != null ? newTree.Id : null; var diffOptions = DiffModifiers.None; if (explicitPathsOptions != null) { diffOptions |= DiffModifiers.DisablePathspecMatch; if (explicitPathsOptions.ShouldFailOnUnmatchedPath || explicitPathsOptions.OnUnmatchedPath != null) { diffOptions |= DiffModifiers.IncludeUnmodified; } } using (DiffSafeHandle diff = BuildDiffList(oldTreeId, newTreeId, comparer, diffOptions, paths, explicitPathsOptions, compareOptions)) { return (T)builder(diff); } } /// <summary> /// Show changes between a <see cref="Tree"/> and the Index, the Working Directory, or both. /// <para> /// The level of diff performed can be specified by passing either a <see cref="TreeChanges"/> /// or <see cref="Patch"/> type as the generic parameter. /// </para> /// </summary> /// <param name="oldTree">The <see cref="Tree"/> to compare from.</param> /// <param name="diffTargets">The targets to compare to.</param> /// <param name="paths">The list of paths (either files or directories) that should be compared.</param> /// <param name="explicitPathsOptions"> /// If set, the passed <paramref name="paths"/> will be treated as explicit paths. /// Use these options to determine how unmatched explicit paths should be handled. /// </param> /// <param name="compareOptions">Additional options to define patch generation behavior.</param> /// <typeparam name="T">Can be either a <see cref="TreeChanges"/> if you are only interested in the list of files modified, added, ..., or /// a <see cref="Patch"/> if you want the actual patch content for the whole diff and for individual files.</typeparam> /// <returns>A <typeparamref name="T"/> containing the changes between the <see cref="Tree"/> and the selected target.</returns> public virtual T Compare<T>(Tree oldTree, DiffTargets diffTargets, IEnumerable<string> paths = null, ExplicitPathsOptions explicitPathsOptions = null, CompareOptions compareOptions = null) where T : class { Func<DiffSafeHandle, object> builder; if (!ChangesBuilders.TryGetValue(typeof (T), out builder)) { throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture, "Unexpected type '{0}' passed to Compare. Supported values are either '{1}' or '{2}'.", typeof (T), typeof (TreeChanges), typeof (Patch))); } var comparer = HandleRetrieverDispatcher[diffTargets](repo); ObjectId oldTreeId = oldTree != null ? oldTree.Id : null; DiffModifiers diffOptions = diffTargets.HasFlag(DiffTargets.WorkingDirectory) ? DiffModifiers.IncludeUntracked : DiffModifiers.None; if (explicitPathsOptions != null) { diffOptions |= DiffModifiers.DisablePathspecMatch; if (explicitPathsOptions.ShouldFailOnUnmatchedPath || explicitPathsOptions.OnUnmatchedPath != null) { diffOptions |= DiffModifiers.IncludeUnmodified; } } using (DiffSafeHandle diff = BuildDiffList(oldTreeId, null, comparer, diffOptions, paths, explicitPathsOptions, compareOptions)) { return (T)builder(diff); } } /// <summary> /// Show changes between the working directory and the index. /// <para> /// The level of diff performed can be specified by passing either a <see cref="TreeChanges"/> /// or <see cref="Patch"/> type as the generic parameter. /// </para> /// </summary> /// <param name="paths">The list of paths (either files or directories) that should be compared.</param> /// <param name="includeUntracked">If true, include untracked files from the working dir as additions. Otherwise ignore them.</param> /// <param name="explicitPathsOptions"> /// If set, the passed <paramref name="paths"/> will be treated as explicit paths. /// Use these options to determine how unmatched explicit paths should be handled. /// </param> /// <param name="compareOptions">Additional options to define patch generation behavior.</param> /// <typeparam name="T">Can be either a <see cref="TreeChanges"/> if you are only interested in the list of files modified, added, ..., or /// a <see cref="Patch"/> if you want the actual patch content for the whole diff and for individual files.</typeparam> /// <returns>A <typeparamref name="T"/> containing the changes between the working directory and the index.</returns> public virtual T Compare<T>(IEnumerable<string> paths = null, bool includeUntracked = false, ExplicitPathsOptions explicitPathsOptions = null, CompareOptions compareOptions = null) where T : class { return Compare<T>(includeUntracked ? DiffModifiers.IncludeUntracked : DiffModifiers.None, paths, explicitPathsOptions, compareOptions); } internal virtual T Compare<T>(DiffModifiers diffOptions, IEnumerable<string> paths = null, ExplicitPathsOptions explicitPathsOptions = null, CompareOptions compareOptions = null) where T : class { Func<DiffSafeHandle, object> builder; if (!ChangesBuilders.TryGetValue(typeof (T), out builder)) { throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture, "Unexpected type '{0}' passed to Compare. Supported values are either '{1}' or '{2}'.", typeof (T), typeof (TreeChanges), typeof (Patch))); } var comparer = WorkdirToIndex(repo); if (explicitPathsOptions != null) { diffOptions |= DiffModifiers.DisablePathspecMatch; if (explicitPathsOptions.ShouldFailOnUnmatchedPath || explicitPathsOptions.OnUnmatchedPath != null) { diffOptions |= DiffModifiers.IncludeUnmodified; } } using (DiffSafeHandle diff = BuildDiffList(null, null, comparer, diffOptions, paths, explicitPathsOptions, compareOptions)) { return (T)builder(diff); } } internal delegate DiffSafeHandle TreeComparisonHandleRetriever(ObjectId oldTreeId, ObjectId newTreeId, GitDiffOptions options); private static TreeComparisonHandleRetriever TreeToTree(Repository repo) { return (oh, nh, o) => Proxy.git_diff_tree_to_tree(repo.Handle, oh, nh, o); } private static TreeComparisonHandleRetriever WorkdirToIndex(Repository repo) { return (oh, nh, o) => Proxy.git_diff_index_to_workdir(repo.Handle, repo.Index.Handle, o); } private static TreeComparisonHandleRetriever WorkdirToTree(Repository repo) { return (oh, nh, o) => Proxy.git_diff_tree_to_workdir(repo.Handle, oh, o); } private static TreeComparisonHandleRetriever WorkdirAndIndexToTree(Repository repo) { TreeComparisonHandleRetriever comparisonHandleRetriever = (oh, nh, o) => { DiffSafeHandle diff = Proxy.git_diff_tree_to_index(repo.Handle, repo.Index.Handle, oh, o); using (DiffSafeHandle diff2 = Proxy.git_diff_index_to_workdir(repo.Handle, repo.Index.Handle, o)) { Proxy.git_diff_merge(diff, diff2); } return diff; }; return comparisonHandleRetriever; } private static TreeComparisonHandleRetriever IndexToTree(Repository repo) { return (oh, nh, o) => Proxy.git_diff_tree_to_index(repo.Handle, repo.Index.Handle, oh, o); } private DiffSafeHandle BuildDiffList(ObjectId oldTreeId, ObjectId newTreeId, TreeComparisonHandleRetriever comparisonHandleRetriever, DiffModifiers diffOptions, IEnumerable<string> paths, ExplicitPathsOptions explicitPathsOptions, CompareOptions compareOptions) { var matchedPaths = new MatchedPathsAggregator(); var filePaths = repo.ToFilePaths(paths); using (GitDiffOptions options = BuildOptions(diffOptions, filePaths, matchedPaths, compareOptions)) { var diffList = comparisonHandleRetriever(oldTreeId, newTreeId, options); if (explicitPathsOptions != null) { try { DispatchUnmatchedPaths(explicitPathsOptions, filePaths, matchedPaths); } catch { diffList.Dispose(); throw; } } DetectRenames(diffList, compareOptions); return diffList; } } private static void DetectRenames(DiffSafeHandle diffList, CompareOptions compareOptions) { var similarityOptions = (compareOptions == null) ? null : compareOptions.Similarity; if (similarityOptions == null || similarityOptions.RenameDetectionMode == RenameDetectionMode.Default) { Proxy.git_diff_find_similar(diffList, null); return; } if (similarityOptions.RenameDetectionMode == RenameDetectionMode.None) { return; } var opts = new GitDiffFindOptions { RenameThreshold = (ushort)similarityOptions.RenameThreshold, RenameFromRewriteThreshold = (ushort)similarityOptions.RenameFromRewriteThreshold, CopyThreshold = (ushort)similarityOptions.CopyThreshold, BreakRewriteThreshold = (ushort)similarityOptions.BreakRewriteThreshold, RenameLimit = (UIntPtr)similarityOptions.RenameLimit, }; switch (similarityOptions.RenameDetectionMode) { case RenameDetectionMode.Exact: opts.Flags = GitDiffFindFlags.GIT_DIFF_FIND_EXACT_MATCH_ONLY | GitDiffFindFlags.GIT_DIFF_FIND_RENAMES | GitDiffFindFlags.GIT_DIFF_FIND_COPIES | GitDiffFindFlags.GIT_DIFF_FIND_COPIES_FROM_UNMODIFIED; break; case RenameDetectionMode.Renames: opts.Flags = GitDiffFindFlags.GIT_DIFF_FIND_RENAMES; break; case RenameDetectionMode.Copies: opts.Flags = GitDiffFindFlags.GIT_DIFF_FIND_RENAMES | GitDiffFindFlags.GIT_DIFF_FIND_COPIES; break; case RenameDetectionMode.CopiesHarder: opts.Flags = GitDiffFindFlags.GIT_DIFF_FIND_RENAMES | GitDiffFindFlags.GIT_DIFF_FIND_COPIES | GitDiffFindFlags.GIT_DIFF_FIND_COPIES_FROM_UNMODIFIED; break; } if (!compareOptions.IncludeUnmodified) { opts.Flags |= GitDiffFindFlags.GIT_DIFF_FIND_REMOVE_UNMODIFIED; } switch (similarityOptions.WhitespaceMode) { case WhitespaceMode.DontIgnoreWhitespace: opts.Flags |= GitDiffFindFlags.GIT_DIFF_FIND_DONT_IGNORE_WHITESPACE; break; case WhitespaceMode.IgnoreLeadingWhitespace: opts.Flags |= GitDiffFindFlags.GIT_DIFF_FIND_IGNORE_LEADING_WHITESPACE; break; case WhitespaceMode.IgnoreAllWhitespace: opts.Flags |= GitDiffFindFlags.GIT_DIFF_FIND_IGNORE_WHITESPACE; break; } Proxy.git_diff_find_similar(diffList, opts); } private static void DispatchUnmatchedPaths(ExplicitPathsOptions explicitPathsOptions, IEnumerable<FilePath> filePaths, IEnumerable<FilePath> matchedPaths) { List<FilePath> unmatchedPaths = (filePaths != null ? filePaths.Except(matchedPaths) : Enumerable.Empty<FilePath>()).ToList(); if (!unmatchedPaths.Any()) { return; } if (explicitPathsOptions.OnUnmatchedPath != null) { unmatchedPaths.ForEach(filePath => explicitPathsOptions.OnUnmatchedPath(filePath.Native)); } if (explicitPathsOptions.ShouldFailOnUnmatchedPath) { throw new UnmatchedPathException(BuildUnmatchedPathsMessage(unmatchedPaths)); } } private static string BuildUnmatchedPathsMessage(List<FilePath> unmatchedPaths) { var message = new StringBuilder("There were some unmatched paths:" + Environment.NewLine); unmatchedPaths.ForEach(filePath => message.AppendFormat("- {0}{1}", filePath.Native, Environment.NewLine)); return message.ToString(); } } }
// Copyright (c) 2015, Outercurve Foundation. // 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 the Outercurve Foundation 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using WebsitePanel.EnterpriseServer; namespace WebsitePanel.Portal { public partial class UserAccountEditDetails : WebsitePanelModuleBase { private const string UserStatusConst = "UserStatus"; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindUser(); if (PortalUtils.GetHideDemoCheckbox()) rowDemo.Visible = false; } if (PanelSecurity.LoggedUser.Role == UserRole.User) { txtSubscriberNumber.ReadOnly = true; } } private void BindUser() { try { UserInfo user = UsersHelper.GetUser(PanelSecurity.SelectedUserId); if (user != null) { // bind roles BindRoles(PanelSecurity.EffectiveUserId); bool editAdminAccount = (user.UserId == PanelSecurity.EffectiveUserId); if(!editAdminAccount) role.Items.Remove("Administrator"); // select role Utils.SelectListItem(role, user.Role.ToString()); // select loginStatus loginStatus.SelectedIndex = user.LoginStatusId; rowRole.Visible = !editAdminAccount; // select status chkDemo.Checked = user.IsDemo; rowDemo.Visible = !editAdminAccount; // account info txtFirstName.Text = PortalAntiXSS.DecodeOld(user.FirstName); txtLastName.Text = PortalAntiXSS.DecodeOld(user.LastName); txtSubscriberNumber.Text = PortalAntiXSS.DecodeOld(user.SubscriberNumber); txtEmail.Text = user.Email; txtSecondaryEmail.Text = user.SecondaryEmail; ddlMailFormat.SelectedIndex = user.HtmlMail ? 1 : 0; lblUsername.Text = user.Username; // contact info contact.CompanyName = user.CompanyName; contact.Address = user.Address; contact.City = user.City; contact.Country = user.Country; contact.State = user.State; contact.Zip = user.Zip; contact.PrimaryPhone = user.PrimaryPhone; contact.SecondaryPhone = user.SecondaryPhone; contact.Fax = user.Fax; contact.MessengerId = user.InstantMessenger; ViewState[UserStatusConst] = user.Status; } else { // can't be found RedirectAccountHomePage(); } } catch (Exception ex) { ShowErrorMessage("USER_GET_USER", ex); return; } } private void SaveUser() { if (Page.IsValid) { // gather data from form UserInfo user = new UserInfo(); user.UserId = PanelSecurity.SelectedUserId; user.Role = (UserRole)Enum.Parse(typeof(UserRole), role.SelectedValue); user.IsDemo = chkDemo.Checked; user.Status = ViewState[UserStatusConst] != null ? (UserStatus) ViewState[UserStatusConst]: UserStatus.Active; user.LoginStatusId = loginStatus.SelectedIndex; // account info user.FirstName = txtFirstName.Text; user.LastName = txtLastName.Text; user.SubscriberNumber = txtSubscriberNumber.Text; user.Email = txtEmail.Text; user.SecondaryEmail = txtSecondaryEmail.Text; user.HtmlMail = ddlMailFormat.SelectedIndex == 1; // contact info user.CompanyName = contact.CompanyName; user.Address = contact.Address; user.City = contact.City; user.Country = contact.Country; user.State = contact.State; user.Zip = contact.Zip; user.PrimaryPhone = contact.PrimaryPhone; user.SecondaryPhone = contact.SecondaryPhone; user.Fax = contact.Fax; user.InstantMessenger = contact.MessengerId; // update existing user try { int result = PortalUtils.UpdateUserAccount(/*TaskID, */user); //int result = ES.Services.Users.UpdateUserTaskAsynchronously(TaskID, user); AsyncTaskID = TaskID; if (result.Equals(-102)) { if (user.RoleId.Equals(3)) { ShowResultMessage(result); return; } } else { if (result < 0) { ShowResultMessage(result); return; } } } catch (Exception ex) { ShowErrorMessage("USER_UPDATE_USER", ex); return; } // return back to the list RedirectAccountHomePage(); } } private void BindRoles(int userId) { // load selected user UserInfo user = UsersHelper.GetUser(userId); if (user != null) { if (user.Role == UserRole.Reseller || user.Role == UserRole.User) role.Items.Remove("Administrator"); if ((user.Role == UserRole.User) |(PanelSecurity.LoggedUser.Role == UserRole.ResellerCSR) | (PanelSecurity.LoggedUser.Role == UserRole.ResellerHelpdesk)) role.Items.Remove("Reseller"); } } protected void btnUpdate_Click(object sender, EventArgs e) { SaveUser(); } protected void btnCancel_Click(object sender, EventArgs e) { RedirectAccountHomePage(); } } }
// JavaScript String instance methods added as extensions methods to System.String instance using System; namespace Bridge.Html5 { /// <summary> /// String global object extension methods for the ECMA String prototype object. /// </summary> [External] public static class StringPrototype { /// <summary> /// The match() method retrieves the matches when matching a string against a regular expression. /// </summary> /// <param name="str">A string instance</param> /// <param name="regex">A regular expression object. If a non-Regex object obj is passed, it is implicitly converted to a Regex by using new Regex(obj).</param> /// <returns>An Array containing the entire match result and any parentheses-captured matched results, or null if there were no matches.</returns> [Template("{str}.match({regex})")] public static extern string[] Match(this string str, RegExp regex); /// <summary> /// The match() method retrieves the matches when matching a string against a regular expression. /// </summary> /// <param name="str">A string instance</param> /// <param name="regex">A regular expression object. If a non-Regex object obj is passed, it is implicitly converted to a Regex by using new Regex(obj).</param> /// <returns>An Array containing the entire match result and any parentheses-captured matched results, or null if there were no matches.</returns> [Template("{str}.match({regex})")] public static extern string[] Match(this string str, string regex); /// <summary> /// The search() method executes a search for a match between a regular expression and this String object. /// </summary> /// <param name="str">A string instance</param> /// <param name="regex">A regular expression object. If a non-Regex object obj is passed, it is implicitly converted to a Regex by using new Regex(obj).</param> /// <returns>If successful, returns the index of the first match of the regular expression inside the string. Otherwise, it returns -1.</returns> [Template("{str}.search({regex})")] public static extern int Search(this string str, RegExp regex); /// <summary> /// The search() method executes a search for a match between a regular expression and this String object. /// </summary> /// <param name="str">A string instance</param> /// <param name="regex">A regular expression object. If a non-Regex object obj is passed, it is implicitly converted to a Regex by using new Regex(obj).</param> /// <returns>If successful, returns the index of the first match of the regular expression inside the string. Otherwise, it returns -1.</returns> [Template("{str}.search({regex})")] public static extern int Search(this string str, string regex); /// <summary> /// The toLowerCase() method returns the calling string value converted to lowercase. /// </summary> /// <param name="str">A string instance</param> /// <returns>A new string representing the calling string converted to lower case.</returns> [Template("{str}.toLowerCase()")] public static extern string ToLowerCase(this string str); /// <summary> /// The toLocaleLowerCase() method returns the calling string value converted to lower case, according to any locale-specific case mappings. /// </summary> /// <param name="str">A string instance</param> /// <returns>A new string representing the calling string converted to lower case, according to any locale-specific case mappings.</returns> [Template("{str}.toLocaleLowerCase()")] public static extern string ToLocaleLowerCase(this string str); /// <summary> /// The toUpperCase() method returns the calling string value converted to uppercase. /// </summary> /// <param name="str">A string instance</param> /// <returns>A new string representing the calling string converted to upper case.</returns> [Template("{str}.toUpperCase()")] public static extern string ToUpperCase(this string str); /// <summary> /// The toLocaleUpperCase() method returns the calling string value converted to upper case, according to any locale-specific case mappings. /// </summary> /// <param name="str">A string instance</param> /// <returns>A new string representing the calling string converted to upper case, according to any locale-specific case mappings.</returns> [Template("{str}.toLocaleUpperCase()")] public static extern string ToLocaleUpperCase(this string str); /// <summary> /// The localeCompare() method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order. /// </summary> /// <param name="str">A string instance</param> /// <param name="compareString">The string against which the referring string is compared</param> /// <returns>A negative number if the reference string occurs before the compare string; positive if the reference string occurs after the compare string; 0 if they are equivalent.</returns> [Template("{str}.localeCompare({compareString})")] public static extern int LocaleCompare(this string str, string compareString); /// <summary> /// The localeCompare() method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order. /// </summary> /// <param name="str">A string instance</param> /// <param name="compareString">The string against which the referring string is compared</param> /// <param name="locales">A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the locales argument, see the Intl page.</param> /// <returns>A negative number if the reference string occurs before the compare string; positive if the reference string occurs after the compare string; 0 if they are equivalent.</returns> /// <returns>A negative number if the reference string occurs before the compare string; positive if the reference string occurs after the compare string; 0 if they are equivalent.</returns> [Template("{str}.localeCompare({compareString}, {locales})")] public static extern int LocaleCompare(this string str, string compareString, string locales); /// <summary> /// The localeCompare() method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order. /// </summary> /// <param name="str">A string instance</param> /// <param name="compareString">The string against which the referring string is compared</param> /// <param name="locales">A string with a BCP 47 language tag, or an array of such strings. For the general form and interpretation of the locales argument, see the Intl page.</param> /// <param name="options">An object with some or all of the following properties:</param> /// <returns>A negative number if the reference string occurs before the compare string; positive if the reference string occurs after the compare string; 0 if they are equivalent.</returns> [Template("{str}.localeCompare({compareString}, {locales}, {options})")] public static extern int LocaleCompare(this string str, string compareString, string locales, LocaleOptions options); /// <summary> /// The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. /// </summary> /// <param name="str">A string instance</param> /// <param name="substr">A String that is to be replaced by newSubStr. It is treated as a verbatim string and is not interpreted as a regular expression. Only the first occurrence will be replaced.</param> /// <param name="newSubStr">The String that replaces the substring specified by the specified regexp or substr parameter. A number of special replacement patterns are supported; see the "Specifying a string as a parameter" section below.</param> /// <returns>A new string with some or all matches of a pattern replaced by a replacement.</returns> [Template("{str}.replace({substr}, {newSubStr})")] public static extern string Replace(this string str, string substr, string newSubStr); /// <summary> /// The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. /// </summary> /// <param name="str">A string instance</param> /// <param name="substr">A String that is to be replaced by newSubStr. It is treated as a verbatim string and is not interpreted as a regular expression. Only the first occurrence will be replaced.</param> /// <param name="function">A function to be invoked to create the new substring to be used to replace the matches to the given regexp or substr. </param> /// <returns>A new string with some or all matches of a pattern replaced by a replacement.</returns> [Template("{str}.replace({substr}, {function})")] public static extern string Replace(this string str, string substr, Delegate function); /// <summary> /// The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. /// </summary> /// <param name="str">A string instance</param> /// <param name="substr">A String that is to be replaced by newSubStr. It is treated as a verbatim string and is not interpreted as a regular expression. Only the first occurrence will be replaced.</param> /// <param name="function">A function to be invoked to create the new substring to be used to replace the matches to the given regexp or substr. </param> /// <returns>A new string with some or all matches of a pattern replaced by a replacement.</returns> [Template("{str}.replace({substr}, {function})")] public static extern string Replace(this string str, string substr, Func<string, string> function); /// <summary> /// The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. /// </summary> /// <param name="str">A string instance</param> /// <param name="substr">A String that is to be replaced by newSubStr. It is treated as a verbatim string and is not interpreted as a regular expression. Only the first occurrence will be replaced.</param> /// <param name="function">A function to be invoked to create the new substring to be used to replace the matches to the given regexp or substr. </param> /// <returns>A new string with some or all matches of a pattern replaced by a replacement.</returns> [Template("{str}.replace({substr}, {function})")] public static extern string Replace(this string str, string substr, Func<string, int, string> function); /// <summary> /// The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. /// </summary> /// <param name="str">A string instance</param> /// <param name="substr">A String that is to be replaced by newSubStr. It is treated as a verbatim string and is not interpreted as a regular expression. Only the first occurrence will be replaced.</param> /// <param name="function">A function to be invoked to create the new substring to be used to replace the matches to the given regexp or substr. </param> /// <returns>A new string with some or all matches of a pattern replaced by a replacement.</returns> [Template("{str}.replace({substr}, {function})")] public static extern string Replace(this string str, string substr, Func<string, int, string, string> function); /// <summary> /// The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. /// </summary> /// <param name="str">A string instance</param> /// <param name="regexp">A RegExp object or literal. The match or matches are replaced with newSubStr or the value returned by the specified function.</param> /// <param name="newSubStr">The String that replaces the substring specified by the specified regexp or substr parameter. A number of special replacement patterns are supported; see the "Specifying a string as a parameter" section below.</param> /// <returns>A new string with some or all matches of a pattern replaced by a replacement.</returns> [Template("{str}.replace({regexp}, {newSubStr})")] public static extern string Replace(this string str, RegExp regexp, string newSubStr); /// <summary> /// The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. /// </summary> /// <param name="str">A string instance</param> /// <param name="regexp">A RegExp object or literal. The match or matches are replaced with newSubStr or the value returned by the specified function.</param> /// <param name="function">A function to be invoked to create the new substring to be used to replace the matches to the given regexp or substr. </param> /// <returns>A new string with some or all matches of a pattern replaced by a replacement.</returns> [Template("{str}.replace({regexp}, {function})")] public static extern string Replace(this string str, RegExp regexp, Delegate function); /// <summary> /// The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. /// </summary> /// <param name="str">A string instance</param> /// <param name="regexp">A RegExp object or literal. The match or matches are replaced with newSubStr or the value returned by the specified function.</param> /// <param name="function">A function to be invoked to create the new substring to be used to replace the matches to the given regexp or substr. </param> /// <returns>A new string with some or all matches of a pattern replaced by a replacement.</returns> [Template("{str}.replace({regexp}, {function})")] public static extern string Replace(this string str, RegExp regexp, Func<string, string> function); /// <summary> /// The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. /// </summary> /// <param name="str">A string instance</param> /// <param name="regexp">A RegExp object or literal. The match or matches are replaced with newSubStr or the value returned by the specified function.</param> /// <param name="function">A function to be invoked to create the new substring to be used to replace the matches to the given regexp or substr. </param> /// <returns>A new string with some or all matches of a pattern replaced by a replacement.</returns> [Template("{str}.replace({regexp}, {function})")] public static extern string Replace(this string str, RegExp regexp, Func<string, int, string> function); /// <summary> /// The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp, and the replacement can be a string or a function to be called for each match. /// </summary> /// <param name="str">A string instance</param> /// <param name="regexp">A RegExp object or literal. The match or matches are replaced with newSubStr or the value returned by the specified function.</param> /// <param name="function">A function to be invoked to create the new substring to be used to replace the matches to the given regexp or substr. </param> /// <returns>A new string with some or all matches of a pattern replaced by a replacement.</returns> [Template("{str}.replace({regexp}, {function})")] public static extern string Replace(this string str, RegExp regexp, Func<string, int, string, string> function); /// <summary> /// The slice() method extracts a section of a string and returns a new string. /// </summary> /// <param name="str">A string instance</param> /// <param name="beginIndex">The zero-based index at which to begin extraction. If negative, it is treated as strLength + beginIndex where strLength is the length of the string (for example, if beginIndex is -3 it is treated as strLength - 3). If beginIndex is greater than or equal to the length of the string, slice() returns an empty string.</param> /// <returns>A new string containing the extracted section of the string.</returns> [Template("{str}.slice({beginIndex})")] public static extern string Slice(this string str, int beginIndex); /// <summary> /// The slice() method extracts a section of a string and returns a new string. /// </summary> /// <param name="str">A string instance</param> /// <param name="beginIndex">The zero-based index at which to begin extraction. If negative, it is treated as strLength + beginIndex where strLength is the length of the string (for example, if beginIndex is -3 it is treated as strLength - 3). If beginIndex is greater than or equal to the length of the string, slice() returns an empty string.</param> /// <param name="endIndex">The zero-based index before which to end extraction. The character at this index will not be included. If endIndex is omitted, slice() extracts to the end of the string. If negative, it is treated as strLength + endIndex where strLength is the length of the string (for example, if endIndex is -3 it is treated as strLength - 3).</param> /// <returns>A new string containing the extracted section of the string.</returns> [Template("{str}.slice({beginIndex}, {endIndex})")] public static extern string Slice(this string str, int beginIndex, int endIndex); /// <summary> /// Splits a String object into an array of strings by separating the string into substrings. /// </summary> /// <param name="str">A string instance</param> /// <param name="separator">Specifies the character to use for separating the string. The separator is treated as a string or a regular expression. If separator is omitted or does not occur in str, the array returned contains one element consisting of the entire string. If separator is an empty string, str is converted to an array of characters.</param> /// <returns>An array of strings split at each point where the separator occurs in the given string.</returns> [Template("{str}.split(String.fromCharCode({separator}))")] public static extern string[] Split(this string str, char separator); /// <summary> /// Splits a String object into an array of strings by separating the string into substrings. /// </summary> /// <param name="str">A string instance</param> /// <param name="limit">Integer specifying a limit on the number of splits to be found. The split() method still splits on every match of separator, until the number of split items match the limit or the string falls short of separator.</param> /// <returns>An array of strings split at each point where the separator occurs in the given string.</returns> [Template("{str}.split({limit})")] public static extern string[] Split(this string str, int limit); /// <summary> /// Splits a String object into an array of strings by separating the string into substrings. /// </summary> /// <param name="str">A string instance</param> /// <param name="separator">Specifies the character to use for separating the string. The separator is treated as a string or a regular expression. If separator is omitted or does not occur in str, the array returned contains one element consisting of the entire string. If separator is an empty string, str is converted to an array of characters.</param> /// <param name="limit">Integer specifying a limit on the number of splits to be found. The split() method still splits on every match of separator, until the number of split items match the limit or the string falls short of separator.</param> /// <returns>An array of strings split at each point where the separator occurs in the given string.</returns> [Template("{str}.split(String.fromCharCode({separator}), {limit})")] public static extern string[] Split(this string str, char separator, int limit); /// <summary> /// The split() method splits a String object into an array of strings by separating the string into substrings. /// </summary> /// <param name="str">A string instance</param> /// <returns>An array of strings split at each point where the separator occurs in the given string.</returns> [Template("{str}.split()")] public static extern string[] Split(this string str); /// <summary> /// The split() method splits a String object into an array of strings by separating the string into substrings. /// </summary> /// <param name="str">A string instance</param> /// <param name="separator">Specifies the character(s) to use for separating the string. The separator is treated as a string or a regular expression. If separator is omitted or does not occur in str, the array returned contains one element consisting of the entire string. If separator is an empty string, str is converted to an array of characters.</param> /// <returns>An array of strings split at each point where the separator occurs in the given string.</returns> [Template("{str}.split({separator})")] public static extern string[] Split(this string str, string separator); /// <summary> /// The split() method splits a String object into an array of strings by separating the string into substrings. /// </summary> /// <param name="str">A string instance</param> /// <param name="separator">Specifies the character(s) to use for separating the string. The separator is treated as a string or a regular expression. If separator is omitted or does not occur in str, the array returned contains one element consisting of the entire string. If separator is an empty string, str is converted to an array of characters.</param> /// <param name="limit">Integer specifying a limit on the number of splits to be found. The split() method still splits on every match of separator, until the number of split items match the limit or the string falls short of separator.</param> /// <returns>An array of strings split at each point where the separator occurs in the given string.</returns> [Template("{str}.split({separator}, {limit})")] public static extern string[] Split(this string str, string separator, int limit); /// <summary> /// The split() method splits a String object into an array of strings by separating the string into substrings. /// </summary> /// <param name="str">A string instance</param> /// <param name="separator">Specifies the character(s) to use for separating the string. The separator is treated as a string or a regular expression. If separator is omitted or does not occur in str, the array returned contains one element consisting of the entire string. If separator is an empty string, str is converted to an array of characters.</param> /// <returns>An array of strings split at each point where the separator occurs in the given string.</returns> [Template("{str}.split({separator})")] public static extern string[] Split(this string str, RegExp separator); /// <summary> /// The split() method splits a String object into an array of strings by separating the string into substrings. /// </summary> /// <param name="str">A string instance</param> /// <param name="separator">Specifies the character(s) to use for separating the string. The separator is treated as a string or a regular expression. If separator is omitted or does not occur in str, the array returned contains one element consisting of the entire string. If separator is an empty string, str is converted to an array of characters.</param> /// <param name="limit">Integer specifying a limit on the number of splits to be found. The split() method still splits on every match of separator, until the number of split items match the limit or the string falls short of separator.</param> /// <returns>An array of strings split at each point where the separator occurs in the given string.</returns> [Template("{str}.split({separator}, {limit})")] public static extern string[] Split(this string str, RegExp separator, int limit); /// <summary> /// The substr() method returns the characters in a string beginning at the specified location through the specified number of characters. /// </summary> /// <param name="str">A string instance</param> /// <param name="start">Location at which to begin extracting characters. If a negative number is given, it is treated as strLength + start where strLength is the length of the string (for example, if start is -3 it is treated as strLength - 3.)</param> /// <returns>A new string containing the extracted section of the given string. If length is 0 or a negative number, an empty string is returned.</returns> [Template("{str}.substr({start})")] public static extern string Substr(this string str, int start); /// <summary> /// The substr() method returns the characters in a string beginning at the specified location through the specified number of characters. /// </summary> /// <param name="str">A string instance</param> /// <param name="start">Location at which to begin extracting characters. If a negative number is given, it is treated as strLength + start where strLength is the length of the string (for example, if start is -3 it is treated as strLength - 3.)</param> /// <param name="length">The number of characters to extract.</param> /// <returns>A new string containing the extracted section of the given string. If length is 0 or a negative number, an empty string is returned.</returns> [Template("{str}.substr({start}, {length})")] public static extern string Substr(this string str, int start, int length); /// <summary> /// The substring() method returns a subset of a string between one index and another, or through the end of the string. /// </summary> /// <param name="str">A string instance</param> /// <param name="indexStart">An integer between 0 and the length of the string, specifying the offset into the string of the first character to include in the returned substring.</param> /// <returns>A new string containing the extracted section of the given string.</returns> [Template("{str}.substring({indexStart})")] public static extern string Substring(this string str, int indexStart); /// <summary> /// The substring() method returns a subset of a string between one index and another, or through the end of the string. /// </summary> /// <param name="str">A string instance</param> /// <param name="indexStart">An integer between 0 and the length of the string, specifying the offset into the string of the first character to include in the returned substring.</param> /// <param name="indexEnd">An integer between 0 and the length of the string, which specifies the offset into the string of the first character not to include in the returned substring.</param> /// <returns>A new string containing the extracted section of the given string.</returns> [Template("{str}.substring({indexStart}, {indexEnd})")] public static extern string Substring(this string str, int indexStart, int indexEnd); /// <summary> /// The charAt() method returns the specified character from a string. /// </summary> /// <param name="str">A string instance</param> /// <param name="index">An integer between 0 and 1-less-than the length of the string. If no index is provided, charAt() will use 0.</param> /// <returns>A string representing the character at the specified index; empty string if index is out of range.</returns> [Template("{str}.charAt({index})")] public static extern string CharAt(this string str, int index); /// <summary> /// The charCodeAt() method returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index (the UTF-16 code unit matches the Unicode code point for code points representable in a single UTF-16 code unit, but might also be the first code unit of a surrogate pair for code points not representable in a single UTF-16 code unit, e.g. Unicode code points > 0x10000). If you want the entire code point value, use codePointAt(). /// </summary> /// <param name="str">A string instance</param> /// <param name="index">An integer greater than or equal to 0 and less than the length of the string; if it is not a number, it defaults to 0.</param> /// <returns>A number representing the UTF-16 code unit value of the character at the given index; NaN if index is out of range.</returns> [Template("{str}.charCodeAt({index})")] public static extern int CharCodeAt(this string str, int index); /// <summary> /// The static String.fromCharCode() method returns a string created by using the specified sequence of Unicode values. /// </summary> /// <returns>String.Empty</returns> [Template("String.fromCharCode()")] public static extern string FromCharCode(); /// <summary> /// The static String.fromCharCode() method returns a string created by using the specified sequence of Unicode values. /// </summary> /// <param name="numbers">A sequence of numbers that are Unicode values.</param> /// <returns></returns> [Template("String.fromCharCode({numbers})")] public static extern string FromCharCode(params int[] numbers); } }
// // 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; using Microsoft.WindowsAzure.Management.Compute.Models; namespace Microsoft.WindowsAzure.Management.Compute.Models { /// <summary> /// A virtual machine disk associated with your subscription. /// </summary> public partial class VirtualMachineDiskGetResponse : OperationResponse { private string _affinityGroup; /// <summary> /// Optional. The affinity group in which the disk 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. /// </summary> public string AffinityGroup { get { return this._affinityGroup; } set { this._affinityGroup = 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? _isCorrupted; /// <summary> /// Optional. Specifies whether the disk is known to be corrupt. /// </summary> public bool? IsCorrupted { get { return this._isCorrupted; } set { this._isCorrupted = value; } } private bool? _isPremium; /// <summary> /// Optional. Specifies whether or not the disk contains a premium /// virtual machine image. /// </summary> public bool? IsPremium { get { return this._isPremium; } set { this._isPremium = value; } } private string _label; /// <summary> /// Optional. The friendly name of the disk. /// </summary> public string Label { get { return this._label; } set { this._label = value; } } private string _location; /// <summary> /// Optional. The geo-location in which the disk is located. The /// Location value is derived from storage account that contains the /// blob in which the disk is located. If the storage account belongs /// to an affinity group the value is NULL. /// </summary> public string Location { get { return this._location; } set { this._location = value; } } private int _logicalSizeInGB; /// <summary> /// Optional. The size, in GB, of the disk. /// </summary> public int LogicalSizeInGB { get { return this._logicalSizeInGB; } set { this._logicalSizeInGB = value; } } private Uri _mediaLinkUri; /// <summary> /// Optional. The location of the blob in the blob store in which the /// media for the disk is located. 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/mydisk.vhd. /// </summary> public Uri MediaLinkUri { get { return this._mediaLinkUri; } set { this._mediaLinkUri = value; } } private string _name; /// <summary> /// Optional. The name of the disk. This is the name that is used when /// creating one or more virtual machines using the disk. /// </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, Windows, or NULL. /// </summary> public string OperatingSystemType { get { return this._operatingSystemType; } set { this._operatingSystemType = value; } } private string _sourceImageName; /// <summary> /// Optional. The name of the OS Image from which the disk was created. /// This property is populated automatically when a disk is created /// from an OS image by calling the Add Role, Create Deployment, or /// Provision Disk operations. /// </summary> public string SourceImageName { get { return this._sourceImageName; } set { this._sourceImageName = value; } } private VirtualMachineDiskGetResponse.VirtualMachineDiskUsageDetails _usageDetails; /// <summary> /// Optional. Contains properties that specify a virtual machine that /// is currently using the disk. A disk cannot be deleted as long as /// it is attached to a virtual machine. /// </summary> public VirtualMachineDiskGetResponse.VirtualMachineDiskUsageDetails UsageDetails { get { return this._usageDetails; } set { this._usageDetails = value; } } /// <summary> /// Initializes a new instance of the VirtualMachineDiskGetResponse /// class. /// </summary> public VirtualMachineDiskGetResponse() { } /// <summary> /// Contains properties that specify a virtual machine that currently /// using the disk. A disk cannot be deleted as long as it is attached /// to a virtual machine. /// </summary> public partial class VirtualMachineDiskUsageDetails { private string _deploymentName; /// <summary> /// Optional. The deployment in which the disk is being used. /// </summary> public string DeploymentName { get { return this._deploymentName; } set { this._deploymentName = value; } } private string _hostedServiceName; /// <summary> /// Optional. The hosted service in which the disk is being used. /// </summary> public string HostedServiceName { get { return this._hostedServiceName; } set { this._hostedServiceName = value; } } private string _roleName; /// <summary> /// Optional. The virtual machine that the disk is attached to. /// </summary> public string RoleName { get { return this._roleName; } set { this._roleName = value; } } /// <summary> /// Initializes a new instance of the /// VirtualMachineDiskUsageDetails class. /// </summary> public VirtualMachineDiskUsageDetails() { } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.12.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsPaging { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; public static partial class PagingOperationsExtensions { /// <summary> /// A paging operation that finishes on the first call without a nextlink /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<Product> GetSinglePages(this IPagingOperations operations) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetSinglePagesAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that finishes on the first call without a nextlink /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> GetSinglePagesAsync( this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<Product>> result = await operations.GetSinglePagesWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<Product> GetMultiplePages(this IPagingOperations operations) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> GetMultiplePagesAsync( this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<Product>> result = await operations.GetMultiplePagesWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// A paging operation that fails on the first call with 500 and then retries /// and then get a response including a nextLink that has 10 pages /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<Product> GetMultiplePagesRetryFirst(this IPagingOperations operations) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesRetryFirstAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that fails on the first call with 500 and then retries /// and then get a response including a nextLink that has 10 pages /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> GetMultiplePagesRetryFirstAsync( this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<Product>> result = await operations.GetMultiplePagesRetryFirstWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// A paging operation that includes a nextLink that has 10 pages, of which /// the 2nd call fails first with 500. The client should retry and finish all /// 10 pages eventually. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<Product> GetMultiplePagesRetrySecond(this IPagingOperations operations) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesRetrySecondAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that includes a nextLink that has 10 pages, of which /// the 2nd call fails first with 500. The client should retry and finish all /// 10 pages eventually. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> GetMultiplePagesRetrySecondAsync( this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<Product>> result = await operations.GetMultiplePagesRetrySecondWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// A paging operation that receives a 400 on the first call /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<Product> GetSinglePagesFailure(this IPagingOperations operations) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetSinglePagesFailureAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that receives a 400 on the first call /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> GetSinglePagesFailureAsync( this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<Product>> result = await operations.GetSinglePagesFailureWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// A paging operation that receives a 400 on the second call /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<Product> GetMultiplePagesFailure(this IPagingOperations operations) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFailureAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that receives a 400 on the second call /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> GetMultiplePagesFailureAsync( this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<Product>> result = await operations.GetMultiplePagesFailureWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// A paging operation that receives an invalid nextLink /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> public static IPage<Product> GetMultiplePagesFailureUri(this IPagingOperations operations) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFailureUriAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that receives an invalid nextLink /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<Product>> GetMultiplePagesFailureUriAsync( this IPagingOperations operations, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<Product>> result = await operations.GetMultiplePagesFailureUriWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// A paging operation that finishes on the first call without a nextlink /// </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<Product> GetSinglePagesNext(this IPagingOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetSinglePagesNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that finishes on the first call without a nextlink /// </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<Product>> GetSinglePagesNextAsync( this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<Product>> result = await operations.GetSinglePagesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </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<Product> GetMultiplePagesNext(this IPagingOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that includes a nextLink that has 10 pages /// </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<Product>> GetMultiplePagesNextAsync( this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<Product>> result = await operations.GetMultiplePagesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// A paging operation that fails on the first call with 500 and then retries /// and then get a response including a nextLink that has 10 pages /// </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<Product> GetMultiplePagesRetryFirstNext(this IPagingOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesRetryFirstNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that fails on the first call with 500 and then retries /// and then get a response including a nextLink that has 10 pages /// </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<Product>> GetMultiplePagesRetryFirstNextAsync( this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<Product>> result = await operations.GetMultiplePagesRetryFirstNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// A paging operation that includes a nextLink that has 10 pages, of which /// the 2nd call fails first with 500. The client should retry and finish all /// 10 pages eventually. /// </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<Product> GetMultiplePagesRetrySecondNext(this IPagingOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesRetrySecondNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that includes a nextLink that has 10 pages, of which /// the 2nd call fails first with 500. The client should retry and finish all /// 10 pages eventually. /// </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<Product>> GetMultiplePagesRetrySecondNextAsync( this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<Product>> result = await operations.GetMultiplePagesRetrySecondNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// A paging operation that receives a 400 on the first call /// </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<Product> GetSinglePagesFailureNext(this IPagingOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetSinglePagesFailureNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that receives a 400 on the first call /// </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<Product>> GetSinglePagesFailureNextAsync( this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<Product>> result = await operations.GetSinglePagesFailureNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// A paging operation that receives a 400 on the second call /// </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<Product> GetMultiplePagesFailureNext(this IPagingOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFailureNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that receives a 400 on the second call /// </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<Product>> GetMultiplePagesFailureNextAsync( this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<Product>> result = await operations.GetMultiplePagesFailureNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// A paging operation that receives an invalid nextLink /// </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<Product> GetMultiplePagesFailureUriNext(this IPagingOperations operations, string nextPageLink) { return Task.Factory.StartNew(s => ((IPagingOperations)s).GetMultiplePagesFailureUriNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// A paging operation that receives an invalid nextLink /// </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<Product>> GetMultiplePagesFailureUriNextAsync( this IPagingOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { AzureOperationResponse<IPage<Product>> result = await operations.GetMultiplePagesFailureUriNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false); return result.Body; } } }
// // XwtComponent.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.ComponentModel; using System.Collections.Generic; using System.Reflection; using Xwt.Backends; using System.Threading; namespace Xwt { /// <summary> /// The base class for all Xwt components. /// </summary> [System.ComponentModel.DesignerCategory ("Code")] public abstract class XwtComponent : Component, IFrontend, ISynchronizeInvoke { BackendHost backendHost; public XwtComponent () { backendHost = CreateBackendHost (); backendHost.Parent = this; } /// <summary> /// Creates the backend host. /// </summary> /// <returns>The backend host.</returns> protected virtual BackendHost CreateBackendHost () { return new BackendHost (); } /// <summary> /// Gets the backend host. /// </summary> /// <value>The backend host.</value> protected BackendHost BackendHost { get { return backendHost; } } Toolkit IFrontend.ToolkitEngine { get { return backendHost.ToolkitEngine; } } object IFrontend.Backend { get { return backendHost.Backend; } } /// <summary> /// A value, that can be used to identify this component /// </summary> public virtual object Tag { get; set; } /// <summary> /// Maps an event handler of an Xwt component to an event identifier. /// </summary> /// <param name="eventId">The event identifier (must be valid event enum value /// like <see cref="Xwt.Backends.WidgetEvent"/>, identifying component specific events).</param> /// <param name="type">The Xwt component type.</param> /// <param name="methodName">The <see cref="System.Reflection.MethodInfo.Name"/> of the event handler.</param> protected static void MapEvent (object eventId, Type type, string methodName) { EventHost.MapEvent (eventId, type, methodName); } /// <summary> /// Verifies that the constructor is not called from a sublass. /// </summary> /// <param name="t">This constructed base instance.</param> /// <typeparam name="T">The base type to verify the constructor for.</typeparam> internal void VerifyConstructorCall<T> (T t) { if (GetType () != typeof(T)) throw new InvalidConstructorInvocation (typeof(T)); } #region ISynchronizeInvoke implementation IAsyncResult ISynchronizeInvoke.BeginInvoke (Delegate method, object[] args) { var asyncResult = new AsyncInvokeResult (); asyncResult.Invoke (method, args); return asyncResult; } object ISynchronizeInvoke.EndInvoke (IAsyncResult result) { var xwtResult = result as AsyncInvokeResult; if (xwtResult != null) { xwtResult.AsyncResetEvent.Wait (); if (xwtResult.Exception != null) throw xwtResult.Exception; } else { result.AsyncWaitHandle.WaitOne (); } return result.AsyncState; } object ISynchronizeInvoke.Invoke (Delegate method, object[] args) { return ((ISynchronizeInvoke)this).EndInvoke (((ISynchronizeInvoke)this).BeginInvoke (method, args)); } bool ISynchronizeInvoke.InvokeRequired { get { return Application.UIThread != Thread.CurrentThread; } } #endregion } class AsyncInvokeResult : IAsyncResult { ManualResetEventSlim asyncResetEvent = new ManualResetEventSlim (false); public AsyncInvokeResult () { this.asyncResetEvent = new ManualResetEventSlim (); } internal void Invoke (Delegate method, object[] args) { Application.Invoke (delegate { try { AsyncState = method.DynamicInvoke(args); } catch (Exception ex){ Exception = ex; } finally { IsCompleted = true; asyncResetEvent.Set (); } }); } #region IAsyncResult implementation public object AsyncState { get; private set; } public Exception Exception { get; private set; } internal ManualResetEventSlim AsyncResetEvent { get { return asyncResetEvent; } } public WaitHandle AsyncWaitHandle { get { if (asyncResetEvent == null) { asyncResetEvent = new ManualResetEventSlim(false); if (IsCompleted) asyncResetEvent.Set(); } return asyncResetEvent.WaitHandle; } } public bool CompletedSynchronously { get { return false; } } public bool IsCompleted { get; private set; } #endregion } }
#region License, Terms and Conditions // // ProductFamilyAttributes.cs // // Authors: Kori Francis <twitter.com/djbyter>, David Ball // Copyright (C) 2013 Clinical Support Systems, Inc. All rights reserved. // // THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW: // // 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 namespace ChargifyNET { #region Imports using System; using System.Diagnostics; using System.Xml; using Json; #endregion /// <summary> /// Class representing basic attributes for a customer /// </summary> [DebuggerDisplay("Name: {Name}, Handle: {Handle}")] [Serializable] public class ProductFamilyAttributes : ChargifyBase, IProductFamilyAttributes { #region Field Keys internal const string NameKey = "name"; internal const string DescriptionKey = "description"; internal const string HandleKey = "handle"; internal const string AccountingCodeKey = "accounting_code"; #endregion #region Constructors /// <summary> /// Default constructor /// </summary> public ProductFamilyAttributes() { } /// <summary> /// Constructor, all values specified. /// </summary> /// <param name="name">The name of the product family</param> /// <param name="description">The description of the product family</param> /// <param name="accountingCode">The accounting code of the product family</param> /// <param name="handle">The handle of the product family</param> public ProductFamilyAttributes(string name, string description, string accountingCode, string handle) : this() { Name = name; Description = description; AccountingCode = accountingCode; Handle = handle; } /// <summary> /// Constructor /// </summary> /// <param name="productFamilyAttributesXml">The XML which corresponds to this classes members, to be parsed</param> public ProductFamilyAttributes(string productFamilyAttributesXml) { // get the XML into an XML document XmlDocument doc = new(); doc.LoadXml(productFamilyAttributesXml); if (doc.ChildNodes.Count == 0) throw new ArgumentException("XML not valid", nameof(productFamilyAttributesXml)); // loop through the child nodes of this node foreach (XmlNode elementNode in doc.ChildNodes) { switch (elementNode.Name) { case "product_family_attributes": case "product_family": LoadFromNode(elementNode); break; } } // if we get here, then no info was found throw new ArgumentException("XML does not contain information", nameof(productFamilyAttributesXml)); } /// <summary> /// Constructor /// </summary> /// <param name="productFamilyAttributesNode">The product family XML node</param> internal ProductFamilyAttributes(XmlNode productFamilyAttributesNode) { if (productFamilyAttributesNode == null) throw new ArgumentNullException(nameof(productFamilyAttributesNode)); if (productFamilyAttributesNode.Name != "product_family") throw new ArgumentException("Not a vaild product family attributes node", nameof(productFamilyAttributesNode)); if (productFamilyAttributesNode.ChildNodes.Count == 0) throw new ArgumentException("XML not valid", nameof(productFamilyAttributesNode)); LoadFromNode(productFamilyAttributesNode); } /// <summary> /// Constructor /// </summary> /// <param name="productFamilyAttributesObject">The product family JSON object</param> public ProductFamilyAttributes(JsonObject productFamilyAttributesObject) { if (productFamilyAttributesObject == null) throw new ArgumentNullException(nameof(productFamilyAttributesObject)); if (productFamilyAttributesObject.Keys.Count <= 0) throw new ArgumentException("Not a vaild product family attributes object", nameof(productFamilyAttributesObject)); LoadFromJson(productFamilyAttributesObject); } /// <summary> /// Load data from a JsonObject /// </summary> /// <param name="obj">The JsonObject containing product family attribute data</param> private void LoadFromJson(JsonObject obj) { foreach (var key in obj.Keys) { switch (key) { case NameKey: Name = obj.GetJSONContentAsString(key); break; case DescriptionKey: Description = obj.GetJSONContentAsString(key); break; case HandleKey: Handle = obj.GetJSONContentAsString(key); break; case AccountingCodeKey: AccountingCode = obj.GetJSONContentAsString(key); break; } } } /// <summary> /// Load data from a product family node /// </summary> /// <param name="customerNode">The product family node</param> private void LoadFromNode(XmlNode customerNode) { foreach (XmlNode dataNode in customerNode.ChildNodes) { switch (dataNode.Name) { case NameKey: Name = dataNode.GetNodeContentAsString(); break; case DescriptionKey: Description = dataNode.GetNodeContentAsString(); break; case HandleKey: Handle = dataNode.GetNodeContentAsString(); break; case AccountingCodeKey: AccountingCode = dataNode.GetNodeContentAsString(); break; } } } #endregion #region IComparable<IProductFamilyAttributes> Members /// <summary> /// Compare this instance to another (by Handle) /// </summary> /// <param name="other">The other instance to compare against</param> /// <returns>The result of the comparison</returns> public int CompareTo(IProductFamilyAttributes other) { return string.Compare(Handle, other.Handle, StringComparison.InvariantCultureIgnoreCase); } #endregion #region IComparable<ProductFamilyAttributes> Members /// <summary> /// Compare this instance to another (by Handle) /// </summary> /// <param name="other">The other instance to compare against</param> /// <returns>The result of the comparison</returns> public int CompareTo(ProductFamilyAttributes other) { return string.Compare(Handle, other.Handle, StringComparison.InvariantCultureIgnoreCase); } #endregion #region IProductFamilyAttribute Members /// <summary> /// The accounting code of the product family /// </summary> public string AccountingCode { get; set; } /// <summary> /// The descrition of the product family /// </summary> public string Description { get; set; } /// <summary> /// The handle of the product family /// </summary> public string Handle { get; set; } /// <summary> /// The name of the product family /// </summary> public string Name { get; set; } #endregion } }
// // SoftDebuggerBacktrace.cs // // Authors: Lluis Sanchez Gual <lluis@novell.com> // Jeffrey Stedfast <jeff@xamarin.com> // // Copyright (c) 2009 Novell, Inc (http://www.novell.com) // Copyright (c) 2012 Xamarin Inc. (http://www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Linq; using System.Text; using System.Collections.Generic; using Mono.Debugging.Client; using Mono.Debugging.Backend; using MDB = Mono.Debugger.Soft; using DC = Mono.Debugging.Client; using Mono.Debugging.Evaluation; namespace Mono.Debugging.Soft { internal class SoftDebuggerStackFrame : Mono.Debugging.Client.StackFrame { public Mono.Debugger.Soft.StackFrame StackFrame { get; private set; } public SoftDebuggerStackFrame (Mono.Debugger.Soft.StackFrame frame, string addressSpace, SourceLocation location, string language, bool isExternalCode, bool hasDebugInfo, bool isDebuggerHidden, string fullModuleName, string fullTypeName) : base (frame.ILOffset, addressSpace, location, language, isExternalCode, hasDebugInfo, isDebuggerHidden, fullModuleName, fullTypeName) { StackFrame = frame; } } public class SoftDebuggerBacktrace: BaseBacktrace { readonly SoftDebuggerSession session; readonly MDB.ThreadMirror thread; readonly int stackVersion; MDB.StackFrame[] frames; public SoftDebuggerBacktrace (SoftDebuggerSession session, MDB.ThreadMirror thread): base (session.Adaptor) { this.session = session; this.thread = thread; stackVersion = session.StackVersion; if (thread != null) this.frames = thread.GetFrames (); else this.frames = new MDB.StackFrame[0]; } void ValidateStack () { if (stackVersion != session.StackVersion && thread != null) frames = thread.GetFrames (); } public override DC.StackFrame[] GetStackFrames (int firstIndex, int lastIndex) { ValidateStack (); if (lastIndex < 0) lastIndex = frames.Length - 1; List<DC.StackFrame> list = new List<DC.StackFrame> (); for (int n = firstIndex; n <= lastIndex && n < frames.Length; n++) list.Add (CreateStackFrame (frames[n], n)); return list.ToArray (); } public override int FrameCount { get { ValidateStack (); return frames.Length; } } DC.StackFrame CreateStackFrame (MDB.StackFrame frame, int frameIndex) { MDB.MethodMirror method = frame.Method; MDB.TypeMirror type = method.DeclaringType; string fileName = frame.FileName; string typeFullName = null; string typeFQN = null; string methodName; if (fileName != null) fileName = SoftDebuggerSession.NormalizePath (fileName); if (method.VirtualMachine.Version.AtLeast (2, 12) && method.IsGenericMethod) { StringBuilder name = new StringBuilder (method.Name); name.Append ('<'); if (method.VirtualMachine.Version.AtLeast (2, 15)) { bool first = true; foreach (var argumentType in method.GetGenericArguments ()) { if (!first) name.Append (", "); name.Append (session.Adaptor.GetDisplayTypeName (argumentType.FullName)); first = false; } } name.Append ('>'); methodName = name.ToString (); } else { methodName = method.Name; } if (string.IsNullOrEmpty (methodName)) methodName = "[Function Without Name]"; // Compiler generated anonymous/lambda methods bool special_method = false; if (methodName [0] == '<' && methodName.Contains (">m__")) { int nidx = methodName.IndexOf (">m__", StringComparison.Ordinal) + 2; methodName = "AnonymousMethod" + methodName.Substring (nidx, method.Name.Length - nidx); special_method = true; } if (type != null) { string typeDisplayName = session.Adaptor.GetDisplayTypeName (type.FullName); if (SoftDebuggerAdaptor.IsGeneratedType (type)) { // The user-friendly method name is embedded in the generated type name var mn = SoftDebuggerAdaptor.GetNameFromGeneratedType (type); // Strip off the generated type name int dot = typeDisplayName.LastIndexOf ('.'); var tname = typeDisplayName.Substring (0, dot); // Keep any type arguments int targs = typeDisplayName.LastIndexOf ('<'); if (targs > dot + 1) mn += typeDisplayName.Substring (targs, typeDisplayName.Length - targs); typeDisplayName = tname; if (special_method) typeDisplayName += "." + mn; else methodName = mn; } methodName = typeDisplayName + "." + methodName; typeFQN = type.Module.FullyQualifiedName; typeFullName = type.FullName; } bool external = false; bool hidden = false; if (session.VirtualMachine.Version.AtLeast (2, 21)) { var ctx = GetEvaluationContext (frameIndex, session.EvaluationOptions); var hiddenAttr = session.Adaptor.GetType (ctx, "System.Diagnostics.DebuggerHiddenAttribute") as MDB.TypeMirror; if (hiddenAttr != null) hidden = method.GetCustomAttributes (hiddenAttr, true).Any (); } if (hidden) { external = true; } else { external = session.IsExternalCode (frame); if (!external && session.Options.ProjectAssembliesOnly && session.VirtualMachine.Version.AtLeast (2, 21)) { var ctx = GetEvaluationContext (frameIndex, session.EvaluationOptions); var nonUserCodeAttr = session.Adaptor.GetType (ctx, "System.Diagnostics.DebuggerNonUserCodeAttribute") as MDB.TypeMirror; if (nonUserCodeAttr != null) external = method.GetCustomAttributes (nonUserCodeAttr, true).Any (); } } var sourceLink = session.GetSourceLink (frame.Method, frame.FileName); var location = new DC.SourceLocation (methodName, fileName, frame.LineNumber, frame.ColumnNumber, frame.Location.EndLineNumber, frame.Location.EndColumnNumber, frame.Location.SourceFileHash, sourceLink); string addressSpace = string.Empty; bool hasDebugInfo = false; string language; if (frame.Method != null) { if (frame.IsNativeTransition) { language = "Transition"; } else { addressSpace = method.FullName; language = "Managed"; hasDebugInfo = true; } } else { language = "Native"; } return new SoftDebuggerStackFrame (frame, addressSpace, location, language, external, hasDebugInfo, hidden, typeFQN, typeFullName); } protected override EvaluationContext GetEvaluationContext (int frameIndex, EvaluationOptions options) { ValidateStack (); if (frameIndex >= frames.Length) return null; var frame = frames[frameIndex]; return new SoftEvaluationContext (session, frame, options); } public override AssemblyLine[] Disassemble (int frameIndex, int firstLine, int count) { return session.Disassemble (frames [frameIndex], firstLine, count); } } }
/* * Copyright (c) 2015, InWorldz Halcyon Developers * 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 halcyon 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 HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Text; using OpenSim.Framework; using log4net; using System.Reflection; using OpenSim.Framework.AssetLoader.Filesystem; namespace InWorldz.Whip.Client { /// <summary> /// Implements the IAssetServer interface for the InWorldz WHIP asset server /// </summary> public class AssetClient : IAssetServer { private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private RemoteServer _readWhipServer; private RemoteServer _writeWhipServer; private IAssetReceiver _receiver; protected IAssetLoader assetLoader = new AssetLoaderFileSystem(); ConfigSettings _settings; private bool _loadingDefaultAssets = false; #region IAssetServer Members public AssetClient() { } public AssetClient(string url) { _log.Info("[WHIP.AssetClient] Direct constructor"); this.SetupConnections(url); } public void Initialize(ConfigSettings settings) { _settings = settings; Nini.Config.IConfig netConfig = settings.SettingsFile["Network"]; if (netConfig != null && netConfig.Contains("asset_server_url")) { string url = netConfig.GetString("asset_server_url"); this.SetupConnections(url); } else { throw new Exception("Network/asset_server_url is a required setting"); } } private void SetupConnections(string url) { if (url.Contains(",")) { List<string[]> rwServers = this.ParseReadWriteWhipURL(url); _readWhipServer = new RemoteServer(rwServers[0][1], Convert.ToUInt16(rwServers[0][2]), rwServers[0][0]); //if the port or hosts are different the write server is separate if (rwServers[0][1] != rwServers[1][1] || rwServers[0][2] != rwServers[1][2]) { _writeWhipServer = new RemoteServer(rwServers[1][1], Convert.ToUInt16(rwServers[1][2]), rwServers[1][0]); } else { //else the servers are the same _writeWhipServer = _readWhipServer; } } else { string[] urlParts = this.ParseSingularWhipURL(url); _readWhipServer = new RemoteServer(urlParts[1], Convert.ToUInt16(urlParts[2]), urlParts[0]); _writeWhipServer = _readWhipServer; } } public virtual void LoadDefaultAssets(string pAssetSetsXml) { _log.Info("[ASSET SERVER]: Setting up asset database"); var signpostMarkerFilename = $"{pAssetSetsXml}.loaded"; if (File.Exists(signpostMarkerFilename)) { _log.Info("[ASSET SERVER]: Asset database marked as already set up. Not reloading default assets."); } else { _loadingDefaultAssets = true; assetLoader.ForEachDefaultXmlAsset(pAssetSetsXml, StoreAsset); _loadingDefaultAssets = false; try { File.CreateText(signpostMarkerFilename).Close(); } catch(Exception e) { _log.Error($"Unable to create file '{signpostMarkerFilename}' to mark default assets as having been already loaded.", e); } } } private List<string[]> ParseReadWriteWhipURL(string url) { // R:whip://pass@127.0.0.1:32700,W:whip://pass@127.0.0.1:32700 //split by , this will give us the two WHIP URLs prefixed by their //usage string[] readAndWriteServers = url.Split(new char[1] { ',' }); string[] readURL = null; string[] writeURL = null; string firstServerType = readAndWriteServers[0].Substring(0, 2); if (firstServerType == "R:") { readURL = this.ParseSingularWhipURL(readAndWriteServers[0].Substring(2)); } else if (firstServerType == "W:") { writeURL = this.ParseSingularWhipURL(readAndWriteServers[0].Substring(2)); } else { throw new Exception("Invalid whip URL. For first server R: or W: type not specified"); } string secondServerType = readAndWriteServers[1].Substring(0, 2); if (secondServerType == "R:") { if (readURL != null) { throw new Exception("Invalid whip URL. Read URL specified twice"); } readURL = this.ParseSingularWhipURL(readAndWriteServers[1].Substring(2)); } else if (secondServerType == "W:") { if (writeURL != null) { throw new Exception("Invalid whip URL. Write URL specified twice"); } writeURL = this.ParseSingularWhipURL(readAndWriteServers[1].Substring(2)); } else { throw new Exception("Invalid whip URL. For second server R: or W: type not specified"); } return new List<string[]>(new[] { readURL, writeURL}); } /// <summary> /// Returns an array with [user, password, host, port] /// </summary> /// <param name="url"></param> private string[] ParseSingularWhipURL(string url) { // whip://pass@127.0.0.1:32700 //url must start with whip if (url.Substring(0, 7) != "whip://") throw new Exception("Invaid whip URL. Must start with whip://"); //strip the Resource ID portion url = url.Substring(7); //split by @ this will give us username:password ip:port string[] userAndHost = url.Split(new char[1]{'@'}); if (userAndHost.Length != 2) throw new Exception("Invalid whip URL, missing @"); //get the user and pass string pass = userAndHost[0]; //get the host and port string[] hostAndPort = userAndHost[1].Split(new char[1]{':'}); if (hostAndPort.Length != 2) throw new Exception("Invalid whip URL, missing : between host and port"); string[] ret = new string[4]; ret[0] = pass; ret[1] = hostAndPort[0]; ret[2] = hostAndPort[1]; return ret; } private bool HasRWSplit() { return _readWhipServer != _writeWhipServer; } public void Start() { _readWhipServer.Start(); if (this.HasRWSplit()) { _writeWhipServer.Start(); } if (_settings != null) this.LoadDefaultAssets(_settings.AssetSetsXMLFile); } public void Stop() { _readWhipServer.Stop(); if (this.HasRWSplit()) { _writeWhipServer.Stop(); } } public void SetReceiver(IAssetReceiver receiver) { _receiver = receiver; } /// <summary> /// Converts a whip asset to an opensim asset /// </summary> /// <param name="whipAsset"></param> /// <returns></returns> private AssetBase WhipAssetToOpensim(Asset whipAsset) { AssetBase osAsset = new AssetBase(); osAsset.Data = whipAsset.Data; osAsset.Name = whipAsset.Name; osAsset.Description = whipAsset.Description; osAsset.Type = (sbyte)whipAsset.Type; osAsset.Local = whipAsset.Local; osAsset.Temporary = whipAsset.Temporary; osAsset.FullID = new OpenMetaverse.UUID(whipAsset.Uuid); return osAsset; } public void RequestAsset(OpenMetaverse.UUID assetID, AssetRequestInfo args) { try { _readWhipServer.GetAssetAsync(assetID.ToString(), delegate(Asset asset, AssetServerError e) { if (e == null) { //no error, pass asset to caller _receiver.AssetReceived(WhipAssetToOpensim(asset), args); } else { string errorString = e.ToString(); if (!errorString.Contains("not found")) { //there is an error, log it, and then tell the caller we have no asset to give _log.ErrorFormat( "[WHIP.AssetClient]: Failure fetching asset {0}" + Environment.NewLine + errorString + Environment.NewLine, assetID); } _receiver.AssetNotFound(assetID, args); } } ); } catch (AssetServerError e) { //there is an error, log it, and then tell the caller we have no asset to give string errorString = e.ToString(); if (!errorString.Contains("not found")) { _log.ErrorFormat( "[WHIP.AssetClient]: Failure fetching asset {0}" + Environment.NewLine + errorString + Environment.NewLine, assetID); } _receiver.AssetNotFound(assetID, args); } } public AssetBase RequestAssetSync(OpenMetaverse.UUID assetID) { try { AssetBase asset = this.WhipAssetToOpensim(_readWhipServer.GetAsset(assetID.ToString())); return asset; } catch (AssetServerError e) { string errorString = e.ToString(); if (!errorString.Contains("not found")) { //there is an error, log it, and then tell the caller we have no asset to give _log.ErrorFormat( "[WHIP.AssetClient]: Failure fetching asset {0}" + Environment.NewLine + errorString + Environment.NewLine, assetID); } return null; } } private Asset OpensimAssetToWhip(AssetBase osAsset) { Asset whipAsset = new Asset(osAsset.FullID.ToString(), (byte)osAsset.Type, osAsset.Local, osAsset.Temporary, OpenSim.Framework.Util.UnixTimeSinceEpoch(), osAsset.Name, osAsset.Description, osAsset.Data); return whipAsset; } public void StoreAsset(AssetBase asset) { try { _writeWhipServer.PutAsset(OpensimAssetToWhip(asset)); } catch (AssetServerError e) { //there is an error, log it, and then tell the caller we have no asset to give if (!_loadingDefaultAssets) { _log.ErrorFormat( "[WHIP.AssetClient]: Failure storing asset {0}" + Environment.NewLine + e.ToString() + Environment.NewLine, asset.FullID); if (e.Message.Contains("already exists")) { //this is hacky, but I dont want to edit the whip client this //late in the game when we're going to be phasing it out throw new AssetAlreadyExistsException(e.Message, e); } else { throw new AssetServerException(e.Message, e); } } } } /// <summary> /// Okay... assets are immutable so im not even sure what place this has here.. /// </summary> /// <param name="asset"></param> public void UpdateAsset(AssetBase asset) { _log.WarnFormat("[WHIP.AssetClient]: UpdateAsset called for {0} Assets are immutable.", asset.FullID); this.StoreAsset(asset); } public AssetStats GetStats(bool resetStats) { return new AssetStats("WHIP"); } #endregion #region IPlugin Members public string Version { get { return "1.0"; } } public string Name { get { return "InWorldz WHIP Asset Client"; } } public void Initialize() { } #endregion #region IDisposable Members public void Dispose() { this.Stop(); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; namespace CommandLine.Analyzer { [DiagnosticAnalyzer(LanguageNames.CSharp)] public partial class CommandLineAnalyzer : DiagnosticAnalyzer { public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(AnalyzeCommandLineType, SymbolKind.NamedType); } private static void AnalyzeCommandLineType(SymbolAnalysisContext context) { // first of all, nothing to do if we don't have an attribute in the Commandline namespace on the properties var namedTypeSymbol = context.Symbol as INamedTypeSymbol; if (namedTypeSymbol == null || !IsCommandLineArgumentClass(namedTypeSymbol)) { return; } Dictionary<string, List<Argument>> mapGroupAndProps = CreateArgumentMapForType(namedTypeSymbol, context, out ActionArgument actionArg); // if an action argument has been specified but no arguments have been added to specific groups, give a warning if (actionArg != null && mapGroupAndProps.Count == 0) { context.ReportDiagnostic(Diagnostic.Create(ActionWithoutArgumentsInGroup, actionArg.Symbol.Locations.First())); } ValidateDefinedProperties(mapGroupAndProps, actionArg, context); } private static Dictionary<string, List<Argument>> CreateArgumentMapForType(INamedTypeSymbol namedTypeSymbol, SymbolAnalysisContext context, out ActionArgument actionArg) { Dictionary<string, List<Argument>> mapGroupAndProps = new Dictionary<string, List<Argument>>(StringComparer.OrdinalIgnoreCase); // find the action arg. var typeMembers = namedTypeSymbol.GetMembers(); actionArg = GetActionArgument(typeMembers, context); // setup the groups available based on the actionArg if (actionArg == null) { // If we don't have an Action attribute, we are going to use the empty string // to represent a single common group for all the properties. mapGroupAndProps.Add("", new List<Argument>()); } else { // If the action attribute has been set (and we could find all the possible values) // then add those as the group values. foreach (var grp in actionArg.Values) { mapGroupAndProps.Add(grp, new List<Argument>()); } } // traverse the properties again and add them to the groups as needed. foreach (var member in typeMembers) { // Make sure that we are only looking at properties. if (!(member is IPropertySymbol)) { continue; } var attributes = member.GetAttributes(); if (!attributes.Any()) { // nothing to do if we don't have any attributes. continue; } // we should skip over the action argument. if (actionArg != null && actionArg.Symbol == member) { continue; } Argument arg = null; List<string> argGroup = new List<string>(); Dictionary<string, Dictionary<ISymbol, int>> mapOfOverridesPerGroup = new Dictionary<string, Dictionary<ISymbol, int>>(); bool isCommon = false; bool isAttributeGroup = false; foreach (var attribute in attributes) { // Do a quick check to make sure the attribute we are looking at is coming from the CommandLine assembly if (!StringComparer.OrdinalIgnoreCase.Equals("CommandLine", attribute.AttributeClass.ContainingAssembly.Name)) { continue; } if (attribute.ConstructorArguments.Length >= 3) { if (attribute.AttributeClass.Name == "RequiredArgumentAttribute") { RequiredArgument ra = new RequiredArgument(); ra.Position = (int)attribute.ConstructorArguments[0].Value; // position ra.Name = attribute.ConstructorArguments[1].Value as string; ra.Description = attribute.ConstructorArguments[2].Value as string; if (attribute.ConstructorArguments.Length == 4) { ra.IsCollection = (bool)attribute.ConstructorArguments[3].Value; } if (arg != null) { // can't have a property be both optional and required context.ReportDiagnostic(Diagnostic.Create(ConflictingPropertyDeclarationRule, member.Locations.First())); } arg = ra; } else if (attribute.AttributeClass.Name == "OptionalArgumentAttribute") { OptionalArgument oa = new OptionalArgument(); oa.DefaultValue = attribute.ConstructorArguments[0].Value; // default value oa.Name = attribute.ConstructorArguments[1].Value as string; oa.Description = attribute.ConstructorArguments[2].Value as string; if (attribute.ConstructorArguments.Length == 4) { oa.IsCollection = (bool)attribute.ConstructorArguments[3].Value; } if (arg != null) { // can't have a property be both optional and required context.ReportDiagnostic(Diagnostic.Create(ConflictingPropertyDeclarationRule, member.Locations.First())); } arg = oa; } } if (attribute.AttributeClass.Name == "CommonArgumentAttribute") { isCommon = true; } if (attribute.AttributeClass.Name == "ArgumentGroupAttribute") { isAttributeGroup = true; string groupName = attribute.ConstructorArguments[0].Value as string; argGroup.Add(groupName); // does it have an additional constructor? if (attribute.ConstructorArguments.Length > 1) { var overridePosition = (int)attribute.ConstructorArguments[1].Value; if (overridePosition >= 0) { // need to map the member to the new position Dictionary<ISymbol, int> map; if (!mapOfOverridesPerGroup.TryGetValue(groupName, out map)) { map = new Dictionary<ISymbol, int>(); mapOfOverridesPerGroup[groupName] = map; } map[member] = overridePosition; } } } } // we did not find the Required/Optional attribute on that type. if (arg == null) { // we could not identify an argument because we don't have the required/optional attribute, but we do have the commonattribute/attributeGroup which does not make sense. if (isCommon == true || isAttributeGroup == true) { context.ReportDiagnostic(Diagnostic.Create(CannotSpecifyAGroupForANonPropertyRule, member.Locations.First())); } // we don't understand this argument, nothing to do. continue; } // store the member symbol on the argument object arg.Symbol = member; // add the argument to all the groups if (isCommon == true) { foreach (var key in mapGroupAndProps.Keys) { mapGroupAndProps[key].Add(arg); } // give an error about the action argument being a string and using a common attribute with that. if (actionArg != null && (actionArg.Symbol as IPropertySymbol).Type.BaseType?.SpecialType != SpecialType.System_Enum) { context.ReportDiagnostic(Diagnostic.Create(CommonArgumentAttributeUsedWhenActionArgumentNotEnumRule, arg.Symbol.Locations.First())); } } else { // if we have found an attribute that specifies a group, add it to that. if (argGroup.Count > 0) { // add the current argument to all the argument groups defined. foreach (var item in argGroup) { if (!mapGroupAndProps.TryGetValue(item, out List<Argument> args)) { args = new List<Argument>(); mapGroupAndProps[item] = args; } // we might need to change the position for this arg based on the override list if (mapOfOverridesPerGroup.ContainsKey(item)) { // if the current symbol is the one redirected, then redirect. if (mapOfOverridesPerGroup[item].ContainsKey(arg.Symbol)) { var overridePosition = mapOfOverridesPerGroup[item][arg.Symbol]; // we need to clone the arg. var reqArg = arg as RequiredArgument; var clonedArg = reqArg.Clone(); clonedArg.Position = overridePosition; args.Add(clonedArg); } else { args.Add(arg); } } else { args.Add(arg); } } } else { //add it to the default one. mapGroupAndProps[string.Empty].Add(arg); } } } return mapGroupAndProps; } private static ActionArgument GetActionArgument(ImmutableArray<ISymbol> typeMembers, SymbolAnalysisContext context) { ActionArgument aa = null; foreach (var member in typeMembers) { // Make sure that we are only looking at properties. if (!(member is IPropertySymbol)) { continue; } var attributes = member.GetAttributes(); if (!attributes.Any()) { continue; } foreach (var attribute in attributes) { if (attribute.AttributeClass.Name == "ActionArgumentAttribute" && StringComparer.OrdinalIgnoreCase.Equals("CommandLine", attribute.AttributeClass.ContainingAssembly.Name)) { if (aa != null) { // we already found another action argument attribute context.ReportDiagnostic(Diagnostic.Create(DuplicateActionArgumentRule, member.Locations.First())); } aa = new ActionArgument(); aa.Symbol = member; var memberAsProperty = member as IPropertySymbol; if (memberAsProperty.Type.BaseType?.SpecialType == SpecialType.System_Enum) { var members = (member as IPropertySymbol).Type.GetMembers(); foreach (var item in members) { if (item is IFieldSymbol) { aa.Values.Add(item.Name); } } } } } } return aa; } private static void ValidateDefinedProperties(Dictionary<string, List<Argument>> mapGroupArgs, ActionArgument actionArg, SymbolAnalysisContext context) { // for each group, validate the parameters. foreach (var groupName in mapGroupArgs.Keys) { ValidateArguments(mapGroupArgs[groupName], context); } } private static void ValidateArguments(List<Argument> args, SymbolAnalysisContext context) { HashSet<string> namesOfAllArgs = new HashSet<string>(); HashSet<int> positionsOrRequiredArgs = new HashSet<int>(); int numberOfPositionalArgs = 0; int indexOfCollectionArg = -1; RequiredArgument collectionArg = null; foreach (var item in args) { if (item is OptionalArgument) { OptionalArgument oag = item as OptionalArgument; // Validate that the same name is not used across required and optional arguments. if (namesOfAllArgs.Contains(oag.Name)) { context.ReportDiagnostic(Diagnostic.Create(DuplicateArgumentNameRule, oag.Symbol.Locations.First(), oag.Name)); } namesOfAllArgs.Add(oag.Name); } else if (item is RequiredArgument) { RequiredArgument rag = item as RequiredArgument; numberOfPositionalArgs++; // Validate that the same position is not used twice if (positionsOrRequiredArgs.Contains(rag.Position)) { context.ReportDiagnostic(Diagnostic.Create(DuplicatePositionalArgumentPositionRule, rag.Symbol.Locations.First(), rag.Position)); } // Validate that the same name is not used across required and optional arguments. if (namesOfAllArgs.Contains(rag.Name)) { context.ReportDiagnostic(Diagnostic.Create(DuplicateArgumentNameRule, rag.Symbol.Locations.First(), rag.Name)); } // is the required collection argument the last one AND do we only have one of them? if (indexOfCollectionArg >= 0 && rag.Position > indexOfCollectionArg) { context.ReportDiagnostic(Diagnostic.Create(OnlyOneRequiredCollection, rag.Symbol.Locations.First(), collectionArg.Name, rag.Name)); } // do we have a collection argument specified? if (rag.IsCollection) { indexOfCollectionArg = rag.Position; collectionArg = rag; } namesOfAllArgs.Add(rag.Name); positionsOrRequiredArgs.Add(rag.Position); } } int checkedPositions = 0; //validate that the positional arguments are in a continuous sequence, starting at 0 for (checkedPositions = 0; checkedPositions < numberOfPositionalArgs; checkedPositions++) { if (!positionsOrRequiredArgs.Contains(checkedPositions)) { // at this point, we could not find the required positional argument 'i' // we should give the error at the type level. context.ReportDiagnostic(Diagnostic.Create(RequiredPositionalArgumentNotFound, args.First().Symbol.ContainingType.Locations.First(), numberOfPositionalArgs, checkedPositions)); break; } } // Ensure that the required collection argument (if present) is last. if (indexOfCollectionArg >= 0 && indexOfCollectionArg != numberOfPositionalArgs - 1) { context.ReportDiagnostic(Diagnostic.Create(CollectionArgumentShouldBeLast, collectionArg.Symbol.Locations.First(), collectionArg.Name)); } } /// <summary> /// Check to see if any of the members on the type have an attribute that is coming from the CommandLine assembly /// </summary> /// <param name="namedTypeSymbol"></param> /// <returns></returns> private static bool IsCommandLineArgumentClass(INamedTypeSymbol namedTypeSymbol) { foreach (var member in namedTypeSymbol.GetMembers()) { // if there aren't attributes defined on the member, nothing to do. var attributes = member.GetAttributes(); if (!attributes.Any()) { continue; } foreach (var attribute in attributes) { if (StringComparer.OrdinalIgnoreCase.Equals("CommandLine", attribute.AttributeClass.ContainingAssembly.Name)) { return true; } } } return false; } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.2.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Reservations { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for ReservationOperations. /// </summary> public static partial class ReservationOperationsExtensions { /// <summary> /// Split the `Reservation`. /// </summary> /// <remarks> /// Split a `Reservation` into two `Reservation`s with specified quantity /// distribution. /// /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='reservationOrderId'> /// Order Id of the reservation /// /// </param> /// <param name='body'> /// Information needed to Split a reservation item /// </param> public static IList<ReservationResponse> Split(this IReservationOperations operations, string reservationOrderId, SplitRequest body) { return operations.SplitAsync(reservationOrderId, body).GetAwaiter().GetResult(); } /// <summary> /// Split the `Reservation`. /// </summary> /// <remarks> /// Split a `Reservation` into two `Reservation`s with specified quantity /// distribution. /// /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='reservationOrderId'> /// Order Id of the reservation /// /// </param> /// <param name='body'> /// Information needed to Split a reservation item /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<ReservationResponse>> SplitAsync(this IReservationOperations operations, string reservationOrderId, SplitRequest body, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.SplitWithHttpMessagesAsync(reservationOrderId, body, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Merges two `Reservation`s. /// </summary> /// <remarks> /// Merge the specified `Reservation`s into a new `Reservation`. The two /// `Reservation`s being merged must have same properties. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='reservationOrderId'> /// Order Id of the reservation /// /// </param> /// <param name='body'> /// Information needed for commercial request for a reservation /// </param> public static IList<ReservationResponse> Merge(this IReservationOperations operations, string reservationOrderId, MergeRequest body) { return operations.MergeAsync(reservationOrderId, body).GetAwaiter().GetResult(); } /// <summary> /// Merges two `Reservation`s. /// </summary> /// <remarks> /// Merge the specified `Reservation`s into a new `Reservation`. The two /// `Reservation`s being merged must have same properties. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='reservationOrderId'> /// Order Id of the reservation /// /// </param> /// <param name='body'> /// Information needed for commercial request for a reservation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<ReservationResponse>> MergeAsync(this IReservationOperations operations, string reservationOrderId, MergeRequest body, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.MergeWithHttpMessagesAsync(reservationOrderId, body, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get `Reservation`s in a given reservation Order /// </summary> /// <remarks> /// List `Reservation`s within a single `ReservationOrder`. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='reservationOrderId'> /// Order Id of the reservation /// /// </param> public static IPage<ReservationResponse> List(this IReservationOperations operations, string reservationOrderId) { return operations.ListAsync(reservationOrderId).GetAwaiter().GetResult(); } /// <summary> /// Get `Reservation`s in a given reservation Order /// </summary> /// <remarks> /// List `Reservation`s within a single `ReservationOrder`. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='reservationOrderId'> /// Order Id of the reservation /// /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ReservationResponse>> ListAsync(this IReservationOperations operations, string reservationOrderId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(reservationOrderId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get `Reservation` details. /// </summary> /// <remarks> /// Get specific `Reservation` details. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='reservationId'> /// Id of the Reservation Item /// </param> /// <param name='reservationOrderId'> /// Order Id of the reservation /// /// </param> public static ReservationResponse Get(this IReservationOperations operations, string reservationId, string reservationOrderId) { return operations.GetAsync(reservationId, reservationOrderId).GetAwaiter().GetResult(); } /// <summary> /// Get `Reservation` details. /// </summary> /// <remarks> /// Get specific `Reservation` details. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='reservationId'> /// Id of the Reservation Item /// </param> /// <param name='reservationOrderId'> /// Order Id of the reservation /// /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ReservationResponse> GetAsync(this IReservationOperations operations, string reservationId, string reservationOrderId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(reservationId, reservationOrderId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates a `Reservation`. /// </summary> /// <remarks> /// Updates the applied scopes of the `Reservation`. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='reservationOrderId'> /// Order Id of the reservation /// /// </param> /// <param name='reservationId'> /// Id of the Reservation Item /// </param> /// <param name='parameters'> /// Information needed to patch a reservation item /// </param> public static ReservationResponse Update(this IReservationOperations operations, string reservationOrderId, string reservationId, Patch parameters) { return operations.UpdateAsync(reservationOrderId, reservationId, parameters).GetAwaiter().GetResult(); } /// <summary> /// Updates a `Reservation`. /// </summary> /// <remarks> /// Updates the applied scopes of the `Reservation`. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='reservationOrderId'> /// Order Id of the reservation /// /// </param> /// <param name='reservationId'> /// Id of the Reservation Item /// </param> /// <param name='parameters'> /// Information needed to patch a reservation item /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ReservationResponse> UpdateAsync(this IReservationOperations operations, string reservationOrderId, string reservationId, Patch parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.UpdateWithHttpMessagesAsync(reservationOrderId, reservationId, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get `Reservation` revisions. /// </summary> /// <remarks> /// List of all the revisions for the `Reservation`. /// /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='reservationId'> /// Id of the Reservation Item /// </param> /// <param name='reservationOrderId'> /// Order Id of the reservation /// /// </param> public static IPage<ReservationResponse> ListRevisions(this IReservationOperations operations, string reservationId, string reservationOrderId) { return operations.ListRevisionsAsync(reservationId, reservationOrderId).GetAwaiter().GetResult(); } /// <summary> /// Get `Reservation` revisions. /// </summary> /// <remarks> /// List of all the revisions for the `Reservation`. /// /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='reservationId'> /// Id of the Reservation Item /// </param> /// <param name='reservationOrderId'> /// Order Id of the reservation /// /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<ReservationResponse>> ListRevisionsAsync(this IReservationOperations operations, string reservationId, string reservationOrderId, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListRevisionsWithHttpMessagesAsync(reservationId, reservationOrderId, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Split the `Reservation`. /// </summary> /// <remarks> /// Split a `Reservation` into two `Reservation`s with specified quantity /// distribution. /// /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='reservationOrderId'> /// Order Id of the reservation /// /// </param> /// <param name='body'> /// Information needed to Split a reservation item /// </param> public static IList<ReservationResponse> BeginSplit(this IReservationOperations operations, string reservationOrderId, SplitRequest body) { return operations.BeginSplitAsync(reservationOrderId, body).GetAwaiter().GetResult(); } /// <summary> /// Split the `Reservation`. /// </summary> /// <remarks> /// Split a `Reservation` into two `Reservation`s with specified quantity /// distribution. /// /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='reservationOrderId'> /// Order Id of the reservation /// /// </param> /// <param name='body'> /// Information needed to Split a reservation item /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<ReservationResponse>> BeginSplitAsync(this IReservationOperations operations, string reservationOrderId, SplitRequest body, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginSplitWithHttpMessagesAsync(reservationOrderId, body, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Merges two `Reservation`s. /// </summary> /// <remarks> /// Merge the specified `Reservation`s into a new `Reservation`. The two /// `Reservation`s being merged must have same properties. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='reservationOrderId'> /// Order Id of the reservation /// /// </param> /// <param name='body'> /// Information needed for commercial request for a reservation /// </param> public static IList<ReservationResponse> BeginMerge(this IReservationOperations operations, string reservationOrderId, MergeRequest body) { return operations.BeginMergeAsync(reservationOrderId, body).GetAwaiter().GetResult(); } /// <summary> /// Merges two `Reservation`s. /// </summary> /// <remarks> /// Merge the specified `Reservation`s into a new `Reservation`. The two /// `Reservation`s being merged must have same properties. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='reservationOrderId'> /// Order Id of the reservation /// /// </param> /// <param name='body'> /// Information needed for commercial request for a reservation /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IList<ReservationResponse>> BeginMergeAsync(this IReservationOperations operations, string reservationOrderId, MergeRequest body, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginMergeWithHttpMessagesAsync(reservationOrderId, body, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Updates a `Reservation`. /// </summary> /// <remarks> /// Updates the applied scopes of the `Reservation`. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='reservationOrderId'> /// Order Id of the reservation /// /// </param> /// <param name='reservationId'> /// Id of the Reservation Item /// </param> /// <param name='parameters'> /// Information needed to patch a reservation item /// </param> public static ReservationResponse BeginUpdate(this IReservationOperations operations, string reservationOrderId, string reservationId, Patch parameters) { return operations.BeginUpdateAsync(reservationOrderId, reservationId, parameters).GetAwaiter().GetResult(); } /// <summary> /// Updates a `Reservation`. /// </summary> /// <remarks> /// Updates the applied scopes of the `Reservation`. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='reservationOrderId'> /// Order Id of the reservation /// /// </param> /// <param name='reservationId'> /// Id of the Reservation Item /// </param> /// <param name='parameters'> /// Information needed to patch a reservation item /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<ReservationResponse> BeginUpdateAsync(this IReservationOperations operations, string reservationOrderId, string reservationId, Patch parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginUpdateWithHttpMessagesAsync(reservationOrderId, reservationId, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get `Reservation`s in a given reservation Order /// </summary> /// <remarks> /// List `Reservation`s within a single `ReservationOrder`. /// </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<ReservationResponse> ListNext(this IReservationOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Get `Reservation`s in a given reservation Order /// </summary> /// <remarks> /// List `Reservation`s within a single `ReservationOrder`. /// </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<ReservationResponse>> ListNextAsync(this IReservationOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Get `Reservation` revisions. /// </summary> /// <remarks> /// List of all the revisions for the `Reservation`. /// /// </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<ReservationResponse> ListRevisionsNext(this IReservationOperations operations, string nextPageLink) { return operations.ListRevisionsNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Get `Reservation` revisions. /// </summary> /// <remarks> /// List of all the revisions for the `Reservation`. /// /// </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<ReservationResponse>> ListRevisionsNextAsync(this IReservationOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListRevisionsNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
// *********************************************************************** // Copyright (c) 2007 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.Generic; using System.Text; using NUnit.Framework; using NUnit.Framework.Constraints; namespace NUnit.TestUtilities { /// <summary> /// A static helper to Verify that Setup/Teardown 'events' occur, and that they are in the correct order... /// </summary> public static class SimpleEventRecorder { /// <summary> /// A helper class for matching test events. /// </summary> public class EventMatcher { private readonly List<string> _expectedEvents; public EventMatcher(IEnumerable<string> expectedEvents) { _expectedEvents = new List<string>(expectedEvents); } /// <summary> /// Matches a test event with one of the expected events. /// </summary> /// <param name="event">A string identifying the test event</param> /// <param name="item">The index of the recorded test event</param> /// <returns>true, if there are expected events left to match, otherwise false.</returns> public bool MatchEvent(string @event, int item) { Assert.Contains(@event, _expectedEvents, "Item {0}", item); _expectedEvents.Remove(@event); return _expectedEvents.Count > 0; } } /// <summary> /// Helper class for recording expected events. /// </summary> public class ExpectedEventsRecorder { private readonly Queue<string> _actualEvents; private readonly Queue<EventMatcher> _eventMatchers; public ExpectedEventsRecorder(Queue<string> actualEvents, params string[] expectedEvents) { _actualEvents = actualEvents; _eventMatchers = new Queue<EventMatcher>(); AndThen(expectedEvents); } /// <summary> /// Adds the specified events as expected events. /// </summary> /// <param name="expectedEvents">An array of strings identifying the test events</param> /// <returns>Returns the ExpectedEventsRecorder for adding new expected events.</returns> public ExpectedEventsRecorder AndThen(params string[] expectedEvents) { _eventMatchers.Enqueue(new EventMatcher(expectedEvents)); return this; } /// <summary> /// Verifies the recorded expected events with the actual recorded events. /// </summary> public void Verify() { EventMatcher eventMatcher = _eventMatchers.Dequeue(); int item = 0; foreach (string actualEvent in _actualEvents) { if (eventMatcher == null) { Assert.Fail( "More events than expected were recorded. Current event: {0} (Item {1})", actualEvent, item); } if (!eventMatcher.MatchEvent(actualEvent, item++)) { if (_eventMatchers.Count > 0) eventMatcher = _eventMatchers.Dequeue(); else eventMatcher = null; } } } } // Because it is static, this class can only be used by one fixture at a time. // Currently, only one fixture uses it, if more use it, they should not be run in parallel. // TODO: Create a utility that can be used by multiple fixtures private static Queue<string> _events; /// <summary> /// Initializes the <see cref="SimpleEventRecorder"/> 'static' class. /// </summary> static SimpleEventRecorder() { _events = new Queue<string>(); } /// <summary> /// Registers an event. /// </summary> /// <param name="evnt">The event to register.</param> public static void RegisterEvent(string evnt) { _events.Enqueue(evnt); } /// <summary> /// Verifies the specified expected events occurred and that they occurred in the specified order. /// </summary> /// <param name="expectedEvents">The expected events.</param> public static void Verify(params string[] expectedEvents) { foreach (string expected in expectedEvents) { int item = 0; string actual = _events.Count > 0 ? _events.Dequeue() : null; Assert.AreEqual( expected, actual, "Item {0}", item++ ); } } /// <summary> /// Record the specified events as recorded expected events. /// </summary> /// <param name="expectedEvents">An array of strings identifying the test events</param> /// <returns>An ExpectedEventsRecorder so that further expected events can be recorded and verified</returns> public static ExpectedEventsRecorder ExpectEvents(params string[] expectedEvents) { return new ExpectedEventsRecorder(_events, expectedEvents); } /// <summary> /// Clears any unverified events. /// </summary> public static void Clear() { _events.Clear(); } } } namespace NUnit.TestData.SetupFixture { namespace Namespace1 { #region SomeFixture [TestFixture] public class SomeFixture { [OneTimeSetUp] public void FixtureSetup() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS1.Fixture.SetUp"); } [SetUp] public void Setup() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS1.Test.SetUp"); } [Test] public void Test() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS1.Test"); } [TearDown] public void TearDown() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS1.Test.TearDown"); } [OneTimeTearDown] public void FixtureTearDown() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS1.Fixture.TearDown"); } } #endregion SomeFixture [SetUpFixture] public class NUnitNamespaceSetUpFixture1 { [OneTimeSetUp] public void DoNamespaceSetUp() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS1.OneTimeSetup"); } [OneTimeTearDown] public void DoNamespaceTearDown() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS1.OneTimeTearDown"); } } } namespace Namespace2 { #region Fixtures /// <summary> /// Summary description for SetUpFixtureTests. /// </summary> [TestFixture] public class SomeFixture { [OneTimeSetUp] public void FixtureSetup() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS2.Fixture.SetUp"); } [SetUp] public void Setup() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS2.Test.SetUp"); } [Test] public void Test() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS2.Test"); } [TearDown] public void TearDown() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS2.Test.TearDown"); } [OneTimeTearDown] public void FixtureTearDown() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS2.Fixture.TearDown"); } } [TestFixture] public class AnotherFixture { [OneTimeSetUp] public void FixtureSetup() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS2.Fixture.SetUp"); } [SetUp] public void Setup() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS2.Test.SetUp"); } [Test] public void Test() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS2.Test"); } [TearDown] public void TearDown() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS2.Test.TearDown"); } [OneTimeTearDown] public void FixtureTearDown() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS2.Fixture.TearDown"); } } #endregion [SetUpFixture] public class NUnitNamespaceSetUpFixture2 { [OneTimeSetUp] public void DoNamespaceSetUp() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS2.OneTimeSetUp"); } [OneTimeTearDown] public void DoNamespaceTearDown() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS2.OneTimeTearDown"); } } } namespace Namespace3 { namespace SubNamespace { #region SomeFixture [TestFixture] public class SomeFixture { [OneTimeSetUp] public void FixtureSetup() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS3.SubNamespace.Fixture.SetUp"); } [SetUp] public void Setup() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS3.SubNamespace.Test.SetUp"); } [Test] public void Test() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS3.SubNamespace.Test"); } [TearDown] public void TearDown() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS3.SubNamespace.Test.TearDown"); } [OneTimeTearDown] public void FixtureTearDown() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS3.SubNamespace.Fixture.TearDown"); } } #endregion SomeTestFixture [SetUpFixture] public class NUnitNamespaceSetUpFixture { [OneTimeSetUp] public void DoNamespaceSetUp() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS3.SubNamespace.OneTimeSetUp"); } [OneTimeTearDown] public void DoNamespaceTearDown() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS3.SubNamespace.OneTimeTearDown"); } } } #region SomeFixture [TestFixture] public class SomeFixture { [OneTimeSetUp] public void FixtureSetup() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS3.Fixture.SetUp"); } [SetUp] public void Setup() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS3.Test.SetUp"); } [Test] public void Test() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS3.Test"); } [TearDown] public void TearDown() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS3.Test.TearDown"); } [OneTimeTearDown] public void FixtureTearDown() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS3.Fixture.TearDown"); } } #endregion SomeTestFixture [SetUpFixture] public class NUnitNamespaceSetUpFixture { [OneTimeSetUp] public static void DoNamespaceSetUp() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS3.OneTimeSetUp"); } [OneTimeTearDown] public void DoNamespaceTearDown() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS3.OneTimeTearDown"); } } } namespace Namespace4 { #region SomeFixture [TestFixture] public class SomeFixture { [OneTimeSetUp] public void FixtureSetup() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS4.Fixture.SetUp"); } [SetUp] public void Setup() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS4.Test.SetUp"); } [Test] public void Test() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS4.Test"); } [TearDown] public void TearDown() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS4.Test.TearDown"); } [OneTimeTearDown] public void FixtureTearDown() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS4.Fixture.TearDown"); } } #endregion SomeTestFixture [SetUpFixture] public class NUnitNamespaceSetUpFixture { [OneTimeSetUp] public void DoNamespaceSetUp() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS4.OneTimeSetUp1"); } [OneTimeTearDown] public void DoNamespaceTearDown() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS4.OneTimeTearDown1"); } } [SetUpFixture] public class NUnitNamespaceSetUpFixture2 { [OneTimeSetUp] public void DoNamespaceSetUp() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS4.OneTimeSetUp2"); } [OneTimeTearDown] public void DoNamespaceTearDown() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS4.OneTimeTearDown2"); } } } namespace Namespace5 { #region SomeFixture [TestFixture] public class SomeFixture { [OneTimeSetUp] public void FixtureSetup() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS5.Fixture.SetUp"); } [SetUp] public void Setup() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS5.Test.SetUp"); } [Test] public void Test() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS5.Test"); } [TearDown] public void TearDown() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS5.Test.TearDown"); } [OneTimeTearDown] public void FixtureTearDown() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS5.Fixture.TearDown"); } } #endregion SomeTestFixture [SetUpFixture] public class NUnitNamespaceSetUpFixture { [OneTimeSetUp] public static void DoNamespaceSetUp() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS5.OneTimeSetUp"); } [OneTimeTearDown] public static void DoNamespaceTearDown() { TestUtilities.SimpleEventRecorder.RegisterEvent("NS5.OneTimeTearDown"); } } } namespace Namespace6 { [SetUpFixture] public class InvalidSetUpFixture { [SetUp] public void InvalidForOneTimeSetUp() { } } [TestFixture] public class SomeFixture { [Test] public void Test() { } } } } #region NoNamespaceSetupFixture [SetUpFixture] public class NoNamespaceSetupFixture { [OneTimeSetUp] public void DoNamespaceSetUp() { NUnit.TestUtilities.SimpleEventRecorder.RegisterEvent("Assembly.OneTimeSetUp"); } [OneTimeTearDown] public void DoNamespaceTearDown() { NUnit.TestUtilities.SimpleEventRecorder.RegisterEvent("Assembly.OneTimeTearDown"); } } [TestFixture] public class SomeFixture { [Test] public void Test() { NUnit.TestUtilities.SimpleEventRecorder.RegisterEvent("NoNamespaceTest"); } } #endregion
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // Copyright (c) 2004 Mainsoft Co. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using Xunit; using System.ComponentModel; using System.Collections; namespace System.Data.Tests { public class DataColumnCollectionTest2 { private int _counter = 0; [Fact] public void Add() { DataColumn dc = null; DataTable dt = new DataTable(); //----------------------------- check default -------------------- dc = dt.Columns.Add(); // Add column 1 Assert.Equal("Column1", dc.ColumnName); // Add column 2 dc = dt.Columns.Add(); Assert.Equal("Column2", dc.ColumnName); dc = dt.Columns.Add(); // Add column 3 Assert.Equal("Column3", dc.ColumnName); dc = dt.Columns.Add(); // Add column 4 Assert.Equal("Column4", dc.ColumnName); dc = dt.Columns.Add(); // Add column 5 Assert.Equal("Column5", dc.ColumnName); Assert.Equal(5, dt.Columns.Count); //----------------------------- check Add/Remove from begining -------------------- dt = initTable(); dt.Columns.Remove(dt.Columns[0]); dt.Columns.Remove(dt.Columns[0]); dt.Columns.Remove(dt.Columns[0]); // check column 4 - remove - from begining Assert.Equal("Column4", dt.Columns[0].ColumnName); // check column 5 - remove - from begining Assert.Equal("Column5", dt.Columns[1].ColumnName); Assert.Equal(2, dt.Columns.Count); dt.Columns.Add(); dt.Columns.Add(); dt.Columns.Add(); dt.Columns.Add(); // check column 0 - Add new - from begining Assert.Equal("Column4", dt.Columns[0].ColumnName); // check column 1 - Add new - from begining Assert.Equal("Column5", dt.Columns[1].ColumnName); // check column 2 - Add new - from begining Assert.Equal("Column6", dt.Columns[2].ColumnName); // check column 3 - Add new - from begining Assert.Equal("Column7", dt.Columns[3].ColumnName); // check column 4 - Add new - from begining Assert.Equal("Column8", dt.Columns[4].ColumnName); // check column 5 - Add new - from begining Assert.Equal("Column9", dt.Columns[5].ColumnName); //----------------------------- check Add/Remove from middle -------------------- dt = initTable(); dt.Columns.Remove(dt.Columns[2]); dt.Columns.Remove(dt.Columns[2]); dt.Columns.Remove(dt.Columns[2]); // check column 0 - remove - from Middle Assert.Equal("Column1", dt.Columns[0].ColumnName); // check column 1 - remove - from Middle Assert.Equal("Column2", dt.Columns[1].ColumnName); dt.Columns.Add(); dt.Columns.Add(); dt.Columns.Add(); dt.Columns.Add(); // check column 0 - Add new - from Middle Assert.Equal("Column1", dt.Columns[0].ColumnName); // check column 1 - Add new - from Middle Assert.Equal("Column2", dt.Columns[1].ColumnName); // check column 2 - Add new - from Middle Assert.Equal("Column3", dt.Columns[2].ColumnName); // check column 3 - Add new - from Middle Assert.Equal("Column4", dt.Columns[3].ColumnName); // check column 4 - Add new - from Middle Assert.Equal("Column5", dt.Columns[4].ColumnName); // check column 5 - Add new - from Middle Assert.Equal("Column6", dt.Columns[5].ColumnName); //----------------------------- check Add/Remove from end -------------------- dt = initTable(); dt.Columns.Remove(dt.Columns[4]); dt.Columns.Remove(dt.Columns[3]); dt.Columns.Remove(dt.Columns[2]); // check column 0 - remove - from end Assert.Equal("Column1", dt.Columns[0].ColumnName); // check column 1 - remove - from end Assert.Equal("Column2", dt.Columns[1].ColumnName); dt.Columns.Add(); dt.Columns.Add(); dt.Columns.Add(); dt.Columns.Add(); // check column 0 - Add new - from end Assert.Equal("Column1", dt.Columns[0].ColumnName); // check column 1 - Add new - from end Assert.Equal("Column2", dt.Columns[1].ColumnName); // check column 2 - Add new - from end Assert.Equal("Column3", dt.Columns[2].ColumnName); // check column 3 - Add new - from end Assert.Equal("Column4", dt.Columns[3].ColumnName); // check column 4 - Add new - from end Assert.Equal("Column5", dt.Columns[4].ColumnName); // check column 5 - Add new - from end Assert.Equal("Column6", dt.Columns[5].ColumnName); } private DataTable initTable() { DataTable dt = new DataTable(); for (int i = 0; i < 5; i++) { dt.Columns.Add(); } return dt; } [Fact] public void TestAdd_ByTableName() { //this test is from boris var ds = new DataSet(); DataTable dt = new DataTable(); ds.Tables.Add(dt); // add one column dt.Columns.Add("id1", typeof(int)); // DataColumnCollection add Assert.Equal(1, dt.Columns.Count); // add row DataRow dr = dt.NewRow(); dt.Rows.Add(dr); // remove column dt.Columns.Remove("id1"); // DataColumnCollection remove Assert.Equal(0, dt.Columns.Count); //row is still there // now add column dt.Columns.Add("id2", typeof(int)); // DataColumnCollection add again Assert.Equal(1, dt.Columns.Count); } [Fact] public void TestCanRemove_ByDataColumn() { DataTable dt = DataProvider.CreateUniqueConstraint(); DataColumn dummyCol = new DataColumn(); Assert.Equal(false, dt.Columns.CanRemove(null)); Assert.Equal(false, dt.Columns.CanRemove(dummyCol)); Assert.Equal(false, dt.Columns.CanRemove(dt.Columns[0])); Assert.Equal(true, dt.Columns.CanRemove(dt.Columns[1])); } [Fact] public void TestCanRemove_ForigenConstraint() { DataSet ds = DataProvider.CreateForeignConstraint(); Assert.Equal(false, ds.Tables["child"].Columns.CanRemove(ds.Tables["child"].Columns["parentId"])); Assert.Equal(false, ds.Tables["parent"].Columns.CanRemove(ds.Tables["child"].Columns["parentId"])); } [Fact] public void TestCanRemove_ParentRelations() { var ds = new DataSet(); ds.Tables.Add("table1"); ds.Tables.Add("table2"); ds.Tables["table1"].Columns.Add("col1"); ds.Tables["table2"].Columns.Add("col1"); ds.Tables[1].ParentRelations.Add("name1", ds.Tables[0].Columns["col1"], ds.Tables[1].Columns["col1"], false); Assert.Equal(false, ds.Tables[1].Columns.CanRemove(ds.Tables[1].Columns["col1"])); Assert.Equal(false, ds.Tables[0].Columns.CanRemove(ds.Tables[0].Columns["col1"])); } [Fact] public void TestCanRemove_Expression() { DataTable dt = new DataTable(); dt.Columns.Add("col1", typeof(string)); dt.Columns.Add("col2", typeof(string), "sum(col1)"); Assert.Equal(false, dt.Columns.CanRemove(dt.Columns["col1"])); } [Fact] public void TestAdd_CollectionChanged() { DataTable dt = DataProvider.CreateParentDataTable(); dt.Columns.CollectionChanged += new CollectionChangeEventHandler(Columns_CollectionChanged); _counter = 0; DataColumn c = dt.Columns.Add("tempCol"); Assert.Equal(1, _counter); Assert.Equal(c, _change_element); } [Fact] public void TestRemove_CollectionChanged() { DataTable dt = DataProvider.CreateParentDataTable(); dt.Columns.CollectionChanged += new CollectionChangeEventHandler(Columns_CollectionChanged); DataColumn c = dt.Columns.Add("tempCol"); _counter = 0; dt.Columns.Remove("tempCol"); Assert.Equal(1, _counter); Assert.Equal(c, _change_element); } [Fact] public void TestSetName_CollectionChanged() { DataTable dt = DataProvider.CreateParentDataTable(); dt.Columns.CollectionChanged += new CollectionChangeEventHandler(Columns_CollectionChanged); dt.Columns.Add("tempCol"); _counter = 0; dt.Columns[0].ColumnName = "tempCol2"; Assert.Equal(0, _counter); } private object _change_element; private void Columns_CollectionChanged(object sender, CollectionChangeEventArgs e) { _counter++; _change_element = e.Element; } [Fact] public void TestContains_ByColumnName() { DataTable dt = DataProvider.CreateParentDataTable(); Assert.Equal(true, dt.Columns.Contains("ParentId")); Assert.Equal(true, dt.Columns.Contains("String1")); Assert.Equal(true, dt.Columns.Contains("ParentBool")); Assert.Equal(false, dt.Columns.Contains("ParentId1")); dt.Columns.Remove("ParentId"); Assert.Equal(false, dt.Columns.Contains("ParentId")); dt.Columns["String1"].ColumnName = "Temp1"; Assert.Equal(false, dt.Columns.Contains("String1")); Assert.Equal(true, dt.Columns.Contains("Temp1")); } public void NotReadyTestContains_S2() // FIXME: fails in MS { DataTable dt = DataProvider.CreateParentDataTable(); Assert.Equal(false, dt.Columns.Contains(null)); } [Fact] public void Count() { DataTable dt = DataProvider.CreateParentDataTable(); Assert.Equal(6, dt.Columns.Count); dt.Columns.Add("temp1"); Assert.Equal(7, dt.Columns.Count); dt.Columns.Remove("temp1"); Assert.Equal(6, dt.Columns.Count); dt.Columns.Remove("ParentId"); Assert.Equal(5, dt.Columns.Count); } [Fact] public void TestIndexOf_ByDataColumn() { DataTable dt = DataProvider.CreateParentDataTable(); for (int i = 0; i < dt.Columns.Count; i++) { Assert.Equal(i, dt.Columns.IndexOf(dt.Columns[i])); } DataColumn col = new DataColumn(); Assert.Equal(-1, dt.Columns.IndexOf(col)); Assert.Equal(-1, dt.Columns.IndexOf((DataColumn)null)); } [Fact] public void TestIndexOf_ByColumnName() { DataTable dt = DataProvider.CreateParentDataTable(); for (int i = 0; i < dt.Columns.Count; i++) { Assert.Equal(i, dt.Columns.IndexOf(dt.Columns[i].ColumnName)); } DataColumn col = new DataColumn(); Assert.Equal(-1, dt.Columns.IndexOf("temp1")); Assert.Equal(-1, dt.Columns.IndexOf((string)null)); } [Fact] public void TestRemove_ByDataColumn() { //prepare a DataSet with DataTable to be checked DataTable dtSource = new DataTable(); dtSource.Columns.Add("Col_0", typeof(int)); dtSource.Columns.Add("Col_1", typeof(int)); dtSource.Columns.Add("Col_2", typeof(int)); dtSource.Rows.Add(new object[] { 0, 1, 2 }); DataTable dt = null; //------Check Remove first column--------- dt = dtSource.Clone(); dt.ImportRow(dtSource.Rows[0]); dt.Columns.Remove(dt.Columns[0]); // Remove first column - check column count Assert.Equal(2, dt.Columns.Count); // Remove first column - check column removed Assert.Equal(false, dt.Columns.Contains("Col_0")); // Remove first column - check column 0 data Assert.Equal(1, dt.Rows[0][0]); // Remove first column - check column 1 data Assert.Equal(2, dt.Rows[0][1]); //------Check Remove middle column--------- dt = dtSource.Clone(); dt.ImportRow(dtSource.Rows[0]); dt.Columns.Remove(dt.Columns[1]); // Remove middle column - check column count Assert.Equal(2, dt.Columns.Count); // Remove middle column - check column removed Assert.Equal(false, dt.Columns.Contains("Col_1")); // Remove middle column - check column 0 data Assert.Equal(0, dt.Rows[0][0]); // Remove middle column - check column 1 data Assert.Equal(2, dt.Rows[0][1]); //------Check Remove last column--------- dt = dtSource.Clone(); dt.ImportRow(dtSource.Rows[0]); dt.Columns.Remove(dt.Columns[2]); // Remove last column - check column count Assert.Equal(2, dt.Columns.Count); // Remove last column - check column removed Assert.Equal(false, dt.Columns.Contains("Col_2")); // Remove last column - check column 0 data Assert.Equal(0, dt.Rows[0][0]); // Remove last column - check column 1 data Assert.Equal(1, dt.Rows[0][1]); //------Check Remove column exception--------- dt = dtSource.Clone(); dt.ImportRow(dtSource.Rows[0]); AssertExtensions.Throws<ArgumentException>(null, () => { DataColumn dc = new DataColumn(); dt.Columns.Remove(dc); }); } [Fact] public void Add_DataColumn1() { DataTable dt = new DataTable(); DataColumn col = new DataColumn("col1", Type.GetType("System.String")); dt.Columns.Add(col); Assert.Equal(1, dt.Columns.Count); Assert.Equal("col1", dt.Columns[0].ColumnName); Assert.Equal("System.String", dt.Columns[0].DataType.ToString()); } [Fact] public void Add_DataColumn2() { DataTable dt = new DataTable(); DataColumn col = new DataColumn("col1", Type.GetType("System.String")); dt.Columns.Add(col); AssertExtensions.Throws<ArgumentException>(null, () => dt.Columns.Add(col)); } [Fact] public void Add_DataColumn3() { DataTable dt = new DataTable(); DataColumn col = new DataColumn("col1", Type.GetType("System.String")); dt.Columns.Add(col); Assert.Throws<DuplicateNameException>(() => { DataColumn col1 = new DataColumn("col1", Type.GetType("System.String")); dt.Columns.Add(col1); }); } [Fact] public void Add_String1() { DataTable dt = new DataTable(); dt.Columns.Add("col1"); Assert.Equal(1, dt.Columns.Count); Assert.Equal("col1", dt.Columns[0].ColumnName); } [Fact] public void Add_String2() { DataTable dt = new DataTable(); dt.Columns.Add("col1"); Assert.Throws<DuplicateNameException>(() => { dt.Columns.Add("col1"); }); } [Fact] public void AddRange_DataColumn1() { DataTable dt = new DataTable(); dt.Columns.AddRange(GetDataColumArray()); Assert.Equal(2, dt.Columns.Count); Assert.Equal("col1", dt.Columns[0].ColumnName); Assert.Equal("col2", dt.Columns[1].ColumnName); Assert.Equal(typeof(int), dt.Columns[0].DataType); Assert.Equal(typeof(string), dt.Columns[1].DataType); } [Fact] public void AddRange_DataColumn2() { DataTable dt = new DataTable(); Assert.Throws<DuplicateNameException>(() => { dt.Columns.AddRange(GetBadDataColumArray()); }); } [Fact] public void DataColumnCollection_AddRange_DataColumn3() { DataTable dt = new DataTable(); dt.Columns.AddRange(null); } private DataColumn[] GetDataColumArray() { DataColumn[] arr = new DataColumn[2]; arr[0] = new DataColumn("col1", typeof(int)); arr[1] = new DataColumn("col2", typeof(string)); return arr; } private DataColumn[] GetBadDataColumArray() { DataColumn[] arr = new DataColumn[2]; arr[0] = new DataColumn("col1", typeof(int)); arr[1] = new DataColumn("col1", typeof(string)); return arr; } [Fact] public void Clear1() { DataTable dt = DataProvider.CreateParentDataTable(); dt.Columns.Clear(); Assert.Equal(0, dt.Columns.Count); } [Fact] public void Clear2() { DataSet ds = DataProvider.CreateForeignConstraint(); AssertExtensions.Throws<ArgumentException>(null, () => { ds.Tables[0].Columns.Clear(); }); } [Fact] public void Clear3() { DataSet ds = DataProvider.CreateForeignConstraint(); ds.Tables[1].Constraints.RemoveAt(0); ds.Tables[0].Constraints.RemoveAt(0); ds.Tables[0].Columns.Clear(); ds.Tables[1].Columns.Clear(); Assert.Equal(0, ds.Tables[0].Columns.Count); Assert.Equal(0, ds.Tables[1].Columns.Count); } [Fact] public void GetEnumerator() { DataTable dt = DataProvider.CreateUniqueConstraint(); int counter = 0; IEnumerator myEnumerator = dt.Columns.GetEnumerator(); while (myEnumerator.MoveNext()) { counter++; } Assert.Equal(6, counter); Assert.Throws<InvalidOperationException>(() => { DataColumn col = (DataColumn)myEnumerator.Current; }); } [Fact] // this [Int32] public void Indexer1() { DataTable dt = DataProvider.CreateParentDataTable(); DataColumn col; col = dt.Columns[5]; Assert.NotNull(col); Assert.Equal("ParentBool", col.ColumnName); col = dt.Columns[0]; Assert.NotNull(col); Assert.Equal("ParentId", col.ColumnName); col = dt.Columns[3]; Assert.NotNull(col); Assert.Equal("ParentDateTime", col.ColumnName); } [Fact] // this [Int32] public void Indexer1_Index_Negative() { DataTable dt = DataProvider.CreateParentDataTable(); try { DataColumn column = dt.Columns[-1]; Assert.False(true); } catch (IndexOutOfRangeException ex) { // Cannot find column -1 Assert.Equal(typeof(IndexOutOfRangeException), ex.GetType()); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } } [Fact] // this [Int32] public void Indexer1_Index_Overflow() { DataTable dt = DataProvider.CreateParentDataTable(); try { DataColumn column = dt.Columns[6]; Assert.False(true); } catch (IndexOutOfRangeException ex) { // Cannot find column 6 Assert.Equal(typeof(IndexOutOfRangeException), ex.GetType()); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); } } [Fact] // this [String] public void Indexer2() { DataTable dt = DataProvider.CreateParentDataTable(); DataColumnCollection cols = dt.Columns; DataColumn col; col = cols["ParentId"]; Assert.NotNull(col); Assert.Equal("ParentId", col.ColumnName); col = cols["parentiD"]; Assert.NotNull(col); Assert.Equal("ParentId", col.ColumnName); col = cols["DoesNotExist"]; Assert.Null(col); } [Fact] // this [String] public void Indexer2_Name_Empty() { DataTable dt = new DataTable(); DataColumnCollection cols = dt.Columns; cols.Add(string.Empty, typeof(int)); cols.Add(null, typeof(bool)); DataColumn column = cols[string.Empty]; Assert.Null(column); } [Fact] // this [String] public void Indexer2_Name_Null() { DataTable dt = DataProvider.CreateParentDataTable(); try { DataColumn column = dt.Columns[null]; Assert.False(true); } catch (ArgumentNullException ex) { Assert.Equal(typeof(ArgumentNullException), ex.GetType()); Assert.Null(ex.InnerException); Assert.NotNull(ex.Message); Assert.Equal("name", ex.ParamName); } } [Fact] public void Remove() { //prepare a DataSet with DataTable to be checked DataTable dtSource = new DataTable(); dtSource.Columns.Add("Col_0", typeof(int)); dtSource.Columns.Add("Col_1", typeof(int)); dtSource.Columns.Add("Col_2", typeof(int)); dtSource.Rows.Add(new object[] { 0, 1, 2 }); DataTable dt = null; //------Check Remove first column--------- dt = dtSource.Clone(); dt.ImportRow(dtSource.Rows[0]); dt.Columns.Remove(dt.Columns[0].ColumnName); Assert.Equal(2, dt.Columns.Count); Assert.Equal(false, dt.Columns.Contains("Col_0")); Assert.Equal(1, dt.Rows[0][0]); Assert.Equal(2, dt.Rows[0][1]); //------Check Remove middle column--------- dt = dtSource.Clone(); dt.ImportRow(dtSource.Rows[0]); dt.Columns.Remove(dt.Columns[1].ColumnName); Assert.Equal(2, dt.Columns.Count); Assert.Equal(false, dt.Columns.Contains("Col_1")); Assert.Equal(0, dt.Rows[0][0]); Assert.Equal(2, dt.Rows[0][1]); //------Check Remove last column--------- dt = dtSource.Clone(); dt.ImportRow(dtSource.Rows[0]); dt.Columns.Remove(dt.Columns[2].ColumnName); Assert.Equal(2, dt.Columns.Count); Assert.Equal(false, dt.Columns.Contains("Col_2")); Assert.Equal(0, dt.Rows[0][0]); Assert.Equal(1, dt.Rows[0][1]); //------Check Remove column exception--------- dt = dtSource.Clone(); dt.ImportRow(dtSource.Rows[0]); AssertExtensions.Throws<ArgumentException>(null, () => { dt.Columns.Remove("NotExist"); }); dt.Columns.Clear(); AssertExtensions.Throws<ArgumentException>(null, () => { dt.Columns.Remove("Col_0"); }); } private bool _eventOccurred = false; [Fact] public void RemoveAt_Integer() { DataTable dt = DataProvider.CreateParentDataTable(); dt.Columns.CollectionChanged += new CollectionChangeEventHandler(Columns_CollectionChanged1); int originalColumnCount = dt.Columns.Count; dt.Columns.RemoveAt(0); Assert.Equal(originalColumnCount - 1, dt.Columns.Count); Assert.Equal(true, _eventOccurred); Assert.Throws<IndexOutOfRangeException>(() => { dt.Columns.RemoveAt(-1); }); } [Fact] public void Test_Indexes() { DataTable dt = new DataTable(); DataColumn dc = new DataColumn("A"); dt.Columns.Add(dc); dc = new DataColumn("B"); dt.Columns.Add(dc); dc = new DataColumn("C"); dt.Columns.Add(dc); for (int i = 0; i < 10; i++) { DataRow dr = dt.NewRow(); dr["A"] = i; dr["B"] = i + 1; dr["C"] = i + 2; dt.Rows.Add(dr); } DataRow[] rows = dt.Select("A=5"); Assert.Equal(1, rows.Length); dt.Columns.Remove("A"); dc = new DataColumn("A"); dc.DefaultValue = 5; dt.Columns.Add(dc); rows = dt.Select("A=5"); Assert.Equal(10, rows.Length); } private void Columns_CollectionChanged1(object sender, CollectionChangeEventArgs e) { _eventOccurred = true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.DotNet.Build.Tasks.Packaging.Tests { public class EnsureOOBFrameworkTests { private Log _log; private TestBuildEngine _engine; public EnsureOOBFrameworkTests(ITestOutputHelper output) { _log = new Log(output); _engine = new TestBuildEngine(_log); } [Fact] public void OOBFxShouldAddRef() { ITaskItem[] files = new[] { CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/MonoAndroid10", "MonoAndroid10"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/MonoTouch10", "MonoTouch10"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/net45", "net45"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/win8", "win8"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/wp80", "wp80"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/wpa81", "wpa81"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/xamarinios10", "xamarinios10"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/xamarinmac20", "xamarinmac20"), CreateItem(@"D:\K2\binaries\x86ret\Contracts\System.Threading\4.0.0.0\System.Threading.dll", "ref/netstandard1.0", "netstandard1.0"), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1033\System.Threading.xml", "ref/netstandard1.0", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1028\System.Threading.xml", "ref/netstandard1.0/zh-hant", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1031\System.Threading.xml", "ref/netstandard1.0/de", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1036\System.Threading.xml", "ref/netstandard1.0/fr", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1040\System.Threading.xml", "ref/netstandard1.0/it", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1041\System.Threading.xml", "ref/netstandard1.0/ja", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1042\System.Threading.xml", "ref/netstandard1.0/ko", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1049\System.Threading.xml", "ref/netstandard1.0/ru", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\2052\System.Threading.xml", "ref/netstandard1.0/zh-hans", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\3082\System.Threading.xml", "ref/netstandard1.0/es", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1028\System.Threading.xml", "ref/netstandard1.3/zh-hant", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1031\System.Threading.xml", "ref/netstandard1.3/de", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1033\System.Threading.xml", "ref/netstandard1.3", ""), CreateItem(@"D:\K2\binaries\x86ret\Contracts\System.Threading\4.0.11.0\System.Threading.dll", "ref/netstandard1.3", "netstandard1.3"), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1036\System.Threading.xml", "ref/netstandard1.3/fr", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1040\System.Threading.xml", "ref/netstandard1.3/it", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1041\System.Threading.xml", "ref/netstandard1.3/ja", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1042\System.Threading.xml", "ref/netstandard1.3/ko", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1049\System.Threading.xml", "ref/netstandard1.3/ru", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\2052\System.Threading.xml", "ref/netstandard1.3/zh-hans", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\3082\System.Threading.xml", "ref/netstandard1.3/es", ""), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/MonoAndroid10", "MonoAndroid10"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/MonoTouch10", "MonoTouch10"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/net45", "net45"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/win8", "win8"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/wp80", "wp80"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/wpa81", "wpa81"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/xamarinios10", "xamarinios10"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/xamarinmac20", "xamarinmac20"), CreateItem(@"D:\K2\binaries\x86ret\NETCore\Manifests\System.Threading\runtime.json", "", "") }; ITaskItem[] oobFx = new[] { new TaskItem("netcore50") }; EnsureOOBFramework task = new EnsureOOBFramework() { BuildEngine = _engine, Files = files, OOBFrameworks = oobFx }; _log.Reset(); task.Execute(); Assert.Equal(0, _log.ErrorsLogged); Assert.Equal(0, _log.WarningsLogged); Assert.Equal(11, task.AdditionalFiles.Length); Assert.All(task.AdditionalFiles, f => f.GetMetadata("TargetPath").Contains(oobFx[0].ItemSpec)); Assert.All(task.AdditionalFiles, f => f.GetMetadata("TargetPath").StartsWith("ref")); Assert.All(task.AdditionalFiles, f => f.GetMetadata("TargetFramework").Equals(oobFx[0].ItemSpec)); } [Fact] public void OOBFxShouldAddRefAndLib() { ITaskItem[] files = new[] { CreateItem(@"D:\K2\binaries\x86ret\NETCore\Libraries\System.Collections.Concurrent.dll", "lib/netstandard1.3", "netstandard1.3"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/MonoAndroid10", "MonoAndroid10"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/MonoTouch10", "MonoTouch10"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/net45", "net45"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/win8", "win8"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/wpa81", "wpa81"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/xamarinios10", "xamarinios10"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/xamarinmac20", "xamarinmac20"), CreateItem(@"D:\K2\binaries\x86ret\Contracts\System.Collections.Concurrent\4.0.0.0\System.Collections.Concurrent.dll", "ref/netstandard1.1", "netstandard1.1"), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1033\System.Collections.Concurrent.xml", "ref/netstandard1.1", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1028\System.Collections.Concurrent.xml", "ref/netstandard1.1/zh-hant", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1031\System.Collections.Concurrent.xml", "ref/netstandard1.1/de", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1036\System.Collections.Concurrent.xml", "ref/netstandard1.1/fr", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1040\System.Collections.Concurrent.xml", "ref/netstandard1.1/it", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1041\System.Collections.Concurrent.xml", "ref/netstandard1.1/ja", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1042\System.Collections.Concurrent.xml", "ref/netstandard1.1/ko", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1049\System.Collections.Concurrent.xml", "ref/netstandard1.1/ru", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\2052\System.Collections.Concurrent.xml", "ref/netstandard1.1/zh-hans", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\3082\System.Collections.Concurrent.xml", "ref/netstandard1.1/es", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1028\System.Collections.Concurrent.xml", "ref/netstandard1.3/zh-hant", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1031\System.Collections.Concurrent.xml", "ref/netstandard1.3/de", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1033\System.Collections.Concurrent.xml", "ref/netstandard1.3", ""), CreateItem(@"D:\K2\binaries\x86ret\Contracts\System.Collections.Concurrent\4.0.11.0\System.Collections.Concurrent.dll", "ref/netstandard1.3", "netstandard1.3"), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1036\System.Collections.Concurrent.xml", "ref/netstandard1.3/fr", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1040\System.Collections.Concurrent.xml", "ref/netstandard1.3/it", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1041\System.Collections.Concurrent.xml", "ref/netstandard1.3/ja", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1042\System.Collections.Concurrent.xml", "ref/netstandard1.3/ko", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1049\System.Collections.Concurrent.xml", "ref/netstandard1.3/ru", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\2052\System.Collections.Concurrent.xml", "ref/netstandard1.3/zh-hans", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\3082\System.Collections.Concurrent.xml", "ref/netstandard1.3/es", ""), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/MonoAndroid10", "MonoAndroid10"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/MonoTouch10", "MonoTouch10"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/net45", "net45"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/win8", "win8"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/wpa81", "wpa81"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/xamarinios10", "xamarinios10"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/xamarinmac20", "xamarinmac20") }; ITaskItem[] oobFx = new[] { new TaskItem("netcore50") }; EnsureOOBFramework task = new EnsureOOBFramework() { BuildEngine = _engine, Files = files, OOBFrameworks = oobFx }; _log.Reset(); task.Execute(); Assert.Equal(0, _log.ErrorsLogged); Assert.Equal(0, _log.WarningsLogged); Assert.Equal(12, task.AdditionalFiles.Length); Assert.All(task.AdditionalFiles, f => f.GetMetadata("TargetPath").Contains(oobFx[0].ItemSpec)); Assert.All(task.AdditionalFiles, f => f.GetMetadata("TargetFramework").Equals(oobFx[0].ItemSpec)); } [Fact] public void OOBFxShouldDoNothing() { ITaskItem[] files = new[] { CreateItem(@"D:\K2\binaries\x86ret\NETCore\Libraries\System.Xml.XmlSerializer.dll", "lib/netcoreapp1.0", "netcoreapp1.0"), CreateItem(@"D:\K2\binaries\x86ret\NETCore\Libraries\System.Xml.XmlSerializer.dll", "lib/netcore50", "netcore50"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/MonoAndroid10", "MonoAndroid10"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/MonoTouch10", "MonoTouch10"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/net45", "net45"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/win8", "win8"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/wpa81", "wpa81"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/xamarinios10", "xamarinios10"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/xamarinmac20", "xamarinmac20") }; ITaskItem[] oobFx = new[] { new TaskItem("netcore50") }; EnsureOOBFramework task = new EnsureOOBFramework() { BuildEngine = _engine, Files = files, OOBFrameworks = oobFx }; _log.Reset(); task.Execute(); Assert.Equal(0, _log.ErrorsLogged); Assert.Equal(0, _log.WarningsLogged); Assert.Equal(0, task.AdditionalFiles.Length); } [Fact] public void OOBFxShouldNotAddForCompletelyOOB() { ITaskItem[] files = new[] { CreateItem(@"D:\K2\binaries\x86ret\NETCore\Libraries\System.Xml.XPath.XDocument.dll", "lib/netstandard1.3", "netstandard1.3"), CreateItem(@"D:\K2\binaries\x86ret\NETCore\Libraries\net\System.Xml.XPath.XDocument.dll", "lib/net46", "net46"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/MonoAndroid10", "MonoAndroid10"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/MonoTouch10", "MonoTouch10"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/xamarinios10", "xamarinios10"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/xamarinmac20", "xamarinmac20"), CreateItem(@"D:\K2\binaries\x86ret\Contracts\System.Xml.XPath.XDocument\4.0.1.0\System.Xml.XPath.XDocument.dll", "ref/netstandard1.0", "netstandard1.0"), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1033\System.Xml.XPath.XDocument.xml", "ref/netstandard1.0", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1028\System.Xml.XPath.XDocument.xml", "ref/netstandard1.0/zh-hant", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1031\System.Xml.XPath.XDocument.xml", "ref/netstandard1.0/de", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1036\System.Xml.XPath.XDocument.xml", "ref/netstandard1.0/fr", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1040\System.Xml.XPath.XDocument.xml", "ref/netstandard1.0/it", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1041\System.Xml.XPath.XDocument.xml", "ref/netstandard1.0/ja", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1042\System.Xml.XPath.XDocument.xml", "ref/netstandard1.0/ko", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1049\System.Xml.XPath.XDocument.xml", "ref/netstandard1.0/ru", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\2052\System.Xml.XPath.XDocument.xml", "ref/netstandard1.0/zh-hans", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\3082\System.Xml.XPath.XDocument.xml", "ref/netstandard1.0/es", ""), CreateItem(@"D:\K2\binaries\x86ret\NETCore\Libraries\net\System.Xml.XPath.XDocument.dll", "ref/net46", "net46"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/MonoAndroid10", "MonoAndroid10"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/MonoTouch10", "MonoTouch10"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/xamarinios10", "xamarinios10"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/xamarinmac20", "xamarinmac20") }; ITaskItem[] oobFx = new[] { new TaskItem("netcore50") }; EnsureOOBFramework task = new EnsureOOBFramework() { BuildEngine = _engine, Files = files, OOBFrameworks = oobFx }; _log.Reset(); task.Execute(); Assert.Equal(0, _log.ErrorsLogged); Assert.Equal(0, _log.WarningsLogged); Assert.Equal(0, task.AdditionalFiles.Length); } [Fact] public void OOBFxShouldNotAddWhenAlreadyExists() { ITaskItem[] files = new[] { CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "runtimes/aot/lib/netcore50", ""), CreateItem(@"D:\K2\binaries\x86ret\Contracts\System.Reflection.Emit\4.0.1.0\System.Reflection.Emit.dll", "ref/netstandard1.1", "netstandard1.1"), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1033\System.Reflection.Emit.xml", "ref/netstandard1.1", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1028\System.Reflection.Emit.xml", "ref/netstandard1.1/zh-hant", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1031\System.Reflection.Emit.xml", "ref/netstandard1.1/de", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1036\System.Reflection.Emit.xml", "ref/netstandard1.1/fr", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1040\System.Reflection.Emit.xml", "ref/netstandard1.1/it", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1041\System.Reflection.Emit.xml", "ref/netstandard1.1/ja", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1042\System.Reflection.Emit.xml", "ref/netstandard1.1/ko", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\1049\System.Reflection.Emit.xml", "ref/netstandard1.1/ru", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\2052\System.Reflection.Emit.xml", "ref/netstandard1.1/zh-hans", ""), CreateItem(@"D:\K2\src\Redist\x86\retail\bin\i386\HelpDocs\intellisense\NETCore5\3082\System.Reflection.Emit.xml", "ref/netstandard1.1/es", ""), CreateItem(@"D:\K2\binaries\x86ret\NETCore\Libraries\System.Reflection.Emit.dll", "lib/netcoreapp1.0", "netcoreapp1.0"), CreateItem(@"D:\K2\binaries\x86ret\NETCore\Libraries\netcoreforcoreclr\System.Reflection.Emit.dll", "lib/netcore50", "netcore50"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/MonoAndroid10", ""), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/MonoAndroid10", ""), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/xamarinmac20", ""), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/xamarinmac20", ""), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "lib/net45", ""), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/net45", "") }; ITaskItem[] oobFx = new[] { new TaskItem("netcore50") }; EnsureOOBFramework task = new EnsureOOBFramework() { BuildEngine = _engine, Files = files, OOBFrameworks = oobFx, RuntimeId = "", RuntimeJson = "runtime.json" }; _log.Reset(); task.Execute(); Assert.Equal(0, _log.ErrorsLogged); Assert.Equal(0, _log.WarningsLogged); Assert.Equal(0, task.AdditionalFiles.Length); } [Fact] public void OOBFxRuntimePackage() { ITaskItem[] files = new[] { CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "runtimes/win7/lib/win8", "win8"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "runtimes/win7/lib/wp8", "wp8"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "runtimes/win7/lib/wpa81", "wpa81"), CreateItem(@"D:\K2\binaries\x86ret\NETCore\Libraries\System.Diagnostics.FileVersionInfo.dll", "runtimes/win7/lib/netstandard1.3", "netstandard1.3"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/netstandard", "netstandard") }; ITaskItem[] oobFx = new[] { new TaskItem("netcore50") }; EnsureOOBFramework task = new EnsureOOBFramework() { BuildEngine = _engine, Files = files, OOBFrameworks = oobFx, RuntimeJson = "runtime.json", RuntimeId = "win7" }; _log.Reset(); task.Execute(); Assert.Equal(0, _log.ErrorsLogged); Assert.Equal(0, _log.WarningsLogged); Assert.Equal(1, task.AdditionalFiles.Length); } [Fact] public void OOBFxRuntimePackageExplicitNotSupported() { ITaskItem[] files = new[] { CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "runtimes/win7/lib/win8", "win8"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "runtimes/win7/lib/wp8", "wp8"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "runtimes/win7/lib/wpa81", "wpa81"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "runtimes/win7/lib/netcore50", "netcore50"), CreateItem(@"D:\K2\binaries\x86ret\NETCore\Libraries\System.Diagnostics.FileVersionInfo.dll", "runtimes/win7/lib/netstandard1.3", "netstandard1.3"), CreateItem(@"D:\K2\src\NDP\FxCore\src\Packages\_._", "ref/netstandard", "netstandard") }; ITaskItem[] oobFx = new[] { new TaskItem("netcore50") }; EnsureOOBFramework task = new EnsureOOBFramework() { BuildEngine = _engine, Files = files, OOBFrameworks = oobFx, RuntimeJson = "runtime.json", RuntimeId = "win7" }; _log.Reset(); task.Execute(); Assert.Equal(0, _log.ErrorsLogged); Assert.Equal(0, _log.WarningsLogged); Assert.Equal(0, task.AdditionalFiles.Length); } private static ITaskItem CreateItem(string sourcePath, string targetPath, string targetFramework) { TaskItem item = new TaskItem(sourcePath); item.SetMetadata("TargetPath", targetPath); item.SetMetadata("TargetFramework", targetFramework); return item; } } }
using System; using System.Linq; using System.Net.WebSockets; using System.Threading; using System.Threading.Tasks; using BTCPayServer.Abstractions.Constants; using BTCPayServer.Client; using BTCPayServer.Data; using BTCPayServer.Filters; using BTCPayServer.Models.NotificationViewModels; using BTCPayServer.Security; using BTCPayServer.Services; using BTCPayServer.Services.Notifications; using BTCPayServer.Services.Notifications.Blobs; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; namespace BTCPayServer.Controllers { [BitpayAPIConstraint(false)] [Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie, Policy = Policies.CanViewNotificationsForUser)] [Route("notifications/{action:lowercase=Index}")] public class UINotificationsController : Controller { private readonly BTCPayServerEnvironment _env; private readonly NotificationSender _notificationSender; private readonly UserManager<ApplicationUser> _userManager; private readonly NotificationManager _notificationManager; private readonly EventAggregator _eventAggregator; public UINotificationsController(BTCPayServerEnvironment env, NotificationSender notificationSender, UserManager<ApplicationUser> userManager, NotificationManager notificationManager, EventAggregator eventAggregator) { _env = env; _notificationSender = notificationSender; _userManager = userManager; _notificationManager = notificationManager; _eventAggregator = eventAggregator; } [HttpGet] public IActionResult GetNotificationDropdownUI() { return ViewComponent("Notifications", new { appearance = "Dropdown" }); } [HttpGet] public async Task<IActionResult> SubscribeUpdates(CancellationToken cancellationToken) { if (!HttpContext.WebSockets.IsWebSocketRequest) { return BadRequest(); } var websocket = await HttpContext.WebSockets.AcceptWebSocketAsync(); var userId = _userManager.GetUserId(User); var websocketHelper = new WebSocketHelper(websocket); IEventAggregatorSubscription subscription = null; try { subscription = _eventAggregator.SubscribeAsync<UserNotificationsUpdatedEvent>(async evt => { if (evt.UserId == userId) { await websocketHelper.Send("update"); } }); await websocketHelper.NextMessageAsync(cancellationToken); } catch (OperationCanceledException) { // ignored } catch (WebSocketException) { } finally { subscription?.Dispose(); await websocketHelper.DisposeAsync(CancellationToken.None); } return new EmptyResult(); } #if DEBUG [HttpGet] public async Task<IActionResult> GenerateJunk(int x = 100, bool admin = true) { for (int i = 0; i < x; i++) { await _notificationSender.SendNotification( admin ? (NotificationScope)new AdminScope() : new UserScope(_userManager.GetUserId(User)), new JunkNotification()); } return RedirectToAction("Index"); } #endif [HttpGet] public async Task<IActionResult> Index(int skip = 0, int count = 50, int timezoneOffset = 0) { if (!ValidUserClaim(out var userId)) return RedirectToAction("Index", "UIHome"); var res = await _notificationManager.GetNotifications(new NotificationsQuery() { Skip = skip, Take = count, UserId = userId }); var model = new IndexViewModel() { Skip = skip, Count = count, Items = res.Items, Total = res.Count }; return View(model); } [HttpGet] public async Task<IActionResult> Generate(string version) { if (_env.NetworkType != NBitcoin.ChainName.Regtest) return NotFound(); await _notificationSender.SendNotification(new AdminScope(), new NewVersionNotification(version)); return RedirectToAction(nameof(Index)); } [HttpPost] [Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie, Policy = Policies.CanManageNotificationsForUser)] public async Task<IActionResult> FlipRead(string id) { if (ValidUserClaim(out var userId)) { await _notificationManager.ToggleSeen(new NotificationsQuery() { Ids = new[] { id }, UserId = userId }, null); return RedirectToAction(nameof(Index)); } return BadRequest(); } [HttpGet] public async Task<IActionResult> NotificationPassThrough(string id) { if (ValidUserClaim(out var userId)) { var items = await _notificationManager.ToggleSeen(new NotificationsQuery() { Ids = new[] { id }, UserId = userId }, true); var link = items.FirstOrDefault()?.ActionLink ?? ""; if (string.IsNullOrEmpty(link)) { return RedirectToAction(nameof(Index)); } return Redirect(link); } return NotFound(); } [HttpPost] [Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie, Policy = Policies.CanManageNotificationsForUser)] public async Task<IActionResult> MassAction(string command, string[] selectedItems) { if (!ValidUserClaim(out var userId)) { return NotFound(); } if (command.StartsWith("flip-individual", StringComparison.InvariantCulture)) { var id = command.Split(":")[1]; return await FlipRead(id); } if (selectedItems != null) { switch (command) { case "delete": await _notificationManager.Remove(new NotificationsQuery() { UserId = userId, Ids = selectedItems }); break; case "mark-seen": await _notificationManager.ToggleSeen(new NotificationsQuery() { UserId = userId, Ids = selectedItems, Seen = false }, true); break; case "mark-unseen": await _notificationManager.ToggleSeen(new NotificationsQuery() { UserId = userId, Ids = selectedItems, Seen = true }, false); break; } return RedirectToAction(nameof(Index)); } return RedirectToAction(nameof(Index)); } [HttpPost] [Authorize(AuthenticationSchemes = AuthenticationSchemes.Cookie, Policy = Policies.CanManageNotificationsForUser)] public async Task<IActionResult> MarkAllAsSeen(string returnUrl) { if (!ValidUserClaim(out var userId)) { return NotFound(); } await _notificationManager.ToggleSeen(new NotificationsQuery() { Seen = false, UserId = userId }, true); return Redirect(returnUrl); } private bool ValidUserClaim(out string userId) { userId = _userManager.GetUserId(User); return userId != null; } } }
#pragma warning disable 1634, 1691 /********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ #pragma warning disable 1634, 1691 #pragma warning disable 56523 using Dbg = System.Management.Automation; using System.IO; using System.Management.Automation.Internal; using System.Management.Automation.Security; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; #if CORECLR // Use stub for using Microsoft.PowerShell.CoreClr.Stubs; #endif using DWORD = System.UInt32; namespace System.Management.Automation { /// <summary> /// Defines the options that control what data is embedded in the /// signature blob /// </summary> /// public enum SigningOption { /// <summary> /// Embeds only the signer's certificate. /// </summary> AddOnlyCertificate, /// <summary> /// Embeds the entire certificate chain. /// </summary> AddFullCertificateChain, /// <summary> /// Embeds the entire certificate chain, except for the root /// certificate. /// </summary> AddFullCertificateChainExceptRoot, /// <summary> /// Default: Embeds the entire certificate chain, except for the /// root certificate. /// </summary> Default = AddFullCertificateChainExceptRoot } /// <summary> /// Helper functions for signature functionality /// </summary> internal static class SignatureHelper { /// <summary> /// tracer for SignatureHelper /// </summary> [Dbg.TraceSource("SignatureHelper", "tracer for SignatureHelper")] private static readonly Dbg.PSTraceSource s_tracer = Dbg.PSTraceSource.GetTracer("SignatureHelper", "tracer for SignatureHelper"); /// <summary> /// Sign a file /// </summary> /// /// <param name="option"> option that controls what gets embedded in the signature blob </param> /// /// <param name="fileName"> name of file to sign </param> /// /// <param name="certificate"> signing cert </param> /// /// <param name="timeStampServerUrl"> URL of time stamping server </param> /// /// <param name="hashAlgorithm"> The name of the hash /// algorithm to use. </param> /// /// <returns> Does not return a value </returns> /// /// /// <exception cref="System.ArgumentNullException"> /// Thrown if argument fileName or certificate is null. /// </exception> /// /// /// <exception cref="System.ArgumentException"> /// Thrown if /// -- argument fileName is empty OR /// -- the specified certificate is not suitable for /// signing code /// </exception> /// /// /// <exception cref="System.Security.Cryptography.CryptographicException"> /// This exception can be thrown if any cryptographic error occurs. /// It is not possible to know exactly what went wrong. /// This is because of the way CryptographicException is designed. /// Possible reasons: /// -- certificate is invalid /// -- certificate has no private key /// -- certificate password mismatch /// -- etc /// </exception> /// /// /// <exception cref="System.IO.FileNotFoundException"> /// Thrown if the file specified by argument fileName is not found /// </exception> /// /// <remarks> </remarks> /// [ArchitectureSensitive] internal static Signature SignFile(SigningOption option, string fileName, X509Certificate2 certificate, string timeStampServerUrl, string hashAlgorithm) { bool result = false; Signature signature = null; IntPtr pSignInfo = IntPtr.Zero; DWORD error = 0; string hashOid = null; Utils.CheckArgForNullOrEmpty(fileName, "fileName"); Utils.CheckArgForNull(certificate, "certificate"); // If given, TimeStamp server URLs must begin with http:// if (!String.IsNullOrEmpty(timeStampServerUrl)) { if ((timeStampServerUrl.Length <= 7) || (timeStampServerUrl.IndexOf("http://", StringComparison.OrdinalIgnoreCase) != 0)) { throw PSTraceSource.NewArgumentException( "certificate", Authenticode.TimeStampUrlRequired); } } // Validate that the hash algorithm is valid if (!String.IsNullOrEmpty(hashAlgorithm)) { IntPtr intptrAlgorithm = Marshal.StringToHGlobalUni(hashAlgorithm); IntPtr oidPtr = NativeMethods.CryptFindOIDInfo(NativeConstants.CRYPT_OID_INFO_NAME_KEY, intptrAlgorithm, 0); // If we couldn't find an OID for the hash // algorithm, it was invalid. if (oidPtr == IntPtr.Zero) { throw PSTraceSource.NewArgumentException( "certificate", Authenticode.InvalidHashAlgorithm); } else { NativeMethods.CRYPT_OID_INFO oidInfo = ClrFacade.PtrToStructure<NativeMethods.CRYPT_OID_INFO>(oidPtr); hashOid = oidInfo.pszOID; } } if (!SecuritySupport.CertIsGoodForSigning(certificate)) { throw PSTraceSource.NewArgumentException( "certificate", Authenticode.CertNotGoodForSigning); } SecuritySupport.CheckIfFileExists(fileName); //SecurityUtils.CheckIfFileSmallerThan4Bytes(fileName); try { // CryptUI is not documented either way, but does not // support empty strings for the timestamp server URL. // It expects null, only. Instead, it randomly AVs if you // try. string timeStampServerUrlForCryptUI = null; if (!String.IsNullOrEmpty(timeStampServerUrl)) { timeStampServerUrlForCryptUI = timeStampServerUrl; } // // first initialize the struct to pass to // CryptUIWizDigitalSign() function // NativeMethods.CRYPTUI_WIZ_DIGITAL_SIGN_INFO si = NativeMethods.InitSignInfoStruct(fileName, certificate, timeStampServerUrlForCryptUI, hashOid, option); pSignInfo = Marshal.AllocCoTaskMem(Marshal.SizeOf(si)); Marshal.StructureToPtr(si, pSignInfo, false); // // sign the file // // The GetLastWin32Error of this is checked, but PreSharp doesn't seem to be // able to see that. #pragma warning disable 56523 result = NativeMethods.CryptUIWizDigitalSign( (DWORD)NativeMethods.CryptUIFlags.CRYPTUI_WIZ_NO_UI, IntPtr.Zero, IntPtr.Zero, pSignInfo, IntPtr.Zero); #pragma warning enable 56523 if (si.pSignExtInfo != null) { ClrFacade.DestroyStructure<NativeMethods.CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO>(si.pSignExtInfo); Marshal.FreeCoTaskMem(si.pSignExtInfo); } if (!result) { error = GetLastWin32Error(); // // ISSUE-2004/05/08-kumarp : there seems to be a bug // in CryptUIWizDigitalSign(). // It returns 80004005 or 80070001 // but it signs the file correctly. Mask this error // till we figure out this odd behavior. // if ((error == 0x80004005) || (error == 0x80070001) || // CryptUIWizDigitalSign introduced a breaking change in Win8 to return this // error code (ERROR_INTERNET_NAME_NOT_RESOLVED) when you provide an invalid // timestamp server. It used to be 0x80070001. // Also masking this out so that we don't introduce a breaking change ourselves. (error == 0x80072EE7) ) { result = true; } else { if (error == Win32Errors.NTE_BAD_ALGID) { throw PSTraceSource.NewArgumentException( "certificate", Authenticode.InvalidHashAlgorithm); } s_tracer.TraceError("CryptUIWizDigitalSign: failed: {0:x}", error); } } if (result) { signature = GetSignature(fileName, null); } else { signature = new Signature(fileName, (DWORD)error); } } finally { ClrFacade.DestroyStructure<NativeMethods.CRYPTUI_WIZ_DIGITAL_SIGN_INFO>(pSignInfo); Marshal.FreeCoTaskMem(pSignInfo); } return signature; } /// <summary> /// Get signature on the specified file /// </summary> /// /// <param name="fileName"> name of file to check </param> /// /// <param name="fileContent"> content of file to check </param> /// /// <returns> Signature object </returns> /// /// <exception cref="System.ArgumentException"> /// Thrown if argument fileName is empty. /// </exception> /// /// /// <exception cref="System.ArgumentNullException"> /// Thrown if argument fileName is null /// </exception> /// /// /// <exception cref="System.IO.FileNotFoundException"> /// Thrown if the file specified by argument fileName is not found. /// </exception> /// /// <remarks> </remarks> /// [ArchitectureSensitive] internal static Signature GetSignature(string fileName, string fileContent) { Signature signature = null; if (fileContent == null) { // First, try to get the signature from the catalog signature APIs. signature = GetSignatureFromCatalog(fileName); } // If there is no signature or it is invalid, go by the file content // with the older WinVerifyTrust APIs if ((signature == null) || (signature.Status != SignatureStatus.Valid)) { signature = GetSignatureFromWinVerifyTrust(fileName, fileContent); } return signature; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")] private static Signature GetSignatureFromCatalog(string filename) { if (Signature.CatalogApiAvailable.HasValue && !Signature.CatalogApiAvailable.Value) { // Signature.CatalogApiAvailable would be set to false the first time it is detected that // WTGetSignatureInfo API does not exist on the platform, or if the API is not functional on the target platform. // Just return from the function instead of revalidating. return null; } Signature signature = null; Utils.CheckArgForNullOrEmpty(filename, "fileName"); SecuritySupport.CheckIfFileExists(filename); try { using (FileStream stream = File.OpenRead(filename)) { NativeMethods.SIGNATURE_INFO sigInfo = new NativeMethods.SIGNATURE_INFO(); sigInfo.cbSize = (uint)Marshal.SizeOf(sigInfo); IntPtr ppCertContext = IntPtr.Zero; IntPtr phStateData = IntPtr.Zero; try { int hresult = NativeMethods.WTGetSignatureInfo(filename, stream.SafeFileHandle.DangerousGetHandle(), NativeMethods.SIGNATURE_INFO_FLAGS.SIF_CATALOG_SIGNED | NativeMethods.SIGNATURE_INFO_FLAGS.SIF_CATALOG_FIRST | NativeMethods.SIGNATURE_INFO_FLAGS.SIF_AUTHENTICODE_SIGNED | NativeMethods.SIGNATURE_INFO_FLAGS.SIF_BASE_VERIFICATION | NativeMethods.SIGNATURE_INFO_FLAGS.SIF_CHECK_OS_BINARY, ref sigInfo, ref ppCertContext, ref phStateData); if (Utils.Succeeded(hresult)) { DWORD error = GetErrorFromSignatureState(sigInfo.nSignatureState); X509Certificate2 cert = null; if (ppCertContext != IntPtr.Zero) { cert = new X509Certificate2(ppCertContext); signature = new Signature(filename, error, cert); switch (sigInfo.nSignatureType) { case NativeMethods.SIGNATURE_INFO_TYPE.SIT_AUTHENTICODE: signature.SignatureType = SignatureType.Authenticode; break; case NativeMethods.SIGNATURE_INFO_TYPE.SIT_CATALOG: signature.SignatureType = SignatureType.Catalog; break; } if (sigInfo.fOSBinary == 1) { signature.IsOSBinary = true; } } else { signature = new Signature(filename, error); } if (!Signature.CatalogApiAvailable.HasValue) { string productFile = Path.Combine(Utils.GetApplicationBase(Utils.DefaultPowerShellShellID), "Modules\\Microsoft.PowerShell.Utility\\Microsoft.PowerShell.Utility.psm1"); if (signature.Status != SignatureStatus.Valid) { if (string.Equals(filename, productFile, StringComparison.OrdinalIgnoreCase)) { Signature.CatalogApiAvailable = false; } else { // ProductFile has to be Catalog signed. Hence validating // to see if the Catalog API is functional using the ProductFile. Signature productFileSignature = GetSignatureFromCatalog(productFile); Signature.CatalogApiAvailable = (productFileSignature != null && productFileSignature.Status == SignatureStatus.Valid); } } } } else { // If calling NativeMethods.WTGetSignatureInfo failed (returned a non-zero value), we still want to set Signature.CatalogApiAvailable to false. Signature.CatalogApiAvailable = false; } } finally { if (phStateData != IntPtr.Zero) { NativeMethods.FreeWVTStateData(phStateData); } if (ppCertContext != IntPtr.Zero) { NativeMethods.CertFreeCertificateContext(ppCertContext); } } } } catch (TypeLoadException) { // If we don't have WTGetSignatureInfo, don't return a Signature. Signature.CatalogApiAvailable = false; return null; } return signature; } private static DWORD GetErrorFromSignatureState(NativeMethods.SIGNATURE_STATE state) { switch (state) { case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_UNSIGNED_MISSING: return Win32Errors.TRUST_E_NOSIGNATURE; case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_UNSIGNED_UNSUPPORTED: return Win32Errors.TRUST_E_NOSIGNATURE; case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_UNSIGNED_POLICY: return Win32Errors.TRUST_E_NOSIGNATURE; case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_INVALID_CORRUPT: return Win32Errors.TRUST_E_BAD_DIGEST; case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_INVALID_POLICY: return Win32Errors.CRYPT_E_BAD_MSG; case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_VALID: return Win32Errors.NO_ERROR; case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_TRUSTED: return Win32Errors.NO_ERROR; case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_UNTRUSTED: return Win32Errors.TRUST_E_EXPLICIT_DISTRUST; // Should not happen default: System.Diagnostics.Debug.Fail("Should not get here - could not map SIGNATURE_STATE"); return Win32Errors.TRUST_E_NOSIGNATURE; } } private static Signature GetSignatureFromWinVerifyTrust(string fileName, string fileContent) { Signature signature = null; NativeMethods.WINTRUST_DATA wtd; DWORD error = Win32Errors.E_FAIL; if (fileContent == null) { Utils.CheckArgForNullOrEmpty(fileName, "fileName"); SecuritySupport.CheckIfFileExists(fileName); //SecurityUtils.CheckIfFileSmallerThan4Bytes(fileName); } try { error = GetWinTrustData(fileName, fileContent, out wtd); if (error != Win32Errors.NO_ERROR) { s_tracer.WriteLine("GetWinTrustData failed: {0:x}", error); } signature = GetSignatureFromWintrustData(fileName, error, wtd); error = NativeMethods.DestroyWintrustDataStruct(wtd); if (error != Win32Errors.NO_ERROR) { s_tracer.WriteLine("DestroyWinTrustDataStruct failed: {0:x}", error); } } catch (AccessViolationException) { signature = new Signature(fileName, Win32Errors.TRUST_E_NOSIGNATURE); } return signature; } [ArchitectureSensitive] private static DWORD GetWinTrustData(string fileName, string fileContent, out NativeMethods.WINTRUST_DATA wtData) { DWORD dwResult = Win32Errors.E_FAIL; IntPtr WINTRUST_ACTION_GENERIC_VERIFY_V2 = IntPtr.Zero; IntPtr wtdBuffer = IntPtr.Zero; Guid actionVerify = new Guid("00AAC56B-CD44-11d0-8CC2-00C04FC295EE"); try { WINTRUST_ACTION_GENERIC_VERIFY_V2 = Marshal.AllocCoTaskMem(Marshal.SizeOf(actionVerify)); Marshal.StructureToPtr(actionVerify, WINTRUST_ACTION_GENERIC_VERIFY_V2, false); NativeMethods.WINTRUST_DATA wtd; if (fileContent == null) { NativeMethods.WINTRUST_FILE_INFO wfi = NativeMethods.InitWintrustFileInfoStruct(fileName); wtd = NativeMethods.InitWintrustDataStructFromFile(wfi); } else { NativeMethods.WINTRUST_BLOB_INFO wbi = NativeMethods.InitWintrustBlobInfoStruct(fileName, fileContent); wtd = NativeMethods.InitWintrustDataStructFromBlob(wbi); } wtdBuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(wtd)); Marshal.StructureToPtr(wtd, wtdBuffer, false); // The result is returned to the caller, and handled generically. // Disable the PreFast check for Win32 error codes, as we don't care. #pragma warning disable 56523 dwResult = NativeMethods.WinVerifyTrust( IntPtr.Zero, WINTRUST_ACTION_GENERIC_VERIFY_V2, wtdBuffer); #pragma warning enable 56523 wtData = ClrFacade.PtrToStructure<NativeMethods.WINTRUST_DATA>(wtdBuffer); } finally { ClrFacade.DestroyStructure<Guid>(WINTRUST_ACTION_GENERIC_VERIFY_V2); Marshal.FreeCoTaskMem(WINTRUST_ACTION_GENERIC_VERIFY_V2); ClrFacade.DestroyStructure<NativeMethods.WINTRUST_DATA>(wtdBuffer); Marshal.FreeCoTaskMem(wtdBuffer); } return dwResult; } [ArchitectureSensitive] private static X509Certificate2 GetCertFromChain(IntPtr pSigner) { X509Certificate2 signerCert = null; // We don't care about the Win32 error code here, so disable // the PreFast complaint that we're not retrieving it. #pragma warning disable 56523 IntPtr pCert = NativeMethods.WTHelperGetProvCertFromChain(pSigner, 0); #pragma warning enable 56523 if (pCert != IntPtr.Zero) { NativeMethods.CRYPT_PROVIDER_CERT provCert = (NativeMethods.CRYPT_PROVIDER_CERT) ClrFacade.PtrToStructure<NativeMethods.CRYPT_PROVIDER_CERT>(pCert); signerCert = new X509Certificate2(provCert.pCert); } return signerCert; } [ArchitectureSensitive] private static Signature GetSignatureFromWintrustData( string filePath, DWORD error, NativeMethods.WINTRUST_DATA wtd) { Signature signature = null; X509Certificate2 signerCert = null; X509Certificate2 timestamperCert = null; s_tracer.WriteLine("GetSignatureFromWintrustData: error: {0}", error); // The GetLastWin32Error of this is checked, but PreSharp doesn't seem to be // able to see that. #pragma warning disable 56523 IntPtr pProvData = NativeMethods.WTHelperProvDataFromStateData(wtd.hWVTStateData); #pragma warning enable 56523 if (pProvData != IntPtr.Zero) { IntPtr pProvSigner = NativeMethods.WTHelperGetProvSignerFromChain(pProvData, 0, 0, 0); if (pProvSigner != IntPtr.Zero) { // // get cert of the signer // signerCert = GetCertFromChain(pProvSigner); if (signerCert != null) { NativeMethods.CRYPT_PROVIDER_SGNR provSigner = (NativeMethods.CRYPT_PROVIDER_SGNR) ClrFacade.PtrToStructure<NativeMethods.CRYPT_PROVIDER_SGNR>(pProvSigner); if (provSigner.csCounterSigners == 1) { // // time stamper cert available // timestamperCert = GetCertFromChain(provSigner.pasCounterSigners); } if (timestamperCert != null) { signature = new Signature(filePath, error, signerCert, timestamperCert); } else { signature = new Signature(filePath, error, signerCert); } signature.SignatureType = SignatureType.Authenticode; } } } Diagnostics.Assert(((error == 0) && (signature != null)) || (error != 0), "GetSignatureFromWintrustData: general crypto failure"); if ((signature == null) && (error != 0)) { signature = new Signature(filePath, error); } return signature; } [ArchitectureSensitive] private static DWORD GetLastWin32Error() { int error = Marshal.GetLastWin32Error(); return SecuritySupport.GetDWORDFromInt(error); } } } #pragma warning restore 56523
/* * DocuSign REST API * * The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. * * OpenAPI spec version: v2.1 * Contact: devcenter@docusign.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter; namespace DocuSign.eSign.Model { /// <summary> /// Provides properties that describe user authorization to a workspace. /// </summary> [DataContract] public partial class WorkspaceUserAuthorization : IEquatable<WorkspaceUserAuthorization>, IValidatableObject { public WorkspaceUserAuthorization() { // Empty Constructor } /// <summary> /// Initializes a new instance of the <see cref="WorkspaceUserAuthorization" /> class. /// </summary> /// <param name="CanDelete">CanDelete.</param> /// <param name="CanMove">CanMove.</param> /// <param name="CanTransact">CanTransact.</param> /// <param name="CanView">CanView.</param> /// <param name="Created">The UTC DateTime when the workspace user authorization was created..</param> /// <param name="CreatedById">CreatedById.</param> /// <param name="ErrorDetails">ErrorDetails.</param> /// <param name="Modified">Modified.</param> /// <param name="ModifiedById">ModifiedById.</param> /// <param name="WorkspaceUserId">WorkspaceUserId.</param> /// <param name="WorkspaceUserInformation">WorkspaceUserInformation.</param> public WorkspaceUserAuthorization(string CanDelete = default(string), string CanMove = default(string), string CanTransact = default(string), string CanView = default(string), string Created = default(string), string CreatedById = default(string), ErrorDetails ErrorDetails = default(ErrorDetails), string Modified = default(string), string ModifiedById = default(string), string WorkspaceUserId = default(string), WorkspaceUser WorkspaceUserInformation = default(WorkspaceUser)) { this.CanDelete = CanDelete; this.CanMove = CanMove; this.CanTransact = CanTransact; this.CanView = CanView; this.Created = Created; this.CreatedById = CreatedById; this.ErrorDetails = ErrorDetails; this.Modified = Modified; this.ModifiedById = ModifiedById; this.WorkspaceUserId = WorkspaceUserId; this.WorkspaceUserInformation = WorkspaceUserInformation; } /// <summary> /// Gets or Sets CanDelete /// </summary> [DataMember(Name="canDelete", EmitDefaultValue=false)] public string CanDelete { get; set; } /// <summary> /// Gets or Sets CanMove /// </summary> [DataMember(Name="canMove", EmitDefaultValue=false)] public string CanMove { get; set; } /// <summary> /// Gets or Sets CanTransact /// </summary> [DataMember(Name="canTransact", EmitDefaultValue=false)] public string CanTransact { get; set; } /// <summary> /// Gets or Sets CanView /// </summary> [DataMember(Name="canView", EmitDefaultValue=false)] public string CanView { get; set; } /// <summary> /// The UTC DateTime when the workspace user authorization was created. /// </summary> /// <value>The UTC DateTime when the workspace user authorization was created.</value> [DataMember(Name="created", EmitDefaultValue=false)] public string Created { get; set; } /// <summary> /// Gets or Sets CreatedById /// </summary> [DataMember(Name="createdById", EmitDefaultValue=false)] public string CreatedById { get; set; } /// <summary> /// Gets or Sets ErrorDetails /// </summary> [DataMember(Name="errorDetails", EmitDefaultValue=false)] public ErrorDetails ErrorDetails { get; set; } /// <summary> /// Gets or Sets Modified /// </summary> [DataMember(Name="modified", EmitDefaultValue=false)] public string Modified { get; set; } /// <summary> /// Gets or Sets ModifiedById /// </summary> [DataMember(Name="modifiedById", EmitDefaultValue=false)] public string ModifiedById { get; set; } /// <summary> /// Gets or Sets WorkspaceUserId /// </summary> [DataMember(Name="workspaceUserId", EmitDefaultValue=false)] public string WorkspaceUserId { get; set; } /// <summary> /// Gets or Sets WorkspaceUserInformation /// </summary> [DataMember(Name="workspaceUserInformation", EmitDefaultValue=false)] public WorkspaceUser WorkspaceUserInformation { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class WorkspaceUserAuthorization {\n"); sb.Append(" CanDelete: ").Append(CanDelete).Append("\n"); sb.Append(" CanMove: ").Append(CanMove).Append("\n"); sb.Append(" CanTransact: ").Append(CanTransact).Append("\n"); sb.Append(" CanView: ").Append(CanView).Append("\n"); sb.Append(" Created: ").Append(Created).Append("\n"); sb.Append(" CreatedById: ").Append(CreatedById).Append("\n"); sb.Append(" ErrorDetails: ").Append(ErrorDetails).Append("\n"); sb.Append(" Modified: ").Append(Modified).Append("\n"); sb.Append(" ModifiedById: ").Append(ModifiedById).Append("\n"); sb.Append(" WorkspaceUserId: ").Append(WorkspaceUserId).Append("\n"); sb.Append(" WorkspaceUserInformation: ").Append(WorkspaceUserInformation).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as WorkspaceUserAuthorization); } /// <summary> /// Returns true if WorkspaceUserAuthorization instances are equal /// </summary> /// <param name="other">Instance of WorkspaceUserAuthorization to be compared</param> /// <returns>Boolean</returns> public bool Equals(WorkspaceUserAuthorization other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.CanDelete == other.CanDelete || this.CanDelete != null && this.CanDelete.Equals(other.CanDelete) ) && ( this.CanMove == other.CanMove || this.CanMove != null && this.CanMove.Equals(other.CanMove) ) && ( this.CanTransact == other.CanTransact || this.CanTransact != null && this.CanTransact.Equals(other.CanTransact) ) && ( this.CanView == other.CanView || this.CanView != null && this.CanView.Equals(other.CanView) ) && ( this.Created == other.Created || this.Created != null && this.Created.Equals(other.Created) ) && ( this.CreatedById == other.CreatedById || this.CreatedById != null && this.CreatedById.Equals(other.CreatedById) ) && ( this.ErrorDetails == other.ErrorDetails || this.ErrorDetails != null && this.ErrorDetails.Equals(other.ErrorDetails) ) && ( this.Modified == other.Modified || this.Modified != null && this.Modified.Equals(other.Modified) ) && ( this.ModifiedById == other.ModifiedById || this.ModifiedById != null && this.ModifiedById.Equals(other.ModifiedById) ) && ( this.WorkspaceUserId == other.WorkspaceUserId || this.WorkspaceUserId != null && this.WorkspaceUserId.Equals(other.WorkspaceUserId) ) && ( this.WorkspaceUserInformation == other.WorkspaceUserInformation || this.WorkspaceUserInformation != null && this.WorkspaceUserInformation.Equals(other.WorkspaceUserInformation) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.CanDelete != null) hash = hash * 59 + this.CanDelete.GetHashCode(); if (this.CanMove != null) hash = hash * 59 + this.CanMove.GetHashCode(); if (this.CanTransact != null) hash = hash * 59 + this.CanTransact.GetHashCode(); if (this.CanView != null) hash = hash * 59 + this.CanView.GetHashCode(); if (this.Created != null) hash = hash * 59 + this.Created.GetHashCode(); if (this.CreatedById != null) hash = hash * 59 + this.CreatedById.GetHashCode(); if (this.ErrorDetails != null) hash = hash * 59 + this.ErrorDetails.GetHashCode(); if (this.Modified != null) hash = hash * 59 + this.Modified.GetHashCode(); if (this.ModifiedById != null) hash = hash * 59 + this.ModifiedById.GetHashCode(); if (this.WorkspaceUserId != null) hash = hash * 59 + this.WorkspaceUserId.GetHashCode(); if (this.WorkspaceUserInformation != null) hash = hash * 59 + this.WorkspaceUserInformation.GetHashCode(); return hash; } } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
#region Copyright notice and license // Copyright 2015 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Diagnostics; using System.IO; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Grpc.Core.Internal; using Grpc.Core.Logging; using Grpc.Core.Profiling; using Grpc.Core.Utils; namespace Grpc.Core.Internal { /// <summary> /// Base for handling both client side and server side calls. /// Manages native call lifecycle and provides convenience methods. /// </summary> internal abstract class AsyncCallBase<TWrite, TRead> : IReceivedMessageCallback, ISendCompletionCallback { static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCallBase<TWrite, TRead>>(); protected static readonly Status DeserializeResponseFailureStatus = new Status(StatusCode.Internal, "Failed to deserialize response message."); readonly Action<TWrite, SerializationContext> serializer; readonly Func<DeserializationContext, TRead> deserializer; protected readonly object myLock = new object(); protected INativeCall call; protected bool disposed; protected bool started; protected bool cancelRequested; protected TaskCompletionSource<TRead> streamingReadTcs; // Completion of a pending streaming read if not null. protected TaskCompletionSource<object> streamingWriteTcs; // Completion of a pending streaming write or send close from client if not null. protected TaskCompletionSource<object> sendStatusFromServerTcs; protected bool isStreamingWriteCompletionDelayed; // Only used for the client side. protected bool readingDone; // True if last read (i.e. read with null payload) was already received. protected bool halfcloseRequested; // True if send close have been initiated. protected bool finished; // True if close has been received from the peer. protected bool initialMetadataSent; protected long streamingWritesCounter; // Number of streaming send operations started so far. public AsyncCallBase(Action<TWrite, SerializationContext> serializer, Func<DeserializationContext, TRead> deserializer) { this.serializer = GrpcPreconditions.CheckNotNull(serializer); this.deserializer = GrpcPreconditions.CheckNotNull(deserializer); } /// <summary> /// Requests cancelling the call. /// </summary> public void Cancel() { lock (myLock) { GrpcPreconditions.CheckState(started); cancelRequested = true; if (!disposed) { call.Cancel(); } } } /// <summary> /// Requests cancelling the call with given status. /// </summary> protected void CancelWithStatus(Status status) { lock (myLock) { cancelRequested = true; if (!disposed) { call.CancelWithStatus(status); } } } protected void InitializeInternal(INativeCall call) { lock (myLock) { this.call = call; } } /// <summary> /// Initiates sending a message. Only one send operation can be active at a time. /// </summary> protected Task SendMessageInternalAsync(TWrite msg, WriteFlags writeFlags) { byte[] payload = UnsafeSerialize(msg); lock (myLock) { GrpcPreconditions.CheckState(started); var earlyResult = CheckSendAllowedOrEarlyResult(); if (earlyResult != null) { return earlyResult; } call.StartSendMessage(SendCompletionCallback, payload, writeFlags, !initialMetadataSent); initialMetadataSent = true; streamingWritesCounter++; streamingWriteTcs = new TaskCompletionSource<object>(); return streamingWriteTcs.Task; } } /// <summary> /// Initiates reading a message. Only one read operation can be active at a time. /// </summary> protected Task<TRead> ReadMessageInternalAsync() { lock (myLock) { GrpcPreconditions.CheckState(started); if (readingDone) { // the last read that returns null or throws an exception is idempotent // and maintains its state. GrpcPreconditions.CheckState(streamingReadTcs != null, "Call does not support streaming reads."); return streamingReadTcs.Task; } GrpcPreconditions.CheckState(streamingReadTcs == null, "Only one read can be pending at a time"); GrpcPreconditions.CheckState(!disposed); call.StartReceiveMessage(ReceivedMessageCallback); streamingReadTcs = new TaskCompletionSource<TRead>(); return streamingReadTcs.Task; } } /// <summary> /// If there are no more pending actions and no new actions can be started, releases /// the underlying native resources. /// </summary> protected bool ReleaseResourcesIfPossible() { if (!disposed && call != null) { bool noMoreSendCompletions = streamingWriteTcs == null && (halfcloseRequested || cancelRequested || finished); if (noMoreSendCompletions && readingDone && finished) { ReleaseResources(); return true; } } return false; } protected abstract bool IsClient { get; } /// <summary> /// Returns an exception to throw for a failed send operation. /// It is only allowed to call this method for a call that has already finished. /// </summary> protected abstract Exception GetRpcExceptionClientOnly(); protected void ReleaseResources() { if (call != null) { call.Dispose(); } disposed = true; OnAfterReleaseResourcesLocked(); } protected virtual void OnAfterReleaseResourcesLocked() { } protected virtual void OnAfterReleaseResourcesUnlocked() { } /// <summary> /// Checks if sending is allowed and possibly returns a Task that allows short-circuiting the send /// logic by directly returning the write operation result task. Normally, null is returned. /// </summary> protected abstract Task CheckSendAllowedOrEarlyResult(); protected byte[] UnsafeSerialize(TWrite msg) { DefaultSerializationContext context = null; try { context = DefaultSerializationContext.GetInitializedThreadLocal(); serializer(msg, context); return context.GetPayload(); } finally { context?.Reset(); } } protected Exception TryDeserialize(byte[] payload, out TRead msg) { DefaultDeserializationContext context = null; try { context = DefaultDeserializationContext.GetInitializedThreadLocal(payload); msg = deserializer(context); return null; } catch (Exception e) { msg = default(TRead); return e; } finally { context?.Reset(); } } /// <summary> /// Handles send completion (including SendCloseFromClient). /// </summary> protected void HandleSendFinished(bool success) { bool delayCompletion = false; TaskCompletionSource<object> origTcs = null; bool releasedResources; lock (myLock) { if (!success && !finished && IsClient) { // We should be setting this only once per call, following writes will be short circuited // because they cannot start until the entire call finishes. GrpcPreconditions.CheckState(!isStreamingWriteCompletionDelayed); // leave streamingWriteTcs set, it will be completed once call finished. isStreamingWriteCompletionDelayed = true; delayCompletion = true; } else { origTcs = streamingWriteTcs; streamingWriteTcs = null; } releasedResources = ReleaseResourcesIfPossible(); } if (releasedResources) { OnAfterReleaseResourcesUnlocked(); } if (!success) { if (!delayCompletion) { if (IsClient) { GrpcPreconditions.CheckState(finished); // implied by !success && !delayCompletion && IsClient origTcs.SetException(GetRpcExceptionClientOnly()); } else { origTcs.SetException (new IOException("Error sending from server.")); } } // if delayCompletion == true, postpone SetException until call finishes. } else { origTcs.SetResult(null); } } /// <summary> /// Handles send status from server completion. /// </summary> protected void HandleSendStatusFromServerFinished(bool success) { bool releasedResources; lock (myLock) { releasedResources = ReleaseResourcesIfPossible(); } if (releasedResources) { OnAfterReleaseResourcesUnlocked(); } if (!success) { sendStatusFromServerTcs.SetException(new IOException("Error sending status from server.")); } else { sendStatusFromServerTcs.SetResult(null); } } /// <summary> /// Handles streaming read completion. /// </summary> protected void HandleReadFinished(bool success, byte[] receivedMessage) { // if success == false, received message will be null. It that case we will // treat this completion as the last read an rely on C core to handle the failed // read (e.g. deliver approriate statusCode on the clientside). TRead msg = default(TRead); var deserializeException = (success && receivedMessage != null) ? TryDeserialize(receivedMessage, out msg) : null; TaskCompletionSource<TRead> origTcs = null; bool releasedResources; lock (myLock) { origTcs = streamingReadTcs; if (receivedMessage == null) { // This was the last read. readingDone = true; } if (deserializeException != null && IsClient) { readingDone = true; // TODO(jtattermusch): it might be too late to set the status CancelWithStatus(DeserializeResponseFailureStatus); } if (!readingDone) { streamingReadTcs = null; } releasedResources = ReleaseResourcesIfPossible(); } if (releasedResources) { OnAfterReleaseResourcesUnlocked(); } if (deserializeException != null && !IsClient) { origTcs.SetException(new IOException("Failed to deserialize request message.", deserializeException)); return; } origTcs.SetResult(msg); } protected ISendCompletionCallback SendCompletionCallback => this; void ISendCompletionCallback.OnSendCompletion(bool success) { HandleSendFinished(success); } IReceivedMessageCallback ReceivedMessageCallback => this; void IReceivedMessageCallback.OnReceivedMessage(bool success, byte[] receivedMessage) { HandleReadFinished(success, receivedMessage); } } }
// <copyright file=Circle.cs // <copyright> // Copyright (c) 2016, University of Stuttgart // 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> // <license>MIT License</license> // <main contributors> // Markus Funk, Thomas Kosch, Sven Mayer // </main contributors> // <co-contributors> // Paul Brombosch, Mai El-Komy, Juana Heusler, // Matthias Hoppe, Robert Konrad, Alexander Martin // </co-contributors> // <patent information> // We are aware that this software implements patterns and ideas, // which might be protected by patents in your country. // Example patents in Germany are: // Patent reference number: DE 103 20 557.8 // Patent reference number: DE 10 2013 220 107.9 // Please make sure when using this software not to violate any existing patents in your country. // </patent information> // <date> 11/2/2016 12:25:57 PM</date> using HciLab.Utilities.Mathematics.Core; using System; using System.ComponentModel; using System.Runtime.Serialization; using System.Text.RegularExpressions; namespace HciLab.Utilities.Mathematics.Geometry2D { /// <summary> /// Represents a circle in 2D space. /// </summary> [Serializable] [TypeConverter(typeof(CircleConverter))] public struct Circle : ICloneable, ISerializable { private Vector2 center; private double radius; #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Circle"/> class using center and radius values. /// </summary> /// <param name="center">The circle's center point.</param> /// <param name="radius">The circle's radius.</param> public Circle(Vector2 center, double radius) { this.center = center; this.radius = radius; } /// <summary> /// Initializes a new instance of the <see cref="Circle"/> class using values from another circle instance. /// </summary> /// <param name="circle">A <see cref="Circle"/> instance to take values from.</param> public Circle(Circle circle) { this.center = circle.center; this.radius = circle.radius; } /// <summary> /// Initializes a new instance of the <see cref="Vector2"/> class with serialized data. /// </summary> /// <param name="info">The object that holds the serialized object data.</param> /// <param name="context">The contextual information about the source or destination.</param> private Circle(SerializationInfo info, StreamingContext context) { this.center = (Vector2)info.GetValue("Center", typeof(Vector2)); this.radius = info.GetSingle("Radius"); } #endregion #region Constants /// <summary> /// Unit sphere. /// </summary> public static readonly Circle UnitCircle = new Circle(new Vector2(0.0f,0.0f), 1.0f); #endregion #region Public Properties /// <summary> /// The circle's center. /// </summary> public Vector2 Center { get { return this.center; } set { this.center = value; } } /// <summary> /// The circle's radius. /// </summary> public double Radius { get { return this.radius; } set { this.radius = value; } } #endregion #region ISerializable Members /// <summary> /// Populates a <see cref="SerializationInfo"/> with the data needed to serialize the target object. /// </summary> /// <param name="info">The <see cref="SerializationInfo"/> to populate with data. </param> /// <param name="context">The destination (see <see cref="StreamingContext"/>) for this serialization.</param> //[SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter=true)] public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Center", this.center, typeof(Vector2)); info.AddValue("Radius", this.radius); } #endregion #region ICloneable Members /// <summary> /// Creates a new object that is a copy of the current instance. /// </summary> /// <returns>A new object that is a copy of this instance.</returns> object ICloneable.Clone() { return new Circle(this); } /// <summary> /// Creates a new object that is a copy of the current instance. /// </summary> /// <returns>A new object that is a copy of this instance.</returns> public Circle Clone() { return new Circle(this); } #endregion #region Public Static Parse Methods /// <summary> /// Converts the specified string to its <see cref="Circle"/> equivalent. /// </summary> /// <param name="s">A string representation of a <see cref="Circle"/></param> /// <returns>A <see cref="Circle"/> that represents the vector specified by the <paramref name="s"/> parameter.</returns> public static Circle Parse(string s) { Regex r = new Regex(@"Circle\(Center=(?<center>\([^\)]*\)), Radius=(?<radius>.*)\)", RegexOptions.None); Match m = r.Match(s); if (m.Success) { return new Circle( Vector2.Parse(m.Result("${center}")), double.Parse(m.Result("${radius}")) ); } else { throw new ParseException("Unsuccessful Match."); } } #endregion #region Overrides /// <summary> /// Get the hashcode for this vector instance. /// </summary> /// <returns>Returns the hash code for this vector instance.</returns> public override int GetHashCode() { return this.center.GetHashCode() ^ this.radius.GetHashCode(); } /// <summary> /// Checks if a given <see cref="Circle"/> equals to self. /// </summary> /// <param name="o">Object to check if equal to.</param> /// <returns></returns> public override bool Equals(object o) { if( o is Circle ) { Circle c = (Circle) o; return (this.center == c.Center) && (this.radius == c.radius); } return false; } /// <summary> /// Convert <see cref="Circle"/> to a string. /// </summary> /// <returns></returns> public override string ToString() { return string.Format( "Circle(Center={0}, Radius={1})", this.center, this.radius); } #endregion #region Operators /// <summary> /// Checks if the two given circles are equal. /// </summary> /// <param name="a">The first of two 2D circles to compare.</param> /// <param name="b">The second of two 2D circles to compare.</param> /// <returns><b>true</b> if the circles are equal; otherwise, <b>false</b>.</returns> public static bool operator==(Circle a, Circle b) { return ValueType.Equals(a,b); } /// <summary> /// Checks if the two given circles are not equal. /// </summary> /// <param name="a">The first of two 2D circles to compare.</param> /// <param name="b">The second of two 2D circles to compare.</param> /// <returns><b>true</b> if the circles are not equal; otherwise, <b>false</b>.</returns> public static bool operator!=(Circle a, Circle b) { return !ValueType.Equals(a,b); } #endregion /// <summary> /// Tests if a ray intersects the sphere. /// </summary> /// <param name="ray">The ray to test.</param> /// <returns>Returns True if the ray intersects the sphere. otherwise, <see langword="false"/>.</returns> public bool TestIntersection(Ray ray) { double squaredDistance = DistanceMethods.SquaredDistance(this.center, ray); return (squaredDistance <= this.radius*this.radius); } /// <summary> /// Find the intersection of a ray and a sphere. /// Only works with unit rays (normalized direction)!!! /// </summary> /// <remarks> /// This is the optimized Ray-Sphere intersection algorithms described in "Real-Time Rendering". /// </remarks> /// <param name="ray">The ray to test.</param> /// <param name="t"> /// If intersection accurs, the function outputs the distance from the ray's origin /// to the closest intersection point to this parameter. /// </param> /// <returns>Returns True if the ray intersects the sphere. otherwise, <see langword="false"/>.</returns> public bool FindIntersections(Ray ray, ref double t) { // Only gives correct result for unit rays. //Debug.Assert(MathUtils.ApproxEquals(1.0f, ray.Direction.GetLength()), "Ray direction should be normalized!"); // Calculates a vector from the ray origin to the sphere center. Vector2 diff = this.center - ray.Origin; // Compute the projection of diff onto the ray direction double d = Vector2.DotProduct(diff, ray.Direction); double diffSquared = diff.GetLengthSquared(); double radiusSquared = this.radius * this.radius; // First rejection test : // if d<0 and the ray origin is outside the sphere than the sphere is behind the ray if ((d < 0.0f) && (diffSquared > radiusSquared)) { return false; } // Compute the distance from the sphere center to the projection double mSquared = diffSquared - d*d; // Second rejection test: // if mSquared > radiusSquared than the ray misses the sphere if (mSquared > radiusSquared) { return false; } double q = (double)System.Math.Sqrt(radiusSquared - mSquared); // We are interested only in the first intersection point: if (diffSquared > radiusSquared) { // If the origin is outside the sphere t = d - q is the first intersection point t = d - q; } else { // If the origin is inside the sphere t = d + q is the first intersection point t = d + q; } return true; } } #region CircleConverter class /// <summary> /// Converts a <see cref="Circle"/> to and from string representation. /// </summary> public class CircleConverter : ExpandableObjectConverter { /// <summary> /// Returns whether this converter can convert an object of the given type to the type of this converter, using the specified context. /// </summary> /// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param> /// <param name="sourceType">A <see cref="Type"/> that represents the type you want to convert from.</param> /// <returns><b>true</b> if this converter can perform the conversion; otherwise, <b>false</b>.</returns> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) return true; return base.CanConvertFrom (context, sourceType); } /// <summary> /// Returns whether this converter can convert the object to the specified type, using the specified context. /// </summary> /// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param> /// <param name="destinationType">A <see cref="Type"/> that represents the type you want to convert to.</param> /// <returns><b>true</b> if this converter can perform the conversion; otherwise, <b>false</b>.</returns> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(string)) return true; return base.CanConvertTo (context, destinationType); } /// <summary> /// Converts the given value object to the specified type, using the specified context and culture information. /// </summary> /// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param> /// <param name="culture">A <see cref="System.Globalization.CultureInfo"/> object. If a null reference (Nothing in Visual Basic) is passed, the current culture is assumed.</param> /// <param name="value">The <see cref="Object"/> to convert.</param> /// <param name="destinationType">The Type to convert the <paramref name="value"/> parameter to.</param> /// <returns>An <see cref="Object"/> that represents the converted value.</returns> public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if ((destinationType == typeof(string)) && (value is Circle)) { Circle c = (Circle)value; return c.ToString(); } return base.ConvertTo (context, culture, value, destinationType); } /// <summary> /// Converts the given object to the type of this converter, using the specified context and culture information. /// </summary> /// <param name="context">An <see cref="ITypeDescriptorContext"/> that provides a format context.</param> /// <param name="culture">The <see cref="System.Globalization.CultureInfo"/> to use as the current culture. </param> /// <param name="value">The <see cref="Object"/> to convert.</param> /// <returns>An <see cref="Object"/> that represents the converted value.</returns> /// <exception cref="ParseException">Failed parsing from string.</exception> public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { if (value.GetType() == typeof(string)) { return Circle.Parse((string)value); } return base.ConvertFrom (context, culture, value); } } #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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeFixes.RemoveUnusedUsings; using Microsoft.CodeAnalysis.CSharp.Diagnostics.RemoveUnnecessaryImports; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.RemoveUnnecessaryUsings { public partial class RemoveUnnecessaryUsingsTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override Tuple<DiagnosticAnalyzer, CodeFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, CodeFixProvider>( new CSharpRemoveUnnecessaryImportsDiagnosticAnalyzer(), new RemoveUnnecessaryUsingsCodeFixProvider()); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestNoReferences() { await TestAsync( @"[|using System ; using System . Collections . Generic ; using System . Linq ; class Program { static void Main ( string [ ] args ) { } } |]", @"class Program { static void Main ( string [ ] args ) { } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestIdentifierReferenceInTypeContext() { await TestAsync( @"[|using System ; using System . Collections . Generic ; using System . Linq ; class Program { static void Main ( string [ ] args ) { DateTime d ; } } |]", @"using System ; class Program { static void Main ( string [ ] args ) { DateTime d ; } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestGenericReferenceInTypeContext() { await TestAsync( @"[|using System ; using System . Collections . Generic ; using System . Linq ; class Program { static void Main ( string [ ] args ) { List < int > list ; } } |]", @"using System . Collections . Generic ; class Program { static void Main ( string [ ] args ) { List < int > list ; } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestMultipleReferences() { await TestAsync( @"[|using System ; using System . Collections . Generic ; using System . Linq ; class Program { static void Main ( string [ ] args ) { List < int > list ; DateTime d ; } } |]", @"using System ; using System . Collections . Generic ; class Program { static void Main ( string [ ] args ) { List < int > list ; DateTime d ; } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestExtensionMethodReference() { await TestAsync( @"[|using System ; using System . Collections . Generic ; using System . Linq ; class Program { static void Main ( string [ ] args ) { args . Where ( a => a . Length > 10 ) ; } } |]", @"using System . Linq ; class Program { static void Main ( string [ ] args ) { args . Where ( a => a . Length > 10 ) ; } } "); } [WorkItem(541827)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestExtensionMethodLinq() { // NOTE: Intentionally not running this test with Script options, because in Script, // NOTE: class "Foo" is placed inside the script class, and can't be seen by the extension // NOTE: method Select, which is not inside the script class. await TestMissingAsync( @"[|using System; using System.Collections; using SomeNS; class Program { static void Main() { Foo qq = new Foo(); IEnumerable x = from q in qq select q; } } public class Foo { public Foo() { } } namespace SomeNS { public static class SomeClass { public static IEnumerable Select(this Foo o, Func<object, object> f) { return null; } } }|]"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestAliasQualifiedAliasReference() { await TestAsync( @"[|using System ; using G = System . Collections . Generic ; using System . Linq ; class Program { static void Main ( string [ ] args ) { G :: List < int > list ; } } |]", @"using G = System . Collections . Generic ; class Program { static void Main ( string [ ] args ) { G :: List < int > list ; } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestQualifiedAliasReference() { await TestAsync( @"[|using System ; using G = System . Collections . Generic ; class Program { static void Main ( string [ ] args ) { G . List < int > list ; } } |]", @"using G = System . Collections . Generic ; class Program { static void Main ( string [ ] args ) { G . List < int > list ; } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestNestedUnusedUsings() { await TestAsync( @"[|using System ; using System . Collections . Generic ; using System . Linq ; namespace N { using System ; class Program { static void Main ( string [ ] args ) { DateTime d ; } } } |]", @"namespace N { using System ; class Program { static void Main ( string [ ] args ) { DateTime d ; } } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestNestedUsedUsings() { await TestAsync( @"[|using System ; using System . Collections . Generic ; using System . Linq ; namespace N { using System ; class Program { static void Main ( string [ ] args ) { DateTime d ; } } } class F { DateTime d ; } |]", @"using System ; namespace N { using System ; class Program { static void Main ( string [ ] args ) { DateTime d ; } } } class F { DateTime d ; } "); } [WorkItem(712656)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestNestedUsedUsings2() { await TestAsync( @"using System ; using System . Collections . Generic ; using System . Linq ; namespace N { [|using System ;|] using System . Collections . Generic ; class Program { static void Main ( string [ ] args ) { DateTime d ; } } } class F { DateTime d ; } ", @"using System ; namespace N { using System ; class Program { static void Main ( string [ ] args ) { DateTime d ; } } } class F { DateTime d ; } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestAttribute() { await TestMissingAsync( @"[|using SomeNamespace ; [ SomeAttr ] class Foo { } namespace SomeNamespace { public class SomeAttrAttribute : System . Attribute { } } |]"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestAttributeArgument() { await TestMissingAsync( @"[|using foo ; [ SomeAttribute ( typeof ( SomeClass ) ) ] class Program { static void Main ( ) { } } public class SomeAttribute : System . Attribute { public SomeAttribute ( object f ) { } } namespace foo { public class SomeClass { } } |]"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestRemoveAllWithSurroundingPreprocessor() { await TestAsync( @"#if true [|using System; using System.Collections.Generic; #endif class Program { static void Main(string[] args) { } }|]", @"#if true #endif class Program { static void Main(string[] args) { } }", compareTokens: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestRemoveFirstWithSurroundingPreprocessor() { await TestAsync( @"#if true [|using System; using System.Collections.Generic; #endif class Program { static void Main(string[] args) { List<int> list; } }|]", @"#if true using System.Collections.Generic; #endif class Program { static void Main(string[] args) { List<int> list; } }", compareTokens: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestRemoveAllWithSurroundingPreprocessor2() { await TestAsync( @"[|namespace N { #if true using System; using System.Collections.Generic; #endif class Program { static void Main(string[] args) { } } }|]", @"namespace N { #if true #endif class Program { static void Main(string[] args) { } } }", compareTokens: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestRemoveOneWithSurroundingPreprocessor2() { await TestAsync( @"[|namespace N { #if true using System; using System.Collections.Generic; #endif class Program { static void Main(string[] args) { List<int> list; } } }|]", @"namespace N { #if true using System.Collections.Generic; #endif class Program { static void Main(string[] args) { List<int> list; } } }", compareTokens: false); } [WorkItem(541817)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestComments8718() { await TestAsync( @"[|using Foo; using System.Collections.Generic; /*comment*/ using Foo2; class Program { static void Main(string[] args) { Bar q; Bar2 qq; } } namespace Foo { public class Bar { } } namespace Foo2 { public class Bar2 { } }|]", @"using Foo; using Foo2; class Program { static void Main(string[] args) { Bar q; Bar2 qq; } } namespace Foo { public class Bar { } } namespace Foo2 { public class Bar2 { } }", compareTokens: false); } [WorkItem(528609)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestComments() { await TestAsync( @"//c1 /*c2*/ [|using/*c3*/ System/*c4*/; //c5 //c6 class Program { } |]", @"//c1 /*c2*/ //c6 class Program { } ", compareTokens: false); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestUnusedUsing() { await TestAsync( @"[|using System.Collections.Generic; class Program { static void Main() { } }|]", @"class Program { static void Main() { } }", compareTokens: false); } [WorkItem(541827)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestSimpleQuery() { await TestAsync( @"[|using System ; using System . Collections . Generic ; using System . Linq ; class Program { static void Main ( string [ ] args ) { var q = from a in args where a . Length > 21 select a ; } } |]", @"using System . Linq ; class Program { static void Main ( string [ ] args ) { var q = from a in args where a . Length > 21 select a ; } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestUsingStaticClassAccessField1() { await TestAsync( @"[|using SomeNS . Foo ; class Program { static void Main ( ) { var q = x ; } } namespace SomeNS { static class Foo { public static int x ; } } |]", @"class Program { static void Main ( ) { var q = x ; } } namespace SomeNS { static class Foo { public static int x ; } } ", CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5)); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestUsingStaticClassAccessField2() { await TestMissingAsync( @"[|using static SomeNS . Foo ; class Program { static void Main ( ) { var q = x ; } } namespace SomeNS { static class Foo { public static int x ; } } |]"); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestUsingStaticClassAccessMethod1() { await TestAsync( @"[|using SomeNS . Foo ; class Program { static void Main ( ) { var q = X ( ) ; } } namespace SomeNS { static class Foo { public static int X ( ) { return 42 ; } } } |]", @"[|class Program { static void Main ( ) { var q = X ( ) ; } } namespace SomeNS { static class Foo { public static int X ( ) { return 42 ; } } } |]", CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5)); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestUsingStaticClassAccessMethod2() { await TestMissingAsync( @"[|using static SomeNS . Foo ; class Program { static void Main ( ) { var q = X ( ) ; } } namespace SomeNS { static class Foo { public static int X ( ) { return 42 ; } } } |]"); } [WorkItem(8846, "DevDiv_Projects/Roslyn")] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestUnusedTypeImportIsRemoved() { await TestAsync( @"[|using SomeNS.Foo; class Program { static void Main() { } } namespace SomeNS { static class Foo { } }|]", @" class Program { static void Main() { } } namespace SomeNS { static class Foo { } }"); } [WorkItem(541817)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestRemoveTrailingComment() { await TestAsync( @"[|using System.Collections.Generic; // comment class Program { static void Main(string[] args) { } } |]", @"class Program { static void Main(string[] args) { } } ", compareTokens: false); } [WorkItem(541914)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestRemovingUnbindableUsing() { await TestAsync( @"[|using gibberish ; public static class Program { } |]", @"public static class Program { } "); } [WorkItem(541937)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestAliasInUse() { await TestMissingAsync( @"[|using GIBBERISH = Foo.Bar; class Program { static void Main(string[] args) { GIBBERISH x; } } namespace Foo { public class Bar { } }|]"); } [WorkItem(541914)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestRemoveUnboundUsing() { await TestAsync( @"[|using gibberish; public static class Program { }|]", @"public static class Program { }"); } [WorkItem(542016)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestLeadingNewlines1() { await TestAsync( @"[|using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { } }|]", @"class Program { static void Main(string[] args) { } }", compareTokens: false); } [WorkItem(542016)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestRemoveLeadingNewLines2() { await TestAsync( @"[|namespace N { using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { } } }|]", @"namespace N { class Program { static void Main(string[] args) { } } }", compareTokens: false); } [WorkItem(542134)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestImportedTypeUsedAsGenericTypeArgument() { await TestMissingAsync( @"[|using GenericThingie; public class GenericType<T> { } namespace GenericThingie { public class Something { } } public class Program { void foo() { GenericType<Something> type; } }|]"); } [WorkItem(542723)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestRemoveCorrectUsing1() { await TestAsync( @"[|using System . Collections . Generic ; namespace Foo { using Bar = Dictionary < string , string > ; } |]", @"using System . Collections . Generic ; namespace Foo { } ", parseOptions: null); } [WorkItem(542723)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestRemoveCorrectUsing2() { await TestMissingAsync( @"[|using System . Collections . Generic ; namespace Foo { using Bar = Dictionary < string , string > ; class C { Bar b; } } |]", parseOptions: null); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestSpan() { await TestSpansAsync( @"[|namespace N { using System; }|]", @"namespace N { [|using System;|] }"); } [WorkItem(543000)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestMissingWhenErrorsWouldBeGenerated() { await TestMissingAsync( @"[|using System ; using X ; using Y ; class B { static void Main ( ) { Bar ( x => x . Foo ( ) ) ; } static void Bar ( Action < int > x ) { } static void Bar ( Action < string > x ) { } } namespace X { public static class A { public static void Foo ( this int x ) { } public static void Foo ( this string x ) { } } } namespace Y { public static class B { public static void Foo ( this int x ) { } } } |]"); } [WorkItem(544976)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestMissingWhenMeaningWouldChangeInLambda() { await TestMissingAsync( @"[|using System; using X; using Y; class B { static void Main() { Bar(x => x.Foo(), null); // Prints 1 } static void Bar(Action<string> x, object y) { Console.WriteLine(1); } static void Bar(Action<int> x, string y) { Console.WriteLine(2); } } namespace X { public static class A { public static void Foo(this int x) { } public static void Foo(this string x) { } } } namespace Y { public static class B { public static void Foo(this int x) { } } }|]"); } [WorkItem(544976)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestCasesWithLambdas1() { // NOTE: Y is used when speculatively binding "x => x.Foo()". As such, it is marked as // used even though it isn't in the final bind, and could be removed. However, as we do // not know if it was necessary to eliminate a speculative lambda bind, we must leave // it. await TestMissingAsync( @"[|using System; using X; using Y; class B { static void Main() { Bar(x => x.Foo(), null); // Prints 1 } static void Bar(Action<string> x, object y) { } } namespace X { public static class A { public static void Foo(this string x) { } } } namespace Y { public static class B { public static void Foo(this int x) { } } }|]"); } [WorkItem(545646)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestCasesWithLambdas2() { await TestMissingAsync( @"[|using System; using N; // Falsely claimed as unnecessary static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, string y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => x.Ex(), y), null); } } namespace N { static class E { public static void Ex(this int x) { } } }|]"); } [WorkItem(545741)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestMissingOnAliasedVar() { await TestMissingAsync( @"[|using var = var ; class var { } class B { static void Main ( ) { var a = 1 ; } }|] "); } [WorkItem(546115)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestBrokenCode() { await TestMissingAsync( @"[|using System.Linq; public class QueryExpressionTest { public static void Main() { var expr1 = new[] { }; var expr2 = new[] { }; var query8 = from int i in expr1 join int fixed in expr2 on i equals fixed select new { i, fixed }; var query9 = from object i in expr1 join object fixed in expr2 on i equals fixed select new { i, fixed }; } }|]"); } [WorkItem(530980)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestReferenceInCref() { // parsing doc comments as simple trivia; System is unnecessary await TestAsync(@"[|using System ; /// <summary><see cref=""String"" /></summary> class C { }|] ", @"/// <summary><see cref=""String"" /></summary> class C { } "); // fully parsing doc comments; System is necessary await TestMissingAsync( @"[|using System ; /// <summary><see cref=""String"" /></summary> class C { }|] ", Options.Regular.WithDocumentationMode(DocumentationMode.Diagnose)); } [WorkItem(751283)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryImports)] public async Task TestUnusedUsingOverLinq() { await TestAsync( @"using System ; [|using System . Linq ; using System . Threading . Tasks ;|] class Program { static void Main ( string [ ] args ) { Console . WriteLine ( ) ; } } ", @"using System ; class Program { static void Main ( string [ ] args ) { Console . WriteLine ( ) ; } } "); } } }
using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.Common; using System.Collections; namespace CsDO.Lib.MockDriver { public class MockDataReader : DbDataReader { #region Private Vars private DataTable[] _data = null; private int[] _row = null; private int _current = 0; private int _recordsAffected = -1; private bool _readerClosed = false; private IDbConnection _connectionToClose = null; #endregion #region Constructors public MockDataReader(DataTable data, int recordsAffected) { DataTable[] param = { data }; SetInternalState(param, recordsAffected); } public MockDataReader(DataSet data, int recordsAffected) { DataTable[] param = new DataTable[data.Tables.Count]; for (int i = 0; i < data.Tables.Count; i++) { DataTable table = data.Tables[i]; param[i] = table; } SetInternalState(param, recordsAffected); } public MockDataReader(DataTable[] data, int recordsAffected) { SetInternalState(data, recordsAffected); } #endregion #region Properties public IDbConnection ConnectionToClose { get { return _connectionToClose; } set { _connectionToClose = value; } } public override int FieldCount { get { return this.Data.Columns.Count; } } public override object this[int ordinal] { get { return GetValue(ordinal); } } public override object this[string name] { get { return GetValue(GetOrdinal(name)); } } public override int Depth { get { return 0; } } public override bool IsClosed { get { return _readerClosed; } } public override int RecordsAffected { get { return _recordsAffected; } } public override bool HasRows { get { return (!(this.Row + 1 > this.Data.Rows.Count - 1)); } } private DataTable Data { get { return _data[_current]; } } private int Row { get { return _row[_current]; } set { _row[_current] = value; } } #endregion #region Public Methods public override bool GetBoolean(int ordinal) { return Convert.ToBoolean(this.Data.Rows[this.Row][ordinal]); } public override byte GetByte(int ordinal) { return Convert.ToByte(this.Data.Rows[this.Row][ordinal]); } public override long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length) { throw new NotImplementedException(); } public override char GetChar(int ordinal) { return Convert.ToChar(this.Data.Rows[this.Row][ordinal]); } public override long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length) { throw new NotImplementedException(); } public override string GetDataTypeName(int ordinal) { return GetFieldType(ordinal).FullName; } public override DateTime GetDateTime(int ordinal) { return Convert.ToDateTime(this.Data.Rows[this.Row][ordinal]); } public override decimal GetDecimal(int ordinal) { return Convert.ToDecimal(this.Data.Rows[this.Row][ordinal]); } public override double GetDouble(int ordinal) { return Convert.ToDouble(this.Data.Rows[this.Row][ordinal]); } public override Type GetFieldType(int ordinal) { return this.Data.Columns[ordinal].DataType; } public override float GetFloat(int ordinal) { return (float)GetDouble(ordinal); } public override Guid GetGuid(int ordinal) { return new Guid(GetString(ordinal)); } public override short GetInt16(int ordinal) { return Convert.ToInt16(this.Data.Rows[this.Row][ordinal]); } public override int GetInt32(int ordinal) { return Convert.ToInt32(this.Data.Rows[this.Row][ordinal]); } public override long GetInt64(int ordinal) { return Convert.ToInt64(this.Data.Rows[this.Row][ordinal]); } public override string GetName(int ordinal) { return this.Data.Columns[ordinal].ColumnName; } public override int GetOrdinal(string name) { return this.Data.Columns[name].Ordinal; } public override string GetString(int ordinal) { return Convert.ToString(this.Data.Rows[this.Row][ordinal]); } public override object GetValue(int ordinal) { return this.Data.Rows[this.Row][ordinal]; } public override int GetValues(object[] values) { object[] rowVals = this.Data.Rows[this.Row].ItemArray; int c = Math.Min(values.Length, rowVals.Length); int i; for (i = 0; i < c; i++) values[i] = rowVals[i]; return i; } public override bool IsDBNull(int ordinal) { return Convert.IsDBNull(this.Data.Rows[this.Row][ordinal]); } public override void Close() { if (null != _connectionToClose) _connectionToClose.Close(); _readerClosed = true; } public override DataTable GetSchemaTable() { return this.Data.Clone(); } public override bool NextResult() { if ((_current + 1) > _data.Length - 1) return false; _current++; return true; } public override bool Read() { if (!this.HasRows) return false; this.Row++; return true; } public override IEnumerator GetEnumerator() { throw new NotImplementedException(); } #endregion #region Private Methods private void SetInternalState(DataTable[] data, int recordsAffected) { _data = new DataTable[data.Length]; _row = new int[data.Length]; _recordsAffected = recordsAffected; for (int i = 0; i < data.Length; ++i) { _data[i] = data[i]; _row[i] = -1; } } #endregion } internal class DataReaderConverter : DbDataAdapter { public int FillFromReader(DataTable data, IDataReader dataReader) { return this.Fill(data, dataReader); } protected override RowUpdatedEventArgs CreateRowUpdatedEvent(DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping) { return null; } protected override RowUpdatingEventArgs CreateRowUpdatingEvent(DataRow dataRow, IDbCommand command, StatementType statementType, DataTableMapping tableMapping) { return null; } protected override void OnRowUpdated(RowUpdatedEventArgs value) { } protected override void OnRowUpdating(RowUpdatingEventArgs value) { } public static void FillDataSetFromReader(DataSet data, IDataReader dataReader) { DataReaderConverter converter = new DataReaderConverter(); do { DataTable table = new DataTable(); converter.FillFromReader(table, dataReader); data.Tables.Add(table); } while (dataReader.NextResult()); } } }
/* * Copyright 2002 Fluent Consulting, Inc. All rights reserved. * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ using System; using System.Data; using System.Collections; using System.Reflection; using System.Text; namespace Inform.Common { /// <summary> /// This type supports the Inform infrastructure and is not intended to be used directly from your code. /// </summary> public abstract class DataStorageManager { private RegisteredMemberMappingCollection registeredMemberTypeMappings; private RelationshipMappingCollection relationshipMappings; private TypeMappingCollection typeMappings; private DataStore dataStore; /// <summary> /// Provides access to a DataStore's DataStorageManager. /// </summary> /// <param name="dataStore"></param> /// <returns></returns> public static DataStorageManager GetDataStorageManager(DataStore dataStore) { return dataStore.DataStorageManager; } /// <summary> /// Gets the TypeMappingCollection. /// </summary> public TypeMappingCollection TypeMappings { get { return typeMappings; } } /// <summary> /// Gets the RelationshipMappingCollection. /// </summary> public RelationshipMappingCollection RelationshipMappings { get { return relationshipMappings; } } /// <summary> /// Gets the DataStore that created this DataStorageManager. /// </summary> protected DataStore ManagedDataStore { get { return dataStore; } } protected DataStorageManager(DataStore dataStore) { this.dataStore = dataStore; this.typeMappings = new TypeMappingCollection(); this.registeredMemberTypeMappings = new RegisteredMemberMappingCollection(); this.relationshipMappings = new RelationshipMappingCollection(); } #region Abstract Methods abstract public bool TableExists(string tableName); abstract public bool ExistsStorage(TypeMapping typeMapping); abstract public string GenerateCreateTableSql(TypeMapping typeMapping); abstract public string GenerateDeleteTableSql(TypeMapping typeMapping); abstract public string GenerateCreateRelationshipSql(RelationshipMapping rm); abstract public string GenerateCreateInsertProcedureSql(TypeMapping typeMapping); abstract public string GenerateCreateUpdateProcedureSql(TypeMapping typeMapping); abstract public string GenerateCreateDeleteProcedureSql(TypeMapping typeMapping); abstract public string GenerateInsertSql(TypeMapping typeMapping); abstract public string GenerateUpdateSql(TypeMapping typeMapping); abstract public string GenerateDeleteSql(TypeMapping typeMapping); abstract public string GenerateDropProcedureSql(string procedureName); abstract public string GenerateFindByPrimaryKeySql(TypeMapping typeMapping); #endregion public void CreateStorage(TypeMapping typeMapping){ if(typeMapping == null){ throw new ArgumentNullException("typeMapping"); } IDataAccessCommand createCommand; RelationshipMapping baseMapping = null; if(typeMapping.BaseType != null){ TypeMapping baseTypeMapping = this.GetTypeMapping(typeMapping.BaseType); TypeMappingState state = CheckMapping(baseTypeMapping); if (state.Condition == TypeMappingState.TypeMappingStateCondition.TableMissing){ CreateStorage(baseTypeMapping); } else if (state.Condition != TypeMappingState.TypeMappingStateCondition.None) { throw new TypeMappingException("TypeMappingState: " + state.Condition.ToString()); } baseMapping = new RelationshipMapping(); baseMapping.Name = string.Format("{0}_{1}",typeMapping.TableName,baseTypeMapping.TableName); baseMapping.ChildType = typeMapping.MappedType; baseMapping.ParentType = baseTypeMapping.MappedType; baseMapping.ChildMember = typeMapping.PrimaryKey.MemberInfo.Name; baseMapping.ParentMember = baseTypeMapping.PrimaryKey.MemberInfo.Name; baseMapping.Type = Relationship.OneToOne; } createCommand = ManagedDataStore.CreateDataAccessCommand( GenerateCreateTableSql(typeMapping), CommandType.Text); createCommand.ExecuteNonQuery(); if(baseMapping != null){ createCommand = ManagedDataStore.CreateDataAccessCommand( GenerateCreateRelationshipSql(baseMapping), CommandType.Text); createCommand.ExecuteNonQuery(); } if(typeMapping.UseStoredProcedures){ CreateInsertProcedure(typeMapping); CreateUpdateProcedure(typeMapping); CreateDeleteProcedure(typeMapping); } foreach(RelationshipMapping rm in RelationshipMappings){ if(rm.ChildType == typeMapping.MappedType){ createCommand = ManagedDataStore.CreateDataAccessCommand( GenerateCreateRelationshipSql(rm), CommandType.Text); createCommand.ExecuteNonQuery(); } } } public void DeleteStorage(TypeMapping typeMapping){ IDataAccessCommand deleteCommand; //delete table deleteCommand = ManagedDataStore.CreateDataAccessCommand(GenerateDeleteTableSql(typeMapping), CommandType.Text); deleteCommand.ExecuteNonQuery(); //delete insert if(typeMapping.UseStoredProcedures){ deleteCommand = ManagedDataStore.CreateDataAccessCommand(GenerateDropProcedureSql(GetInsertProcedureName(typeMapping)), CommandType.Text); deleteCommand.ExecuteNonQuery(); //delete update deleteCommand = ManagedDataStore.CreateDataAccessCommand(GenerateDropProcedureSql(GetUpdateProcedureName(typeMapping)), CommandType.Text); deleteCommand.ExecuteNonQuery(); //delete delete deleteCommand = ManagedDataStore.CreateDataAccessCommand(GenerateDropProcedureSql(GetDeleteProcedureName(typeMapping)), CommandType.Text); deleteCommand.ExecuteNonQuery(); } } public string GetInsertProcedureName(TypeMapping typeMapping){ return typeMapping.TableName + "_Insert"; } public string GetUpdateProcedureName(TypeMapping typeMapping){ return typeMapping.TableName + "_Update"; } public string GetDeleteProcedureName(TypeMapping typeMapping){ return typeMapping.TableName + "_Delete"; } public void CreateInsertProcedure(TypeMapping typeMapping){ IDataAccessCommand createCommand = ManagedDataStore.CreateDataAccessCommand(GenerateCreateInsertProcedureSql(typeMapping), CommandType.Text); createCommand.ExecuteNonQuery(); } public void CreateUpdateProcedure(TypeMapping typeMapping){ if(typeMapping.PrimaryKey != null){ IDataAccessCommand createCommand = ManagedDataStore.CreateDataAccessCommand(GenerateCreateUpdateProcedureSql(typeMapping), CommandType.Text); createCommand.ExecuteNonQuery(); } } public void CreateDeleteProcedure(TypeMapping typeMapping){ if(typeMapping.PrimaryKey != null){ IDataAccessCommand createCommand = ManagedDataStore.CreateDataAccessCommand(GenerateCreateDeleteProcedureSql(typeMapping), CommandType.Text); createCommand.ExecuteNonQuery(); } } public TypeMapping GetTypeMapping(Type type){ TypeMapping typeMapping = (TypeMapping)this.typeMappings[type.FullName]; if(typeMapping == null && this.dataStore.Settings.AutoGenerate){ typeMapping = CreateTypeMappingFromAttributes(type); AddTypeMapping(typeMapping); AddDefaultRelationshipMappings(type); } return typeMapping; } public TypeMapping GetTypeMapping(Type type, bool throwError){ TypeMapping typeMapping = GetTypeMapping(type); if(typeMapping == null && throwError){ throw new ApplicationException("There is no TypeMapping defined for " + type.FullName); } return typeMapping; } public void AddTypeMapping(TypeMapping typeMapping){ this.typeMappings.Add(typeMapping); if(typeMapping.BaseType != null){ this.GetTypeMapping(typeMapping.BaseType).SubClasses.Add(typeMapping.MappedType); } } public IMemberMapping CreateDefaultMemberMapping(MemberInfo memberInfo, MemberMappingAttribute mma){ Type mappedType; if(memberInfo is FieldInfo){ mappedType = ((FieldInfo)memberInfo).FieldType; } else if(memberInfo is PropertyInfo) { mappedType = ((PropertyInfo)memberInfo).PropertyType; } else { throw new DataStoreException("Unsupported MemberType: " + memberInfo.MemberType ); } IMemberMapping mapping = GetPropertyMapping(mappedType); if (mapping == null){ throw new ArgumentException("Could not create MemberMapping for " + mappedType.FullName ); } if(mma.ColumnName != null){ mapping.ColumnName = mma.ColumnName; } else { mapping.ColumnName = memberInfo.Name; } mapping.PrimaryKey = mma.PrimaryKey; mapping.Identity = mma.Identity; mapping.MemberDbType.IsNullable = mma.AllowNulls; mapping.MemberInfo = memberInfo; if(mma.UseDbType){ mapping.MemberDbType.DbType = mma.DbType; } //TODO: Only apply to Decimal? if(mma.UseLength){ mapping.MemberDbType.Length = mma.Length; } if(mma.UsePrecision){ mapping.MemberDbType.Precision = mma.Precision;} if(mma.UseScale){ mapping.MemberDbType.Scale = mma.Scale; } return mapping; } /// <summary> /// Creates a TypeMapping using special attributes to classes and members. /// </summary> /// <param name="type"></param> /// <returns></returns> public TypeMapping CreateTypeMappingFromAttributes(Type type){ TypeMapping typeMapping = new TypeMapping(); typeMapping.UseStoredProcedures = dataStore.Settings.UseStoredProcedures; //Set the type typeMapping.MappedType = type; TypeMappingAttribute[] typeMappingAttributes = (TypeMappingAttribute[])type.GetCustomAttributes(typeof(TypeMappingAttribute),false); TypeMappingAttribute typeMappingAttibute = null; if(typeMappingAttributes.Length > 0){ typeMappingAttibute = typeMappingAttributes[0]; } if(typeMappingAttibute != null && typeMappingAttibute.BaseType != null){ typeMapping.BaseType = typeMappingAttibute.BaseType; } if(typeMappingAttibute != null && typeMappingAttibute.TableName != null){ typeMapping.TableName = typeMappingAttibute.TableName; } else { typeMapping.TableName = CreateDefaultTableName(type); } foreach(MemberInfo memberInfo in type.GetMembers(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)){ if(!((memberInfo is PropertyInfo) || (memberInfo is FieldInfo))){ continue; } MemberMappingAttribute mma = (MemberMappingAttribute)Attribute.GetCustomAttribute(memberInfo, typeof(MemberMappingAttribute), true); if(mma != null && !mma.Ignore){ if(typeMapping.BaseType != null && !mma.PrimaryKey && !MemberIsDeclaredAbove(memberInfo,typeMapping.BaseType)){ continue; } if(mma.PrimaryKey){ if(typeMapping.BaseType != null){ // && MemberIsDeclaredAbove(memberInfo,typeMapping.BaseType) mma.Identity = false; } } IMemberMapping mapping = CreateDefaultMemberMapping(memberInfo, mma); typeMapping.MemberMappings.Add(mapping); } AddDefaultCacheMappings(memberInfo, typeMapping); } AddDefaultRelationshipMappings(type); if(typeMapping.MemberMappings.Count == 0 && typeMapping.BaseType == null){ throw new TypeMappingException(string.Format("TypeMapping has no MemberMappings defined for type '{0}'.", type.FullName)); } return typeMapping; } private void AddDefaultRelationshipMappings(Type type){ RelationshipMappingAttribute[] relationshipMappingAttributes = (RelationshipMappingAttribute[])type.GetCustomAttributes(typeof(RelationshipMappingAttribute),false); foreach(RelationshipMappingAttribute rma in relationshipMappingAttributes){ RelationshipMapping rm = new RelationshipMapping(); rm.Name = rma.Name; if(rma.ParentType != null){ rm.ParentType = rma.ParentType; rm.ChildType = type; } else { rm.ParentType = type; rm.ChildType = rma.ChildType; } rm.ParentMember = rma.ParentMember; rm.ChildMember = rma.ChildMember; rm.Type = rma.Type; //TODO: rename RelationshipType relationshipMappings.Add(rm); } } private void AddDefaultCacheMappings(MemberInfo memberInfo, TypeMapping typeMapping){ RelationshipMappingAttribute rma = (RelationshipMappingAttribute)Attribute.GetCustomAttribute(memberInfo, typeof(RelationshipMappingAttribute),false); if(rma != null){ RelationshipMapping rm = new RelationshipMapping(); rm.Name = rma.Name; if(rma.ParentType != null){ rm.ParentType = rma.ParentType; rm.ChildType = typeMapping.MappedType; } else { rm.ParentType = typeMapping.MappedType; rm.ChildType = rma.ChildType; } rm.ParentMember = rma.ParentMember; rm.ChildMember = rma.ChildMember; rm.Type = rma.Type; relationshipMappings.Add(rm); } CacheMappingAttribute ca = (CacheMappingAttribute)Attribute.GetCustomAttribute(memberInfo, typeof(CacheMappingAttribute), false); if(ca != null){ CacheMapping cm = new CacheMapping(); cm.Relationship = ca.Relationship == null ? rma.Name : ca.Relationship; cm.MemberInfo = memberInfo; cm.DataStore = this.dataStore; cm.OrderBy = ca.OrderBy; typeMapping.CacheMappings.Add(cm); } else if(rma != null){ CacheMapping cm = new CacheMapping(); cm.Relationship = rma.Name; cm.MemberInfo = memberInfo; cm.DataStore = this.dataStore; typeMapping.CacheMappings.Add(cm); } } public RelationshipMapping GetRelationshipMapping(string name){ return (RelationshipMapping)relationshipMappings[name]; } public bool MemberIsDeclaredAbove(MemberInfo memberInfo, Type type){ Type reflectedType = memberInfo.ReflectedType; Type declaringType = memberInfo.DeclaringType; while(reflectedType != null){ if(reflectedType.FullName == type.FullName){ return false; } if(reflectedType.FullName == declaringType.FullName){ return true; } reflectedType = reflectedType.BaseType; } return false; } public IMemberMapping GetPropertyMapping(Type type){ Type memberMappingType = (Type)registeredMemberTypeMappings[type]; //TODO: Review if this is the best method for capturing enums if(type.IsEnum){ memberMappingType = (Type)registeredMemberTypeMappings[typeof(Enum)]; } if(memberMappingType == null){ throw new ApplicationException("DataStore does not contain IMemberMapping for " + type.FullName); } object memberMapping = memberMappingType.GetConstructor(new Type[]{}).Invoke(null); if(memberMapping == null){ throw new ApplicationException("DataStore could not create IMemberMapping for " + type.FullName); } return (IMemberMapping)memberMapping; } public void AddPropertyMappingType(Type type, Type memberMappingType){ registeredMemberTypeMappings.Register(type, memberMappingType); } internal string CreateDefaultTableName(Type type){ if(type.Name.EndsWith("Y")){ return type.Name.Substring(0,type.Name.Length-1) + "IES"; } else if(type.Name.EndsWith("y")) { return type.Name.Substring(0,type.Name.Length-1) + "ies"; } else if(type.Name.EndsWith("S")) { return type.Name + "ES"; } else if(type.Name.EndsWith("s")) { return type.Name + "es"; } else if(char.IsUpper(type.Name,type.Name.Length-1)) { return type.Name + "S"; } else { return type.Name + "s"; } } abstract public TypeMappingState CheckMapping(TypeMapping typeMapping); abstract public string CreateQuery(Type type, string filter, bool polymorphic); public string BuildSubClassColumnList(TypeMapping typeMapping){ StringBuilder columns = new StringBuilder(); bool notFirst = false; foreach(IMemberMapping propertyMapping in typeMapping.MemberMappings){ if(notFirst){ columns.Append(","); } else { notFirst = true; } columns.AppendFormat(" [{0}].[{1}] AS [{0}_{1}]", typeMapping.TableName, propertyMapping.ColumnName); } foreach(Type subClass in typeMapping.SubClasses){ string subClassColumns = BuildSubClassColumnList(GetTypeMapping(subClass)); if(subClassColumns.Length > 0){ columns.Append("," + subClassColumns); } } return columns.ToString(); } public string PolymorphicPrimaryKey(TypeMapping typeMapping){ return string.Format("{0}_{1}", typeMapping.TableName, typeMapping.PrimaryKey.ColumnName); } public string BuildBaseClassColumnList(TypeMapping typeMapping){ if(typeMapping.BaseType != null){ typeMapping = GetTypeMapping(typeMapping.BaseType); StringBuilder columns = new StringBuilder(); bool addComma = true; foreach(IMemberMapping propertyMapping in typeMapping.MemberMappings){ if(addComma){ columns.Append(","); } else { addComma = true; } columns.AppendFormat(" {0}.{1} AS [{0}_{1}]", typeMapping.TableName, propertyMapping.ColumnName); } columns.Append(BuildBaseClassColumnList(typeMapping)); return columns.ToString(); } else { return string.Empty; } } } }
//--------------------------------------------------------------------- // <copyright file="FunctionUpdateCommand.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner [....] // @backupOwner [....] //--------------------------------------------------------------------- namespace System.Data.Mapping.Update.Internal { using System.Collections.Generic; using System.Data.Common; using System.Data.Common.Utils; using System.Data.EntityClient; using System.Data.Metadata.Edm; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Data.Spatial; /// <summary> /// Aggregates information about a modification command delegated to a store function. /// </summary> internal sealed class FunctionUpdateCommand : UpdateCommand { #region Constructors /// <summary> /// Initialize a new function command. Initializes the command object. /// </summary> /// <param name="functionMapping">Function mapping metadata</param> /// <param name="translator">Translator</param> /// <param name="stateEntries">State entries handled by this operation.</param> /// <param name="stateEntry">'Root' state entry being handled by this function.</param> internal FunctionUpdateCommand(StorageModificationFunctionMapping functionMapping, UpdateTranslator translator, System.Collections.ObjectModel.ReadOnlyCollection<IEntityStateEntry> stateEntries, ExtractedStateEntry stateEntry) : base(stateEntry.Original, stateEntry.Current) { EntityUtil.CheckArgumentNull(functionMapping, "functionMapping"); EntityUtil.CheckArgumentNull(translator, "translator"); EntityUtil.CheckArgumentNull(stateEntries, "stateEntries"); // populate the main state entry for error reporting m_stateEntries = stateEntries; // create a command DbCommandDefinition commandDefinition = translator.GenerateCommandDefinition(functionMapping); m_dbCommand = commandDefinition.CreateCommand(); } #endregion #region Fields private readonly System.Collections.ObjectModel.ReadOnlyCollection<IEntityStateEntry> m_stateEntries; /// <summary> /// Gets the store command wrapped by this command. /// </summary> private readonly DbCommand m_dbCommand; /// <summary> /// Gets pairs for column names and propagator results (so that we can associate reader results with /// the source records for server generated values). /// </summary> private List<KeyValuePair<string, PropagatorResult>> m_resultColumns; /// <summary> /// Gets map from identifiers (key component proxies) to parameters holding the actual /// key values. Supports propagation of identifier values (fixup for server-gen keys) /// </summary> private List<KeyValuePair<int, DbParameter>> m_inputIdentifiers; /// <summary> /// Gets map from identifiers (key component proxies) to column names producing the actual /// key values. Supports propagation of identifier values (fixup for server-gen keys) /// </summary> private Dictionary<int, string> m_outputIdentifiers; /// <summary> /// Gets a reference to the rows affected output parameter for the stored procedure. May be null. /// </summary> private DbParameter m_rowsAffectedParameter; #endregion #region Properties internal override IEnumerable<int> InputIdentifiers { get { if (null == m_inputIdentifiers) { yield break; } else { foreach (KeyValuePair<int, DbParameter> inputIdentifier in m_inputIdentifiers) { yield return inputIdentifier.Key; } } } } internal override IEnumerable<int> OutputIdentifiers { get { if (null == m_outputIdentifiers) { return Enumerable.Empty<int>(); } return m_outputIdentifiers.Keys; } } internal override UpdateCommandKind Kind { get { return UpdateCommandKind.Function; } } #endregion #region Methods /// <summary> /// Gets state entries contributing to this function. Supports error reporting. /// </summary> internal override IList<IEntityStateEntry> GetStateEntries(UpdateTranslator translator) { return m_stateEntries; } // Adds and register a DbParameter to the current command. internal void SetParameterValue(PropagatorResult result, StorageModificationFunctionParameterBinding parameterBinding, UpdateTranslator translator) { // retrieve DbParameter DbParameter parameter = this.m_dbCommand.Parameters[parameterBinding.Parameter.Name]; TypeUsage parameterType = parameterBinding.Parameter.TypeUsage; object parameterValue = translator.KeyManager.GetPrincipalValue(result); translator.SetParameterValue(parameter, parameterType, parameterValue); // if the parameter corresponds to an identifier (key component), remember this fact in case // it's important for dependency ordering (e.g., output the identifier before creating it) int identifier = result.Identifier; if (PropagatorResult.NullIdentifier != identifier) { const int initialSize = 2; // expect on average less than two input identifiers per command if (null == m_inputIdentifiers) { m_inputIdentifiers = new List<KeyValuePair<int, DbParameter>>(initialSize); } foreach (int principal in translator.KeyManager.GetPrincipals(identifier)) { m_inputIdentifiers.Add(new KeyValuePair<int, DbParameter>(principal, parameter)); } } } // Adds and registers a DbParameter taking the number of rows affected internal void RegisterRowsAffectedParameter(FunctionParameter rowsAffectedParameter) { if (null != rowsAffectedParameter) { Debug.Assert(rowsAffectedParameter.Mode == ParameterMode.Out || rowsAffectedParameter.Mode == ParameterMode.InOut, "when loading mapping metadata, we check that the parameter is an out parameter"); m_rowsAffectedParameter = m_dbCommand.Parameters[rowsAffectedParameter.Name]; } } // Adds a result column binding from a column name (from the result set for the function) to // a propagator result (which contains the context necessary to back-propagate the result). // If the result is an identifier, binds the internal void AddResultColumn(UpdateTranslator translator, String columnName, PropagatorResult result) { const int initializeSize = 2; // expect on average less than two result columns per command if (null == m_resultColumns) { m_resultColumns = new List<KeyValuePair<string, PropagatorResult>>(initializeSize); } m_resultColumns.Add(new KeyValuePair<string, PropagatorResult>(columnName, result)); int identifier = result.Identifier; if (PropagatorResult.NullIdentifier != identifier) { if (translator.KeyManager.HasPrincipals(identifier)) { throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.Update_GeneratedDependent(columnName)); } // register output identifier to enable fix-up and dependency tracking AddOutputIdentifier(columnName, identifier); } } // Indicate that a column in the command result set (specified by 'columnName') produces the // value for a key component (specified by 'identifier') private void AddOutputIdentifier(String columnName, int identifier) { const int initialSize = 2; // expect on average less than two identifier output per command if (null == m_outputIdentifiers) { m_outputIdentifiers = new Dictionary<int, string>(initialSize); } m_outputIdentifiers[identifier] = columnName; } // efects: Executes the current function command in the given transaction and connection context. // All server-generated values are added to the generatedValues list. If those values are identifiers, they are // also added to the identifierValues dictionary, which associates proxy identifiers for keys in the session // with their actual values, permitting fix-up of identifiers across relationships. internal override long Execute(UpdateTranslator translator, EntityConnection connection, Dictionary<int, object> identifierValues, List<KeyValuePair<PropagatorResult, object>> generatedValues) { // configure command to use the connection and transaction for this session m_dbCommand.Transaction = ((null != connection.CurrentTransaction) ? connection.CurrentTransaction.StoreTransaction : null); m_dbCommand.Connection = connection.StoreConnection; if (translator.CommandTimeout.HasValue) { m_dbCommand.CommandTimeout = translator.CommandTimeout.Value; } // set all identifier inputs (to support propagation of identifier values across relationship // boundaries) if (null != m_inputIdentifiers) { foreach (KeyValuePair<int, DbParameter> inputIdentifier in m_inputIdentifiers) { object value; if (identifierValues.TryGetValue(inputIdentifier.Key, out value)) { // set the actual value for the identifier if it has been produced by some // other command inputIdentifier.Value.Value = value; } } } // Execute the query long rowsAffected; if (null != m_resultColumns) { // If there are result columns, read the server gen results rowsAffected = 0; IBaseList<EdmMember> members = TypeHelpers.GetAllStructuralMembers(this.CurrentValues.StructuralType); using (DbDataReader reader = m_dbCommand.ExecuteReader(CommandBehavior.SequentialAccess)) { // Retrieve only the first row from the first result set if (reader.Read()) { rowsAffected++; foreach (var resultColumn in m_resultColumns .Select(r => new KeyValuePair<int, PropagatorResult>(GetColumnOrdinal(translator, reader, r.Key), r.Value)) .OrderBy(r => r.Key)) // order by column ordinal to avoid breaking SequentialAccess readers { int columnOrdinal = resultColumn.Key; TypeUsage columnType = members[resultColumn.Value.RecordOrdinal].TypeUsage; object value; if (Helper.IsSpatialType(columnType) && !reader.IsDBNull(columnOrdinal)) { value = SpatialHelpers.GetSpatialValue(translator.MetadataWorkspace, reader, columnType, columnOrdinal); } else { value = reader.GetValue(columnOrdinal); } // register for back-propagation PropagatorResult result = resultColumn.Value; generatedValues.Add(new KeyValuePair<PropagatorResult, object>(result, value)); // register identifier if it exists int identifier = result.Identifier; if (PropagatorResult.NullIdentifier != identifier) { identifierValues.Add(identifier, value); } } } // Consume the current reader (and subsequent result sets) so that any errors // executing the function can be intercepted CommandHelper.ConsumeReader(reader); } } else { rowsAffected = m_dbCommand.ExecuteNonQuery(); } // if an explicit rows affected parameter exists, use this value instead if (null != m_rowsAffectedParameter) { // by design, negative row counts indicate failure iff. an explicit rows // affected parameter is used if (DBNull.Value.Equals(m_rowsAffectedParameter.Value)) { rowsAffected = 0; } else { try { rowsAffected = Convert.ToInt64(m_rowsAffectedParameter.Value, CultureInfo.InvariantCulture); } catch (Exception e) { if (UpdateTranslator.RequiresContext(e)) { // wrap the exception throw EntityUtil.Update(System.Data.Entity.Strings.Update_UnableToConvertRowsAffectedParameterToInt32( m_rowsAffectedParameter.ParameterName, typeof(int).FullName), e, this.GetStateEntries(translator)); } throw; } } } return rowsAffected; } private int GetColumnOrdinal(UpdateTranslator translator, DbDataReader reader, string columnName) { int columnOrdinal; try { columnOrdinal = reader.GetOrdinal(columnName); } catch (IndexOutOfRangeException) { throw EntityUtil.Update(System.Data.Entity.Strings.Update_MissingResultColumn(columnName), null, this.GetStateEntries(translator)); } return columnOrdinal; } /// <summary> /// Gets modification operator corresponding to the given entity state. /// </summary> private static ModificationOperator GetModificationOperator(EntityState state) { switch (state) { case EntityState.Modified: case EntityState.Unchanged: // unchanged entities correspond to updates (consider the case where // the entity is not being modified but a collocated relationship is) return ModificationOperator.Update; case EntityState.Added: return ModificationOperator.Insert; case EntityState.Deleted: return ModificationOperator.Delete; default: Debug.Fail("unexpected entity state " + state); return default(ModificationOperator); } } internal override int CompareToType(UpdateCommand otherCommand) { Debug.Assert(!object.ReferenceEquals(this, otherCommand), "caller should ensure other command is different"); FunctionUpdateCommand other = (FunctionUpdateCommand)otherCommand; // first state entry is the 'main' state entry for the command (see ctor) IEntityStateEntry thisParent = this.m_stateEntries[0]; IEntityStateEntry otherParent = other.m_stateEntries[0]; // order by operator int result = (int)GetModificationOperator(thisParent.State) - (int)GetModificationOperator(otherParent.State); if (0 != result) { return result; } // order by entity set result = StringComparer.Ordinal.Compare(thisParent.EntitySet.Name, otherParent.EntitySet.Name); if (0 != result) { return result; } result = StringComparer.Ordinal.Compare(thisParent.EntitySet.EntityContainer.Name, otherParent.EntitySet.EntityContainer.Name); if (0 != result) { return result; } // order by key values int thisInputIdentifierCount = (null == this.m_inputIdentifiers ? 0 : this.m_inputIdentifiers.Count); int otherInputIdentifierCount = (null == other.m_inputIdentifiers ? 0 : other.m_inputIdentifiers.Count); result = thisInputIdentifierCount - otherInputIdentifierCount; if (0 != result) { return result; } for (int i = 0; i < thisInputIdentifierCount; i++) { DbParameter thisParameter = this.m_inputIdentifiers[i].Value; DbParameter otherParameter = other.m_inputIdentifiers[i].Value; result = ByValueComparer.Default.Compare(thisParameter.Value, otherParameter.Value); if (0 != result) { return result; } } // If the result is still zero, it means key values are all the same. Switch to synthetic identifiers // to differentiate. for (int i = 0; i < thisInputIdentifierCount; i++) { int thisIdentifier = this.m_inputIdentifiers[i].Key; int otherIdentifier = other.m_inputIdentifiers[i].Key; result = thisIdentifier - otherIdentifier; if (0 != result) { return result; } } return result; } #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 Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations { public class LongKeywordRecommenderTests : KeywordRecommenderTests { [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AtRoot_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"$$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterClass_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"class C { } $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterGlobalStatement_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"System.Console.WriteLine(); $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterGlobalVariableDeclaration_Interactive() { VerifyKeyword(SourceCodeKind.Script, @"int i = 0; $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInUsingAlias() { VerifyAbsence( @"using Foo = $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterStackAlloc() { VerifyKeyword( @"class C { int* foo = stackalloc $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterOuterConst() { VerifyKeyword( @"class C { const $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterInnerConst() { VerifyKeyword(AddInsideMethod( @"const $$")); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InFixedStatement() { VerifyKeyword( @"fixed ($$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InDelegateReturnType() { VerifyKeyword( @"public delegate $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InCastType() { VerifyKeyword(AddInsideMethod( @"var str = (($$")); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InCastType2() { VerifyKeyword(AddInsideMethod( @"var str = (($$)items) as string;")); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InEmptyStatement() { VerifyKeyword(AddInsideMethod( @"$$")); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void EnumBaseTypes() { VerifyKeyword( @"enum E : $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InGenericType1() { VerifyKeyword(AddInsideMethod( @"IList<$$")); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InGenericType2() { VerifyKeyword(AddInsideMethod( @"IList<int,$$")); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InGenericType3() { VerifyKeyword(AddInsideMethod( @"IList<int[],$$")); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InGenericType4() { VerifyKeyword(AddInsideMethod( @"IList<IFoo<int?,byte*>,$$")); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInBaseList() { VerifyAbsence( @"class C : $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InGenericType_InBaseList() { VerifyKeyword( @"class C : IList<$$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterIs() { VerifyKeyword(AddInsideMethod( @"var v = foo is $$")); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterAs() { VerifyKeyword(AddInsideMethod( @"var v = foo as $$")); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterMethod() { VerifyKeyword( @"class C { void Foo() {} $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterField() { VerifyKeyword( @"class C { int i; $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterProperty() { VerifyKeyword( @"class C { int i { get; } $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedAttribute() { VerifyKeyword( @"class C { [foo] $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InsideStruct() { VerifyKeyword( @"struct S { $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InsideInterface() { VerifyKeyword( @"interface I { $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InsideClass() { VerifyKeyword( @"class C { $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterPartial() { VerifyAbsence(@"partial $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterNestedPartial() { VerifyAbsence( @"class C { partial $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedAbstract() { VerifyKeyword( @"class C { abstract $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedInternal() { VerifyKeyword( @"class C { internal $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedStaticPublic() { VerifyKeyword( @"class C { static public $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedPublicStatic() { VerifyKeyword( @"class C { public static $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterVirtualPublic() { VerifyKeyword( @"class C { virtual public $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedPublic() { VerifyKeyword( @"class C { public $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedPrivate() { VerifyKeyword( @"class C { private $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedProtected() { VerifyKeyword( @"class C { protected $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedSealed() { VerifyKeyword( @"class C { sealed $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNestedStatic() { VerifyKeyword( @"class C { static $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InLocalVariableDeclaration() { VerifyKeyword(AddInsideMethod( @"$$")); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InForVariableDeclaration() { VerifyKeyword(AddInsideMethod( @"for ($$")); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InForeachVariableDeclaration() { VerifyKeyword(AddInsideMethod( @"foreach ($$")); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InUsingVariableDeclaration() { VerifyKeyword(AddInsideMethod( @"using ($$")); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InFromVariableDeclaration() { VerifyKeyword(AddInsideMethod( @"var q = from $$")); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InJoinVariableDeclaration() { VerifyKeyword(AddInsideMethod( @"var q = from a in b join $$")); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterMethodOpenParen() { VerifyKeyword( @"class C { void Foo($$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterMethodComma() { VerifyKeyword( @"class C { void Foo(int i, $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterMethodAttribute() { VerifyKeyword( @"class C { void Foo(int i, [Foo]$$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterConstructorOpenParen() { VerifyKeyword( @"class C { public C($$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterConstructorComma() { VerifyKeyword( @"class C { public C(int i, $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterConstructorAttribute() { VerifyKeyword( @"class C { public C(int i, [Foo]$$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterDelegateOpenParen() { VerifyKeyword( @"delegate void D($$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterDelegateComma() { VerifyKeyword( @"delegate void D(int i, $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterDelegateAttribute() { VerifyKeyword( @"delegate void D(int i, [Foo]$$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterThis() { VerifyKeyword( @"static class C { public static void Foo(this $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterRef() { VerifyKeyword( @"class C { void Foo(ref $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterOut() { VerifyKeyword( @"class C { void Foo(out $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterLambdaRef() { VerifyKeyword( @"class C { void Foo() { System.Func<int, int> f = (ref $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterLambdaOut() { VerifyKeyword( @"class C { void Foo() { System.Func<int, int> f = (out $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterParams() { VerifyKeyword( @"class C { void Foo(params $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InImplicitOperator() { VerifyKeyword( @"class C { public static implicit operator $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InExplicitOperator() { VerifyKeyword( @"class C { public static explicit operator $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterIndexerBracket() { VerifyKeyword( @"class C { int this[$$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterIndexerBracketComma() { VerifyKeyword( @"class C { int this[int i, $$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterNewInExpression() { VerifyKeyword(AddInsideMethod( @"new $$")); } [WorkItem(538804)] [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InTypeOf() { VerifyKeyword(AddInsideMethod( @"typeof($$")); } [WorkItem(538804)] [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InDefault() { VerifyKeyword(AddInsideMethod( @"default($$")); } [WorkItem(538804)] [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InSizeOf() { VerifyKeyword(AddInsideMethod( @"sizeof($$")); } [WorkItem(544219)] [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInObjectInitializerMemberContext() { VerifyAbsence(@" class C { public int x, y; void M() { var c = new C { x = 2, y = 3, $$"); } [WorkItem(546938)] [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InCrefContext() { VerifyKeyword(@" class Program { /// <see cref=""$$""> static void Main(string[] args) { } }"); } [WorkItem(546955)] [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void InCrefContextNotAfterDot() { VerifyAbsence(@" /// <see cref=""System.$$"" /> class C { } "); } [WorkItem(18374)] [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void AfterAsync() { VerifyKeyword(@"class c { async $$ }"); } [WorkItem(18374)] [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotAfterAsyncAsType() { VerifyAbsence(@"class c { async async $$ }"); } [WorkItem(1468, "https://github.com/dotnet/roslyn/issues/1468")] [WpfFact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)] public void NotInCrefTypeParameter() { VerifyAbsence(@" using System; /// <see cref=""List{$$}"" /> class C { } "); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Globalization; using System.IO; using System.Xml; using System.Net; using System.Drawing; using System.Drawing.Imaging; using System.Collections; using System.Diagnostics; using OpenLiveWriter.CoreServices; using OpenLiveWriter.Extensibility.BlogClient; using mshtml ; namespace OpenLiveWriter.BlogClient.Detection { internal class WriterEditingManifest { public static WriterEditingManifest FromHomepage(LazyHomepageDownloader homepageDownloader, Uri homepageUri, IBlogClient blogClient, IBlogCredentialsAccessor credentials) { if ( homepageUri == null ) return null; WriterEditingManifest editingManifest = null ; try { // compute the "by-convention" url for the manifest string homepageUrl = UrlHelper.InsureTrailingSlash(UrlHelper.SafeToAbsoluteUri(homepageUri)) ; string manifestUrl = UrlHelper.UrlCombine(homepageUrl, "wlwmanifest.xml") ; // test to see whether this url exists and has a valid manifest editingManifest = FromUrl(new Uri(manifestUrl), blogClient, credentials, false) ; // if we still don't have one then scan homepage contents for a link tag if ( editingManifest == null ) { string manifestLinkTagUrl = ScanHomepageContentsForManifestLink(homepageUri, homepageDownloader) ; if ( manifestLinkTagUrl != null ) { // test to see whether this url exists and has a valid manifest try { editingManifest = FromUrl(new Uri(manifestLinkTagUrl), blogClient, credentials, true) ; } catch(Exception ex) { Trace.WriteLine("Error attempting to download manifest from " + manifestLinkTagUrl + ": " + ex.ToString()); } } } } catch(Exception ex) { Trace.WriteLine("Unexpected exception attempting to discover manifest from " + UrlHelper.SafeToAbsoluteUri(homepageUri) + ": " + ex.ToString()); } // return whatever editing manifest we found return editingManifest ; } public static WriterEditingManifest FromUrl(Uri manifestUri, IBlogClient blogClient, IBlogCredentialsAccessor credentials, bool expectedAvailable ) { return FromDownloadInfo(new WriterEditingManifestDownloadInfo(UrlHelper.SafeToAbsoluteUri(manifestUri)), blogClient, credentials, expectedAvailable ); } public static WriterEditingManifest FromDownloadInfo(WriterEditingManifestDownloadInfo downloadInfo, IBlogClient blogClient, IBlogCredentialsAccessor credentials, bool expectedAvailable ) { if ( downloadInfo == null ) return null ; try { // if the manifest is not yet expired then don't try a download at all if ( downloadInfo.Expires > DateTimeHelper.UtcNow ) return new WriterEditingManifest(downloadInfo) ; // execute the download HttpWebResponse response = null ; try { if (credentials != null) response = blogClient.SendAuthenticatedHttpRequest(downloadInfo.SourceUrl, REQUEST_TIMEOUT, new HttpRequestFilter(new EditingManifestFilter(downloadInfo).Filter)); else response = HttpRequestHelper.SendRequest(downloadInfo.SourceUrl, new HttpRequestFilter(new EditingManifestFilter(downloadInfo).Filter)); } catch(WebException ex) { // Not modified -- return ONLY an updated downloadInfo (not a document) HttpWebResponse errorResponse = ex.Response as HttpWebResponse; if(errorResponse != null && errorResponse.StatusCode == HttpStatusCode.NotModified) { return new WriterEditingManifest( new WriterEditingManifestDownloadInfo( downloadInfo.SourceUrl, HttpRequestHelper.GetExpiresHeader(errorResponse), downloadInfo.LastModified, HttpRequestHelper.GetETagHeader(errorResponse) ) ); } else throw ; } // read headers DateTime expires = HttpRequestHelper.GetExpiresHeader(response) ; DateTime lastModified = response.LastModified ; string eTag = HttpRequestHelper.GetETagHeader(response); // read document using ( Stream stream = response.GetResponseStream() ) { XmlDocument manifestXmlDocument = new XmlDocument(); manifestXmlDocument.Load(stream); // return the manifest return new WriterEditingManifest( new WriterEditingManifestDownloadInfo(downloadInfo.SourceUrl, expires, lastModified, eTag), manifestXmlDocument, blogClient, credentials) ; } } catch(Exception ex) { if ( expectedAvailable ) { Trace.WriteLine("Error attempting to download manifest from " + downloadInfo.SourceUrl + ": " + ex.ToString()); } return null ; } } private class EditingManifestFilter { private WriterEditingManifestDownloadInfo _previousDownloadInfo ; public EditingManifestFilter(WriterEditingManifestDownloadInfo previousDownloadInfo) { _previousDownloadInfo = previousDownloadInfo ; } public void Filter(HttpWebRequest contentRequest) { if ( _previousDownloadInfo.LastModified != DateTime.MinValue ) contentRequest.IfModifiedSince = _previousDownloadInfo.LastModified ; if ( _previousDownloadInfo.ETag != String.Empty ) contentRequest.Headers.Add("If-None-Match", _previousDownloadInfo.ETag); } } public static WriterEditingManifest FromResource(string resourcePath) { try { using ( MemoryStream manifestStream = new MemoryStream() ) { ResourceHelper.SaveAssemblyResourceToStream(resourcePath, manifestStream) ; manifestStream.Seek(0, SeekOrigin.Begin) ; XmlDocument manifestXmlDocument = new XmlDocument(); manifestXmlDocument.Load(manifestStream); return new WriterEditingManifest(new WriterEditingManifestDownloadInfo("Clients.Manifests"), manifestXmlDocument, null, null); } } catch(Exception ex) { Trace.Fail("Unexpected exception attempting to load manifest from resource: " + ex.ToString()); return null ; } } public static string DiscoverUrl(string homepageUrl, IHTMLDocument2 weblogDOM) { if ( weblogDOM == null ) return String.Empty ; try { // look in the first HEAD tag IHTMLElementCollection headElements = ((IHTMLDocument3)weblogDOM).getElementsByTagName( "HEAD" ) ; if ( headElements.length > 0 ) { // get the first head element IHTMLElement2 firstHeadElement = (IHTMLElement2)headElements.item(0,0); // look for link tags within the head foreach ( IHTMLElement element in firstHeadElement.getElementsByTagName( "LINK" ) ) { IHTMLLinkElement linkElement = element as IHTMLLinkElement ; if ( linkElement != null ) { string linkRel = linkElement.rel ; if ( linkRel != null && (linkRel.ToUpperInvariant().Equals("WLWMANIFEST") ) ) { if ( linkElement.href != null && linkElement.href != String.Empty) return UrlHelper.UrlCombineIfRelative(homepageUrl, linkElement.href) ; } } } } } catch(Exception ex) { Trace.Fail("Unexpected error attempting to discover manifest URL: " + ex.ToString()); } // couldn't find one return String.Empty ; } public WriterEditingManifestDownloadInfo DownloadInfo { get { return _downloadInfo ; } } private readonly WriterEditingManifestDownloadInfo _downloadInfo ; public string ClientType { get { return _clientType ; } } private readonly string _clientType = null; public byte[] Image { get { return _image ; } } private readonly byte[] _image = null; public byte[] Watermark { get { return _watermark ; } } private readonly byte[] _watermark = null; public IDictionary OptionOverrides { get { return _optionOverrides ; } } private readonly IDictionary _optionOverrides = null; public IBlogProviderButtonDescription[] ButtonDescriptions { get { return _buttonDescriptions ; } } private readonly IBlogProviderButtonDescription[] _buttonDescriptions = null; public string WebLayoutUrl { get { return _webLayoutUrl ; } } private readonly string _webLayoutUrl ; public string WebPreviewUrl { get { return _webPreviewUrl ; } } private readonly string _webPreviewUrl ; private IBlogClient _blogClient = null ; private IBlogCredentialsAccessor _credentials = null ; private WriterEditingManifest(WriterEditingManifestDownloadInfo downloadInfo) : this(downloadInfo, null, null, null) { } private WriterEditingManifest(WriterEditingManifestDownloadInfo downloadInfo, XmlDocument xmlDocument, IBlogClient blogClient, IBlogCredentialsAccessor credentials) { // record blog client and credentials _blogClient = blogClient ; _credentials = credentials ; // record download info if ( UrlHelper.IsUrl(downloadInfo.SourceUrl) ) _downloadInfo = downloadInfo ; // only process an xml document if we got one if ( xmlDocument == null ) return ; // create namespace manager XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDocument.NameTable); nsmgr.AddNamespace("m", "http://schemas.microsoft.com/wlw/manifest/weblog" ); // throw if the root element is not manifest if ( xmlDocument.DocumentElement.LocalName.ToUpperInvariant() != "MANIFEST") throw new ArgumentException("Not a valid writer editing manifest") ; // get button descriptions _buttonDescriptions = new IBlogProviderButtonDescription[] {}; XmlNode buttonsNode = xmlDocument.SelectSingleNode("//m:buttons", nsmgr) ; if ( buttonsNode != null) { ArrayList buttons = new ArrayList(); foreach ( XmlNode buttonNode in buttonsNode.SelectNodes("m:button", nsmgr) ) { try { // id string id = XmlHelper.NodeText(buttonNode.SelectSingleNode("m:id", nsmgr)) ; if ( id == String.Empty ) throw new ArgumentException("Missing id field") ; // title string description = XmlHelper.NodeText(buttonNode.SelectSingleNode( "m:text", nsmgr )) ; if ( description == String.Empty ) throw new ArgumentException("Missing text field") ; // imageUrl string imageUrl = XmlHelper.NodeText(buttonNode.SelectSingleNode( "m:imageUrl", nsmgr )) ; if ( imageUrl == String.Empty ) throw new ArgumentException("Missing imageUrl field") ; // download the image Bitmap image = DownloadImage(imageUrl, downloadInfo.SourceUrl) ; // clickUrl string clickUrl = BlogClientHelper.GetAbsoluteUrl(XmlHelper.NodeText(buttonNode.SelectSingleNode( "m:clickUrl", nsmgr )), downloadInfo.SourceUrl) ; // contentUrl string contentUrl = BlogClientHelper.GetAbsoluteUrl(XmlHelper.NodeText(buttonNode.SelectSingleNode( "m:contentUrl", nsmgr )), downloadInfo.SourceUrl) ; // contentDisplaySize Size contentDisplaySize = XmlHelper.NodeSize(buttonNode.SelectSingleNode("m:contentDisplaySize", nsmgr), Size.Empty ) ; // button must have either clickUrl or hasContent if ( clickUrl == String.Empty && contentUrl == String.Empty ) throw new ArgumentException("Must either specify a clickUrl or contentUrl") ; // notificationUrl string notificationUrl = BlogClientHelper.GetAbsoluteUrl(XmlHelper.NodeText(buttonNode.SelectSingleNode( "m:notificationUrl", nsmgr )), downloadInfo.SourceUrl) ; // add the button buttons.Add( new BlogProviderButtonDescription(id, imageUrl, image, description, clickUrl, contentUrl, contentDisplaySize, notificationUrl)) ; } catch(Exception ex) { // buttons fail silently and are not "all or nothing" Trace.WriteLine("Error occurred reading custom button description: " + ex.Message ) ; } } _buttonDescriptions = buttons.ToArray(typeof(IBlogProviderButtonDescription)) as IBlogProviderButtonDescription[] ; } // get options _optionOverrides = new Hashtable() ; AddOptionsFromNode( xmlDocument.SelectSingleNode("//m:weblog", nsmgr), _optionOverrides ) ; AddOptionsFromNode( xmlDocument.SelectSingleNode("//m:options", nsmgr), _optionOverrides ) ; AddOptionsFromNode( xmlDocument.SelectSingleNode("//m:apiOptions[@name='" + _blogClient.ProtocolName + "']", nsmgr), _optionOverrides ) ; XmlNode defaultViewNode = xmlDocument.SelectSingleNode("//m:views/m:default", nsmgr) ; if ( defaultViewNode != null ) _optionOverrides["defaultView"] = XmlHelper.NodeText(defaultViewNode) ; // separate out client type const string CLIENT_TYPE = "clientType" ; if ( _optionOverrides.Contains(CLIENT_TYPE) ) { string type = _optionOverrides[CLIENT_TYPE].ToString() ; if ( ValidateClientType(type) ) _clientType = type ; _optionOverrides.Remove(CLIENT_TYPE); } // separate out image const string IMAGE_URL = "imageUrl" ; _image = GetImageBytes(IMAGE_URL, _optionOverrides, downloadInfo.SourceUrl, new Size(16,16)) ; _optionOverrides.Remove(IMAGE_URL); // separate out watermark image const string WATERMARK_IMAGE_URL = "watermarkImageUrl" ; _watermark = GetImageBytes(WATERMARK_IMAGE_URL, _optionOverrides, downloadInfo.SourceUrl, new Size(84,84)) ; _optionOverrides.Remove(WATERMARK_IMAGE_URL); // get templates XmlNode webLayoutUrlNode = xmlDocument.SelectSingleNode("//m:views/m:view[@type='WebLayout']/@src", nsmgr) ; if ( webLayoutUrlNode != null ) { string webLayoutUrl = XmlHelper.NodeText(webLayoutUrlNode) ; if ( webLayoutUrl != String.Empty ) _webLayoutUrl = BlogClientHelper.GetAbsoluteUrl(webLayoutUrl, downloadInfo.SourceUrl) ; } XmlNode webPreviewUrlNode = xmlDocument.SelectSingleNode("//m:views/m:view[@type='WebPreview']/@src", nsmgr) ; if ( webPreviewUrlNode != null ) { string webPreviewUrl = XmlHelper.NodeText(webPreviewUrlNode) ; if ( webPreviewUrl != String.Empty ) _webPreviewUrl = BlogClientHelper.GetAbsoluteUrl(webPreviewUrl, downloadInfo.SourceUrl) ; } } private void AddOptionsFromNode( XmlNode optionsNode, IDictionary optionOverrides ) { if ( optionsNode != null ) { foreach ( XmlNode node in optionsNode.ChildNodes ) { if ( node.NodeType == XmlNodeType.Element ) optionOverrides.Add(node.LocalName, node.InnerText.Trim()); } } } private bool ValidateClientType(string clientType) { clientType = clientType.Trim().ToUpperInvariant() ; return clientType == "METAWEBLOG" || clientType == "MOVABLETYPE" || clientType == "WORDPRESS" ; } private byte[] GetImageBytes( string elementName, IDictionary options, string basePath, Size requiredSize ) { byte[] imageBytes = null ; string imageUrl = options[elementName] as string ; if ( imageUrl != null && imageUrl != String.Empty ) { try { Bitmap bitmap = DownloadImage(imageUrl,basePath) ; ImageFormat bitmapFormat = bitmap.RawFormat ; if ( requiredSize != Size.Empty && bitmap.Size != requiredSize ) { // shrink or grow the bitmap as appropriate Bitmap correctedBitmap = new Bitmap(bitmap, requiredSize); // dispose the original bitmap.Dispose(); // return corrected bitmap = correctedBitmap ; } imageBytes = ImageHelper.GetBitmapBytes(bitmap, bitmapFormat) ; } catch (Exception ex) { Trace.WriteLine(String.Format(CultureInfo.CurrentCulture, "Unexpected error downloading image from {0}: {1}", imageUrl, ex.ToString())); } } else { // indicates that no attempt to provide us an image was made imageBytes = new byte[0]; } return imageBytes ; } private Bitmap DownloadImage(string imageUrl, string basePath ) { // non-url base path means embedded resource if ( !UrlHelper.IsUrl(basePath) ) { string imagePath = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", basePath, imageUrl ); Bitmap image = ResourceHelper.LoadAssemblyResourceBitmap(imagePath) ; if ( image != null ) return image ; else throw new ArgumentException("Invalid Image Resource Path: " + imageUrl) ; } else { // calculate the image url imageUrl = UrlHelper.UrlCombineIfRelative(basePath, imageUrl) ; // try to get the credentials context WinInetCredentialsContext credentialsContext = null ; try { credentialsContext = BlogClientHelper.GetCredentialsContext(_blogClient, _credentials, imageUrl) ; } catch(BlogClientOperationCancelledException) { } // download the image return ImageHelper.DownloadBitmap(imageUrl, credentialsContext ) ; } } private static string ScanHomepageContentsForManifestLink(Uri homepageUri, LazyHomepageDownloader homepageDownloader) { if ( homepageDownloader.HtmlDocument != null ) { LightWeightTag[] linkTags = homepageDownloader.HtmlDocument.GetTagsByName(HTMLTokens.Link); foreach ( LightWeightTag linkTag in linkTags ) { string rel = linkTag.BeginTag.GetAttributeValue("rel") ; string href = linkTag.BeginTag.GetAttributeValue("href") ; if ( rel != null && (rel.Trim().ToUpperInvariant().Equals("WLWMANIFEST") && href != null) ) { return UrlHelper.UrlCombineIfRelative(UrlHelper.SafeToAbsoluteUri(homepageUri), href) ; } } } // didn't find it return null ; } // 20-second request timeout private const int REQUEST_TIMEOUT = 20000 ; } }
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------- namespace System.Activities.Presentation.View { using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Input; using System.Windows.Media; using System.Runtime; using System.Globalization; using System.Diagnostics.CodeAnalysis; delegate void ExtensionWindowCloseEventHandler(object sender, RoutedEventArgs e); delegate void ExtensionWindowClosingEventHandler(object sender, ExtensionWindowClosingRoutedEventArgs e); //This class provides PopupWindow like expirience while editing data on designer surface. It //behaves like ordinary popup, with additional functionality - allows resizing, moving, and //easier styling. [TemplatePart(Name = "PART_Content"), TemplatePart(Name = "PART_ShapeBorder")] class ExtensionWindow : ContentControl { public static readonly DependencyProperty DataProperty = DependencyProperty.Register( "Data", typeof(object), typeof(ExtensionWindow), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsRender, new PropertyChangedCallback(OnDataChanged))); public static readonly DependencyProperty TitleProperty = DependencyProperty.Register( "Title", typeof(string), typeof(ExtensionWindow), new UIPropertyMetadata(string.Empty)); public static readonly DependencyProperty IconProperty = DependencyProperty.Register( "Icon", typeof(DrawingBrush), typeof(ExtensionWindow), new UIPropertyMetadata(null)); public static readonly DependencyProperty ShowWindowHeaderProperty = DependencyProperty.Register( "ShowWindowHeader", typeof(bool), typeof(ExtensionWindow), new UIPropertyMetadata(true)); public static readonly DependencyProperty ShowResizeGripProperty = DependencyProperty.Register( "ShowResizeGrip", typeof(bool), typeof(ExtensionWindow), new UIPropertyMetadata(true)); public static readonly DependencyProperty MenuItemsProperty = DependencyProperty.Register( "MenuItems", typeof(ObservableCollection<MenuItem>), typeof(ExtensionWindow)); public static readonly DependencyProperty IsResizableProperty = DependencyProperty.Register( "IsResizable", typeof(bool), typeof(ExtensionWindow), new UIPropertyMetadata(false)); public static readonly RoutedEvent ClosingEvent = EventManager.RegisterRoutedEvent("Closing", RoutingStrategy.Bubble, typeof(ExtensionWindowClosingEventHandler), typeof(ExtensionWindow)); public static readonly RoutedEvent CloseEvent = EventManager.RegisterRoutedEvent("Close", RoutingStrategy.Bubble, typeof(ExtensionWindowCloseEventHandler), typeof(ExtensionWindow)); public static readonly RoutedEvent VisibilityChangedEvent = EventManager.RegisterRoutedEvent("VisibilityChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(ExtensionWindow)); static readonly double BorderOffset = 20.0; ContentPresenter presenter; ExtensionSurface surface; Border border; ResizeValues resizeOption = ResizeValues.NONE; Point bottomRight; [SuppressMessage(FxCop.Category.Performance, FxCop.Rule.InitializeReferenceTypeStaticFieldsInline, Justification = "Overriding metadata for dependency properties in static constructor is the way suggested by WPF")] static ExtensionWindow() { VisibilityProperty.AddOwner(typeof(ExtensionWindow), new PropertyMetadata(OnVisibilityChanged)); DefaultStyleKeyProperty.OverrideMetadata( typeof(ExtensionWindow), new FrameworkPropertyMetadata(typeof(ExtensionWindow))); } [SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "This is internal code with no derived class")] public ExtensionWindow() { this.MenuItems = new ObservableCollection<MenuItem>(); } protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); this.MenuItems.CollectionChanged += new NotifyCollectionChangedEventHandler(OnMenuItemsChanged); this.DataContext = this; } public event ExtensionWindowClosingEventHandler Closing { add { AddHandler(ClosingEvent, value); } remove { RemoveHandler(ClosingEvent, value); } } public event ExtensionWindowCloseEventHandler Close { add { AddHandler(CloseEvent, value); } remove { RemoveHandler(CloseEvent, value); } } public event RoutedEventHandler VisibilityChanged { add { AddHandler(VisibilityChangedEvent, value); } remove { RemoveHandler(VisibilityChangedEvent, value); } } public object Data { get { return (object)GetValue(DataProperty); } set { SetValue(DataProperty, value); } } public string Title { get { return (string)GetValue(TitleProperty); } set { SetValue(TitleProperty, value); } } [Fx.Tag.KnownXamlExternal] public DrawingBrush Icon { get { return (DrawingBrush)GetValue(IconProperty); } set { SetValue(IconProperty, value); } } public bool ShowWindowHeader { get { return (bool)GetValue(ShowWindowHeaderProperty); } set { SetValue(ShowWindowHeaderProperty, value); } } public bool ShowResizeGrip { get { return (bool)GetValue(ShowResizeGripProperty); } set { SetValue(ShowResizeGripProperty, value); } } [Fx.Tag.KnownXamlExternal] public ObservableCollection<MenuItem> MenuItems { get { return (ObservableCollection<MenuItem>)GetValue(MenuItemsProperty); } private set { SetValue(MenuItemsProperty, value); } } public ExtensionSurface Surface { get { return this.surface; } } public bool IsResizable { get { return (bool)GetValue(IsResizableProperty); } set { SetValue(IsResizableProperty, value); } } protected ContentPresenter ContentPresenter { get { return this.presenter; } } public Point GetPlacementTargetOffset() { Point offset = new Point(); FrameworkElement target = ExtensionSurface.GetPlacementTarget(this); if (null != target) { FrameworkElement commonRoot = target.FindCommonVisualAncestor(this) as FrameworkElement; MatrixTransform transform = (MatrixTransform)target.TransformToAncestor(commonRoot); Point targetPosition = transform.Transform(new Point()); Point windowPosition = ExtensionSurface.GetPosition(this); offset.X = targetPosition.X - windowPosition.X; offset.Y = targetPosition.Y - windowPosition.Y; } return offset; } static void OnDataChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) { ((ExtensionWindow)sender).OnDataChanged(args.OldValue, args.NewValue); } static void OnPositionChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) { ((ExtensionWindow)sender).OnPositionChanged((Point)args.NewValue); } static void OnVisibilityChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { ((ExtensionWindow)sender).OnVisibilityChanged((Visibility)e.OldValue, (Visibility)e.NewValue); } protected override void OnVisualParentChanged(DependencyObject oldParent) { base.OnVisualParentChanged(oldParent); ExtensionWindow dummy; if (!DesignerProperties.GetIsInDesignMode(this) && !TryGetParentExtensionWindow(this, out dummy, out this.surface)) { Fx.Assert(string.Format(CultureInfo.InvariantCulture, "ExtensionWindow '{0}' cannot be used outside ExtensionSurface", this.Name)); } } protected virtual void OnDataChanged(object oldData, object newData) { } protected virtual void OnVisibilityChanged(Visibility oldValue, Visibility newValue) { RaiseEvent(new RoutedEventArgs(VisibilityChangedEvent, this)); } protected virtual void OnPositionChanged(Point position) { if (null != this.surface) { this.surface.SetWindowPosition(this, position); } } public bool TryFindElement(string elementName, out object element) { //helper method - it looks for named visual elements in the template provided by the user element = null; if (null != this.presenter) { element = this.presenter.ContentTemplate.FindName(elementName, this.presenter); } return (null != element); } public override void OnApplyTemplate() { base.OnApplyTemplate(); //lookup for content presenter (should always be there) this.presenter = this.Template.FindName("PART_Content", this) as ContentPresenter; if (!DesignerProperties.GetIsInDesignMode(this) && null != this.presenter && null == this.presenter.Content) { //setup bindings - datacontext and content may possibly change, so i want them beeing set via databinding Binding binding = new Binding(); binding.Source = this; this.presenter.SetBinding(ContentPresenter.ContentProperty, binding); binding = new Binding(); binding.Source = this; this.presenter.SetBinding(ContentPresenter.DataContextProperty, binding); this.presenter.ApplyTemplate(); } this.border = this.Template.FindName("PART_ShapeBorder", this) as Border; if (null != this.border) { this.border.MouseMove += OnBorderMouseMove; this.border.MouseDown += OnBorderMouseDown; this.border.MouseUp += OnBorderMouseUp; this.border.MouseLeave += OnBorderMouseLeave; } } static internal void RaiseWindowCloseEvent(ExtensionWindow sender) { ExtensionWindowClosingRoutedEventArgs args = new ExtensionWindowClosingRoutedEventArgs(ClosingEvent, sender); sender.RaiseEvent(args); if (!args.Cancel) { sender.RaiseEvent(new RoutedEventArgs(CloseEvent, sender)); } } void OnBorderMouseMove(object sender, MouseEventArgs e) { if (!this.border.IsMouseCaptured) { if (this.border.IsMouseDirectlyOver && this.IsResizable && ExtensionSurface.GetMode(this) == ExtensionSurface.PlacementMode.Absolute) { Point position = e.GetPosition(this.border); if (position.X <= BorderOffset && position.Y <= BorderOffset) { this.resizeOption = ResizeValues.TopLeft; Mouse.OverrideCursor = Cursors.SizeNWSE; } else if (position.X >= this.border.ActualWidth - BorderOffset && position.Y <= BorderOffset) { this.resizeOption = ResizeValues.TopRight; Mouse.OverrideCursor = Cursors.SizeNESW; } else if (position.X <= BorderOffset && position.Y >= this.border.ActualHeight - BorderOffset) { this.resizeOption = ResizeValues.BottomLeft; Mouse.OverrideCursor = Cursors.SizeNESW; } else if (position.X >= this.border.ActualWidth - BorderOffset && position.Y >= this.border.ActualHeight - BorderOffset) { this.resizeOption = ResizeValues.BottomRight; Mouse.OverrideCursor = Cursors.SizeNWSE; } else if (position.Y <= (BorderOffset / 2.0)) { this.resizeOption = ResizeValues.Top; Mouse.OverrideCursor = Cursors.SizeNS; } else if (position.Y >= this.border.ActualHeight - (BorderOffset / 2.0)) { this.resizeOption = ResizeValues.Bottom; Mouse.OverrideCursor = Cursors.SizeNS; } else if (position.X <= (BorderOffset / 2.0)) { this.resizeOption = ResizeValues.Left; Mouse.OverrideCursor = Cursors.SizeWE; } else if (position.X >= this.border.ActualWidth - (BorderOffset / 2.0)) { this.resizeOption = ResizeValues.Right; Mouse.OverrideCursor = Cursors.SizeWE; } else { Mouse.OverrideCursor = null; this.resizeOption = ResizeValues.NONE; } Point topLeft = ExtensionSurface.GetPosition(this); this.bottomRight = new Point(topLeft.X + Width, topLeft.Y + Height); } else if (Mouse.OverrideCursor != null) { Mouse.OverrideCursor = null; this.resizeOption = ResizeValues.NONE; } } else if (e.LeftButton == MouseButtonState.Pressed) { this.HandleWindowResize(); } } void OnBorderMouseDown(object sender, MouseButtonEventArgs e) { if (this.resizeOption != ResizeValues.NONE && sender == this.border) { Mouse.Capture(this.border); } } void OnBorderMouseUp(object sender, MouseButtonEventArgs e) { if (this.border.IsMouseCaptured) { Mouse.Capture(null); } } void OnBorderMouseLeave(object sender, MouseEventArgs e) { this.resizeOption = ResizeValues.NONE; Mouse.OverrideCursor = null; } void HandleWindowResize() { switch (this.resizeOption) { case ResizeValues.Top: CalculateSize(false, true, false, true); break; case ResizeValues.TopLeft: CalculateSize(true, true, true, true); break; case ResizeValues.Left: CalculateSize(true, false, true, false); break; case ResizeValues.BottomLeft: CalculateSize(true, false, true, true); break; case ResizeValues.TopRight: CalculateSize(false, true, true, true); break; case ResizeValues.Bottom: CalculateSize(false, false, false, true); break; case ResizeValues.Right: CalculateSize(false, false, true, false); break; case ResizeValues.BottomRight: CalculateSize(false, false, true, true); break; default: Fx.Assert("not supported resize option " + this.resizeOption); break; }; } void CalculateSize(bool changeX, bool changeY, bool changeWidth, bool changeHeight) { Point current = Mouse.GetPosition(this); Point absolutePosition = Mouse.GetPosition(this.surface); Point topLeft = ExtensionSurface.GetPosition(this); double initialHeight = this.bottomRight.Y - topLeft.Y; double initialWidth = this.bottomRight.X - topLeft.X; Size size = new Size(initialWidth, initialHeight); if (changeX) { if (bottomRight.X > absolutePosition.X) { if ((double.IsNaN(MinWidth) || double.IsInfinity(MinWidth) || bottomRight.X - absolutePosition.X >= MinWidth) && (double.IsNaN(MaxWidth) || double.IsInfinity(MaxWidth) || bottomRight.X - absolutePosition.X <= MaxWidth)) { size.Width = this.bottomRight.X - absolutePosition.X; topLeft.X = absolutePosition.X; } } } else { if (changeWidth) { size.Width = Math.Min(Math.Max(MinWidth, current.X), MaxWidth); } } if (changeY) { if (bottomRight.Y > absolutePosition.Y) { if ((double.IsNaN(MinHeight) || double.IsInfinity(MinHeight) || bottomRight.Y - absolutePosition.Y >= MinHeight) && (double.IsNaN(MaxHeight) || double.IsInfinity(MaxHeight) || bottomRight.Y - absolutePosition.Y <= MaxHeight)) { size.Height = this.bottomRight.Y - absolutePosition.Y; topLeft.Y = absolutePosition.Y; } } } else { if (changeHeight) { size.Height = Math.Min(Math.Max(MinHeight, current.Y), MaxHeight); } } if (changeX || changeY) { this.surface.SetWindowPosition(this, topLeft); } this.surface.SetSize(this, size); } protected override void OnKeyDown(KeyEventArgs e) { //if ESC - close me if (e.Key == Key.Escape) { RaiseWindowCloseEvent(this); } base.OnKeyDown(e); } protected override void OnMouseDown(MouseButtonEventArgs e) { base.OnMouseDown(e); this.SelectWindow(); } public void SelectWindow() { this.surface.SelectWindow(this); } void OnMenuItemsChanged(object sender, NotifyCollectionChangedEventArgs e) { if (null != e.NewItems) { foreach (MenuItem item in e.NewItems) { item.DataContext = this; } } } internal static bool TryGetParentExtensionWindow(FrameworkElement element, out ExtensionWindow window, out ExtensionSurface surface) { window = null; surface = null; if (null != element) { FrameworkElement current = element; window = element.TemplatedParent as ExtensionWindow; while (null == window && null != current) { window = current as ExtensionWindow; current = (FrameworkElement)current.Parent; } if (null != window) { current = window; surface = window.TemplatedParent as ExtensionSurface; while (null == surface && null != current) { surface = current as ExtensionSurface; current = (FrameworkElement)current.Parent; } } } return (null != window && null != surface); } enum ResizeValues { NONE, TopLeft, Left, BottomLeft, Bottom, BottomRight, Right, TopRight, Top, }; } }
// 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 Microsoft.Win32; namespace System.Diagnostics.Eventing.Reader { /// <summary> /// Log Type /// </summary> public enum EventLogType { Administrative = 0, Operational, Analytical, Debug } /// <summary> /// Log Isolation /// </summary> public enum EventLogIsolation { Application = 0, System, Custom } /// <summary> /// Log Mode /// </summary> public enum EventLogMode { Circular = 0, AutoBackup, Retain } /// <summary> /// Provides access to static log information and configures /// log publishing and log file properties. /// </summary> public class EventLogConfiguration : IDisposable { private readonly EventLogHandle _handle = EventLogHandle.Zero; private readonly EventLogSession _session = null; public EventLogConfiguration(string logName) : this(logName, null) { } public EventLogConfiguration(string logName, EventLogSession session) { if (session == null) session = EventLogSession.GlobalSession; _session = session; LogName = logName; _handle = NativeWrapper.EvtOpenChannelConfig(_session.Handle, LogName, 0); } public string LogName { get; } public EventLogType LogType { get { return (EventLogType)((uint)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigType)); } } public EventLogIsolation LogIsolation { get { return (EventLogIsolation)((uint)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigIsolation)); } } public bool IsEnabled { get { return (bool)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigEnabled); } set { NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigEnabled, (object)value); } } public bool IsClassicLog { get { return (bool)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigClassicEventlog); } } public string SecurityDescriptor { get { return (string)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigAccess); } set { NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigAccess, (object)value); } } public string LogFilePath { get { return (string)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigLogFilePath); } set { NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigLogFilePath, (object)value); } } public long MaximumSizeInBytes { get { return (long)((ulong)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigMaxSize)); } set { NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigMaxSize, (object)value); } } public EventLogMode LogMode { get { object nativeRetentionObject = NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention); object nativeAutoBackupObject = NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup); bool nativeRetention = nativeRetentionObject == null ? false : (bool)nativeRetentionObject; bool nativeAutoBackup = nativeAutoBackupObject == null ? false : (bool)nativeAutoBackupObject; if (nativeAutoBackup) return EventLogMode.AutoBackup; if (nativeRetention) return EventLogMode.Retain; return EventLogMode.Circular; } set { switch (value) { case EventLogMode.Circular: NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup, (object)false); NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention, (object)false); break; case EventLogMode.AutoBackup: NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup, (object)true); NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention, (object)true); break; case EventLogMode.Retain: NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigAutoBackup, (object)false); NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelLoggingConfigRetention, (object)true); break; } } } public string OwningProviderName { get { return (string)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelConfigOwningPublisher); } } public IEnumerable<string> ProviderNames { get { return (string[])NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublisherList); } } public int? ProviderLevel { get { return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLevel)); } set { NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLevel, (object)value); } } public long? ProviderKeywords { get { return (long?)((ulong?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigKeywords)); } set { NativeWrapper.EvtSetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigKeywords, (object)value); } } public int? ProviderBufferSize { get { return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigBufferSize)); } } public int? ProviderMinimumNumberOfBuffers { get { return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigMinBuffers)); } } public int? ProviderMaximumNumberOfBuffers { get { return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigMaxBuffers)); } } public int? ProviderLatency { get { return (int?)((uint?)NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigLatency)); } } public Guid? ProviderControlGuid { get { return (Guid?)(NativeWrapper.EvtGetChannelConfigProperty(_handle, UnsafeNativeMethods.EvtChannelConfigPropertyId.EvtChannelPublishingConfigControlGuid)); } } public void SaveChanges() { NativeWrapper.EvtSaveChannelConfig(_handle, 0); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (_handle != null && !_handle.IsInvalid) _handle.Dispose(); } } }
using Geofence.Plugin.Abstractions; using System; using System.Collections.Generic; using Android.Util; using Android.Gms.Common.Apis; using Android.Gms.Common; using Android.App; using Android.Content; using Android.OS; using System.Linq; using Android.Support.V4.App; using Android.Media; using Java.Lang; using Android.Text; using System.Runtime.Remoting.Messaging; using Java.Interop; using System.Collections.ObjectModel; using Android.Gms.Location; using Android; using Android.Content.PM; using Android.Gms.Tasks; namespace Geofence.Plugin { /// <summary> /// Implementation for Feature /// </summary> /// public class GeofenceImplementation : Java.Lang.Object, Geofence.Plugin.Abstractions.IGeofence, IResultCallback, Android.Gms.Tasks.IOnCompleteListener, GoogleApiClient.IConnectionCallbacks, GoogleApiClient.IOnConnectionFailedListener { public int REQUEST_PERMISSIONS_REQUEST_CODE = 101; private Dictionary<string,GeofenceCircularRegion> mRegions = GeofenceStore.SharedInstance.GetAll(); private Dictionary<string, GeofenceResult> mGeofenceResults = new Dictionary<string, GeofenceResult>(); private GeofenceLocation mLastKnownGeofenceLocation; private PendingIntent mGeofencePendingIntent = null; private GoogleApiClient mGoogleApiClient; private GeofencingClient mGeofencingClient; private IList<Android.Gms.Location.IGeofence> mGeofenceList; private LocationRequest mLocationRequest; private FusedLocationProviderClient mFusedLocationProviderClient; // Defines the allowable request types internal enum RequestType { Add, Update, Delete, Clear, Default } /// <summary> /// Get all regions been monitored /// </summary> public IReadOnlyDictionary<string, GeofenceCircularRegion> Regions { get { return mRegions; } } /// <summary> /// Get geofence state change results. /// </summary> public IReadOnlyDictionary<string, GeofenceResult> GeofenceResults { get { return mGeofenceResults; } } private IList<string> mRequestedRegionIdentifiers; /// <summary> /// Get last known location /// </summary> public GeofenceLocation LastKnownLocation { get { return mLastKnownGeofenceLocation; } } internal RequestType CurrentRequestType { get; set; } /// <summary> /// Checks if region are been monitored /// </summary> public bool IsMonitoring { get { return mRegions.Count > 0; } } /// <summary> /// Gets or sets a value indicating whether this <see cref="Geofence.Plugin.GeofenceImplementation"/> location has error. /// </summary> /// <value><c>true</c> if location has error; otherwise, <c>false</c>.</value> public bool LocationHasError { get; set; } public bool RequestNotificationPermission { get; set; } public bool RequestLocationPermission { get; set; } public static object Lock { get; private set; } = new object(); //IsMonitoring?RequestType.Add: private PendingIntent GeofenceTransitionPendingIntent { // New geofence intent for Android O: // https://stackoverflow.com/questions/50564251/geofencing-doesnt-work-with-jonintentservice-anymore // https://developer.android.com/training/location/geofencing get { if (mGeofencePendingIntent != null) { return mGeofencePendingIntent; } var intent = new Intent(Application.Context, typeof(GeofenceTransitionsIntentService)); System.Diagnostics.Debug.WriteLine("Returning intent"); mGeofencePendingIntent = PendingIntent.GetService(Application.Context, 0, intent, PendingIntentFlags.UpdateCurrent); return mGeofencePendingIntent; } } /// <summary> /// Android Geofence plugin implementation /// </summary> public GeofenceImplementation() { if (!CheckPermissions()) { RequestPermissions(); } //Check if location services are enabled IsLocationEnabled((bool locationIsEnabled) => { if(locationIsEnabled) { CurrentRequestType = RequestType.Default; if(IsMonitoring) { StartMonitoring(Regions.Values.ToList()); System.Diagnostics.Debug.WriteLine(string.Format("{0} - {1}", CrossGeofence.Id, "Monitoring was restored")); } } else { string message = string.Format("{0} - {1}", CrossGeofence.Id, "You need to enabled Location Services"); System.Diagnostics.Debug.WriteLine(message); CrossGeofence.GeofenceListener.OnError(message); } }); } public void IsLocationEnabled(Action<bool> returnAction) { InitializeGoogleAPI(); if(mGoogleApiClient == null || CheckPermissions() == false) { returnAction(false); return; } mFusedLocationProviderClient = LocationServices.GetFusedLocationProviderClient(Android.App.Application.Context); mGeofencingClient = LocationServices.GetGeofencingClient(Application.Context); mGeofenceList = new List<Android.Gms.Location.IGeofence>(); var locationRequestPriority = LocationRequest.PriorityBalancedPowerAccuracy; switch (CrossGeofence.GeofencePriority) { case GeofencePriority.HighAccuracy: locationRequestPriority = LocationRequest.PriorityHighAccuracy; break; case GeofencePriority.LowAccuracy: locationRequestPriority = LocationRequest.PriorityLowPower; break; case GeofencePriority.LowestAccuracy: locationRequestPriority = LocationRequest.PriorityNoPower; break; } mLocationRequest = new LocationRequest(); mLocationRequest.SetPriority(locationRequestPriority); mLocationRequest.SetInterval(CrossGeofence.LocationUpdatesInterval); mLocationRequest.SetFastestInterval(CrossGeofence.FastestLocationUpdatesInterval); LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().AddLocationRequest(mLocationRequest); var pendingResult = LocationServices.SettingsApi.CheckLocationSettings(mGoogleApiClient, builder.Build()); pendingResult.SetResultCallback((LocationSettingsResult locationSettingsResult) => { if (locationSettingsResult != null) { returnAction(locationSettingsResult.Status.StatusCode <= CommonStatusCodes.Success); } }); System.Diagnostics.Debug.WriteLine("End of IsLocationEnabled, clients should be created"); } /// <summary> /// Starts monitoring specified region /// </summary> /// <param name="region"></param> public void StartMonitoring(GeofenceCircularRegion region) { lock (Lock) { if (IsMonitoring) { mGeofencingClient.RemoveGeofences(GeofenceTransitionPendingIntent).AddOnCompleteListener(this); } if (!mRegions.ContainsKey(region.Id)) { mRegions.Add(region.Id, region); } } RequestMonitoringStart(); } void RequestMonitoringStart() { //If connected to google play services then add regions if (mGoogleApiClient.IsConnected) { AddGeofences(); } else { //If not connection then connect if (!mGoogleApiClient.IsConnecting) { mGoogleApiClient.Connect(); } //Request to add geofence regions once connected CurrentRequestType = RequestType.Add; } } /// <summary> /// Starts geofence monitoring on specified regions /// </summary> /// <param name="regions"></param> public void StartMonitoring(IList<GeofenceCircularRegion> regions) { lock (Lock) { if (IsMonitoring) { mGeofencingClient.RemoveGeofences(GeofenceTransitionPendingIntent).AddOnCompleteListener(this); } foreach (var region in regions) { if (!mRegions.ContainsKey(region.Id)) { mRegions.Add(region.Id, region); } } RequestMonitoringStart(); } System.Diagnostics.Debug.WriteLine("Monitoring has begun"); } internal void AddGeofenceResult(string identifier) { mGeofenceResults.Add(identifier, new GeofenceResult() { RegionId = identifier, Transition = GeofenceTransition.Unknown }); } /// <summary> /// Adds geofences using Android's geofence client. /// </summary> public void AddGeofences() { try { // Operate on copy of regions to reduce scope of lock var regionsClone = new List<GeofenceCircularRegion>(); lock (Lock) foreach (var region in Regions.Values) { System.Diagnostics.Debug.WriteLine("Here is region " + region.Id); regionsClone.Add(new GeofenceCircularRegion(region)); if (GeofenceStore.SharedInstance.Get(region.Id) == null) GeofenceStore.SharedInstance.Save(region); } mGeofenceList.Clear(); foreach (GeofenceCircularRegion region in regionsClone) { int transitionTypes = 0; if (region.NotifyOnStay) { transitionTypes |= Android.Gms.Location.Geofence.GeofenceTransitionDwell; } if (region.NotifyOnEntry) { transitionTypes |= Android.Gms.Location.Geofence.GeofenceTransitionEnter; } if (region.NotifyOnExit) { transitionTypes |= Android.Gms.Location.Geofence.GeofenceTransitionExit; } if (transitionTypes != 0) { mGeofenceList.Add(new Android.Gms.Location.GeofenceBuilder() .SetRequestId(region.Id) .SetCircularRegion(region.Latitude, region.Longitude, (float)region.Radius) .SetLoiteringDelay((int)region.StayedInThresholdDuration.TotalMilliseconds) //.SetNotificationResponsiveness(mNotificationResponsivness) .SetExpirationDuration(Android.Gms.Location.Geofence.NeverExpire) .SetTransitionTypes(transitionTypes) .Build()); CrossGeofence.GeofenceListener.OnMonitoringStarted(region.Id); } } System.Diagnostics.Debug.WriteLine("Add geofences"); if (mGeofenceList.Count > 0) { mGeofencingClient.AddGeofences(GetGeofencingRequest(mGeofenceList), GeofenceTransitionPendingIntent).AddOnCompleteListener(this); CurrentRequestType = RequestType.Default; } } catch (Java.Lang.Exception ex1) { string message = string.Format("{0} - Error: {1}", CrossGeofence.Id, ex1.ToString()); System.Diagnostics.Debug.WriteLine(message); CrossGeofence.GeofenceListener.OnError(message); } catch (System.Exception ex2) { string message = string.Format("{0} - Error: {1}", CrossGeofence.Id, ex2.ToString()); System.Diagnostics.Debug.WriteLine(message); CrossGeofence.GeofenceListener.OnError(message); } } private GeofencingRequest GetGeofencingRequest(IList<Android.Gms.Location.IGeofence> geofenceList) { GeofencingRequest.Builder builder = new GeofencingRequest.Builder(); builder.SetInitialTrigger(GeofencingRequest.InitialTriggerEnter); builder.AddGeofences(geofenceList); System.Diagnostics.Debug.WriteLine("Request"); return builder.Build(); } /// <summary> /// Stops monitoring a specific geofence region /// </summary> /// <param name="regionIdentifier"></param> public void StopMonitoring(string regionIdentifier) { StopMonitoring(new List<string>() { regionIdentifier }); } internal void OnMonitoringRemoval() { if (mRegions.Count == 0) { CrossGeofence.GeofenceListener.OnMonitoringStopped(); StopLocationUpdates(); mGoogleApiClient.Disconnect(); } } private void RemoveGeofences(IList<string> regionIdentifiers) { foreach (string identifier in regionIdentifiers) { //Remove this region from regions dictionary and results RemoveRegion(identifier); //Remove from persistent store GeofenceStore.SharedInstance.Remove(identifier); //Notify monitoring was stopped CrossGeofence.GeofenceListener.OnMonitoringStopped(identifier); } //Stop Monitoring if (regionIdentifiers.Count > 0) mGeofencingClient.RemoveGeofences(regionIdentifiers).AddOnCompleteListener(this); //Check if there are still regions OnMonitoringRemoval(); System.Diagnostics.Debug.WriteLine("Removed specific regions"); } /// <summary> /// Stops monitoring specified geofence regions /// </summary> public void StopMonitoring(IList<string> regionIdentifiers) { mRequestedRegionIdentifiers = new List<string>(); ((List<string>)mRequestedRegionIdentifiers).AddRange(regionIdentifiers); if (IsMonitoring) { RemoveGeofences(mRequestedRegionIdentifiers); } else { //If not connection then connect if (!mGoogleApiClient.IsConnecting) { mGoogleApiClient.Connect(); } //Request to add geofence regions once connected CurrentRequestType = RequestType.Delete; } // } /// <summary> /// Stops monitoring all geofence regions /// </summary> public void StopMonitoringAllRegions() { if (IsMonitoring && mGoogleApiClient.IsConnected) { RemoveGeofences(); } else { //If not connection then connect if (!mGoogleApiClient.IsConnecting) { mGoogleApiClient.Connect(); } //Request to add geofence regions once connected CurrentRequestType = RequestType.Clear; } } private void RemoveGeofences() { lock (Lock) { GeofenceStore.SharedInstance.RemoveAll(); mRegions.Clear(); mGeofenceResults.Clear(); StopLocationUpdates(); IList<string> regionIds = mRegions.Select(r => r.Key).ToList(); if (regionIds.Count > 0) mGeofencingClient.RemoveGeofences(regionIds).AddOnCompleteListener(this); mGoogleApiClient.Disconnect(); } System.Diagnostics.Debug.WriteLine("Cleared the geofences"); CrossGeofence.GeofenceListener.OnMonitoringStopped(); } private void InitializeGoogleAPI() { int queryResult = GoogleApiAvailability.Instance.IsGooglePlayServicesAvailable(Android.App.Application.Context); if (queryResult == ConnectionResult.Success) { if (mGoogleApiClient == null) { mGoogleApiClient = new GoogleApiClient.Builder(Android.App.Application.Context).AddApi(Android.Gms.Location.LocationServices.API).AddConnectionCallbacks(this).AddOnConnectionFailedListener(this).Build(); string message = string.Format("{0} - {1}", CrossGeofence.Id, "Google Play services is available."); System.Diagnostics.Debug.WriteLine(message); } if (!mGoogleApiClient.IsConnected) { mGoogleApiClient.Connect(); } } else { string message = string.Format("{0} - {1}", CrossGeofence.Id, "Google Play services is unavailable."); System.Diagnostics.Debug.WriteLine(message); CrossGeofence.GeofenceListener.OnError(message); } } /// <summary> /// Google play connection failed handling /// </summary> /// <param name="result"></param> public void OnConnectionFailed(Android.Gms.Common.ConnectionResult result) { int errorCode = result.ErrorCode; string message = string.Format("{0} - {1} {2}", CrossGeofence.Id, "Connection to Google Play services failed with error code ", errorCode); System.Diagnostics.Debug.WriteLine(message); CrossGeofence.GeofenceListener.OnError(message); } internal void SetLastKnownLocation(Android.Locations.Location location) { if (location != null) { GeofenceLocation eventLoc; lock (Lock) { if (mLastKnownGeofenceLocation == null) { mLastKnownGeofenceLocation = new GeofenceLocation(); } mLastKnownGeofenceLocation.Latitude = location.Latitude; mLastKnownGeofenceLocation.Longitude = location.Longitude; double seconds = location.Time / 1000; mLastKnownGeofenceLocation.Date = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Local).AddSeconds(seconds); mLastKnownGeofenceLocation.Accuracy = location.Accuracy; eventLoc = new GeofenceLocation(mLastKnownGeofenceLocation); } CrossGeofence.GeofenceListener.OnLocationChanged(eventLoc); } System.Diagnostics.Debug.WriteLine("Setting last location"); } /// <summary> /// On Google play services Connection handling /// </summary> /// <param name="connectionHint"></param> async public void OnConnected(Bundle connectionHint) { Android.Locations.Location location = await mFusedLocationProviderClient.GetLastLocationAsync(); SetLastKnownLocation(location); if (CurrentRequestType == RequestType.Add) { AddGeofences(); StartLocationUpdates(); } else if (CurrentRequestType == RequestType.Clear) { RemoveGeofences(); } else if (CurrentRequestType == RequestType.Delete) { if (mRequestedRegionIdentifiers != null) { RemoveGeofences(mRequestedRegionIdentifiers); } } CurrentRequestType = RequestType.Default; System.Diagnostics.Debug.WriteLine("Connection obtained, starting service"); } /// <summary> /// On Geofence Request Result /// </summary> /// <param name="result"></param> public void OnResult(Java.Lang.Object result) { var res = result.JavaCast<IResult>(); int statusCode = res.Status.StatusCode; string message = string.Empty; switch (res.Status.StatusCode) { case Android.Gms.Location.GeofenceStatusCodes.SuccessCache: case Android.Gms.Location.GeofenceStatusCodes.Success: if (CurrentRequestType == RequestType.Add) { message = string.Format("{0} - {1}", CrossGeofence.Id, "Successfully added Geofence."); foreach (GeofenceCircularRegion region in Regions.Values) { CrossGeofence.GeofenceListener.OnMonitoringStarted(region.Id); } } else { message = string.Format("{0} - {1}", CrossGeofence.Id, "Geofence Update Received"); } break; case Android.Gms.Location.GeofenceStatusCodes.Error: message = string.Format("{0} - {1}", CrossGeofence.Id, "Error adding Geofence."); break; case Android.Gms.Location.GeofenceStatusCodes.GeofenceTooManyGeofences: message = string.Format("{0} - {1}", CrossGeofence.Id, "Too many geofences."); break; case Android.Gms.Location.GeofenceStatusCodes.GeofenceTooManyPendingIntents: message = string.Format("{0} - {1}", CrossGeofence.Id, "Too many pending intents."); break; case Android.Gms.Location.GeofenceStatusCodes.GeofenceNotAvailable: message = string.Format("{0} - {1}", CrossGeofence.Id, "Geofence not available."); break; } System.Diagnostics.Debug.WriteLine(message); if (statusCode != Android.Gms.Location.GeofenceStatusCodes.Success && statusCode != Android.Gms.Location.GeofenceStatusCodes.SuccessCache && IsMonitoring) { // Rather than force killing all running geofences, delegate action on geofence failures to the application. // This lets the application decide to ignore the error, perform retry logic, stop monitoring as below, or any other behavior. // StopMonitoringAllRegions(); ((GeofenceImplementation)CrossGeofence.Current).LocationHasError = true; if (!string.IsNullOrEmpty(message)) CrossGeofence.GeofenceListener.OnError(message); } } /// <summary> /// Connection suspended handling /// </summary> /// <param name="cause"></param> public void OnConnectionSuspended(int cause) { string message = string.Format("{0} - {1} {2}", CrossGeofence.Id, "Connection to Google Play services suspended with error code ", cause); System.Diagnostics.Debug.WriteLine(message); CrossGeofence.GeofenceListener.OnError(message); } private void RemoveRegion(string regionIdentifier) { lock (Lock) { if (mRegions.ContainsKey(regionIdentifier)) { mRegions.Remove(regionIdentifier); } if (mGeofenceResults.ContainsKey(regionIdentifier)) { mGeofenceResults.Remove(regionIdentifier); } } System.Diagnostics.Debug.WriteLine("Removed a region"); } internal void StartLocationUpdates() { Android.Gms.Location.LocationRequest mLocationRequest = new Android.Gms.Location.LocationRequest(); mLocationRequest.SetInterval(CrossGeofence.LocationUpdatesInterval == 0 ? 30000 : CrossGeofence.LocationUpdatesInterval); mLocationRequest.SetFastestInterval(CrossGeofence.FastestLocationUpdatesInterval == 0 ? 5000 : CrossGeofence.FastestLocationUpdatesInterval); string priorityType = "Balanced Power"; switch (CrossGeofence.GeofencePriority) { case GeofencePriority.HighAccuracy: priorityType = "High Accuracy"; mLocationRequest.SetPriority(Android.Gms.Location.LocationRequest.PriorityHighAccuracy); break; case GeofencePriority.LowAccuracy: priorityType = "Low Accuracy"; mLocationRequest.SetPriority(Android.Gms.Location.LocationRequest.PriorityLowPower); break; case GeofencePriority.LowestAccuracy: priorityType = "Lowest Accuracy"; mLocationRequest.SetPriority(Android.Gms.Location.LocationRequest.PriorityNoPower); break; case GeofencePriority.MediumAccuracy: case GeofencePriority.AcceptableAccuracy: default: mLocationRequest.SetPriority(Android.Gms.Location.LocationRequest.PriorityBalancedPowerAccuracy); break; } System.Diagnostics.Debug.WriteLine(string.Format("{0} - {1}: {2}", CrossGeofence.Id, "Priority set to", priorityType)); //(Regions.Count == 0) ? (CrossGeofence.SmallestDisplacement==0?50 :CrossGeofence.SmallestDisplacement): Regions.Min(s => (float)s.Value.Radius) if (CrossGeofence.SmallestDisplacement > 0) { mLocationRequest.SetSmallestDisplacement(CrossGeofence.SmallestDisplacement); System.Diagnostics.Debug.WriteLine(string.Format("{0} - {1}: {2} meters", CrossGeofence.Id, "Location smallest displacement set to", CrossGeofence.SmallestDisplacement)); } try { mFusedLocationProviderClient.RequestLocationUpdatesAsync(this.mLocationRequest, GeofenceLocationListener.SharedInstance); } catch(System.Exception e) { // Do not crash the app if permissions are disabled on Android Marshmallow System.Diagnostics.Debug.WriteLine(e.Message); CrossGeofence.GeofenceListener.OnError(e.Message); } } internal void StopLocationUpdates() { mFusedLocationProviderClient.RemoveLocationUpdates(GeofenceLocationListener.SharedInstance); } private bool CheckPermissions() { if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.M) { var permissionState = Application.Context.CheckSelfPermission(Manifest.Permission.AccessFineLocation); System.Diagnostics.Debug.WriteLine("Checking permissions"); return permissionState == (int)Permission.Granted; } else return true; } private void RequestPermissions() { ActivityCompat.RequestPermissions((Activity) Application.Context, new[] { Manifest.Permission.AccessFineLocation }, REQUEST_PERMISSIONS_REQUEST_CODE); System.Diagnostics.Debug.WriteLine("Requesting permissions"); } public void OnComplete(Task task) { CurrentRequestType = RequestType.Default; System.Diagnostics.Debug.WriteLine("Completed request"); } } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Messages.Messages File: Level1ChangeMessage.cs Created: 2015, 11, 11, 2:32 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Messages { using System; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Runtime.Serialization; using Ecng.Common; using StockSharp.Localization; /// <summary> /// Level1 fields of market-data. /// </summary> [DataContract] [Serializable] public enum Level1Fields { /// <summary> /// Opening price. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str79Key)] OpenPrice, /// <summary> /// Highest price. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str287Key)] HighPrice, /// <summary> /// Lowest price. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str288Key)] LowPrice, /// <summary> /// Closing price. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.ClosingPriceKey)] ClosePrice, /// <summary> /// Last trade. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str289Key)] [Obsolete] LastTrade, /// <summary> /// Step price. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str290Key)] StepPrice, /// <summary> /// Best bid. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str291Key)] [Obsolete] BestBid, /// <summary> /// Best ask. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str292Key)] [Obsolete] BestAsk, /// <summary> /// Volatility (implied). /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str293Key)] ImpliedVolatility, /// <summary> /// Theoretical price. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str294Key)] TheorPrice, /// <summary> /// Open interest. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str150Key)] OpenInterest, /// <summary> /// Price (min). /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.PriceMinKey)] MinPrice, /// <summary> /// Price (max). /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.PriceMaxKey)] MaxPrice, /// <summary> /// Bids volume. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str295Key)] BidsVolume, /// <summary> /// Number of bids. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str296Key)] BidsCount, /// <summary> /// Ask volume. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str297Key)] AsksVolume, /// <summary> /// Number of asks. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str298Key)] AsksCount, /// <summary> /// Volatility (historical). /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str299Key)] HistoricalVolatility, /// <summary> /// Delta. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.DeltaKey)] Delta, /// <summary> /// Gamma. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.GammaKey)] Gamma, /// <summary> /// Vega. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.VegaKey)] Vega, /// <summary> /// Theta. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.ThetaKey)] Theta, /// <summary> /// Initial margin to buy. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str304Key)] MarginBuy, /// <summary> /// Initial margin to sell. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str305Key)] MarginSell, /// <summary> /// Minimum price step. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str306Key)] PriceStep, /// <summary> /// Minimum volume step. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str307Key)] VolumeStep, /// <summary> /// Extended information. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.ExtendedInfoKey)] [Obsolete] ExtensionInfo, /// <summary> /// State. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.StateKey)] State, /// <summary> /// Last trade price. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str308Key)] LastTradePrice, /// <summary> /// Last trade volume. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str309Key)] LastTradeVolume, /// <summary> /// Volume per session. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str310Key)] Volume, /// <summary> /// Average price per session. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str311Key)] AveragePrice, /// <summary> /// Settlement price. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str312Key)] SettlementPrice, /// <summary> /// Change,%. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.ChangeKey)] Change, /// <summary> /// Best bid price. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str313Key)] BestBidPrice, /// <summary> /// Best buy volume. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str314Key)] BestBidVolume, /// <summary> /// Best ask price. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str315Key)] BestAskPrice, /// <summary> /// Best sell volume. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str316Key)] BestAskVolume, /// <summary> /// Rho. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.RhoKey)] Rho, /// <summary> /// Accrued coupon income (ACI). /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str318Key)] AccruedCouponIncome, /// <summary> /// Maximum bid during the session. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str319Key)] HighBidPrice, /// <summary> /// Minimum ask during the session. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str320Key)] LowAskPrice, /// <summary> /// Yield. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str321Key)] Yield, /// <summary> /// Time of last trade. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str322Key)] LastTradeTime, /// <summary> /// Number of trades. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.NumOfTradesKey)] TradesCount, /// <summary> /// Average price. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.AveragePriceKey)] VWAP, /// <summary> /// Last trade ID. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str325Key)] LastTradeId, /// <summary> /// Best bid time. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str326Key)] BestBidTime, /// <summary> /// Best ask time. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str327Key)] BestAskTime, /// <summary> /// Is tick ascending or descending in price. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str328Key)] LastTradeUpDown, /// <summary> /// Initiator of the last trade (buyer or seller). /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str329Key)] LastTradeOrigin, /// <summary> /// Lot multiplier. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str330Key)] Multiplier, /// <summary> /// Price/profit. /// </summary> [EnumMember] [Display(Name = "P/E")] PriceEarnings, /// <summary> /// Price target/profit. /// </summary> [EnumMember] [Display(Name = "Forward P/E")] ForwardPriceEarnings, /// <summary> /// Price/profit (increase). /// </summary> [EnumMember] [Display(Name = "PEG")] PriceEarningsGrowth, /// <summary> /// Price/buy. /// </summary> [EnumMember] [Display(Name = "P/S")] PriceSales, /// <summary> /// Price/sell. /// </summary> [EnumMember] [Display(Name = "P/B")] PriceBook, /// <summary> /// Price/amount. /// </summary> [EnumMember] [Display(Name = "P/CF")] PriceCash, /// <summary> /// Price/amount (free). /// </summary> [EnumMember] [Display(Name = "P/FCF")] PriceFreeCash, /// <summary> /// Payments. /// </summary> [EnumMember] [Display(Name = "Payout")] Payout, /// <summary> /// Number of shares. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str331Key)] SharesOutstanding, /// <summary> /// Shares Float. /// </summary> [EnumMember] [Display(Name = "Shares Float")] SharesFloat, /// <summary> /// Float Short. /// </summary> [EnumMember] [Display(Name = "Float Short")] FloatShort, /// <summary> /// Short. /// </summary> [EnumMember] [Display(Name = "Short")] ShortRatio, /// <summary> /// Return on assets. /// </summary> [EnumMember] [Display(Name = "ROA")] ReturnOnAssets, /// <summary> /// Return on equity. /// </summary> [EnumMember] [Display(Name = "ROE")] ReturnOnEquity, /// <summary> /// Return on investment. /// </summary> [EnumMember] [Display(Name = "ROI")] ReturnOnInvestment, /// <summary> /// Liquidity (current). /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str332Key)] CurrentRatio, /// <summary> /// Liquidity (instantaneous). /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str333Key)] QuickRatio, /// <summary> /// Capital (long-term debt). /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str334Key)] LongTermDebtEquity, /// <summary> /// Capital (debt). /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str335Key)] TotalDebtEquity, /// <summary> /// Assets margin (gross). /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str336Key)] GrossMargin, /// <summary> /// Assets margin. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str337Key)] OperatingMargin, /// <summary> /// Profit margin. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str338Key)] ProfitMargin, /// <summary> /// Beta. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.BetaKey)] Beta, /// <summary> /// ATR. /// </summary> [EnumMember] [Display(Name = "ATR")] AverageTrueRange, /// <summary> /// Volatility (week). /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str340Key)] HistoricalVolatilityWeek, /// <summary> /// Volatility (month). /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str341Key)] HistoricalVolatilityMonth, /// <summary> /// System info. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.Str342Key)] IsSystem, /// <summary> /// Number of digits in price after coma. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.DecimalsKey)] Decimals, /// <summary> /// Duration. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.DurationKey)] Duration, /// <summary> /// Number of issued contracts. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.IssueSizeKey)] IssueSize, /// <summary> /// BuyBack date. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.BuyBackDateKey)] BuyBackDate, /// <summary> /// BuyBack price. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.BuyBackPriceKey)] BuyBackPrice, /// <summary> /// Turnover. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.TurnoverKey)] Turnover, /// <summary> /// The middle of spread. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.SpreadKey)] SpreadMiddle, /// <summary> /// The dividend amount on shares. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.DividendKey)] Dividend, /// <summary> /// Price after split. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.AfterSplitKey)] AfterSplit, /// <summary> /// Price before split. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.BeforeSplitKey)] BeforeSplit, /// <summary> /// Commission (taker). /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.CommissionTakerKey)] CommissionTaker, /// <summary> /// Commission (maker). /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.CommissionMakerKey)] CommissionMaker, /// <summary> /// Minimum volume allowed in order. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.MinVolumeKey)] MinVolume, /// <summary> /// Minimum volume allowed in order for underlying security. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.UnderlyingMinVolumeKey)] UnderlyingMinVolume, /// <summary> /// Coupon value. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.CouponValueKey)] CouponValue, /// <summary> /// Coupon date. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.CouponDateKey)] CouponDate, /// <summary> /// Coupon period. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.CouponPeriodKey)] CouponPeriod, /// <summary> /// Market price (yesterday). /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.MarketPriceYesterdayKey)] MarketPriceYesterday, /// <summary> /// Market price (today). /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.MarketPriceTodayKey)] MarketPriceToday, /// <summary> /// VWAP (prev). /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.VWAPPrevKey)] VWAPPrev, /// <summary> /// Yield by VWAP. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.YieldVWAPKey)] YieldVWAP, /// <summary> /// Yield by VWAP (prev). /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.YieldVWAPPrevKey)] YieldVWAPPrev, /// <summary> /// Index. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.IndexKey)] Index, /// <summary> /// Imbalance. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.ImbalanceKey)] Imbalance, /// <summary> /// Underlying price. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.UnderlyingKey)] UnderlyingPrice, /// <summary> /// Maximum volume allowed in order. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.MaxVolumeKey)] MaxVolume, /// <summary> /// Lowest bid during the session. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.LowBidPriceKey, Description = LocalizedStrings.LowBidPriceDescKey)] LowBidPrice, /// <summary> /// Highest ask during the session. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.HighAskPriceKey, Description = LocalizedStrings.HighAskPriceDescKey)] HighAskPrice, /// <summary> /// Lowest last trade volume. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.LastTradeVolumeLowKey, Description = LocalizedStrings.LastTradeVolumeLowDescKey)] LastTradeVolumeLow, /// <summary> /// Highest last trade volume. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.LastTradeVolumeHighKey, Description = LocalizedStrings.LastTradeVolumeHighDescKey)] LastTradeVolumeHigh, /// <summary> /// Option margin leverage. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.OptionMarginKey, Description = LocalizedStrings.OptionMarginDescKey)] OptionMargin, /// <summary> /// Synthetic option position margin leverage. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.OptionSyntheticMarginKey, Description = LocalizedStrings.OptionSyntheticMarginDescKey)] OptionSyntheticMargin, /// <summary> /// Volume of the lowest bid. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.LowBidVolumeKey, Description = LocalizedStrings.LowBidVolumeDescKey)] LowBidVolume, /// <summary> /// Volume of the highest ask. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.HighAskVolumeKey, Description = LocalizedStrings.HighAskVolumeDescKey)] HighAskVolume, /// <summary> /// Underlying asset best bid price. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.UnderlyingBestBidPriceKey, Description = LocalizedStrings.UnderlyingBestBidPriceDescKey)] UnderlyingBestBidPrice, /// <summary> /// Underlying asset best ask price. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.UnderlyingBestAskPriceKey, Description = LocalizedStrings.UnderlyingBestAskPriceDescKey)] UnderlyingBestAskPrice, /// <summary> /// Median price. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.MedianKey, Description = LocalizedStrings.Str745Key)] MedianPrice, /// <summary> /// The highest price for 52 weeks. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.HighPrice52WeekKey, Description = LocalizedStrings.HighPrice52WeekDescKey)] HighPrice52Week, /// <summary> /// The lowest price for 52 weeks. /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.LowPrice52WeekKey, Description = LocalizedStrings.LowPrice52WeekDescKey)] LowPrice52Week, /// <summary> /// Last trade ID (string). /// </summary> [EnumMember] [Display(ResourceType = typeof(LocalizedStrings), Name = LocalizedStrings.LastTradeStringIdKey, Description = LocalizedStrings.LastTradeStringIdDescKey)] LastTradeStringId, } /// <summary> /// The message containing the level1 market data. /// </summary> [DataContract] [Serializable] [DisplayNameLoc(LocalizedStrings.Level1Key)] [DescriptionLoc(LocalizedStrings.Level1MarketDataKey)] public class Level1ChangeMessage : BaseChangeMessage<Level1ChangeMessage, Level1Fields>, ISecurityIdMessage, ISeqNumMessage { /// <inheritdoc /> [DataMember] [DisplayNameLoc(LocalizedStrings.SecurityKey)] [DescriptionLoc(LocalizedStrings.SecurityIdKey, true)] [MainCategory] public SecurityId SecurityId { get; set; } /// <inheritdoc /> [DataMember] public long SeqNum { get; set; } /// <inheritdoc /> public override DataType DataType => DataType.Level1; /// <summary> /// Initializes a new instance of the <see cref="Level1ChangeMessage"/>. /// </summary> public Level1ChangeMessage() : base(MessageTypes.Level1Change) { } /// <inheritdoc /> public override void CopyTo(Level1ChangeMessage destination) { base.CopyTo(destination); destination.SecurityId = SecurityId; destination.SeqNum = SeqNum; } /// <inheritdoc /> public override string ToString() { var str = base.ToString() + $",Sec={SecurityId},Changes={Changes.Select(c => c.ToString()).JoinComma()}"; if (SeqNum != default) str += $",SQ={SeqNum}"; return str; } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using Vanara.PInvoke; using static Vanara.PInvoke.BITS; namespace Vanara.IO { /// <summary>Manages the set of files for a background copy job.</summary> public class BackgroundCopyFileCollection : ICollection<BackgroundCopyFileInfo>, IDisposable { private IBackgroundCopyJob m_ijob; internal BackgroundCopyFileCollection(IBackgroundCopyJob ijob) => m_ijob = ijob; internal BackgroundCopyFileCollection() { } /// <summary>Gets the number of files in the current job.</summary> public int Count { get { try { return (int)m_ijob.EnumFiles().GetCount(); } catch (COMException cex) { HandleCOMException(cex); } return 0; } } /// <summary>Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only.</summary> bool ICollection<BackgroundCopyFileInfo>.IsReadOnly => false; /// <summary>Add a file to a download or an upload job. Only one file can be added to upload jobs.</summary> /// <param name="remoteFilePath"> /// Contains the name of the file on the server (for example, http://[server]/[path]/file.ext). The format of the name must conform /// to the transfer protocol you use. You cannot use wildcards in the path or file name. The URL must contain only legal URL /// characters; no escape processing is performed. The URL is limited to 2,200 characters, not including the null terminator. You can /// use SMB to express the remote name of the file to download or upload; there is no SMB support for upload-reply jobs. You can /// specify the remote name as a UNC path, full path with a network drive, or use the "file://" prefix. /// </param> /// <param name="localFilePath"> /// Contains the name of the file on the client. The file name must include the full path (for example, d:\myapp\updates\file.ext). /// You cannot use wildcards in the path or file name, and directories in the path must exist. The user must have permission to write /// to the local directory for downloads and the reply portion of an upload-reply job. BITS does not support NTFS streams. Instead of /// using network drives, which are session specific, use UNC paths. /// </param> /// <remarks> /// <para> /// To add more than one file at a time to a job, call the <see cref="AddRange(Uri, DirectoryInfo, IEnumerable{string})"/> method. It /// is more efficient to call the <c>AddRange</c> method when adding multiple files to a job than to call the <c>Add</c> method in a loop. /// </para> /// <para> /// To add a file to a job from which BITS downloads ranges of data from the file, call the /// <see cref="Add(string, string, long, long)"/> method. /// </para> /// <para>Upload jobs can only contain one file. If you add a second file, the method returns BG_E_TOO_MANY_FILES.</para> /// <para> /// For downloads, BITS guarantees that the version of a file (based on file size and date, not content) that it transfers will be /// consistent; however, it does not guarantee that a set of files will be consistent. For example, if BITS is in the middle of /// downloading the second of two files in the job at the time that the files are updated on the server, BITS restarts the download /// of the second file; however, the first file is not downloaded again. /// </para> /// <para> /// Note that if you own the file being downloaded from the server, you should create a new URL for each new version of the file. If /// you use the same URL for new versions of the file, some proxy servers may serve stale data from their cache because they do not /// verify with the original server if the file is stale. /// </para> /// <para> /// For uploads, BITS generates an error if the local file changes while the file is transferring. The error code is /// BG_E_FILE_CHANGED and the context is BG_ERROR_CONTEXT_LOCAL_FILE. /// </para> /// <para> /// BITS transfers the files within a job sequentially. If an error occurs while transferring a file, the job moves to an error state /// and no more files within the job are processed until the error is resolved. /// </para> /// <para> /// By default, a user can add up to 200 files to a job. This limit does not apply to administrators or service accounts. To change /// the default, set the <c>MaxFilesPerJob</c> group policies. /// </para> /// <para><c>Prior to Windows Vista:</c> There is no limit on the number of files that a user can add to a job.</para> /// </remarks> public void Add(string remoteFilePath, string localFilePath) { // remoteFilePath must not have a trailing backslash. if (!string.IsNullOrEmpty(remoteFilePath)) remoteFilePath.TrimEnd('/'); try { m_ijob.AddFile(remoteFilePath, localFilePath); } catch (COMException cex) { HandleCOMException(cex); } } /// <summary>Add a file to a download job and specify the ranges of the file you want to download.</summary> /// <param name="remoteFilePath"> /// Contains the name of the file on the server (for example, http://[server]/[path]/file.ext). The format of the name must conform /// to the transfer protocol you use. You cannot use wildcards in the path or file name. The URL must contain only legal URL /// characters; no escape processing is performed. The URL is limited to 2,200 characters, not including the null terminator. You can /// use SMB to express the remote name of the file to download or upload; there is no SMB support for upload-reply jobs. You can /// specify the remote name as a UNC path, full path with a network drive, or use the "file://" prefix. /// </param> /// <param name="localFilePath"> /// Contains the name of the file on the client. The file name must include the full path (for example, d:\myapp\updates\file.ext). /// You cannot use wildcards in the path or file name, and directories in the path must exist. The user must have permission to write /// to the local directory for downloads and the reply portion of an upload-reply job. BITS does not support NTFS streams. Instead of /// using network drives, which are session specific, use UNC paths. /// </param> /// <param name="initialOffset">Zero-based offset to the beginning of the range of bytes to download from a file.</param> /// <param name="length">Number of bytes in the range.</param> public void Add(string remoteFilePath, string localFilePath, long initialOffset, long length = -1) { IBackgroundCopyJob3 ijob3 = null; try { ijob3 = (IBackgroundCopyJob3)m_ijob; } catch { throw new NotSupportedException(); } var rng = new[] { new BG_FILE_RANGE { InitialOffset = (ulong)initialOffset, Length = length == -1 ? ulong.MaxValue : (ulong)length } }; try { ijob3.AddFileWithRanges(remoteFilePath, localFilePath, 1, rng); } catch (COMException cex) { HandleCOMException(cex); } } /// <summary>Add a list of files to download from a URL.</summary> /// <param name="remoteUrlRoot"> /// Contains the name of the directory on the server (for example, http://[server]/[path]/). The format of the name must conform to /// the transfer protocol you use. You cannot use wildcards in the path or file name. The URL must contain only legal URL characters; /// no escape processing is performed. The URL is limited to 2,200 characters, not including the null terminator. You can use SMB to /// express the remote name of the file to download or upload; there is no SMB support for upload-reply jobs. You can specify the /// remote name as a UNC path, full path with a network drive, or use the "file://" prefix. /// </param> /// <param name="localDirectory"> /// Contains the name of the directory on the client. The directory must exist. The user must have permission to write to the /// directory for downloads. BITS does not support NTFS streams. Instead of using network drives, which are session specific, use UNC paths. /// </param> /// <param name="files"> /// List of relative file names to retrieve from the remote directory. Filename will be appended to both the remoteUrlRoot and the localDirectory. /// </param> public void AddRange(Uri remoteUrlRoot, DirectoryInfo localDirectory, IEnumerable<string> files) { var array = files.Select(s => new BG_FILE_INFO(new Uri(remoteUrlRoot, s).AbsoluteUri, Path.Combine(localDirectory.FullName, s))).ToArray(); try { m_ijob.AddFileSet((uint)array.Length, array); } catch (COMException cex) { HandleCOMException(cex); } } /// <summary>Add a list of files to download from a URL.</summary> /// <param name="remoteUrlRoot"> /// Contains the name of the directory on the server (for example, http://[server]/[path]/). The format of the name must conform to /// the transfer protocol you use. You cannot use wildcards in the path or file name. The URL must contain only legal URL characters; /// no escape processing is performed. The URL is limited to 2,200 characters, not including the null terminator. You can use SMB to /// express the remote name of the file to download or upload; there is no SMB support for upload-reply jobs. You can specify the /// remote name as a UNC path, full path with a network drive, or use the "file://" prefix. /// </param> /// <param name="localDirectory"> /// Contains the name of the directory on the client. The directory must exist. The user must have permission to write to the /// directory for downloads. BITS does not support NTFS streams. Instead of using network drives, which are session specific, use UNC paths. /// </param> /// <param name="files"> /// List of relative file names to retrieve from the remote directory. Filename will be appended to both the remoteUrlRoot and the localDirectory. /// </param> public void AddRange(string remoteUrlRoot, string localDirectory, IEnumerable<string> files) { // remoteUrlRoot must have a trailing backslash. if (!string.IsNullOrEmpty(remoteUrlRoot) && !remoteUrlRoot.EndsWith("/", StringComparison.Ordinal)) remoteUrlRoot += "/"; AddRange(new Uri(remoteUrlRoot), new DirectoryInfo(localDirectory), files); } /// <summary> /// Returns an object that implements the <see cref="IEnumerator"/> interface and that can iterate through the /// <see cref="BackgroundCopyFileInfo"/> objects within the <see cref="BackgroundCopyFileCollection"/> collection. /// </summary> /// <returns> /// Returns an object that implements the <see cref="IEnumerator"/> interface and that can iterate through the /// <see cref="BackgroundCopyFileInfo"/> objects within the <see cref="BackgroundCopyFileCollection"/> collection. /// </returns> public IEnumerator<BackgroundCopyFileInfo> GetEnumerator() => new Enumerator(m_ijob.EnumFiles()); /// <summary>Adds an item to the <see cref="ICollection{T}"/>.</summary> /// <param name="item">The object to add to the <see cref="ICollection{T}"/>.</param> /// <exception cref="NotImplementedException"></exception> void ICollection<BackgroundCopyFileInfo>.Add(BackgroundCopyFileInfo item) { } /// <summary>Removes all items from the <see cref="ICollection{T}"/>.</summary> /// <exception cref="NotImplementedException"></exception> void ICollection<BackgroundCopyFileInfo>.Clear() => throw new NotSupportedException(); /// <summary>Determines whether the <see cref="ICollection{T}"/> contains a specific value.</summary> /// <param name="item">The object to locate in the <see cref="ICollection{T}"/>.</param> /// <returns>true if <paramref name="item"/> is found in the <see cref="ICollection{T}"/>; otherwise, false.</returns> /// <exception cref="NotImplementedException"></exception> bool ICollection<BackgroundCopyFileInfo>.Contains(BackgroundCopyFileInfo item) => throw new NotSupportedException(); /// <summary> /// Copies the elements of the <see cref="ICollection{T}"/> to an <see cref="T:System.Array"/>, starting at a particular /// <see cref="T:System.Array"/> index. /// </summary> /// <param name="array"> /// The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from /// <see cref="ICollection{T}"/>. The <see cref="T:System.Array"/> must have zero-based indexing. /// </param> /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param> /// <exception cref="NotImplementedException"></exception> void ICollection<BackgroundCopyFileInfo>.CopyTo(BackgroundCopyFileInfo[] array, int arrayIndex) => throw new NotSupportedException(); /// <summary>Disposes of the BackgroundCopyFileSet object.</summary> void IDisposable.Dispose() => m_ijob = null; /// <summary>Returns an enumerator that iterates through a collection.</summary> /// <returns>An <see cref="IEnumerator"/> object that can be used to iterate through the collection.</returns> IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); /// <summary>Removes the first occurrence of a specific object from the <see cref="ICollection{T}"/>.</summary> /// <param name="item">The object to remove from the <see cref="ICollection{T}"/>.</param> /// <returns> /// true if <paramref name="item"/> was successfully removed from the <see cref="ICollection{T}"/>; otherwise, false. This method /// also returns false if <paramref name="item"/> is not found in the original <see cref="ICollection{T}"/>. /// </returns> /// <exception cref="NotImplementedException"></exception> bool ICollection<BackgroundCopyFileInfo>.Remove(BackgroundCopyFileInfo item) => throw new NotSupportedException(); internal BackgroundCopyFileInfo[] GetBCFIArray() => this.ToArray(); private void HandleCOMException(COMException cex) { var state = m_ijob.GetState(); if (state == BG_JOB_STATE.BG_JOB_STATE_ERROR || state == BG_JOB_STATE.BG_JOB_STATE_TRANSIENT_ERROR) { var pErr = m_ijob.GetError(); throw new BackgroundCopyException(pErr); } else throw new BackgroundCopyException(cex); } /// <summary> /// An implementation the <see cref="IEnumerator"/> interface that can iterate through the <see cref="BackgroundCopyFileInfo"/> /// objects within the <see cref="BackgroundCopyFileCollection"/> collection. /// </summary> private sealed class Enumerator : Vanara.Collections.IEnumeratorFromNext<IEnumBackgroundCopyFiles, BackgroundCopyFileInfo> { internal Enumerator(IEnumBackgroundCopyFiles enumfiles) : base(enumfiles, TryGetNext, e => e.Reset()) { } private static bool TryGetNext(IEnumBackgroundCopyFiles e, out BackgroundCopyFileInfo i) { var ifi = e.Next(1)?.FirstOrDefault(); i = ifi != null ? new BackgroundCopyFileInfo(ifi) : null; return i != 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.Collections.Generic; using System.Net.Security; using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; namespace System.Net.Http { public partial class HttpClientHandler : HttpMessageHandler { // Only one of these two handlers will be initialized. private readonly CurlHandler _curlHandler; private readonly SocketsHttpHandler _socketsHttpHandler; private readonly DiagnosticsHandler _diagnosticsHandler; public HttpClientHandler() : this(UseSocketsHttpHandler) { } private HttpClientHandler(bool useSocketsHttpHandler) // used by parameterless ctor and as hook for testing { if (useSocketsHttpHandler) { _socketsHttpHandler = new SocketsHttpHandler(); _diagnosticsHandler = new DiagnosticsHandler(_socketsHttpHandler); } else { _curlHandler = new CurlHandler(); _diagnosticsHandler = new DiagnosticsHandler(_curlHandler); } } protected override void Dispose(bool disposing) { if (disposing) { ((HttpMessageHandler)_curlHandler ?? _socketsHttpHandler).Dispose(); } base.Dispose(disposing); } public virtual bool SupportsAutomaticDecompression => _curlHandler == null || _curlHandler.SupportsAutomaticDecompression; public virtual bool SupportsProxy => true; public virtual bool SupportsRedirectConfiguration => true; public bool UseCookies { get => _curlHandler != null ? _curlHandler.UseCookies : _socketsHttpHandler.UseCookies; set { if (_curlHandler != null) { _curlHandler.UseCookies = value; } else { _socketsHttpHandler.UseCookies = value; } } } public CookieContainer CookieContainer { get => _curlHandler != null ? _curlHandler.CookieContainer : _socketsHttpHandler.CookieContainer; set { if (_curlHandler != null) { _curlHandler.CookieContainer = value; } else { _socketsHttpHandler.CookieContainer = value; } } } public ClientCertificateOption ClientCertificateOptions { get { if (_curlHandler != null) { return _curlHandler.ClientCertificateOptions; } else { return _socketsHttpHandler.SslOptions.LocalCertificateSelectionCallback != null ? ClientCertificateOption.Automatic : ClientCertificateOption.Manual; } } set { if (_curlHandler != null) { _curlHandler.ClientCertificateOptions = value; } else { switch (value) { case ClientCertificateOption.Manual: ThrowForModifiedManagedSslOptionsIfStarted(); _socketsHttpHandler.SslOptions.LocalCertificateSelectionCallback = null; break; case ClientCertificateOption.Automatic: ThrowForModifiedManagedSslOptionsIfStarted(); _socketsHttpHandler.SslOptions.LocalCertificateSelectionCallback = (sender, targetHost, localCertificates, remoteCertificate, acceptableIssuers) => CertificateHelper.GetEligibleClientCertificate(); break; default: throw new ArgumentOutOfRangeException(nameof(value)); } } } } public X509CertificateCollection ClientCertificates { get { if (_curlHandler != null) { return _curlHandler.ClientCertificates; } else { if (ClientCertificateOptions != ClientCertificateOption.Manual) { throw new InvalidOperationException(SR.Format(SR.net_http_invalid_enable_first, nameof(ClientCertificateOptions), nameof(ClientCertificateOption.Manual))); } return _socketsHttpHandler.SslOptions.ClientCertificates ?? (_socketsHttpHandler.SslOptions.ClientCertificates = new X509CertificateCollection()); } } } public Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> ServerCertificateCustomValidationCallback { get { return _curlHandler != null ? _curlHandler.ServerCertificateCustomValidationCallback : (_socketsHttpHandler.SslOptions.RemoteCertificateValidationCallback?.Target as ConnectHelper.CertificateCallbackMapper)?.FromHttpClientHandler; } set { if (_curlHandler != null) { _curlHandler.ServerCertificateCustomValidationCallback = value; } else { ThrowForModifiedManagedSslOptionsIfStarted(); _socketsHttpHandler.SslOptions.RemoteCertificateValidationCallback = value != null ? new ConnectHelper.CertificateCallbackMapper(value).ForSocketsHttpHandler : null; } } } public bool CheckCertificateRevocationList { get => _curlHandler != null ? _curlHandler.CheckCertificateRevocationList : _socketsHttpHandler.SslOptions.CertificateRevocationCheckMode == X509RevocationMode.Online; set { if (_curlHandler != null) { _curlHandler.CheckCertificateRevocationList = value; } else { ThrowForModifiedManagedSslOptionsIfStarted(); _socketsHttpHandler.SslOptions.CertificateRevocationCheckMode = value ? X509RevocationMode.Online : X509RevocationMode.NoCheck; } } } public SslProtocols SslProtocols { get => _curlHandler != null ? _curlHandler.SslProtocols : _socketsHttpHandler.SslOptions.EnabledSslProtocols; set { if (_curlHandler != null) { _curlHandler.SslProtocols = value; } else { SecurityProtocol.ThrowOnNotAllowed(value, allowNone: true); ThrowForModifiedManagedSslOptionsIfStarted(); _socketsHttpHandler.SslOptions.EnabledSslProtocols = value; } } } public DecompressionMethods AutomaticDecompression { get => _curlHandler != null ? _curlHandler.AutomaticDecompression : _socketsHttpHandler.AutomaticDecompression; set { if (_curlHandler != null) { _curlHandler.AutomaticDecompression = value; } else { _socketsHttpHandler.AutomaticDecompression = value; } } } public bool UseProxy { get => _curlHandler != null ? _curlHandler.UseProxy : _socketsHttpHandler.UseProxy; set { if (_curlHandler != null) { _curlHandler.UseProxy = value; } else { _socketsHttpHandler.UseProxy = value; } } } public IWebProxy Proxy { get => _curlHandler != null ? _curlHandler.Proxy : _socketsHttpHandler.Proxy; set { if (_curlHandler != null) { _curlHandler.Proxy = value; } else { _socketsHttpHandler.Proxy = value; } } } public ICredentials DefaultProxyCredentials { get => _curlHandler != null ? _curlHandler.DefaultProxyCredentials : _socketsHttpHandler.DefaultProxyCredentials; set { if (_curlHandler != null) { _curlHandler.DefaultProxyCredentials = value; } else { _socketsHttpHandler.DefaultProxyCredentials = value; } } } public bool PreAuthenticate { get => _curlHandler != null ? _curlHandler.PreAuthenticate : _socketsHttpHandler.PreAuthenticate; set { if (_curlHandler != null) { _curlHandler.PreAuthenticate = value; } else { _socketsHttpHandler.PreAuthenticate = value; } } } public bool UseDefaultCredentials { get => _curlHandler != null ? _curlHandler.UseDefaultCredentials : false; set { if (_curlHandler != null) { _curlHandler.UseDefaultCredentials = value; } } } public ICredentials Credentials { get => _curlHandler != null ? _curlHandler.Credentials : _socketsHttpHandler.Credentials; set { if (_curlHandler != null) { _curlHandler.Credentials = value; } else { _socketsHttpHandler.Credentials = value; } } } public bool AllowAutoRedirect { get => _curlHandler != null ? _curlHandler.AllowAutoRedirect : _socketsHttpHandler.AllowAutoRedirect; set { if (_curlHandler != null) { _curlHandler.AllowAutoRedirect = value; } else { _socketsHttpHandler.AllowAutoRedirect = value; } } } public int MaxAutomaticRedirections { get => _curlHandler != null ? _curlHandler.MaxAutomaticRedirections : _socketsHttpHandler.MaxAutomaticRedirections; set { if (_curlHandler != null) { _curlHandler.MaxAutomaticRedirections = value; } else { _socketsHttpHandler.MaxAutomaticRedirections = value; } } } public int MaxConnectionsPerServer { get => _curlHandler != null ? _curlHandler.MaxConnectionsPerServer : _socketsHttpHandler.MaxConnectionsPerServer; set { if (_curlHandler != null) { _curlHandler.MaxConnectionsPerServer = value; } else { _socketsHttpHandler.MaxConnectionsPerServer = value; } } } public int MaxResponseHeadersLength { get => _curlHandler != null ? _curlHandler.MaxResponseHeadersLength : _socketsHttpHandler.MaxResponseHeadersLength; set { if (_curlHandler != null) { _curlHandler.MaxResponseHeadersLength = value; } else { _socketsHttpHandler.MaxResponseHeadersLength = value; } } } public IDictionary<string, object> Properties => _curlHandler != null ? _curlHandler.Properties : _socketsHttpHandler.Properties; protected internal override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => DiagnosticsHandler.IsEnabled() ? _diagnosticsHandler.SendAsync(request, cancellationToken) : _curlHandler != null ? _curlHandler.SendAsync(request, cancellationToken) : _socketsHttpHandler.SendAsync(request, cancellationToken); } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.2.2.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Reservations { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; 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> /// ReservationOperations operations. /// </summary> internal partial class ReservationOperations : IServiceOperations<AzureReservationAPIClient>, IReservationOperations { /// <summary> /// Initializes a new instance of the ReservationOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ReservationOperations(AzureReservationAPIClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the AzureReservationAPIClient /// </summary> public AzureReservationAPIClient Client { get; private set; } /// <summary> /// Split the `Reservation`. /// </summary> /// <remarks> /// Split a `Reservation` into two `Reservation`s with specified quantity /// distribution. /// /// </remarks> /// <param name='reservationOrderId'> /// Order Id of the reservation /// /// </param> /// <param name='body'> /// Information needed to Split a reservation item /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IList<ReservationResponse>>> SplitWithHttpMessagesAsync(string reservationOrderId, SplitRequest body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse<IList<ReservationResponse>> _response = await BeginSplitWithHttpMessagesAsync(reservationOrderId, body, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Merges two `Reservation`s. /// </summary> /// <remarks> /// Merge the specified `Reservation`s into a new `Reservation`. The two /// `Reservation`s being merged must have same properties. /// </remarks> /// <param name='reservationOrderId'> /// Order Id of the reservation /// /// </param> /// <param name='body'> /// Information needed for commercial request for a reservation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IList<ReservationResponse>>> MergeWithHttpMessagesAsync(string reservationOrderId, MergeRequest body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse<IList<ReservationResponse>> _response = await BeginMergeWithHttpMessagesAsync(reservationOrderId, body, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get `Reservation`s in a given reservation Order /// </summary> /// <remarks> /// List `Reservation`s within a single `ReservationOrder`. /// </remarks> /// <param name='reservationOrderId'> /// Order Id of the reservation /// /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// 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<ReservationResponse>>> ListWithHttpMessagesAsync(string reservationOrderId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (reservationOrderId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "reservationOrderId"); } 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("reservationOrderId", reservationOrderId); 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("/") ? "" : "/")), "providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations").ToString(); _url = _url.Replace("{reservationOrderId}", System.Uri.EscapeDataString(reservationOrderId)); 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ReservationResponse>>(); _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<ReservationResponse>>(_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 `Reservation` details. /// </summary> /// <remarks> /// Get specific `Reservation` details. /// </remarks> /// <param name='reservationId'> /// Id of the Reservation Item /// </param> /// <param name='reservationOrderId'> /// Order Id of the reservation /// /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// 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<ReservationResponse>> GetWithHttpMessagesAsync(string reservationId, string reservationOrderId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (reservationId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "reservationId"); } if (reservationOrderId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "reservationOrderId"); } 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("reservationId", reservationId); tracingParameters.Add("reservationOrderId", reservationOrderId); 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("/") ? "" : "/")), "providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}").ToString(); _url = _url.Replace("{reservationId}", System.Uri.EscapeDataString(reservationId)); _url = _url.Replace("{reservationOrderId}", System.Uri.EscapeDataString(reservationOrderId)); 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ReservationResponse>(); _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<ReservationResponse>(_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> /// Updates a `Reservation`. /// </summary> /// <remarks> /// Updates the applied scopes of the `Reservation`. /// </remarks> /// <param name='reservationOrderId'> /// Order Id of the reservation /// /// </param> /// <param name='reservationId'> /// Id of the Reservation Item /// </param> /// <param name='parameters'> /// Information needed to patch a reservation item /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<ReservationResponse>> UpdateWithHttpMessagesAsync(string reservationOrderId, string reservationId, Patch parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<ReservationResponse> _response = await BeginUpdateWithHttpMessagesAsync(reservationOrderId, reservationId, parameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get `Reservation` revisions. /// </summary> /// <remarks> /// List of all the revisions for the `Reservation`. /// /// </remarks> /// <param name='reservationId'> /// Id of the Reservation Item /// </param> /// <param name='reservationOrderId'> /// Order Id of the reservation /// /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// 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<ReservationResponse>>> ListRevisionsWithHttpMessagesAsync(string reservationId, string reservationOrderId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (reservationId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "reservationId"); } if (reservationOrderId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "reservationOrderId"); } 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("reservationId", reservationId); tracingParameters.Add("reservationOrderId", reservationOrderId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListRevisions", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}/revisions").ToString(); _url = _url.Replace("{reservationId}", System.Uri.EscapeDataString(reservationId)); _url = _url.Replace("{reservationOrderId}", System.Uri.EscapeDataString(reservationOrderId)); 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ReservationResponse>>(); _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<ReservationResponse>>(_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> /// Split the `Reservation`. /// </summary> /// <remarks> /// Split a `Reservation` into two `Reservation`s with specified quantity /// distribution. /// /// </remarks> /// <param name='reservationOrderId'> /// Order Id of the reservation /// /// </param> /// <param name='body'> /// Information needed to Split a reservation item /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// 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<IList<ReservationResponse>>> BeginSplitWithHttpMessagesAsync(string reservationOrderId, SplitRequest body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (reservationOrderId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "reservationOrderId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (body == null) { throw new ValidationException(ValidationRules.CannotBeNull, "body"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("reservationOrderId", reservationOrderId); tracingParameters.Add("body", body); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginSplit", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/split").ToString(); _url = _url.Replace("{reservationOrderId}", System.Uri.EscapeDataString(reservationOrderId)); 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("POST"); _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(body != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(body, 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IList<ReservationResponse>>(); _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<IList<ReservationResponse>>(_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> /// Merges two `Reservation`s. /// </summary> /// <remarks> /// Merge the specified `Reservation`s into a new `Reservation`. The two /// `Reservation`s being merged must have same properties. /// </remarks> /// <param name='reservationOrderId'> /// Order Id of the reservation /// /// </param> /// <param name='body'> /// Information needed for commercial request for a reservation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// 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<IList<ReservationResponse>>> BeginMergeWithHttpMessagesAsync(string reservationOrderId, MergeRequest body, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (reservationOrderId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "reservationOrderId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (body == null) { throw new ValidationException(ValidationRules.CannotBeNull, "body"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("reservationOrderId", reservationOrderId); tracingParameters.Add("body", body); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginMerge", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/merge").ToString(); _url = _url.Replace("{reservationOrderId}", System.Uri.EscapeDataString(reservationOrderId)); 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("POST"); _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(body != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(body, 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IList<ReservationResponse>>(); _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<IList<ReservationResponse>>(_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> /// Updates a `Reservation`. /// </summary> /// <remarks> /// Updates the applied scopes of the `Reservation`. /// </remarks> /// <param name='reservationOrderId'> /// Order Id of the reservation /// /// </param> /// <param name='reservationId'> /// Id of the Reservation Item /// </param> /// <param name='parameters'> /// Information needed to patch a reservation item /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// 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<ReservationResponse>> BeginUpdateWithHttpMessagesAsync(string reservationOrderId, string reservationId, Patch parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (reservationOrderId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "reservationOrderId"); } if (reservationId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "reservationId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("reservationOrderId", reservationOrderId); tracingParameters.Add("reservationId", reservationId); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Capacity/reservationOrders/{reservationOrderId}/reservations/{reservationId}").ToString(); _url = _url.Replace("{reservationOrderId}", System.Uri.EscapeDataString(reservationOrderId)); _url = _url.Replace("{reservationId}", System.Uri.EscapeDataString(reservationId)); 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("PATCH"); _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(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ReservationResponse>(); _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<ReservationResponse>(_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 `Reservation`s in a given reservation Order /// </summary> /// <remarks> /// List `Reservation`s within a single `ReservationOrder`. /// </remarks> /// <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="ErrorException"> /// 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<ReservationResponse>>> 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ReservationResponse>>(); _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<ReservationResponse>>(_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 `Reservation` revisions. /// </summary> /// <remarks> /// List of all the revisions for the `Reservation`. /// /// </remarks> /// <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="ErrorException"> /// 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<ReservationResponse>>> ListRevisionsNextWithHttpMessagesAsync(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, "ListRevisionsNext", 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 ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ReservationResponse>>(); _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<ReservationResponse>>(_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; } } }
/* The MIT License (MIT) Copyright (c) 2016 - 2018 Bogdan Rechi This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ using System; using Xunit; using System.Threading; using System.Globalization; using Commons.Formatting; namespace Commons.Tests { public class FormatExtensionsTests { public FormatExtensionsTests() { Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-US"); } [Fact] public void FormatWithStandardFormatStrings() { // Given var format = "double: {double_Param_1:000.000}, string: {string_Param_2}, char: {char_Param_3}, datetime: {datetime_Param_4:yyyy/MM/dd HH:mm:ss}"; // When var parameter = new { double_Param_1 = 12.3456, string_Param_2 = "second", char_Param_3 = 't', datetime_Param_4 = new DateTime(2018, 02, 18, 22, 51, 00), dummy = 180 }; var result = FormatExtensions.FormatNamed(format, parameter); // Then Assert.Equal("double: 012.346, string: second, char: t, datetime: 2018/02/18 22:51:00", result); } [Fact] public void FormatWithStandardFormatStringsAndNonEnglishCulture() { // Given Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("ro-RO"); var format = "double: {double_Param_1:000.000}, string: {string_Param_2}, char: {char_Param_3}, datetime: {datetime_Param_4:yyyy/MM/dd HH:mm:ss}"; // When var parameter = new { double_Param_1 = 12.3456, string_Param_2 = "second", char_Param_3 = 't', datetime_Param_4 = new DateTime(2018, 02, 18, 22, 51, 00), dummy = 180 }; var result = FormatExtensions.FormatNamed(format, parameter); // Then Assert.Equal("double: 012,346, string: second, char: t, datetime: 2018.02.18 22:51:00", result); } [Fact] public void FormatWithComplexEscapedBrackets() { // Given var format = "}} {{ {{parameter:0.00}} {{{{text inside}}}} {{ {{{parameter}}} }}{{ another text }} : end"; // When var result = format.FormatNamed(new { parameter = 123 }); // Then Assert.Equal("} { {parameter:0.00} {{text inside}} { {123} }{ another text } : end", result); } [Theory] [InlineData("{{text }} {{ }}} {parameter}")] [InlineData(" { {{text }} {{ }} {parameter}")] [InlineData("{{text }} } {{ }} {parameter}")] [InlineData("{{ }} { parameter}")] [InlineData("{} { parameter}")] public void ThrowFormatExceptionWhenFormatIsIncorrect(string format) { // Then Assert.Throws<FormatException>(() => format.FormatNamed(new { parameter = 0 })); } [Fact] public void ThrowFormatExceptionWhenParameterIsNotProvided() { // Given var format = "parameter = {parameter}"; // Then var exception = Assert.Throws<FormatException>(() => format.FormatNamed(new { other_parameter = 123 })); Assert.Equal(string.Format(CultureInfo.CurrentCulture, FormatErrors.ErrorParameterNotFound, "parameter"), exception.Message); } [Fact] public void FormatWithNonAnonymousObjectAsHolder() { // Given var holder = new FormatTestsHolder { IntProperty = 10, StringProperty = "text", DateTimeProperty = new DateTime(2018, 02, 23) }; // When var result = "{IntProperty}, {StringProperty}, {DateTimeProperty:yyyy/MM/dd}".FormatNamed(holder); // Then Assert.Equal("10, text, 2018/02/23", result); } [Fact] public void FormatWithMultipleHolders() { // Given var holder = new FormatTestsHolder { IntProperty = 10, StringProperty = "text", DateTimeProperty = new DateTime(2018, 02, 23) }; // When var result = "{IntProperty}, {extra1}, {StringProperty}, {DateTimeProperty:yyyy/MM/dd}, {extra2}".FormatNamed(holder, new { extra1 = "extra 1", extra2 = "extra 2" }); // Then Assert.Equal("10, extra 1, text, 2018/02/23, extra 2", result); } [Fact] public void FormatWithParametersUsingAccessors() { // Given var format = "{one_1.two_2.three_3:00.000}, {d_4}, {five_5.six_6}"; // When var result = format.FormatNamed(new { one_1 = new { two_2 = new { three_3 = 12.345 } }, five_5 = new { six_6 = "the six" }, d_4 = "ok" }); // Then Assert.Equal("12.345, ok, the six", result); } [Theory] [InlineData("{a.b.c.d:00.000}, {d}")] [InlineData("{a.b.c:00.000}, {d.e}")] [InlineData("{z.a.b.c:00.000}, {d}")] [InlineData("{a.c:00.000}, {d}")] public void FormatWithIncorrectParameterAccessorsThrowsFormatException(string format) { // Then Assert.Throws<FormatException>(() => format.FormatNamed(new { a = new { b = new { c = 12.345 } }, d = "ok" })); } [Fact] public void NullFormatThrowsException() { // Given string format = null; // Then var exception = Assert.Throws<Exception>(() => format.FormatNamed(new { })); Assert.Equal(FormatErrors.ErrorNull, exception.Message); } [Fact] public void NullFormatAsParameterThrowsException() { // Given string format = null; // Then var exception = Assert.Throws<Exception>(() => string.Empty.FormatNamed(format, new { })); Assert.Equal(FormatErrors.ErrorNull, exception.Message); } [Fact] public void NoFormatAsParameterThrowsException() { // Then var exception = Assert.Throws<Exception>(() => string.Empty.FormatNamed()); Assert.Equal(FormatErrors.ErrorNoFormatString, exception.Message); } [Fact] public void NotNullNullableFormatCallsFormatFunc() { // Given var x = 10; // When var result = x.Format(obj => obj.ToString(CultureInfo.CurrentCulture)); // Then Assert.Equal("10", result); } [Fact] public void NullNullableFormatWithNoNullFormatFuncReturnsEmptyString() { // Given int? x = null; // When var result = x.Format(null, null); // Then Assert.Equal(string.Empty, result); } [Fact] public void NullNullableWithNullFormatFuncCallsNullFormatFunc() { // Given int? x = null; // When var result = x.Format(null, () => "ok"); // Then Assert.Equal("ok", result); } [Fact] public void FormatWithSpecificCulture() { // Given var romanianCulture = CultureInfo.GetCultureInfo("ro-RO"); var x = 12.34; // When var result = "{x}".FormatNamed(romanianCulture, new { x = x }); // Then Assert.Equal("12,34", result); } [Fact] public void FormatWithInvariantCulture() { // Given var x = 12.34; // When var result = "{x}".FormatNamed(CultureInfo.InvariantCulture, new { x = x }); // Then Assert.Equal("12.34", result); } } }
// 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.Diagnostics; using System.Xml; using System.Xml.XPath; using System.Xml.Schema; namespace System.Xml.Xsl.Runtime { /// <summary> /// External XmlWriter Cached Sequence /// =================================================================================================== /// Multiple Trees Merged into Entity Multiple Trees /// /// Attributes Error Floating /// at top-level Attribute /// /// Namespace Error Floating /// at top-level Namespace /// /// Elements, Text, PI Implicit Root Floating /// Comments at top-level Nodes /// /// Root at top-level Ignored Root /// /// Atomic Values Whitespace-Separated Atomic Values /// at top-level Text Node /// /// Nodes By Reference Copied Preserve Identity /// </summary> internal abstract class XmlSequenceWriter { /// <summary> /// Start construction of a new Xml tree (document or fragment). /// </summary> public abstract XmlRawWriter StartTree(XPathNodeType rootType, IXmlNamespaceResolver nsResolver, XmlNameTable nameTable); /// <summary> /// End construction of a new Xml tree (document or fragment). /// </summary> public abstract void EndTree(); /// <summary> /// Write a top-level item by reference. /// </summary> public abstract void WriteItem(XPathItem item); } /// <summary> /// An implementation of XmlSequenceWriter that builds a cached XPath/XQuery sequence. /// </summary> internal class XmlCachedSequenceWriter : XmlSequenceWriter { private XmlQueryItemSequence _seqTyped; private XPathDocument _doc; private XmlRawWriter _writer; /// <summary> /// Constructor. /// </summary> public XmlCachedSequenceWriter() { _seqTyped = new XmlQueryItemSequence(); } /// <summary> /// Return the sequence after it has been fully constructed. /// </summary> public XmlQueryItemSequence ResultSequence { get { return _seqTyped; } } /// <summary> /// Start construction of a new Xml tree (document or fragment). /// </summary> public override XmlRawWriter StartTree(XPathNodeType rootType, IXmlNamespaceResolver nsResolver, XmlNameTable nameTable) { // Build XPathDocument // If rootType != XPathNodeType.Root, then build an XQuery fragment _doc = new XPathDocument(nameTable); _writer = _doc.LoadFromWriter(XPathDocument.LoadFlags.AtomizeNames | (rootType == XPathNodeType.Root ? XPathDocument.LoadFlags.None : XPathDocument.LoadFlags.Fragment), string.Empty); _writer.NamespaceResolver = nsResolver; return _writer; } /// <summary> /// End construction of a new Xml tree (document or fragment). /// </summary> public override void EndTree() { // Add newly constructed document to sequence _writer.Close(); _seqTyped.Add(_doc.CreateNavigator()); } /// <summary> /// Write a top-level item by reference. /// </summary> public override void WriteItem(XPathItem item) { // Preserve identity _seqTyped.AddClone(item); } } /// <summary> /// An implementation of XmlSequenceWriter that converts an instance of the XQuery data model into a series /// of calls to XmlRawWriter. The algorithm to do this is designed to be compatible with the rules in the /// "XSLT 2.0 and XQuery 1.0 Serialization" spec. Here are the rules we use: /// 1. An exception is thrown if the top-level sequence contains attribute or namespace nodes /// 2. Each atomic value in the top-level sequence is converted to text, and XmlWriter.WriteString is called /// 3. A call to XmlRawWriter.WriteWhitespace(" ") is made between adjacent atomic values at the top-level /// 4. All items in the top-level sequence are merged together into a single result document. /// </summary> internal class XmlMergeSequenceWriter : XmlSequenceWriter { private XmlRawWriter _xwrt; private bool _lastItemWasAtomic; /// <summary> /// Constructor. /// </summary> public XmlMergeSequenceWriter(XmlRawWriter xwrt) { _xwrt = xwrt; _lastItemWasAtomic = false; } /// <summary> /// Start construction of a new Xml tree (document or fragment). /// </summary> public override XmlRawWriter StartTree(XPathNodeType rootType, IXmlNamespaceResolver nsResolver, XmlNameTable nameTable) { if (rootType == XPathNodeType.Attribute || rootType == XPathNodeType.Namespace) throw new XslTransformException(SR.XmlIl_TopLevelAttrNmsp, string.Empty); // Provide a namespace resolver to the writer _xwrt.NamespaceResolver = nsResolver; return _xwrt; } /// <summary> /// End construction of a new Xml tree (document or fragment). /// </summary> public override void EndTree() { _lastItemWasAtomic = false; } /// <summary> /// Write a top-level item by reference. /// </summary> public override void WriteItem(XPathItem item) { if (item.IsNode) { XPathNavigator nav = item as XPathNavigator; if (nav.NodeType == XPathNodeType.Attribute || nav.NodeType == XPathNodeType.Namespace) throw new XslTransformException(SR.XmlIl_TopLevelAttrNmsp, string.Empty); // Copy navigator to raw writer CopyNode(nav); _lastItemWasAtomic = false; } else { WriteString(item.Value); } } /// <summary> /// Write the string value of a top-level atomic value. /// </summary> private void WriteString(string value) { if (_lastItemWasAtomic) { // Insert space character between adjacent atomic values _xwrt.WriteWhitespace(" "); } else { _lastItemWasAtomic = true; } _xwrt.WriteString(value); } /// <summary> /// Copy the navigator subtree to the raw writer. /// </summary> private void CopyNode(XPathNavigator nav) { XPathNodeType nodeType; int iLevel = 0; while (true) { if (CopyShallowNode(nav)) { nodeType = nav.NodeType; if (nodeType == XPathNodeType.Element) { // Copy attributes if (nav.MoveToFirstAttribute()) { do { CopyShallowNode(nav); } while (nav.MoveToNextAttribute()); nav.MoveToParent(); } // Copy namespaces in document order (navigator returns them in reverse document order) XPathNamespaceScope nsScope = (iLevel == 0) ? XPathNamespaceScope.ExcludeXml : XPathNamespaceScope.Local; if (nav.MoveToFirstNamespace(nsScope)) { CopyNamespaces(nav, nsScope); nav.MoveToParent(); } _xwrt.StartElementContent(); } // If children exist, move down to next level if (nav.MoveToFirstChild()) { iLevel++; continue; } else { // EndElement if (nav.NodeType == XPathNodeType.Element) _xwrt.WriteEndElement(nav.Prefix, nav.LocalName, nav.NamespaceURI); } } // No children while (true) { if (iLevel == 0) { // The entire subtree has been copied return; } if (nav.MoveToNext()) { // Found a sibling, so break to outer loop break; } // No siblings, so move up to previous level iLevel--; nav.MoveToParent(); // EndElement if (nav.NodeType == XPathNodeType.Element) _xwrt.WriteFullEndElement(nav.Prefix, nav.LocalName, nav.NamespaceURI); } } } /// <summary> /// Begin shallow copy of the specified node to the writer. Returns true if the node might have content. /// </summary> private bool CopyShallowNode(XPathNavigator nav) { bool mayHaveChildren = false; switch (nav.NodeType) { case XPathNodeType.Element: _xwrt.WriteStartElement(nav.Prefix, nav.LocalName, nav.NamespaceURI); mayHaveChildren = true; break; case XPathNodeType.Attribute: _xwrt.WriteStartAttribute(nav.Prefix, nav.LocalName, nav.NamespaceURI); _xwrt.WriteString(nav.Value); _xwrt.WriteEndAttribute(); break; case XPathNodeType.Text: _xwrt.WriteString(nav.Value); break; case XPathNodeType.SignificantWhitespace: case XPathNodeType.Whitespace: _xwrt.WriteWhitespace(nav.Value); break; case XPathNodeType.Root: mayHaveChildren = true; break; case XPathNodeType.Comment: _xwrt.WriteComment(nav.Value); break; case XPathNodeType.ProcessingInstruction: _xwrt.WriteProcessingInstruction(nav.LocalName, nav.Value); break; case XPathNodeType.Namespace: _xwrt.WriteNamespaceDeclaration(nav.LocalName, nav.Value); break; default: Debug.Assert(false); break; } return mayHaveChildren; } /// <summary> /// Copy all or some (which depends on nsScope) of the namespaces on the navigator's current node to the /// raw writer. /// </summary> private void CopyNamespaces(XPathNavigator nav, XPathNamespaceScope nsScope) { string prefix = nav.LocalName; string ns = nav.Value; if (nav.MoveToNextNamespace(nsScope)) { CopyNamespaces(nav, nsScope); } _xwrt.WriteNamespaceDeclaration(prefix, ns); } } }
using UnityEngine; using System.Collections.Generic; public class MegaDrawSpline : MonoBehaviour { public float updatedist = 1.0f; public float smooth = 0.7f; public Material mat; public float width = 1.0f; public float height = 1.0f; public float radius = 0.1f; public bool closed = true; public MeshShapeType meshtype = MeshShapeType.Box; public float offset = 0.01f; public float tradius = 1.0f; public float meshstep = 1.0f; public float closevalue = 0.1f; public bool constantspd = true; GameObject obj; Vector3 lasthitpos; bool building = false; float travelled = 0.0f; Vector3 lastdir; MegaSpline cspline; MegaShape cshape; int splinecount = 0; void Update() { if ( building ) { Ray mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit info; bool hit = Physics.Raycast(mouseRay, out info); if ( Input.GetMouseButtonUp(0) || hit == false ) { building = false; // Finish of line and make spline if ( ValidSpline() ) FinishSpline(obj, lasthitpos); else Destroy(obj); obj = null; cspline = null; cshape = null; } else { if ( hit ) { Vector3 hp = info.point; hp.y += offset; float dist = Vector3.Distance(lasthitpos, hp); travelled += dist; if ( travelled > updatedist ) { cspline.AddKnot(cshape.transform.worldToLocalMatrix.MultiplyPoint3x4(hp), Vector3.zero, Vector3.zero); cshape.AutoCurve(); travelled -= updatedist; } else { cspline.knots[cspline.knots.Count - 1].p = cshape.transform.worldToLocalMatrix.MultiplyPoint3x4(hp); cshape.AutoCurve(); if ( cspline.knots.Count == 2 ) { float dist1 = cspline.KnotDistance(0, 1); if ( dist1 > 0.1f ) cshape.BuildMesh(); } else { if ( cspline.knots.Count > 2 ) cshape.BuildMesh(); } } lasthitpos = hp; } } } else { if ( Input.GetMouseButtonDown(0) ) { Ray mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit info; bool hit = Physics.Raycast(mouseRay, out info); if ( hit ) { Vector3 hp = info.point; hp.y += offset; lasthitpos = hp; travelled = 0.0f; obj = CreateSpline(hp); building = true; } } } } bool ValidSpline() { if ( cspline.knots.Count == 2 ) { float dist1 = cspline.KnotDistance(0, 1); if ( dist1 <= 0.1f ) return false; } return true; } public MegaSpline NewSpline(MegaShape shape) { if ( shape.splines.Count == 0 ) { MegaSpline newspline = new MegaSpline(); shape.splines.Add(newspline); } MegaSpline spline = shape.splines[0]; spline.knots.Clear(); spline.closed = false; return spline; } GameObject CreateSpline(Vector3 pos) { GameObject obj = new GameObject(); obj.name = name + " - Spline " + splinecount++; obj.transform.position = transform.position; //obj.transform.parent = transform; MegaShape shape = obj.AddComponent<MegaShape>(); shape.smoothness = smooth; shape.drawHandles = false; MegaSpline spline = shape.splines[0]; //NewSpline(shape); spline.knots.Clear(); spline.constantSpeed = constantspd; spline.subdivs = 40; shape.splines.Add(spline); shape.cap = true; Vector3[] ps = new Vector3[2]; ps[0] = obj.transform.worldToLocalMatrix.MultiplyPoint3x4(pos); ps[1] = obj.transform.worldToLocalMatrix.MultiplyPoint3x4(pos); shape.BuildSpline(0, ps, false); shape.CalcLength(); shape.mat1 = mat; shape.drawTwist = true; shape.makeMesh = true; shape.meshType = meshtype; shape.boxwidth = width; shape.boxheight = height; shape.offset = -height * 0.5f; shape.tradius = tradius; shape.stepdist = meshstep; //width * 2.0f * 10.0f; shape.SetMats(); spline.closed = closed; cspline = spline; cshape = shape; return obj; } void FinishSpline(GameObject obj, Vector3 p) { if ( !closed ) { Vector3 lp = obj.transform.worldToLocalMatrix.MultiplyPoint3x4(p); float d = Vector3.Distance(cspline.knots[0].p, lp); if ( d < updatedist * closevalue ) { cspline.closed = true; cshape.cap = false; cspline.knots.RemoveAt(cspline.knots.Count - 1); } else cshape.cap = true; } else { if ( cspline.knots.Count > 2 ) { float d = cspline.KnotDistance(cspline.knots.Count - 1, cspline.knots.Count - 2); if ( d < updatedist * 0.25f ) cspline.knots.RemoveAt(cspline.knots.Count - 1); } float d1 = cspline.KnotDistance(cspline.knots.Count - 1, 0); if ( d1 < updatedist * closevalue ) cspline.knots.RemoveAt(cspline.knots.Count - 1); } cshape.AutoCurve(); cshape.BuildMesh(); } void OnDrawGizmosSelected() { if ( cshape && cspline != null ) { Gizmos.color = Color.white; Gizmos.matrix = obj.transform.localToWorldMatrix; for ( int i = 1; i < cspline.knots.Count; i++ ) Gizmos.DrawLine(cspline.knots[i - 1].p, cspline.knots[i].p); Gizmos.color = Color.green; for ( int i = 0; i < cspline.knots.Count; i++ ) Gizmos.DrawSphere(cspline.knots[i].p, radius); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using WalletWasabi.BitcoinCore.Monitoring; using WalletWasabi.BitcoinCore.Rpc; using WalletWasabi.Blockchain.Analysis.FeesEstimation; using WalletWasabi.Helpers; using WalletWasabi.Logging; namespace NBitcoin.RPC { public static class RPCClientExtensions { public static async Task<EstimateSmartFeeResponse> EstimateSmartFeeAsync(this IRPCClient rpc, int confirmationTarget, FeeRate sanityFeeRate, EstimateSmartFeeMode estimateMode = EstimateSmartFeeMode.Conservative, bool simulateIfRegTest = false) { EstimateSmartFeeResponse result; if (simulateIfRegTest && rpc.Network == Network.RegTest) { result = SimulateRegTestFeeEstimation(confirmationTarget, estimateMode); } else { result = await rpc.EstimateSmartFeeAsync(confirmationTarget, estimateMode).ConfigureAwait(false); } result.FeeRate = FeeRate.Max(sanityFeeRate, result.FeeRate); return result; } private static EstimateSmartFeeResponse SimulateRegTestFeeEstimation(int confirmationTarget, EstimateSmartFeeMode estimateMode) { int satoshiPerByte = estimateMode == EstimateSmartFeeMode.Conservative ? (Constants.SevenDaysConfirmationTarget + 1 + 6 - confirmationTarget) / 7 : (Constants.SevenDaysConfirmationTarget + 1 + 5 - confirmationTarget) / 7; // Economical Money feePerK = Money.Satoshis(satoshiPerByte * 1000); FeeRate feeRate = new FeeRate(feePerK); var resp = new EstimateSmartFeeResponse { Blocks = confirmationTarget, FeeRate = feeRate }; return resp; } /// <summary> /// If null is returned, no exception is thrown, so the test was successful. /// </summary> public static async Task<Exception?> TestAsync(this IRPCClient rpc) { try { await rpc.UptimeAsync().ConfigureAwait(false); } catch (Exception ex) { return ex; } return null; } public static async Task<AllFeeEstimate> EstimateAllFeeAsync(this IRPCClient rpc, EstimateSmartFeeMode estimateMode = EstimateSmartFeeMode.Conservative, bool simulateIfRegTest = false) { var rpcStatus = await rpc.GetRpcStatusAsync(CancellationToken.None).ConfigureAwait(false); var mempoolInfo = await rpc.GetMempoolInfoAsync().ConfigureAwait(false); var sanityFeeRate = mempoolInfo.GetSanityFeeRate(); var estimations = await rpc.EstimateHalfFeesAsync(new Dictionary<int, int>(), 2, 0, Constants.SevenDaysConfirmationTarget, 0, sanityFeeRate, estimateMode, simulateIfRegTest).ConfigureAwait(false); var allFeeEstimate = new AllFeeEstimate(estimateMode, estimations, rpcStatus.Synchronized); return allFeeEstimate; } public static async Task<RpcStatus> GetRpcStatusAsync(this IRPCClient rpc, CancellationToken cancel) { try { var bci = await rpc.GetBlockchainInfoAsync().ConfigureAwait(false); cancel.ThrowIfCancellationRequested(); var pi = await rpc.GetPeersInfoAsync().ConfigureAwait(false); return RpcStatus.Responsive(bci.Headers, bci.Blocks, pi.Length); } catch (Exception ex) when (ex is not OperationCanceledException and not TimeoutException) { Logger.LogTrace(ex); return RpcStatus.Unresponsive; } } private static async Task<Dictionary<int, int>> EstimateHalfFeesAsync(this IRPCClient rpc, IDictionary<int, int> estimations, int smallTarget, int smallTargetFee, int largeTarget, int largeTargetFee, FeeRate sanityFeeRate, EstimateSmartFeeMode estimateMode = EstimateSmartFeeMode.Conservative, bool simulateIfRegTest = false) { var newEstimations = new Dictionary<int, int>(); foreach (var est in estimations) { newEstimations.TryAdd(est.Key, est.Value); } if (Math.Abs(smallTarget - largeTarget) <= 1) { return newEstimations; } if (smallTargetFee == 0) { var smallTargetFeeResult = await rpc.EstimateSmartFeeAsync(smallTarget, sanityFeeRate, estimateMode, simulateIfRegTest).ConfigureAwait(false); smallTargetFee = (int)Math.Ceiling(smallTargetFeeResult.FeeRate.SatoshiPerByte); newEstimations.TryAdd(smallTarget, smallTargetFee); } if (largeTargetFee == 0) { var largeTargetFeeResult = await rpc.EstimateSmartFeeAsync(largeTarget, sanityFeeRate, estimateMode, simulateIfRegTest).ConfigureAwait(false); largeTargetFee = (int)Math.Ceiling(largeTargetFeeResult.FeeRate.SatoshiPerByte); // Blocks should never be larger than the target that we asked for, so it's just a sanity check. largeTarget = Math.Min(largeTarget, largeTargetFeeResult.Blocks); newEstimations.TryAdd(largeTarget, largeTargetFee); } int halfTarget = (smallTarget + largeTarget) / 2; var halfFeeResult = await rpc.EstimateSmartFeeAsync(halfTarget, sanityFeeRate, estimateMode, simulateIfRegTest).ConfigureAwait(false); int halfTargetFee = (int)Math.Ceiling(halfFeeResult.FeeRate.SatoshiPerByte); // Blocks should never be larger than the target that we asked for, so it's just a sanity check. halfTarget = Math.Min(halfTarget, halfFeeResult.Blocks); newEstimations.TryAdd(halfTarget, halfTargetFee); if (smallTargetFee > halfTargetFee) { var smallEstimations = await rpc.EstimateHalfFeesAsync(newEstimations, smallTarget, smallTargetFee, halfTarget, halfTargetFee, sanityFeeRate, estimateMode, simulateIfRegTest).ConfigureAwait(false); foreach (var est in smallEstimations) { newEstimations.TryAdd(est.Key, est.Value); } } if (largeTargetFee < halfTargetFee) { var largeEstimations = await rpc.EstimateHalfFeesAsync(newEstimations, halfTarget, halfTargetFee, largeTarget, largeTargetFee, sanityFeeRate, estimateMode, simulateIfRegTest).ConfigureAwait(false); foreach (var est in largeEstimations) { newEstimations.TryAdd(est.Key, est.Value); } } return newEstimations; } public static async Task<(bool accept, string rejectReason)> TestMempoolAcceptAsync(this IRPCClient rpc, IEnumerable<Coin> coins, int fakeOutputCount, Money feePerInputs, Money feePerOutputs) { // Check if mempool would accept a fake transaction created with the registered inputs. // This will catch ascendant/descendant count and size limits for example. var fakeTransaction = rpc.Network.CreateTransaction(); fakeTransaction.Inputs.AddRange(coins.Select(coin => new TxIn(coin.Outpoint))); Money totalFakeOutputsValue; try { totalFakeOutputsValue = NBitcoinHelpers.TakeFee(coins, fakeOutputCount, feePerInputs, feePerOutputs); } catch (InvalidOperationException ex) { return (false, ex.Message); } for (int i = 0; i < fakeOutputCount; i++) { var fakeOutputValue = totalFakeOutputsValue / fakeOutputCount; fakeTransaction.Outputs.Add(fakeOutputValue, new Key()); } MempoolAcceptResult testMempoolAcceptResult = await rpc.TestMempoolAcceptAsync(fakeTransaction, allowHighFees: true).ConfigureAwait(false); if (!testMempoolAcceptResult.IsAllowed) { string rejected = testMempoolAcceptResult.RejectReason; if (!(rejected.Contains("mandatory-script-verify-flag-failed", StringComparison.OrdinalIgnoreCase) || rejected.Contains("non-mandatory-script-verify-flag", StringComparison.OrdinalIgnoreCase))) { return (false, rejected); } } return (true, ""); } /// <summary> /// Gets the transactions that are unconfirmed using getrawmempool. /// This is efficient when many transaction ids are provided. /// </summary> public static async Task<IEnumerable<uint256>> GetUnconfirmedAsync(this IRPCClient rpc, IEnumerable<uint256> transactionHashes) { uint256[] unconfirmedTransactionHashes = await rpc.GetRawMempoolAsync().ConfigureAwait(false); // If there are common elements, then there's unconfirmed. return transactionHashes.Intersect(unconfirmedTransactionHashes); } /// <summary> /// Recursively gathers all the dependents of the mempool transactions provided. /// </summary> /// <param name="transactionHashes">Mempool transactions to gather their dependents.</param> /// <param name="includingProvided">Should it include in the result the unconfirmed ones from the provided transactionHashes.</param> /// <param name="likelyProvidedManyConfirmedOnes">If many provided transactionHashes are not confirmed then it optimizes by doing a check in the beginning of which ones are unconfirmed.</param> /// <returns>All the dependents of the provided transactionHashes.</returns> public static async Task<ISet<uint256>> GetAllDependentsAsync(this IRPCClient rpc, IEnumerable<uint256> transactionHashes, bool includingProvided, bool likelyProvidedManyConfirmedOnes) { IEnumerable<uint256> workingTxHashes = likelyProvidedManyConfirmedOnes // If confirmed txIds are provided, then do a big check first. ? await rpc.GetUnconfirmedAsync(transactionHashes).ConfigureAwait(false) : transactionHashes; var hashSet = new HashSet<uint256>(); foreach (var txId in workingTxHashes) { // Go through all the txIds provided and getmempoolentry to get the dependents and the confirmation status. var entry = await rpc.GetMempoolEntryAsync(txId, throwIfNotFound: false).ConfigureAwait(false); if (entry is { }) { // If we asked to include the provided transaction hashes into the result then check which ones are confirmed and do so. if (includingProvided) { hashSet.Add(txId); } // Get all the dependents of all the dependents except the ones we already know of. var except = entry.Depends.Except(hashSet); var dependentsOfDependents = await rpc.GetAllDependentsAsync(except, includingProvided: true, likelyProvidedManyConfirmedOnes: false).ConfigureAwait(false); // Add them to the hashset. hashSet.UnionWith(dependentsOfDependents); } } return hashSet; } } }
using DevExpress.Mvvm.POCO; using DevExpress.Mvvm.UI; using NUnit.Framework; using System; using System.Linq; using System.Windows.Controls; using System.ComponentModel; using System.Windows; using System.Reflection; namespace DevExpress.Xpf.DXBinding.Tests { [Platform("NET")] [TestFixture] public class CommandTests { [SetUp] public virtual void Init() { BindingListener.Enable(); BindingTestHelper.TestsSetUp(); BindingTestHelper.SetResolvingMode(DXBindingResolvingMode.LegacyStaticTyping); } [TearDown] public virtual void TearDown() { BindingTestHelper.TestsTearDown(); BindingListener.Disable(); BindingTestHelper.ClearResolvingMode(); } [Test, Retry(3)] public virtual void OneExecute() { var vm = CommandTests_a.Create(); var bt = BindingTestHelper.BindAssert<Button>("Button", "Command", "{b:DXCommand Do1()}", null, vm); BindingTestHelper.DoCommand(bt); Assert.AreEqual(1, vm.Do1Counter); BindingTestHelper.DoCommand(bt); Assert.AreEqual(2, vm.Do1Counter); vm = CommandTests_a.Create(); vm.CanDo1Value = true; bt = BindingTestHelper.BindAssert<Button>("Button", "Command", "{b:DXCommand Do1(), CanExecute='CanDo1()'}", null, vm); Assert.AreEqual(1, vm.CanDo1Counter); vm = CommandTests_a.Create(); bt = BindingTestHelper.BindAssert<Button>("Button", "Command", "{b:DXCommand Do1(), CanExecute='CanDo1()'}", null, vm); Assert.AreEqual(1, vm.CanDo1Counter); Assert.AreEqual(false, BindingTestHelper.CanDoCommand(bt)); Assert.AreEqual(2, vm.CanDo1Counter); Assert.AreEqual(0, vm.Do1Counter); vm.CanDo1Value = true; Assert.AreEqual(true, BindingTestHelper.CanDoCommand(bt)); Assert.AreEqual(3, vm.CanDo1Counter); BindingTestHelper.DoCommand(bt); Assert.AreEqual(1, vm.Do1Counter); } [Test] public virtual void TwoExecute() { var vm = CommandTests_a.Create(); var bt = BindingTestHelper.BindAssert<Button>("Button", "Command", "{b:DXCommand Execute='Do1(); Do2()'}", null, vm); BindingTestHelper.DoCommand(bt); Assert.AreEqual(1, vm.Do1Counter); Assert.AreEqual(1, vm.Do2Counter); BindingTestHelper.DoCommand(bt); Assert.AreEqual(2, vm.Do1Counter); Assert.AreEqual(2, vm.Do2Counter); vm = CommandTests_a.Create(); bt = BindingTestHelper.BindAssert<Button>("Button", "Command", "{b:DXCommand Execute='Do1(); Do2()', CanExecute='CanDo1() &amp;&amp; CanDo2()'}", null, vm); Assert.AreEqual(false, BindingTestHelper.CanDoCommand(bt)); Assert.AreEqual(2, vm.CanDo1Counter); Assert.AreEqual(0, vm.CanDo2Counter); vm.CanDo1Value = true; Assert.AreEqual(false, BindingTestHelper.CanDoCommand(bt)); Assert.AreEqual(3, vm.CanDo1Counter); Assert.AreEqual(1, vm.CanDo2Counter); vm.CanDo2Value = true; Assert.AreEqual(true, BindingTestHelper.CanDoCommand(bt)); Assert.AreEqual(4, vm.CanDo1Counter); Assert.AreEqual(2, vm.CanDo2Counter); BindingTestHelper.DoCommand(bt); Assert.AreEqual(1, vm.Do1Counter); Assert.AreEqual(1, vm.Do2Counter); } [Test] public virtual void Arguments() { var vm = CommandTests_a.Create(); var bt = BindingTestHelper.BindAssert<Button>("Button", "Command", "{b:DXCommand Execute='Do3(@s.Tag.Parameter, @parameter);', CanExecute='CanDo3(@s.Tag.CanDo)'}", null, vm); Assert.AreEqual(false, BindingTestHelper.CanDoCommand(bt)); bt.Tag = new { CanDo = true }; BindingTestHelper.DoEvents(bt); Assert.AreEqual(false, BindingTestHelper.CanDoCommand(bt)); bt.Tag = new { CanDo = true, Parameter = 1 }; BindingTestHelper.DoEvents(bt); Assert.AreEqual(false, BindingTestHelper.CanDoCommand(bt)); bt.CommandParameter = 1; BindingTestHelper.DoEvents(bt); Assert.AreEqual(true, BindingTestHelper.CanDoCommand(bt)); BindingTestHelper.DoCommand(bt); Assert.AreEqual(2, vm.Do3Value); } [Test, Retry(3)] public virtual void CommandInStyleSetter() { string xaml1 = @" <Grid> <Grid.Resources> <Style x:Key=""st"" TargetType=""Button""> <Setter Property=""Command"" Value=""{b:DXCommand Method($test:BindingTests_a.StaticIntProp)}""/> </Style> </Grid.Resources> <Button Style=""{StaticResource st}""/> <Button Style=""{StaticResource st}""/> </Grid> "; string xaml2 = @" <Grid> <Grid.Resources> <Style TargetType=""Button""> <Setter Property=""Command"" Value=""{b:DXCommand Method($test:BindingTests_a.StaticIntProp)}""/> </Style> </Grid.Resources> <Button/> <Button/> </Grid> "; Action<string> test = xamlStr => { BindingTests_a.Static(2); var panel = BindingTestHelper.LoadXaml<Grid>(xamlStr); var tb1 = (Button)panel.Children[0]; var tb2 = (Button)panel.Children[1]; var vm = CommandTests_a.Create(); panel.DataContext = vm; BindingTestHelper.DoEvents(panel); BindingTestHelper.DoCommand(tb1); Assert.AreEqual(2, vm.MethodValue); BindingTests_a.Static(3); BindingTestHelper.DoCommand(tb2); Assert.AreEqual(3, vm.MethodValue); }; test(xaml1); test(xaml2); } [Test] public virtual void CommandInDataTemplate() { string xaml = @" <Grid> <Grid.Resources> <DataTemplate x:Key=""temp""> <Button Command=""{b:DXCommand 'Method($test:BindingTests_a.StaticIntProp)'}""/> </DataTemplate> </Grid.Resources> <ContentControl Content=""{b:DXBinding}"" ContentTemplate=""{StaticResource temp}""/> <ContentControl Content=""{b:DXBinding}"" ContentTemplate=""{StaticResource temp}""/> </Grid> "; var panel = BindingTestHelper.LoadXaml<Grid>(xaml); BindingTestHelper.VisualTest(panel, () => { BindingTests_a.Static(2); var vm = CommandTests_a.Create(); var tb1 = LayoutTreeHelper.GetVisualChildren(panel.Children[0]).OfType<Button>().First(); var tb2 = LayoutTreeHelper.GetVisualChildren(panel.Children[1]).OfType<Button>().First(); panel.DataContext = vm; BindingTestHelper.DoEvents(panel); BindingTestHelper.DoCommand(tb1); Assert.AreEqual(1, vm.MethodCounter); BindingTestHelper.DoCommand(tb2); Assert.AreEqual(2, vm.MethodCounter); }); } [Test] public virtual void StaticMethod() { CommandTests_a.DoValue = 0; var bt = BindingTestHelper.BindAssert<Button>("Button", "Command", "{b:DXCommand '$test:CommandTests_a.DoStatic()'}", null, null); BindingTestHelper.DoCommand(bt); Assert.AreEqual(1, CommandTests_a.DoValue); CommandTests_a.DoValue = 0; bt = BindingTestHelper.BindAssert<Button>("Button", "Command", "{b:DXCommand '$test:CommandTests_a.DoStatic()'}", null, new object()); BindingTestHelper.DoCommand(bt); Assert.AreEqual(1, CommandTests_a.DoValue); } } [Platform("NET")] [TestFixture] public class CommandTests_Dynamic : CommandTests { [SetUp] public override void Init() { base.Init(); BindingTestHelper.SetResolvingMode(DXBindingResolvingMode.DynamicTyping); } [TearDown] public override void TearDown() { base.TearDown(); BindingTestHelper.ClearResolvingMode(); } [Test] public override void Arguments() { var vm = CommandTests_a.Create(); var bt = BindingTestHelper.BindAssert<Button>("Button", "Command", "{b:DXCommand Execute='Do3(@s.Tag.Parameter, @parameter);', CanExecute='CanDo3(@s.Tag.CanDo)'}", null, vm); Assert.AreEqual(false, BindingTestHelper.CanDoCommand(bt)); bt.Tag = new { CanDo = true }; BindingTestHelper.DoEvents(bt); Assert.AreEqual(true, BindingTestHelper.CanDoCommand(bt)); bt.Tag = new { CanDo = true, Parameter = 1 }; BindingTestHelper.DoEvents(bt); Assert.AreEqual(true, BindingTestHelper.CanDoCommand(bt)); bt.CommandParameter = 1; BindingTestHelper.DoEvents(bt); Assert.AreEqual(true, BindingTestHelper.CanDoCommand(bt)); BindingTestHelper.DoCommand(bt); Assert.AreEqual(2, vm.Do3Value); } [Test] public void NewOperator() { var vm = new CommandTests_b(); var bt = BindingTestHelper.BindAssert<Button>( "Button", "Command", @"{b:DXCommand Execute='Do(@s.Margin);', CanExecute='new $Thickness(@s.Margin.Bottom).Left == 1'}", null, vm); Assert.AreEqual(false, BindingTestHelper.CanDoCommand(bt)); Assert.AreEqual(0, vm.DoubleProp); bt.Margin = new Thickness(1, 0, 0, 0); BindingTestHelper.DoEvents(bt); Assert.AreEqual(false, BindingTestHelper.CanDoCommand(bt)); Assert.AreEqual(0, vm.DoubleProp); bt.Margin = new Thickness(1, 0, 0, 1); BindingTestHelper.DoEvents(bt); Assert.AreEqual(true, BindingTestHelper.CanDoCommand(bt)); BindingTestHelper.DoCommand(bt); BindingTestHelper.DoEvents(bt); Assert.AreEqual(1, vm.DoubleProp); } [Test] public void AssignOperator() { var vm = new CommandTests_b() { IntProp = 0 }; var bt = BindingTestHelper.BindAssert<Button>( "Button", "Command", @"{b:DXCommand Execute='IntProp = IntProp + 1'}", null, vm); Assert.AreEqual(0, vm.IntProp); BindingTestHelper.DoCommand(bt); BindingTestHelper.DoEvents(bt); Assert.AreEqual(1, vm.IntProp); vm.IntProp = 0; bt = BindingTestHelper.BindAssert<Button>( "Button", "Command", @"{b:DXCommand Execute='IntProp = IntProp + @parameter'}", null, vm); bt.CommandParameter = 1; Assert.AreEqual(0, vm.IntProp); BindingTestHelper.DoCommand(bt); BindingTestHelper.DoEvents(bt); Assert.AreEqual(1, vm.IntProp); bt.CommandParameter = 2; BindingTestHelper.DoCommand(bt); BindingTestHelper.DoEvents(bt); Assert.AreEqual(3, vm.IntProp); bt = BindingTestHelper.BindAssert<Button>( "Button", "Command", @"{b:DXCommand Execute='@s.Tag = @parameter'}", null, null); bt.CommandParameter = 1; BindingTestHelper.DoCommand(bt); BindingTestHelper.DoEvents(bt); Assert.AreEqual(1, bt.Tag); bt.CommandParameter = 2; BindingTestHelper.DoCommand(bt); BindingTestHelper.DoEvents(bt); Assert.AreEqual(2, bt.Tag); } [Test] public void AssignOperator_ElementName() { string xaml = @" <Grid x:Name=""panel"" Tag=""{b:DXBinding '1'}""> <Button Command=""{b:DXCommand Execute='@e(panel).Tag = @e(panel).Tag + 1'}""/> </Grid> "; var panel = BindingTestHelper.LoadXaml<Grid>(xaml); var bt = (Button)panel.Children[0]; Assert.AreEqual(1, panel.Tag); BindingTestHelper.DoCommand(bt); BindingTestHelper.DoEvents(bt); Assert.AreEqual(2, panel.Tag); } [Test] public void AssignOperators() { var vm = new CommandTests_b() { IntProp = 0 }; var bt = BindingTestHelper.BindAssert<Button>( "Button", "Command", @"{b:DXCommand Execute='IntProp = IntProp + 1; IntProp = IntProp + 1;;'}", null, vm); Assert.AreEqual(0, vm.IntProp); BindingTestHelper.DoCommand(bt); BindingTestHelper.DoEvents(bt); Assert.AreEqual(2, vm.IntProp); } [Test] public void AssignOperator_Static() { CommandTests_a.DoValue = 0; var bt = BindingTestHelper.BindAssert<Button>( "Button", "Command", @"{b:DXCommand Execute='$test:CommandTests_a.DoValue = $test:CommandTests_a.DoValue + 1'}", null, null); Assert.AreEqual(0, CommandTests_a.DoValue); BindingTestHelper.DoCommand(bt); BindingTestHelper.DoEvents(bt); Assert.AreEqual(1, CommandTests_a.DoValue); } [Test] public void AttachedPropertyTest() { var bt = BindingTestHelper.BindAssert<Button>( "Button", "Command", @"{b:DXCommand Execute='@s.($test:CommandTests_a.AttachedProp) = true'}", null, null, false); Assert.AreEqual(null, CommandTests_a.GetAttachedProp(bt)); BindingTestHelper.DoCommand(bt); BindingTestHelper.DoEvents(bt); Assert.AreEqual(true, CommandTests_a.GetAttachedProp(bt)); } [Test] public void T684511() { var vm = new CommandTests_b(); var bt = BindingTestHelper.BindAssert<Button>( "Button", "Command", @"{b:DXCommand Execute='DoException()'}", null, vm); Assert.DoesNotThrow(() => BindingTestHelper.DoCommand(bt)); bt = BindingTestHelper.BindAssert<Button>( "Button", "Command", @"{b:DXCommand Execute='DoException()', CatchExceptions=False}", null, vm); var e = Assert.Throws<TargetInvocationException>(() => BindingTestHelper.DoCommand(bt)); Assert.AreEqual("DoException", e.InnerException.Message); } } public class CommandTests_a { public static readonly DependencyProperty AttachedPropProperty = DependencyProperty.RegisterAttached("AttachedProp", typeof(object), typeof(CommandTests_a), new PropertyMetadata(null)); public static object GetAttachedProp(DependencyObject obj) { return (object)obj.GetValue(AttachedPropProperty); } public static void SetAttachedProp(DependencyObject obj, object value) { obj.SetValue(AttachedPropProperty, value); } public static int DoValue { get; set; } public static void DoStatic() { DoValue++; } public static CommandTests_a Create() { return ViewModelSource.Create(() => new CommandTests_a()); } protected CommandTests_a() { } public virtual int Do1Counter { get; set; } public virtual int Do2Counter { get; set; } public virtual int CanDo1Counter { get; set; } public virtual int CanDo2Counter { get; set; } public virtual bool CanDo1Value { get; set; } public virtual bool CanDo2Value { get; set; } public void Do1() { Do1Counter++; } public void Do2() { Do2Counter++; } public bool CanDo1() { CanDo1Counter++; return CanDo1Value; } public bool CanDo2() { CanDo2Counter++; return CanDo2Value; } public virtual int Do3Value { get; set; } public void Do3(int p1, int p2) { Do3Value = p1 + p2; } public bool CanDo3(bool p) { return p; } public virtual int MethodValue { get; set; } public virtual int MethodCounter { get; set; } public void Method(int p) { MethodValue = p; MethodCounter++; } } public class CommandTests_b : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; int intProp; public int IntProp { get { return intProp; } set { if (intProp == value) return; intProp = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("IntProp")); } } double doubleProp; public double DoubleProp { get { return doubleProp; } set { if (doubleProp == value) return; doubleProp = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("DoubleProp")); } } string stringProp; public string StringProp { get { return stringProp; } set { if (stringProp == value) return; stringProp = value; if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("StringProp")); } } public CommandTests_b GetSelf() { return this; } public CommandTests_b() { } public CommandTests_b(double v) { DoubleProp = v; } public void Do(Thickness thickness) { DoubleProp = thickness.Left; } public void DoException() { throw new Exception("DoException"); } } }
// NewMessage.cs // // Copyright (c) 2013 Brent Knowles (http://www.brentknowles.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Review documentation at http://www.yourothermind.com for updated implementation notes, license updates // or other general information/ // // Author information available at http://www.brentknowles.com or http://www.amazon.com/Brent-Knowles/e/B0035WW7OW // Full source code: https://github.com/BrentKnowles/YourOtherMind //### using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Drawing; using System.IO; namespace CoreUtilities { /// <summary> /// Replacement class for MessageBox that will allow custom text /// </summary> public static class NewMessage { private static Image image = null; private static Icon icon = null; private static bool bSetupRan = false; static ImageLayout newLayout; static Color transKey; static Font captionFont; static Font textFont; static Color buttonColor; static Color captionColor; static Color textColor; static Color formBackColor; static Color captionBackColor; static Color textBackColor; /// <summary> /// because this is static we can set some varibles that /// become true for entire application /// /// This should be called before first use but not essential /// </summary> /// <param name="image"></param> /// <param name="newIcon">STRING to a file, leave NULL if none</param> /// <param name="_buttonColor"></param> public static void SetupBoxFirstTime(Image newImage, Icon newIcon, ImageLayout _newLayout, Color _transKey, Font _captionFont, Font _textFont, Color _buttonColor, Color _captionColor, Color _textColor, Color _formBackColor, Color _captionBackColor, Color _textBackColor) { image = newImage; newLayout = _newLayout; transKey = _transKey; captionFont = _captionFont; textFont = _textFont; buttonColor = _buttonColor; captionColor = _captionColor; textColor = _textColor; formBackColor = _formBackColor; captionBackColor = _captionBackColor; textBackColor = _textBackColor; icon = newIcon; bSetupRan = true; } /// <summary> /// A wrapper for a plain Just text messagebox /// </summary> /// <param name="sCaption"></param> /// <returns></returns> public static DialogResult Show(string sText) { return Show("", sText, MessageBoxButtons.OK, null); } /// <summary> /// A wrapper for a messagebox with caption and text /// </summary> /// <param name="sCaption"></param> /// <param name="sText"></param> /// <returns></returns> public static DialogResult Show(string sCaption, string sText) { return Show(sCaption, sText, MessageBoxButtons.OK, null); } /// <summary> /// For displays a messagebox with an edit box /// /// </summary> /// <param name="sCaption"></param> /// <param name="sText"></param> /// <param name="_picImage"></param> /// <returns>"" if no text or cancel</returns> public static string Show(string sCaption, string sText, Image _picImage, bool bOkEnabled, string sDefault) { string sInput=""; if (Show(sCaption, sText, MessageBoxButtons.OKCancel, _picImage, true, out sInput, bOkEnabled, sDefault) == DialogResult.OK) { return sInput; } return ""; } /// <summary> /// /// </summary> /// <param name="sCaption"></param> /// <param name="sText"></param> /// <param name="buttons"></param> /// <param name="_picImage"></param> /// <param name="bEdit"></param> /// <param name="InputText"></param> /// <param name="bOkDefault"></param> /// <param name="sEditText"></param> /// <param name="sWebLink"></param> /// <param name="sHelpLink"></param> /// <param name="sHelpFile"></param> /// <param name="AlwaysOnTop"></param> /// <param name="editsize"></param> /// <returns></returns> public static string Show(string sCaption, string sText, MessageBoxButtons buttons, Image _picImage, bool bEdit, out string InputText, bool bOkDefault, string sEditText, string sWebLink, string sHelpLink, string sHelpFile, int editsize) { string sInput = ""; InputText = ""; if (Show(sCaption, sText, MessageBoxButtons.OKCancel, _picImage, true, out sInput, bOkDefault, sEditText, sWebLink, sHelpFile, sHelpFile, false, editsize) == DialogResult.OK) { return sInput; } return ""; } /// <summary> /// wrapper for a standard message /// </summary> /// <param name="sCaption"></param> /// <param name="sText"></param> /// <param name="buttons"></param> /// <param name="_picImage"></param> /// <returns></returns> public static DialogResult Show(string sCaption, string sText, MessageBoxButtons buttons, Image _picImage) { string s = ""; return Show(sCaption, sText, buttons, _picImage, false, out s, false, null); } public static DialogResult Show(string sCaption, string sText, MessageBoxButtons buttons, Image _picImage, bool bEdit, out string InputText, bool bOkDefault, string sEditText) { // string s = ""; return Show(sCaption, sText, buttons, _picImage, bEdit, out InputText, bOkDefault, sEditText,"","",""); } /// <summary> /// for help /// </summary> /// <param name="?"></param> /// <returns></returns> public static DialogResult Show(string sCaption, string sText, string sWebLink, string sHelpLink, string sHelpFile) { string s = ""; return Show(sCaption, sText, MessageBoxButtons.OK, null, false, out s, true, "", sWebLink, sHelpLink, sHelpFile); } /// <summary> /// Always On Top, exposed /// </summary> /// <param name="sCaption"></param> /// <param name="sText"></param> /// <returns></returns> public static DialogResult Show(string sCaption, string sText, bool bAlwaysOnTop) { string s = ""; return Show(sCaption, sText, MessageBoxButtons.OK, null, false, out s, false, null,"", "", "", bAlwaysOnTop,-1); } public static DialogResult Show(string sCaption, string sText, MessageBoxButtons buttons, Image _picImage, bool bEdit, out string InputText, bool bOkDefault, string sEditText, string sWebLink, string sHelpLink, string sHelpFile) { return Show(sCaption, sText, buttons, _picImage, bEdit, out InputText, bOkDefault, sEditText, sWebLink, sHelpFile, sHelpFile, false, -1); } /// <summary> /// /// </summary> /// <param name="sCaption"></param> /// <param name="sText"></param> /// <param name="buttons"></param> /// <param name="_picImage">if not null this image will show up on the form</param> /// <param name="bEdit">if true there's an edit field</param> /// <param name="bOkDefault">if set to true the OK button will be default, generally not the case (Cancel is default)</param> /// <param name="InputText">the variable to returnt he modified text if usign this as a textbox entry</param> /// <param name="sEditText">default value for a textbox</param> /// <returns></returns> public static DialogResult Show(string sCaption, string sText, MessageBoxButtons buttons, Image _picImage, bool bEdit, out string InputText, bool bOkDefault, string sEditText, string sWebLink, string sHelpLink, string sHelpFile, bool AlwaysOnTop, int editsize) { if (bSetupRan == false) { lg.Instance.Line("NewMessage.Show", ProblemType.ERROR, "MessageBox invoked without a call to SetupBoxFirstTime"); } form_NewMessage form = new form_NewMessage(); if (true == AlwaysOnTop) { form.TopMost = true; } if (sEditText != null) { form.userinput.Text = sEditText; } if (bEdit == true) { form.userinput.Visible = true; form.userinput.Dock = DockStyle.Top; form.userinput.TabIndex = 0; if (editsize > -1) { form.userinput.MaxLength = editsize; } } form.SetupForButtons(buttons, buttonColor, bOkDefault); form.SetupColors(formBackColor, captionColor, textColor, captionBackColor, textBackColor); form.SetupFonts(captionFont, textFont); form.SetupStrings(sCaption, sText); // adjust image if (image != null) { form.BackgroundImage = image; form.BackgroundImageLayout = newLayout; form.TransparencyKey = transKey; } if (icon != null /*&& File.Exists(icon)*/) { try { form.Icon = icon;//new Icon(icon, 24, 24); } catch (Exception) { lg.Instance.Line("NewMessage.Show", ProblemType.EXCEPTION,"not a valid icon for NewMessage" +icon); } } if (_picImage != null) { form.picImage.BackgroundImage = _picImage; form.picImage.Width = 48; form.picImage.Height = 48; form.picImage.BackgroundImageLayout = ImageLayout.Stretch; form.picImage.Visible = true; } if (sWebLink != "" || sHelpLink != "") { form.SetupForHelpMode(sWebLink, sHelpLink, sHelpFile); } DialogResult result = form.ShowDialog(); InputText = form.userinput.Text; form = null; lg.Instance.Line("NewMessage.Show", ProblemType.TEMPORARY, "NewMessage ShowMessage button response" + result.ToString()); return result; } } }
// 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 System.IO; using System.Text; using Alachisoft.NCache.Caching; using Alachisoft.NCache.Common; using Alachisoft.NCache.Runtime.Serialization; using Alachisoft.NCache.Serialization.Formatters; namespace Alachisoft.NCache.Util { /// <summary> /// {^[\t, ]*}internal{[a-z, ]*}class{[A-Z,a-z,\,,\:,\t, ]*$} /// #if DEBUG\n\1public\2class\3\n#else\n\1internal\2class\3\n#endif /// Utility class to help with common tasks. /// </summary> public class SerializationUtil { /// <summary> /// Serializes the object using CompactSerialization Framwork. /// </summary> /// <param name="graph"></param> /// <returns></returns> public static object CompactSerialize(object graph, string cacheContext) { if (graph != null && graph is ICompactSerializable) { System.IO.MemoryStream stream = new System.IO.MemoryStream(); stream.Write(NCHeader.Version, 0, NCHeader.Length); CompactBinaryFormatter.Serialize(stream, graph, cacheContext); return stream.ToArray(); } return graph; } /// <summary> /// Serializes the object using CompactSerialization Framwork. /// </summary> /// <param name="graph"></param> /// <returns></returns> public static object CompactSerialize(Stream stream, object graph, string cacheContext) { if (graph != null && graph is ICompactSerializable) { byte[] buffer; stream.Position = 0; stream.Write(NCHeader.Version, 0, NCHeader.Length); CompactBinaryFormatter.Serialize(stream, graph, cacheContext, false); buffer = new byte[stream.Position]; stream.Position = 0; stream.Read(buffer, 0, buffer.Length); stream.Position = 0; return buffer; } return graph; } /// <summary> /// Deserializes the byte buffer to an object using CompactSerialization Framwork. /// </summary> /// <param name="buffer"></param> /// <returns></returns> public static object CompactDeserialize(object buffer, string cacheContext) { object obj = buffer; if (buffer != null && buffer is byte[]) { if (HasHCHeader((byte[])buffer)) { System.IO.MemoryStream stream = new System.IO.MemoryStream((byte[])buffer); //Skip the NCHeader. stream.Position += NCHeader.Length; obj = CompactBinaryFormatter.Deserialize(stream, cacheContext); return obj; } } return obj; } public static object SafeDeserialize(object serializedObject, string serializationContext, BitSet flag) { object deserialized = serializedObject; try { if(!flag.IsBitSet(BitSetConstants.BinaryData)) { if (serializedObject is byte[]) { deserialized = CompactBinaryFormatter.FromByteBuffer((byte[])serializedObject, serializationContext); } else if (serializedObject is UserBinaryObject) { deserialized = CompactBinaryFormatter.FromByteBuffer(((UserBinaryObject)serializedObject).GetFullObject(), serializationContext); } } } catch (Exception ex) { //Kill the exception; it is possible that object was serialized by Java //or from any other domain which can not be deserialized by us. deserialized = serializedObject; } return deserialized; } public static object SafeSerialize(object serializableObject, string serializationContext, ref BitSet flag) { if (serializableObject != null) { if (serializableObject is byte[]) { flag.SetBit(BitSetConstants.BinaryData); return serializableObject; } serializableObject = CompactBinaryFormatter.ToByteBuffer(serializableObject, serializationContext); } return serializableObject; } /// <summary> /// Deserializes the byte buffer to an object using CompactSerialization Framwork. /// </summary> /// <param name="buffer"></param> /// <returns></returns> public static object CompactDeserialize(Stream stream, object buffer, string cacheContext) { object obj = buffer; if (buffer != null && buffer is byte[]) { if (HasHCHeader((byte[])buffer)) { byte[] tmp = (byte[])buffer; stream.Position = 0; stream.Write(tmp, 0, tmp.Length); stream.Position = 0; //Skip the NCHeader. stream.Position += NCHeader.Length; obj = CompactBinaryFormatter.Deserialize(stream, cacheContext, false); stream.Position = 0; return obj; } } return obj; } /// <summary> /// CompactBinarySerialize which takes object abd return byte array /// </summary> /// <param name="serializableObject"></param> /// <param name="serializationContext"></param> /// <returns></returns> public static byte[] CompactBinarySerialize(object serializableObject, string serializationContext) { return CompactBinaryFormatter.ToByteBuffer(serializableObject, serializationContext); } /// <summary> /// convert bytes into object /// </summary> /// <param name="buffer"></param> /// <param name="serializationContext"></param> /// <returns></returns> public static object CompactBinaryDeserialize(byte[] buffer, string serializationContext) { return CompactBinaryFormatter.FromByteBuffer(buffer, serializationContext); } /// <summary> /// Checks whtether the given buffer has NCHeader attached or not. /// </summary> /// <param name="serializedBuffer"></param> /// <returns></returns> internal static bool HasHCHeader(byte[] serializedBuffer) { byte[] header = new byte[5]; if (serializedBuffer.Length >= NCHeader.Length) { for (int i = 0; i < NCHeader.Length; i++) { header[i] = serializedBuffer[i]; } return NCHeader.CompareTo(header); } return false; } /// <summary> /// Called recursively and iterates through the string at every '_dictionary' occurance until the string ends /// </summary> /// <param name="protocolString">String sent by the server</param> /// <param name="startIndex">start of string</param> /// <param name="endIndex">sent by the server</param> /// <returns>complete hashmap as stored in config read by service</returns> public static Hashtable GetTypeMapFromProtocolString(string protocolString, ref int startIndex, ref int endIndex) { endIndex = protocolString.IndexOf('"', startIndex + 1); Hashtable tbl = new Hashtable(); string token = protocolString.Substring(startIndex, (endIndex) - (startIndex)); if (token == "__dictionary") { startIndex = endIndex + 1; endIndex = protocolString.IndexOf('"', endIndex + 1); int dicCount = Convert.ToInt32(protocolString.Substring(startIndex, (endIndex) - (startIndex))); for (int i = 0; i < dicCount; i++) { startIndex = endIndex + 1; endIndex = protocolString.IndexOf('"', endIndex + 1); string key = protocolString.Substring(startIndex, (endIndex) - (startIndex)); startIndex = endIndex + 1; endIndex = protocolString.IndexOf('"', endIndex + 1); string value = protocolString.Substring(startIndex, (endIndex) - (startIndex)); if (value == "__dictionary") { tbl[key] = GetTypeMapFromProtocolString(protocolString, ref startIndex, ref endIndex); } else { tbl[key] = value; } } } return tbl; } public static string GetProtocolStringFromTypeMap(Hashtable typeMap) { System.Collections.Stack st = new Stack(); StringBuilder protocolString = new StringBuilder(); protocolString.Append("__dictionary").Append("\""); protocolString.Append(typeMap.Count).Append("\""); IDictionaryEnumerator mapDic = typeMap.GetEnumerator(); while (mapDic.MoveNext()) { if (mapDic.Value is Hashtable) { st.Push(mapDic.Value); st.Push(mapDic.Key); } else { protocolString.Append(mapDic.Key).Append("\""); protocolString.Append(mapDic.Value).Append("\""); } } while (st.Count != 0 && st.Count % 2 == 0) { protocolString.Append(st.Pop() as string).Append("\""); protocolString.Append(GetProtocolStringFromTypeMap(st.Pop() as Hashtable)); } return protocolString.ToString(); } //Helper method to convert Attrib object to NonComapactField public struct TypeHandlePair { public Type _type; public short _handle; public TypeHandlePair(Type type, short handle) { this._type = type; this._handle = handle; } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenMetaverse.StructuredData; using OpenSim.Framework; using OpenSim.Region.CoreModules.Framework.EventQueue; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using Caps = OpenSim.Framework.Capabilities.Caps; namespace OpenSim.Region.OptionalModules.Avatar.XmlRpcGroups { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")] public class GroupsMessagingModule : ISharedRegionModule { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private List<Scene> m_sceneList = new List<Scene>(); private IMessageTransferModule m_msgTransferModule = null; private IGroupsModule m_groupsModule = null; // TODO: Move this off to the Groups Server public Dictionary<Guid, List<Guid>> m_agentsInGroupSession = new Dictionary<Guid, List<Guid>>(); public Dictionary<Guid, List<Guid>> m_agentsDroppedSession = new Dictionary<Guid, List<Guid>>(); // Config Options private bool m_groupMessagingEnabled = false; private bool m_debugEnabled = true; #region IRegionModuleBase Members public void Initialise(IConfigSource config) { IConfig groupsConfig = config.Configs["Groups"]; if (groupsConfig == null) { // Do not run this module by default. return; } else { // if groups aren't enabled, we're not needed. // if we're not specified as the connector to use, then we're not wanted if ((groupsConfig.GetBoolean("Enabled", false) == false) || (groupsConfig.GetString("MessagingModule", "Default") != Name)) { m_groupMessagingEnabled = false; return; } m_groupMessagingEnabled = groupsConfig.GetBoolean("MessagingEnabled", true); if (!m_groupMessagingEnabled) { return; } m_log.Info("[GROUPS-MESSAGING]: Initializing GroupsMessagingModule"); m_debugEnabled = groupsConfig.GetBoolean("DebugEnabled", true); } m_log.Info("[GROUPS-MESSAGING]: GroupsMessagingModule starting up"); } public void AddRegion(Scene scene) { // NoOp } public void RegionLoaded(Scene scene) { if (!m_groupMessagingEnabled) return; if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); m_groupsModule = scene.RequestModuleInterface<IGroupsModule>(); // No groups module, no groups messaging if (m_groupsModule == null) { m_log.Error("[GROUPS-MESSAGING]: Could not get IGroupsModule, GroupsMessagingModule is now disabled."); Close(); m_groupMessagingEnabled = false; return; } m_msgTransferModule = scene.RequestModuleInterface<IMessageTransferModule>(); // No message transfer module, no groups messaging if (m_msgTransferModule == null) { m_log.Error("[GROUPS-MESSAGING]: Could not get MessageTransferModule"); Close(); m_groupMessagingEnabled = false; return; } m_sceneList.Add(scene); scene.EventManager.OnNewClient += OnNewClient; scene.EventManager.OnIncomingInstantMessage += OnGridInstantMessage; } public void RemoveRegion(Scene scene) { if (!m_groupMessagingEnabled) return; if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); m_sceneList.Remove(scene); } public void Close() { if (!m_groupMessagingEnabled) return; if (m_debugEnabled) m_log.Debug("[GROUPS-MESSAGING]: Shutting down GroupsMessagingModule module."); foreach (Scene scene in m_sceneList) { scene.EventManager.OnNewClient -= OnNewClient; scene.EventManager.OnIncomingInstantMessage -= OnGridInstantMessage; } m_sceneList.Clear(); m_groupsModule = null; m_msgTransferModule = null; } public Type ReplaceableInterface { get { return null; } } public string Name { get { return "GroupsMessagingModule"; } } #endregion #region ISharedRegionModule Members public void PostInitialise() { // NoOp } #endregion #region SimGridEventHandlers private void OnNewClient(IClientAPI client) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: OnInstantMessage registered for {0}", client.Name); client.OnInstantMessage += OnInstantMessage; } private void OnGridInstantMessage(GridInstantMessage msg) { // The instant message module will only deliver messages of dialog types: // MessageFromAgent, StartTyping, StopTyping, MessageFromObject // // Any other message type will not be delivered to a client by the // Instant Message Module if (m_debugEnabled) { m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); DebugGridInstantMessage(msg); } // Incoming message from a group if ((msg.fromGroup == true) && ((msg.dialog == (byte)InstantMessageDialog.SessionSend) || (msg.dialog == (byte)InstantMessageDialog.SessionAdd) || (msg.dialog == (byte)InstantMessageDialog.SessionDrop))) { ProcessMessageFromGroupSession(msg); } } private void ProcessMessageFromGroupSession(GridInstantMessage msg) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Session message from {0} going to agent {1}", msg.fromAgentName, msg.toAgentID); switch (msg.dialog) { case (byte)InstantMessageDialog.SessionAdd: AddAgentToGroupSession(msg.fromAgentID, msg.imSessionID); break; case (byte)InstantMessageDialog.SessionDrop: RemoveAgentFromGroupSession(msg.fromAgentID, msg.imSessionID); break; case (byte)InstantMessageDialog.SessionSend: if (!m_agentsInGroupSession.ContainsKey(msg.toAgentID) && !m_agentsDroppedSession.ContainsKey(msg.toAgentID)) { // Agent not in session and hasn't dropped from session // Add them to the session for now, and Invite them AddAgentToGroupSession(msg.toAgentID, msg.imSessionID); UUID toAgentID = new UUID(msg.toAgentID); IClientAPI activeClient = GetActiveClient(toAgentID); if (activeClient != null) { UUID groupID = new UUID(msg.fromAgentID); GroupRecord groupInfo = m_groupsModule.GetGroupRecord(groupID); if (groupInfo != null) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Sending chatterbox invite instant message"); // Force? open the group session dialog??? IEventQueue eq = activeClient.Scene.RequestModuleInterface<IEventQueue>(); eq.ChatterboxInvitation( groupID , groupInfo.GroupName , new UUID(msg.fromAgentID) , msg.message, new UUID(msg.toAgentID) , msg.fromAgentName , msg.dialog , msg.timestamp , msg.offline == 1 , (int)msg.ParentEstateID , msg.Position , 1 , new UUID(msg.imSessionID) , msg.fromGroup , Utils.StringToBytes(groupInfo.GroupName) ); eq.ChatterBoxSessionAgentListUpdates( new UUID(groupID) , new UUID(msg.fromAgentID) , new UUID(msg.toAgentID) , false //canVoiceChat , false //isModerator , false //text mute ); } } } else if (!m_agentsDroppedSession.ContainsKey(msg.toAgentID)) { // User hasn't dropped, so they're in the session, // maybe we should deliver it. IClientAPI client = GetActiveClient(new UUID(msg.toAgentID)); if (client != null) { // Deliver locally, directly if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Delivering to {0} locally", client.Name); client.SendInstantMessage(msg); } else { m_log.WarnFormat("[GROUPS-MESSAGING]: Received a message over the grid for a client that isn't here: {0}", msg.toAgentID); } } break; default: m_log.WarnFormat("[GROUPS-MESSAGING]: I don't know how to proccess a {0} message.", ((InstantMessageDialog)msg.dialog).ToString()); break; } } #endregion #region ClientEvents private void RemoveAgentFromGroupSession(Guid agentID, Guid sessionID) { if (m_agentsInGroupSession.ContainsKey(sessionID)) { // If in session remove if (m_agentsInGroupSession[sessionID].Contains(agentID)) { m_agentsInGroupSession[sessionID].Remove(agentID); } // If not in dropped list, add if (!m_agentsDroppedSession[sessionID].Contains(agentID)) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Dropped {1} from session {0}", sessionID, agentID); m_agentsDroppedSession[sessionID].Add(agentID); } } } private void AddAgentToGroupSession(Guid agentID, Guid sessionID) { // Add Session Status if it doesn't exist for this session CreateGroupSessionTracking(sessionID); // If nessesary, remove from dropped list if (m_agentsDroppedSession[sessionID].Contains(agentID)) { m_agentsDroppedSession[sessionID].Remove(agentID); } // If nessesary, add to in session list if (!m_agentsInGroupSession[sessionID].Contains(agentID)) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Added {1} to session {0}", sessionID, agentID); m_agentsInGroupSession[sessionID].Add(agentID); } } private void CreateGroupSessionTracking(Guid sessionID) { if (!m_agentsInGroupSession.ContainsKey(sessionID)) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Creating session tracking for : {0}", sessionID); m_agentsInGroupSession.Add(sessionID, new List<Guid>()); m_agentsDroppedSession.Add(sessionID, new List<Guid>()); } } private void OnInstantMessage(IClientAPI remoteClient, GridInstantMessage im) { if (m_debugEnabled) { m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); DebugGridInstantMessage(im); } // Start group IM session if ((im.dialog == (byte)InstantMessageDialog.SessionGroupStart)) { UUID groupID = new UUID(im.toAgentID); GroupRecord groupInfo = m_groupsModule.GetGroupRecord(groupID); if (groupInfo != null) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Start Group Session for {0}", groupInfo.GroupName); AddAgentToGroupSession(im.fromAgentID, im.imSessionID); ChatterBoxSessionStartReplyViaCaps(remoteClient, groupInfo.GroupName, groupID); IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>(); queue.ChatterBoxSessionAgentListUpdates( new UUID(groupID) , new UUID(im.fromAgentID) , new UUID(im.toAgentID) , false //canVoiceChat , false //isModerator , false //text mute ); } } // Send a message from locally connected client to a group if ((im.dialog == (byte)InstantMessageDialog.SessionSend)) { UUID groupID = new UUID(im.toAgentID); if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Send message to session for group {0} with session ID {1}", groupID, im.imSessionID.ToString()); SendMessageToGroup(im, groupID); } } #endregion private void SendMessageToGroup(GridInstantMessage im, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); foreach (GroupMembersData member in m_groupsModule.GroupMembersRequest(null, groupID)) { if (!m_agentsDroppedSession.ContainsKey(im.imSessionID) || m_agentsDroppedSession[im.imSessionID].Contains(member.AgentID.Guid)) { // Don't deliver messages to people who have dropped this session if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: {0} has dropped session, not delivering to them", member.AgentID); continue; } // Copy Message GridInstantMessage msg = new GridInstantMessage(); msg.imSessionID = im.imSessionID; msg.fromAgentName = im.fromAgentName; msg.message = im.message; msg.dialog = im.dialog; msg.offline = im.offline; msg.ParentEstateID = im.ParentEstateID; msg.Position = im.Position; msg.RegionID = im.RegionID; msg.binaryBucket = im.binaryBucket; msg.timestamp = (uint)Util.UnixTimeSinceEpoch(); // Updat Pertinate fields to make it a "group message" msg.fromAgentID = groupID.Guid; msg.fromGroup = true; msg.toAgentID = member.AgentID.Guid; IClientAPI client = GetActiveClient(member.AgentID); if (client == null) { // If they're not local, forward across the grid if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Delivering to {0} via Grid", member.AgentID); m_msgTransferModule.SendInstantMessage(msg, delegate(bool success) { }); } else { // Deliver locally, directly if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Passing to ProcessMessageFromGroupSession to deliver to {0} locally", client.Name); ProcessMessageFromGroupSession(msg); } } } void ChatterBoxSessionStartReplyViaCaps(IClientAPI remoteClient, string groupName, UUID groupID) { if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: {0} called", System.Reflection.MethodBase.GetCurrentMethod().Name); OSDMap moderatedMap = new OSDMap(4); moderatedMap.Add("voice", OSD.FromBoolean(false)); OSDMap sessionMap = new OSDMap(4); sessionMap.Add("moderated_mode", moderatedMap); sessionMap.Add("session_name", OSD.FromString(groupName)); sessionMap.Add("type", OSD.FromInteger(0)); sessionMap.Add("voice_enabled", OSD.FromBoolean(false)); OSDMap bodyMap = new OSDMap(4); bodyMap.Add("session_id", OSD.FromUUID(groupID)); bodyMap.Add("temp_session_id", OSD.FromUUID(groupID)); bodyMap.Add("success", OSD.FromBoolean(true)); bodyMap.Add("session_info", sessionMap); IEventQueue queue = remoteClient.Scene.RequestModuleInterface<IEventQueue>(); if (queue != null) { queue.Enqueue(EventQueueHelper.buildEvent("ChatterBoxSessionStartReply", bodyMap), remoteClient.AgentId); } } private void DebugGridInstantMessage(GridInstantMessage im) { // Don't log any normal IMs (privacy!) if (m_debugEnabled && im.dialog != (byte)InstantMessageDialog.MessageFromAgent) { m_log.WarnFormat("[GROUPS-MESSAGING]: IM: fromGroup({0})", im.fromGroup ? "True" : "False"); m_log.WarnFormat("[GROUPS-MESSAGING]: IM: Dialog({0})", ((InstantMessageDialog)im.dialog).ToString()); m_log.WarnFormat("[GROUPS-MESSAGING]: IM: fromAgentID({0})", im.fromAgentID.ToString()); m_log.WarnFormat("[GROUPS-MESSAGING]: IM: fromAgentName({0})", im.fromAgentName.ToString()); m_log.WarnFormat("[GROUPS-MESSAGING]: IM: imSessionID({0})", im.imSessionID.ToString()); m_log.WarnFormat("[GROUPS-MESSAGING]: IM: message({0})", im.message.ToString()); m_log.WarnFormat("[GROUPS-MESSAGING]: IM: offline({0})", im.offline.ToString()); m_log.WarnFormat("[GROUPS-MESSAGING]: IM: toAgentID({0})", im.toAgentID.ToString()); m_log.WarnFormat("[GROUPS-MESSAGING]: IM: binaryBucket({0})", OpenMetaverse.Utils.BytesToHexString(im.binaryBucket, "BinaryBucket")); } } #region Client Tools /// <summary> /// Try to find an active IClientAPI reference for agentID giving preference to root connections /// </summary> private IClientAPI GetActiveClient(UUID agentID) { IClientAPI child = null; // Try root avatar first foreach (Scene scene in m_sceneList) { if (scene.Entities.ContainsKey(agentID) && scene.Entities[agentID] is ScenePresence) { ScenePresence user = (ScenePresence)scene.Entities[agentID]; if (!user.IsChildAgent) { return user.ControllingClient; } else { child = user.ControllingClient; } } } // If we didn't find a root, then just return whichever child we found, or null if none return child; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Buffers; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.HttpSys.Internal; using Microsoft.Extensions.Logging; namespace Microsoft.AspNetCore.Server.HttpSys { /// <summary> /// An HTTP server wrapping the Http.Sys APIs that accepts requests. /// </summary> internal partial class HttpSysListener : IDisposable { // Win8# 559317 fixed a bug in Http.sys's HttpReceiveClientCertificate method. // Without this fix IOCP callbacks were not being called although ERROR_IO_PENDING was // returned from HttpReceiveClientCertificate when using the // FileCompletionNotificationModes.SkipCompletionPortOnSuccess flag. // This bug was only hit when the buffer passed into HttpReceiveClientCertificate // (1500 bytes initially) is too small for the certificate. // Due to this bug in downlevel operating systems the FileCompletionNotificationModes.SkipCompletionPortOnSuccess // flag is only used on Win8 and later. internal static readonly bool SkipIOCPCallbackOnSuccess = ComNetOS.IsWin8orLater; // Mitigate potential DOS attacks by limiting the number of unknown headers we accept. Numerous header names // with hash collisions will cause the server to consume excess CPU. 1000 headers limits CPU time to under // 0.5 seconds per request. Respond with a 400 Bad Request. private const int UnknownHeaderLimit = 1000; internal MemoryPool<byte> MemoryPool { get; } = PinnedBlockMemoryPoolFactory.Create(); private volatile State _state; // m_State is set only within lock blocks, but often read outside locks. private readonly ServerSession _serverSession; private readonly UrlGroup _urlGroup; private readonly RequestQueue _requestQueue; private readonly DisconnectListener _disconnectListener; private readonly object _internalLock; public HttpSysListener(HttpSysOptions options, ILoggerFactory loggerFactory) { if (options == null) { throw new ArgumentNullException(nameof(options)); } if (loggerFactory == null) { throw new ArgumentNullException(nameof(loggerFactory)); } if (!HttpApi.Supported) { throw new PlatformNotSupportedException(); } Debug.Assert(HttpApi.ApiVersion == HttpApiTypes.HTTP_API_VERSION.Version20, "Invalid Http api version"); Options = options; Logger = loggerFactory.CreateLogger<HttpSysListener>(); _state = State.Stopped; _internalLock = new object(); // V2 initialization sequence: // 1. Create server session // 2. Create url group // 3. Create request queue // 4. Add urls to url group - Done in Start() // 5. Attach request queue to url group - Done in Start() try { _serverSession = new ServerSession(); _urlGroup = new UrlGroup(_serverSession, Logger); _requestQueue = new RequestQueue(_urlGroup, options.RequestQueueName, options.RequestQueueMode, Logger); _disconnectListener = new DisconnectListener(_requestQueue, Logger); } catch (Exception exception) { // If Url group or request queue creation failed, close server session before throwing. _requestQueue?.Dispose(); _urlGroup?.Dispose(); _serverSession?.Dispose(); Log.HttpSysListenerCtorError(Logger, exception); throw; } } internal enum State { Stopped, Started, Disposed, } internal ILogger Logger { get; private set; } internal UrlGroup UrlGroup { get { return _urlGroup; } } internal RequestQueue RequestQueue { get { return _requestQueue; } } internal DisconnectListener DisconnectListener { get { return _disconnectListener; } } public HttpSysOptions Options { get; } public bool IsListening { get { return _state == State.Started; } } /// <summary> /// Start accepting incoming requests. /// </summary> public void Start() { CheckDisposed(); Log.ListenerStarting(Logger); // Make sure there are no race conditions between Start/Stop/Abort/Close/Dispose. // Start needs to setup all resources. Abort/Stop must not interfere while Start is // allocating those resources. lock (_internalLock) { try { CheckDisposed(); if (_state == State.Started) { return; } // If this instance created the queue then configure it. if (_requestQueue.Created) { Options.Apply(UrlGroup, RequestQueue); _requestQueue.AttachToUrlGroup(); // All resources are set up correctly. Now add all prefixes. try { Options.UrlPrefixes.RegisterAllPrefixes(UrlGroup); } catch (HttpSysException) { // If an error occurred while adding prefixes, free all resources allocated by previous steps. _requestQueue.DetachFromUrlGroup(); throw; } } _state = State.Started; } catch (Exception exception) { // Make sure the HttpListener instance can't be used if Start() failed. _state = State.Disposed; DisposeInternal(); Log.ListenerStartError(Logger, exception); throw; } } } private void Stop() { try { lock (_internalLock) { CheckDisposed(); if (_state == State.Stopped) { return; } Log.ListenerStopping(Logger); // If this instance created the queue then remove the URL prefixes before shutting down. if (_requestQueue.Created) { Options.UrlPrefixes.UnregisterAllPrefixes(); _requestQueue.DetachFromUrlGroup(); } _state = State.Stopped; } } catch (Exception exception) { Log.ListenerStopError(Logger, exception); throw; } } /// <summary> /// Stop the server and clean up. /// </summary> public void Dispose() { Dispose(true); } private void Dispose(bool disposing) { if (!disposing) { return; } lock (_internalLock) { try { if (_state == State.Disposed) { return; } Log.ListenerDisposing(Logger); Stop(); DisposeInternal(); } catch (Exception exception) { Log.ListenerDisposeError(Logger, exception); throw; } finally { _state = State.Disposed; } } } private void DisposeInternal() { // V2 stopping sequence: // 1. Detach request queue from url group - Done in Stop()/Abort() // 2. Remove urls from url group - Done in Stop() // 3. Close request queue - Done in Stop()/Abort() // 4. Close Url group. // 5. Close server session. _requestQueue.Dispose(); _urlGroup.Dispose(); Debug.Assert(_serverSession != null, "ServerSessionHandle is null in CloseV2Config"); Debug.Assert(!_serverSession.Id.IsInvalid, "ServerSessionHandle is invalid in CloseV2Config"); _serverSession.Dispose(); } /// <summary> /// Accept a request from the incoming request queue. /// </summary> internal ValueTask<RequestContext> AcceptAsync(AsyncAcceptContext acceptContext) { CheckDisposed(); Debug.Assert(_state != State.Stopped, "Listener has been stopped."); return acceptContext.AcceptAsync(); } internal bool ValidateRequest(NativeRequestContext requestMemory) { try { // Block potential DOS attacks if (requestMemory.UnknownHeaderCount > UnknownHeaderLimit) { SendError(requestMemory.RequestId, StatusCodes.Status400BadRequest, authChallenges: null); return false; } if (!Options.Authentication.AllowAnonymous && !requestMemory.CheckAuthenticated()) { SendError(requestMemory.RequestId, StatusCodes.Status401Unauthorized, AuthenticationManager.GenerateChallenges(Options.Authentication.Schemes)); return false; } } catch (Exception ex) { Log.RequestValidationFailed(Logger, ex, requestMemory.RequestId); return false; } return true; } internal unsafe void SendError(ulong requestId, int httpStatusCode, IList<string>? authChallenges = null) { HttpApiTypes.HTTP_RESPONSE_V2 httpResponse = new HttpApiTypes.HTTP_RESPONSE_V2(); httpResponse.Response_V1.Version = new HttpApiTypes.HTTP_VERSION(); httpResponse.Response_V1.Version.MajorVersion = (ushort)1; httpResponse.Response_V1.Version.MinorVersion = (ushort)1; List<GCHandle>? pinnedHeaders = null; GCHandle gcHandle; try { // Copied from the multi-value headers section of SerializeHeaders if (authChallenges != null && authChallenges.Count > 0) { pinnedHeaders = new List<GCHandle>(authChallenges.Count + 3); HttpApiTypes.HTTP_RESPONSE_INFO[] knownHeaderInfo = new HttpApiTypes.HTTP_RESPONSE_INFO[1]; gcHandle = GCHandle.Alloc(knownHeaderInfo, GCHandleType.Pinned); pinnedHeaders.Add(gcHandle); httpResponse.pResponseInfo = (HttpApiTypes.HTTP_RESPONSE_INFO*)gcHandle.AddrOfPinnedObject(); knownHeaderInfo[httpResponse.ResponseInfoCount].Type = HttpApiTypes.HTTP_RESPONSE_INFO_TYPE.HttpResponseInfoTypeMultipleKnownHeaders; knownHeaderInfo[httpResponse.ResponseInfoCount].Length = (uint)Marshal.SizeOf<HttpApiTypes.HTTP_MULTIPLE_KNOWN_HEADERS>(); HttpApiTypes.HTTP_MULTIPLE_KNOWN_HEADERS header = new HttpApiTypes.HTTP_MULTIPLE_KNOWN_HEADERS(); header.HeaderId = HttpApiTypes.HTTP_RESPONSE_HEADER_ID.Enum.HttpHeaderWwwAuthenticate; header.Flags = HttpApiTypes.HTTP_RESPONSE_INFO_FLAGS.PreserveOrder; // The docs say this is for www-auth only. HttpApiTypes.HTTP_KNOWN_HEADER[] nativeHeaderValues = new HttpApiTypes.HTTP_KNOWN_HEADER[authChallenges.Count]; gcHandle = GCHandle.Alloc(nativeHeaderValues, GCHandleType.Pinned); pinnedHeaders.Add(gcHandle); header.KnownHeaders = (HttpApiTypes.HTTP_KNOWN_HEADER*)gcHandle.AddrOfPinnedObject(); for (int headerValueIndex = 0; headerValueIndex < authChallenges.Count; headerValueIndex++) { // Add Value string headerValue = authChallenges[headerValueIndex]; byte[] bytes = HeaderEncoding.GetBytes(headerValue); nativeHeaderValues[header.KnownHeaderCount].RawValueLength = (ushort)bytes.Length; gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned); pinnedHeaders.Add(gcHandle); nativeHeaderValues[header.KnownHeaderCount].pRawValue = (byte*)gcHandle.AddrOfPinnedObject(); header.KnownHeaderCount++; } // This type is a struct, not an object, so pinning it causes a boxed copy to be created. We can't do that until after all the fields are set. gcHandle = GCHandle.Alloc(header, GCHandleType.Pinned); pinnedHeaders.Add(gcHandle); knownHeaderInfo[0].pInfo = (HttpApiTypes.HTTP_MULTIPLE_KNOWN_HEADERS*)gcHandle.AddrOfPinnedObject(); httpResponse.ResponseInfoCount = 1; } httpResponse.Response_V1.StatusCode = (ushort)httpStatusCode; string? statusDescription = HttpReasonPhrase.Get(httpStatusCode); uint dataWritten = 0; uint statusCode; byte[] byteReason = statusDescription != null ? HeaderEncoding.GetBytes(statusDescription) : Array.Empty<byte>(); fixed (byte* pReason = byteReason) { httpResponse.Response_V1.pReason = (byte*)pReason; httpResponse.Response_V1.ReasonLength = (ushort)byteReason.Length; byte[] byteContentLength = new byte[] { (byte)'0' }; fixed (byte* pContentLength = byteContentLength) { (&httpResponse.Response_V1.Headers.KnownHeaders)[(int)HttpSysResponseHeader.ContentLength].pRawValue = (byte*)pContentLength; (&httpResponse.Response_V1.Headers.KnownHeaders)[(int)HttpSysResponseHeader.ContentLength].RawValueLength = (ushort)byteContentLength.Length; httpResponse.Response_V1.Headers.UnknownHeaderCount = 0; statusCode = HttpApi.HttpSendHttpResponse( _requestQueue.Handle, requestId, 0, &httpResponse, null, &dataWritten, IntPtr.Zero, 0, SafeNativeOverlapped.Zero, IntPtr.Zero); } } if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS) { // if we fail to send a 401 something's seriously wrong, abort the request HttpApi.HttpCancelHttpRequest(_requestQueue.Handle, requestId, IntPtr.Zero); } } finally { if (pinnedHeaders != null) { foreach (GCHandle handle in pinnedHeaders) { if (handle.IsAllocated) { handle.Free(); } } } } } private void CheckDisposed() { if (_state == State.Disposed) { throw new ObjectDisposedException(this.GetType().FullName); } } } }
using AjaxControlToolkit.Design; using System; using System.ComponentModel; using System.Drawing; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; namespace AjaxControlToolkit { /// <summary> /// The BalloonPopupExtender control displays a popup which can contain any content. /// </summary> [ClientScriptResource("Sys.Extended.UI.BalloonPopupControlBehavior", Constants.BalloonPopupName)] [RequiredScript(typeof(PopupExtender))] [RequiredScript(typeof(CommonToolkitScripts))] [TargetControlType(typeof(WebControl))] [ClientCssResource(Constants.BalloonPopupName + ".Cloud")] [ClientCssResource(Constants.BalloonPopupName + ".Rectangle")] [Designer(typeof(BalloonPopupExtenderDesigner))] [ToolboxBitmap(typeof(ToolboxIcons.Accessor), Constants.BalloonPopupName + Constants.IconPostfix)] public class BalloonPopupExtender : DynamicPopulateExtenderControlBase { Animation _onHide; Animation _onShow; /// <summary> /// Extender control ID /// </summary> [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public string ExtenderControlID { get { return GetPropertyValue("ExtenderControlID", String.Empty); } set { SetPropertyValue("ExtenderControlID", value); } } /// <summary> /// The ID of the control to display /// </summary> [ExtenderControlProperty] [IDReferenceProperty(typeof(WebControl))] [RequiredProperty] [DefaultValue("")] [ClientPropertyName("balloonPopupControlID")] public string BalloonPopupControlID { get { return GetPropertyValue("BalloonPopupControlID", String.Empty); } set { SetPropertyValue("BalloonPopupControlID", value); } } /// <summary> /// Optional setting specifying where the popup should be positioned relative to the target control /// </summary> /// <remarks> /// (TopRight, TopLeft, BottomRight, BottomLeft, Auto) Default value is Auto /// </remarks> [ExtenderControlProperty] [DefaultValue(BalloonPopupPosition.Auto)] [ClientPropertyName("balloonPopupPosition")] public BalloonPopupPosition Position { get; set; } /// <summary> /// Optional setting specifying the theme of balloon popup. /// Default value is Rectangle /// </summary> [ExtenderControlProperty] [DefaultValue(BalloonPopupStyle.Rectangle)] [ClientPropertyName("balloonPopupStyle")] public BalloonPopupStyle BalloonStyle { get; set; } /// <summary> /// Optional X (horizontal) offset for the popup window (relative to the target control). /// Default value is 0 /// </summary> [ExtenderControlProperty] [DefaultValue(0)] [ClientPropertyName("offsetX")] public int OffsetX { get { return GetPropertyValue("OffsetX", 0); } set { SetPropertyValue("OffsetX", value); } } /// <summary> /// Optional Y (vertical) offset for the popup window (relative to the target control). /// Default value is 0 /// </summary> [ExtenderControlProperty] [DefaultValue(0)] [ClientPropertyName("offsetY")] public int OffsetY { get { return GetPropertyValue("OffsetY", 0); } set { SetPropertyValue("OffsetY", value); } } /// <summary> /// The OnShow animation will be played each time the popup is displayed. /// The popup will be positioned correctly but hidden /// </summary> /// <remarks> /// The animation can use <HideAction Visible="true" /> to display the popup along with any other visual effects /// </remarks> [ExtenderControlProperty] [ClientPropertyName("onShow")] [Browsable(false)] [DefaultValue(null)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Animation OnShow { get { return GetAnimation(ref _onShow, "OnShow"); } set { SetAnimation(ref _onShow, "OnShow", value); } } /// <summary> /// The OnHide animation will be played each time the popup is hidden /// </summary> [ExtenderControlProperty] [ClientPropertyName("onHide")] [Browsable(false)] [DefaultValue(null)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Animation OnHide { get { return GetAnimation(ref _onHide, "OnHide"); } set { SetAnimation(ref _onHide, "OnHide", value); } } /// <summary> /// Optional setting specifying whether to display balloon popup on the client onMouseOver event. Default value is false /// </summary> [ExtenderControlProperty] [ClientPropertyName("displayOnMouseOver")] [DefaultValue(false)] public bool DisplayOnMouseOver { get { return GetPropertyValue("DisplayOnMouseOver", false); } set { SetPropertyValue("DisplayOnMouseOver", value); } } /// <summary> /// Optional setting specifying whether to display balloon popup on the client onFocus event. Default value is false /// </summary> [ExtenderControlProperty] [ClientPropertyName("displayOnFocus")] [DefaultValue(false)] public bool DisplayOnFocus { get { return GetPropertyValue("DisplayOnFocus", false); } set { SetPropertyValue("DisplayOnFocus", value); } } /// <summary> /// Optional setting specifying whether to display balloon popup on the client onClick event. Default value is true /// </summary> [ExtenderControlProperty] [ClientPropertyName("displayOnClick")] [DefaultValue(true)] public bool DisplayOnClick { get { return GetPropertyValue("DisplayOnClick", true); } set { SetPropertyValue("DisplayOnClick", value); } } /// <summary> /// Optional setting specifying the size of balloon popup. (Small, Medium and Large). Default value is Small /// </summary> [ExtenderControlProperty] [ClientPropertyName("balloonSize")] [DefaultValue(BalloonPopupSize.Small)] public BalloonPopupSize BalloonSize { get { return GetPropertyValue("BalloonSize", BalloonPopupSize.Small); } set { SetPropertyValue("BalloonSize", value); } } /// <summary> /// Optional setting specifying whether to display shadow of balloon popup or not /// </summary> [ExtenderControlProperty] [ClientPropertyName("useShadow")] [DefaultValue(true)] public bool UseShadow { get { return GetPropertyValue("UseShadow", true); } set { SetPropertyValue("UseShadow", value); } } /// <summary> /// This is required if user choose BalloonStyle to Custom. This specifies the url of custom css which will display custom theme /// </summary> [DefaultValue("")] public string CustomCssUrl { get; set; } /// <summary> /// Optional setting specifying whether to display scrollbar if contents are overflowing. /// Default value is Auto /// </summary> [DefaultValue(ScrollBars.Auto)] [Category("Behavior")] [ClientPropertyName("scrollBars")] [Description("Scroll bars behavior when content is overflow")] [ExtenderControlProperty] public ScrollBars ScrollBars { get { return GetPropertyValue("ScrollBars", ScrollBars.Auto); } set { SetPropertyValue("ScrollBars", value); } } /// <summary> /// This is required if user choose BalloonStyle to Custom. This specifies the name of the css class for the custom theme /// </summary> [ExtenderControlProperty] [ClientPropertyName("customClassName")] [DefaultValue("")] public string CustomClassName { get { return GetPropertyValue("CustomClassName", String.Empty); } set { SetPropertyValue("CustomClassName", value); } } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); if(BalloonStyle == BalloonPopupStyle.Custom) { if(CustomCssUrl == String.Empty) throw new ArgumentException("Must pass CustomCssUrl value."); if(CustomClassName == String.Empty) throw new ArgumentException("Must pass CustomClassName value."); var isLinked = false; foreach(Control control in Page.Header.Controls) { if(control.ID == "customCssUrl") { isLinked = true; break; } } if(!isLinked) { var css = new HtmlLink(); css.Href = ResolveUrl(CustomCssUrl); css.Attributes["id"] = "customCssUrl"; css.Attributes["rel"] = "stylesheet"; css.Attributes["type"] = "text/css"; css.Attributes["media"] = "all"; Page.Header.Controls.Add(css); } } } } }
// 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.Runtime.ExceptionServices; using System.Text; using System.Threading; using System.Windows; using System.Windows.Automation; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.Language.Intellisense; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudioTools.VSTestHost; using Task = System.Threading.Tasks.Task; namespace TestUtilities.UI { public class EditorWindow : AutomationWrapper, IEditor { private readonly string _filename; public EditorWindow(string filename, AutomationElement element) : base(element) { _filename = filename; } public string Text { get { return GetValue(); } } public virtual IWpfTextView TextView { get { return GetTextView(_filename); } } public void MoveCaret(SnapshotPoint newPoint) { Invoke((Action)(() => { TextView.Caret.MoveTo(newPoint.TranslateTo(newPoint.Snapshot.TextBuffer.CurrentSnapshot, PointTrackingMode.Positive)); })); } public void Select(int line, int column, int length) { var textLine = TextView.TextViewLines[line - 1]; Span span; if (column - 1 == textLine.Length) { span = new Span(textLine.End, length); } else { span = new Span(textLine.Start + column - 1, length); } ((UIElement)TextView).Dispatcher.Invoke((Action)(() => { TextView.Selection.Select( new SnapshotSpan(TextView.TextBuffer.CurrentSnapshot, span), false ); })); } /// <summary> /// Moves the caret to the 1 based line and column /// </summary> public void MoveCaret(int line, int column) { var textLine = TextView.TextBuffer.CurrentSnapshot.GetLineFromLineNumber(line - 1); if (column - 1 == textLine.Length) { MoveCaret(textLine.End); } else { MoveCaret(new SnapshotPoint(TextView.TextBuffer.CurrentSnapshot, textLine.Start + column - 1)); } } public void WaitForText(string text) { for (int i = 0; i < 100; i++) { if (Text != text) { System.Threading.Thread.Sleep(100); } else { break; } } Assert.AreEqual(text, Text); } public void WaitForTextStart(params string[] text) { string expected = GetExpectedText(text); for (int i = 0; i < 100; i++) { string curText = Text; if (Text.StartsWith(expected, StringComparison.CurrentCulture)) { return; } Thread.Sleep(100); } FailWrongText(expected); } public void WaitForTextEnd(params string[] text) { string expected = GetExpectedText(text); for (int i = 0; i < 100; i++) { string curText = Text.TrimEnd(); if (Text.EndsWith(expected, StringComparison.CurrentCulture)) { return; } Thread.Sleep(100); } FailWrongText(expected); } public static string GetExpectedText(IList<string> text) { StringBuilder finalString = new StringBuilder(); for (int i = 0; i < text.Count; i++) { if (i != 0) { finalString.Append(Environment.NewLine); } finalString.Append(text[i]); } string expected = finalString.ToString(); return expected; } private void FailWrongText(string expected) { StringBuilder msg = new StringBuilder("Did not get text: <"); AppendRepr(msg, expected); msg.Append("> instead got <"); AppendRepr(msg, Text); msg.Append(">"); Assert.Fail(msg.ToString()); } public static void AppendRepr(StringBuilder msg, string str) { for (int i = 0; i < str.Length; i++) { if (str[i] >= 32) { msg.Append(str[i]); } else { switch (str[i]) { case '\n': msg.Append("\\n"); break; case '\r': msg.Append("\\r"); break; case '\t': msg.Append("\\t"); break; default: msg.AppendFormat("\\u00{0:D2}", (int)str[i]); break; } } } } #if DEV14_OR_LATER #pragma warning disable 0618 #endif public void StartSmartTagSessionNoSession() { ShowSmartTag(); Thread.Sleep(100); Assert.IsNotInstanceOfType( IntellisenseSessionStack.TopSession, #if DEV14_OR_LATER typeof(ILightBulbSession) #else typeof(ISmartTagSession) #endif ); } private static void ShowSmartTag() { Task.Run(() => { for (int i = 0; i < 40; i++) { try { VSTestContext.DTE.ExecuteCommand("View.ShowSmartTag"); break; } catch { Thread.Sleep(250); } } }).Wait(); } public SessionHolder<SmartTagSessionWrapper> StartSmartTagSession() { ShowSmartTag(); #if DEV14_OR_LATER var sh = WaitForSession<ILightBulbSession>(); #else var sh = WaitForSession<ISmartTagSession>(); #endif return sh == null ? null : new SessionHolder<SmartTagSessionWrapper>(new SmartTagSessionWrapper(sh), this); } public SessionHolder<T> WaitForSession<T>() where T : IIntellisenseSession { return WaitForSession<T>(true); } public SessionHolder<T> WaitForSession<T>(bool assertIfNoSession) where T : IIntellisenseSession { var sessionStack = IntellisenseSessionStack; for (int i = 0; i < 40; i++) { if (sessionStack.TopSession is T) { break; } System.Threading.Thread.Sleep(250); } if (!(sessionStack.TopSession is T)) { if (assertIfNoSession) { Console.WriteLine("Buffer text:\r\n{0}", Text); Console.WriteLine("-----"); AutomationWrapper.DumpVS(); Assert.Fail("failed to find session " + typeof(T).FullName); } else { return null; } } return new SessionHolder<T>((T)sessionStack.TopSession, this); } public IIntellisenseSessionStack IntellisenseSessionStack { get { var compModel = (IComponentModel)VSTestContext.ServiceProvider.GetService(typeof(SComponentModel)); var stackMapService = compModel.GetService<IIntellisenseSessionStackMapService>(); return stackMapService.GetStackForTextView(TextView); } } public void AssertNoIntellisenseSession() { Thread.Sleep(500); Assert.IsNull(IntellisenseSessionStack.TopSession); } public IClassifier Classifier { get { var compModel = (IComponentModel)VSTestContext.ServiceProvider.GetService(typeof(SComponentModel)); var provider = compModel.GetService<IClassifierAggregatorService>(); return provider.GetClassifier(TextView.TextBuffer); } } public ITagAggregator<T> GetTaggerAggregator<T>(ITextBuffer buffer) where T : ITag { var compModel = (IComponentModel)VSTestContext.ServiceProvider.GetService(typeof(SComponentModel)); return compModel.GetService<Microsoft.VisualStudio.Text.Tagging.IBufferTagAggregatorFactoryService>().CreateTagAggregator<T>(buffer); } internal static IWpfTextView GetTextView(string filePath) { IVsUIHierarchy uiHierarchy; uint itemID; IVsWindowFrame windowFrame; if (VsShellUtilities.IsDocumentOpen(VSTestContext.ServiceProvider, filePath, Guid.Empty, out uiHierarchy, out itemID, out windowFrame)) { var textView = VsShellUtilities.GetTextView(windowFrame); IComponentModel compModel = (IComponentModel)VSTestContext.ServiceProvider.GetService(typeof(SComponentModel)); var adapterFact = compModel.GetService<IVsEditorAdaptersFactoryService>(); return adapterFact.GetWpfTextView(textView); } return null; } public void Invoke(Action action) { ExceptionDispatchInfo excep = null; ((UIElement)TextView).Dispatcher.Invoke( (Action)(() => { try { action(); } catch (Exception e) { excep = ExceptionDispatchInfo.Capture(e); } }) ); if (excep != null) { excep.Throw(); } } public T Invoke<T>(Func<T> action) { Exception excep = null; T res = default(T); ((UIElement)TextView).Dispatcher.Invoke( (Action)(() => { try { res = action(); } catch (Exception e) { excep = e; } }) ); if (excep != null) { Assert.Fail("Exception on UI thread: " + excep.ToString()); } return res; } public IIntellisenseSession TopSession { get { return IntellisenseSessionStack.TopSession; } } public void Type(string text) { Keyboard.Type(text); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // // DynamicPropertyHolder manages the dynamically registered properties // and the sinks contributed by them. Dynamic properties may be registered // to contribute sinks on a per-object basis (on the proxy or server side) // or on a per-Context basis (in both the client and server contexts). // // See also: RemotingServices.RegisterDynamicSink() API // namespace System.Runtime.Remoting.Contexts { using System.Runtime.Remoting; using System.Runtime.Remoting.Messaging; using System; using System.Collections; using System.Globalization; internal class DynamicPropertyHolder { private const int GROW_BY = 0x8; private IDynamicProperty[] _props; private int _numProps; private IDynamicMessageSink[] _sinks; [System.Security.SecurityCritical] // auto-generated internal virtual bool AddDynamicProperty(IDynamicProperty prop) { lock(this) { // We have to add a sink specific to the given context CheckPropertyNameClash(prop.Name, _props, _numProps); // check if we need to grow the array. bool bGrow=false; if (_props == null || _numProps == _props.Length) { _props = GrowPropertiesArray(_props); bGrow = true; } // now add the property _props[_numProps++] = prop; // we need to grow the sinks if we grew the props array or we had thrown // away the sinks array due to a recent removal! if (bGrow) { _sinks = GrowDynamicSinksArray(_sinks); } if (_sinks == null) { // Some property got unregistered -- we need to recreate // the list of sinks. _sinks = new IDynamicMessageSink[_props.Length]; for (int i=0; i<_numProps; i++) { _sinks[i] = ((IContributeDynamicSink)_props[i]).GetDynamicSink(); } } else { // append the Sink to the existing array of Sinks _sinks[_numProps-1] = ((IContributeDynamicSink)prop).GetDynamicSink(); } return true; } } [System.Security.SecurityCritical] // auto-generated internal virtual bool RemoveDynamicProperty(String name) { lock(this) { // We have to remove a property for a specific context for (int i=0; i<_numProps; i++) { if (_props[i].Name.Equals(name)) { _props[i] = _props[_numProps-1]; _numProps--; // throw away the dynamic sink list _sinks = null; return true; } } throw new RemotingException( String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Remoting_Contexts_NoProperty"), name)); } } internal virtual IDynamicProperty[] DynamicProperties { get { if (_props == null) { return null; } lock (this) { IDynamicProperty[] retProps = new IDynamicProperty[_numProps]; Array.Copy(_props, retProps, _numProps); return retProps; } } } // We have to do this ArrayWithSize thing instead of // separately providing the Array and a Count ... since they // may not be in synch with multiple threads changing things // We do not want to provide a copy of the array for each // call for perf reasons. Besides this is used internally anyways. internal virtual ArrayWithSize DynamicSinks { [System.Security.SecurityCritical] // auto-generated get { if (_numProps == 0) { return null; } lock (this) { if (_sinks == null) { // Some property got unregistered -- we need to recreate // the list of sinks. _sinks = new IDynamicMessageSink[_numProps+GROW_BY]; for (int i=0; i<_numProps; i++) { _sinks[i] = ((IContributeDynamicSink)_props[i]).GetDynamicSink(); } } } return new ArrayWithSize(_sinks, _numProps); } } private static IDynamicMessageSink[] GrowDynamicSinksArray(IDynamicMessageSink[] sinks) { // grow the array int newSize = (sinks != null ? sinks.Length : 0) + GROW_BY; IDynamicMessageSink[] newSinks = new IDynamicMessageSink[newSize]; if (sinks != null) { // Copy existing properties over // Initial size should be chosen so that this rarely happens Array.Copy(sinks, newSinks, sinks.Length); } return newSinks; } [System.Security.SecurityCritical] // auto-generated internal static void NotifyDynamicSinks(IMessage msg, ArrayWithSize dynSinks, bool bCliSide, bool bStart, bool bAsync) { for (int i=0; i<dynSinks.Count; i++) { if (bStart == true) { dynSinks.Sinks[i].ProcessMessageStart(msg, bCliSide, bAsync); } else { dynSinks.Sinks[i].ProcessMessageFinish(msg, bCliSide, bAsync); } } } [System.Security.SecurityCritical] // auto-generated internal static void CheckPropertyNameClash(String name, IDynamicProperty[] props, int count) { for (int i=0; i<count; i++) { if (props[i].Name.Equals(name)) { throw new InvalidOperationException( Environment.GetResourceString( "InvalidOperation_DuplicatePropertyName")); } } } internal static IDynamicProperty[] GrowPropertiesArray(IDynamicProperty[] props) { // grow the array of IContextProperty objects int newSize = (props != null ? props.Length : 0) + GROW_BY; IDynamicProperty[] newProps = new IDynamicProperty[newSize]; if (props != null) { // Copy existing properties over. Array.Copy(props, newProps, props.Length); } return newProps; } } //class DynamicPropertyHolder // Used to return a reference to an array and the current fill size // in cases where it is not thread safe to provide this info as two // separate properties. This is for internal use only. internal class ArrayWithSize { internal IDynamicMessageSink[] Sinks; internal int Count; internal ArrayWithSize(IDynamicMessageSink[] sinks, int count) { Sinks = sinks; Count = count; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Shared.Extensions; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Undo; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Rename; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Operations; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking { internal sealed partial class RenameTrackingTaggerProvider { private class RenameTrackingCommitter : ForegroundThreadAffinitizedObject { private readonly StateMachine _stateMachine; private readonly SnapshotSpan _snapshotSpan; private readonly IEnumerable<IRefactorNotifyService> _refactorNotifyServices; private readonly ITextUndoHistoryRegistry _undoHistoryRegistry; private readonly string _displayText; private readonly AsyncLazy<RenameTrackingSolutionSet> _renameSymbolResultGetter; public RenameTrackingCommitter( StateMachine stateMachine, SnapshotSpan snapshotSpan, IEnumerable<IRefactorNotifyService> refactorNotifyServices, ITextUndoHistoryRegistry undoHistoryRegistry, string displayText) { _stateMachine = stateMachine; _snapshotSpan = snapshotSpan; _refactorNotifyServices = refactorNotifyServices; _undoHistoryRegistry = undoHistoryRegistry; _displayText = displayText; _renameSymbolResultGetter = new AsyncLazy<RenameTrackingSolutionSet>(c => RenameSymbolWorkerAsync(c), cacheResult: true); } public void Commit(CancellationToken cancellationToken) { AssertIsForeground(); bool clearTrackingSession = ApplyChangesToWorkspace(cancellationToken); // Clear the state machine so that future updates to the same token work, // and any text changes caused by this update are not interpreted as // potential renames if (clearTrackingSession) { _stateMachine.ClearTrackingSession(); } } public async Task<RenameTrackingSolutionSet> RenameSymbolAsync(CancellationToken cancellationToken) { return await _renameSymbolResultGetter.GetValueAsync(cancellationToken).ConfigureAwait(false); } private async Task<RenameTrackingSolutionSet> RenameSymbolWorkerAsync(CancellationToken cancellationToken) { var document = _snapshotSpan.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); var newName = _snapshotSpan.GetText(); if (document == null) { Contract.Fail("Invoked rename tracking smart tag but cannot find the document for the snapshot span."); } // Get copy of solution with the original name in the place of the renamed name var solutionWithOriginalName = CreateSolutionWithOriginalName(document, cancellationToken); var symbol = await TryGetSymbolAsync(solutionWithOriginalName, document.Id, cancellationToken).ConfigureAwait(false); if (symbol == null) { Contract.Fail("Invoked rename tracking smart tag but cannot find the symbol."); } var optionSet = document.Project.Solution.Workspace.Options; if (_stateMachine.TrackingSession.ForceRenameOverloads) { optionSet = optionSet.WithChangedOption(RenameOptions.RenameOverloads, true); } var renamedSolution = await Renamer.RenameSymbolAsync(solutionWithOriginalName, symbol, newName, optionSet, cancellationToken).ConfigureAwait(false); return new RenameTrackingSolutionSet(symbol, solutionWithOriginalName, renamedSolution); } private bool ApplyChangesToWorkspace(CancellationToken cancellationToken) { AssertIsForeground(); // Now that the necessary work has been done to create the intermediate and final // solutions during PreparePreview, check one more time for cancellation before making all of the // workspace changes. cancellationToken.ThrowIfCancellationRequested(); // Undo must backtrack to the state with the original identifier before the state // with the user-edited identifier. For example, // // 1. Original: void M() { M(); } // 2. User types: void Method() { M(); } // 3. Invoke rename: void Method() { Method(); } // // The undo process should be as follows // 1. Back to original name everywhere: void M() { M(); } // No tracking session // 2. Back to state 2 above: void Method() { M(); } // Resume tracking session // 3. Finally, start undoing typing: void M() { M(); } // // As far as the user can see, undo state 1 never actually existed so we must insert // a state here to facilitate the undo. Do the work to obtain the intermediate and // final solution without updating the workspace, and then finally disallow // cancellation and update the workspace twice. var renameTrackingSolutionSet = RenameSymbolAsync(cancellationToken).WaitAndGetResult(cancellationToken); var document = _snapshotSpan.Snapshot.GetOpenDocumentInCurrentContextWithChanges(); var newName = _snapshotSpan.GetText(); var workspace = document.Project.Solution.Workspace; // Since the state machine is only watching buffer changes, it will interpret the // text changes caused by undo and redo actions as potential renames, so carefully // update the state machine after undo/redo actions. var changedDocuments = renameTrackingSolutionSet.RenamedSolution.GetChangedDocuments(renameTrackingSolutionSet.OriginalSolution); // When this action is undone (the user has undone twice), restore the state // machine to so that they can continue their original rename tracking session. UpdateWorkspaceForResetOfTypedIdentifier(workspace, renameTrackingSolutionSet.OriginalSolution); // Now that the solution is back in its original state, notify third parties about // the coming rename operation. if (!_refactorNotifyServices.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocuments, renameTrackingSolutionSet.Symbol, newName, throwOnFailure: false)) { var notificationService = workspace.Services.GetService<INotificationService>(); notificationService.SendNotification( EditorFeaturesResources.RenameOperationWasCancelled, EditorFeaturesResources.RenameSymbol, NotificationSeverity.Error); return true; } // move all changes to final solution based on the workspace's current solution, since the current solution // got updated when we reset it above. var finalSolution = workspace.CurrentSolution; foreach (var docId in changedDocuments) { // because changes have already been made to the workspace (UpdateWorkspaceForResetOfTypedIdentifier() above), // these calls can't be cancelled and must be allowed to complete. var root = renameTrackingSolutionSet.RenamedSolution.GetDocument(docId).GetSyntaxRootAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None); finalSolution = finalSolution.WithDocumentSyntaxRoot(docId, root); } // Undo/redo on this action must always clear the state machine UpdateWorkspaceForGlobalIdentifierRename(workspace, finalSolution, workspace.CurrentSolution, _displayText, changedDocuments, renameTrackingSolutionSet.Symbol, newName); RenameTrackingDismisser.DismissRenameTracking(workspace, changedDocuments); return true; } private Solution CreateSolutionWithOriginalName(Document document, CancellationToken cancellationToken) { var syntaxTree = document.GetSyntaxTreeAsync(cancellationToken).WaitAndGetResult(cancellationToken); var fullText = syntaxTree.GetText(cancellationToken); var textChange = new TextChange(new TextSpan(_snapshotSpan.Start, _snapshotSpan.Length), _stateMachine.TrackingSession.OriginalName); var newFullText = fullText.WithChanges(textChange); #if DEBUG var syntaxTreeWithOriginalName = syntaxTree.WithChangedText(newFullText); var documentWithOriginalName = document.WithSyntaxRoot(syntaxTreeWithOriginalName.GetRoot(cancellationToken)); Contract.Requires(newFullText.ToString() == documentWithOriginalName.GetTextAsync(cancellationToken).WaitAndGetResult(cancellationToken).ToString()); #endif // Apply the original name to all linked documents to construct a consistent solution var solution = document.Project.Solution; foreach (var documentId in document.GetLinkedDocumentIds().Add(document.Id)) { solution = solution.WithDocumentText(documentId, newFullText); } return solution; } private async Task<ISymbol> TryGetSymbolAsync(Solution solutionWithOriginalName, DocumentId documentId, CancellationToken cancellationToken) { var documentWithOriginalName = solutionWithOriginalName.GetDocument(documentId); var syntaxTreeWithOriginalName = await documentWithOriginalName.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var syntaxFacts = documentWithOriginalName.GetLanguageService<ISyntaxFactsService>(); var semanticFacts = documentWithOriginalName.GetLanguageService<ISemanticFactsService>(); var semanticModel = await documentWithOriginalName.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var token = syntaxTreeWithOriginalName.GetTouchingWord(_snapshotSpan.Start, syntaxFacts, cancellationToken); var tokenRenameInfo = RenameUtilities.GetTokenRenameInfo(semanticFacts, semanticModel, token, cancellationToken); return tokenRenameInfo.HasSymbols ? tokenRenameInfo.Symbols.First() : null; } private void UpdateWorkspaceForResetOfTypedIdentifier(Workspace workspace, Solution newSolution) { AssertIsForeground(); // Update document in an ITextUndoTransaction with custom behaviors on undo/redo to // deal with the state machine. var undoHistory = _undoHistoryRegistry.RegisterHistory(_stateMachine.Buffer); using (var localUndoTransaction = undoHistory.CreateTransaction(EditorFeaturesResources.TextBufferChange)) { var undoPrimitiveBefore = new UndoPrimitive(_stateMachine, shouldRestoreStateOnUndo: true); localUndoTransaction.AddUndo(undoPrimitiveBefore); if (!workspace.TryApplyChanges(newSolution)) { Contract.Fail("Rename Tracking could not update solution."); } // Never resume tracking session on redo var undoPrimitiveAfter = new UndoPrimitive(_stateMachine, shouldRestoreStateOnUndo: false); localUndoTransaction.AddUndo(undoPrimitiveAfter); localUndoTransaction.Complete(); } } private void UpdateWorkspaceForGlobalIdentifierRename( Workspace workspace, Solution newSolution, Solution oldSolution, string undoName, IEnumerable<DocumentId> changedDocuments, ISymbol symbol, string newName) { AssertIsForeground(); // Perform rename in a workspace undo action so that undo will revert all // references. It should also be performed in an ITextUndoTransaction to handle var undoHistory = _undoHistoryRegistry.RegisterHistory(_stateMachine.Buffer); using (var workspaceUndoTransaction = workspace.OpenGlobalUndoTransaction(undoName)) using (var localUndoTransaction = undoHistory.CreateTransaction(undoName)) { var undoPrimitiveBefore = new UndoPrimitive(_stateMachine, shouldRestoreStateOnUndo: false); localUndoTransaction.AddUndo(undoPrimitiveBefore); if (!workspace.TryApplyChanges(newSolution)) { Contract.Fail("Rename Tracking could not update solution."); } if (!_refactorNotifyServices.TryOnAfterGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: false)) { var notificationService = workspace.Services.GetService<INotificationService>(); notificationService.SendNotification( EditorFeaturesResources.RenameOperationWasNotProperlyCompleted, EditorFeaturesResources.RenameSymbol, NotificationSeverity.Information); } // Never resume tracking session on redo var undoPrimitiveAfter = new UndoPrimitive(_stateMachine, shouldRestoreStateOnUndo: false); localUndoTransaction.AddUndo(undoPrimitiveAfter); localUndoTransaction.Complete(); workspaceUndoTransaction.Commit(); } } } } }
// 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. #nullable enable using System.Diagnostics; using System.Runtime.InteropServices; using System.Text; namespace System.IO { /// <summary> /// Wrapper to help with path normalization. /// </summary> internal static class PathHelper { /// <summary> /// Normalize the given path. /// </summary> /// <remarks> /// Normalizes via Win32 GetFullPathName(). /// </remarks> /// <param name="path">Path to normalize</param> /// <exception cref="PathTooLongException">Thrown if we have a string that is too large to fit into a UNICODE_STRING.</exception> /// <exception cref="IOException">Thrown if the path is empty.</exception> /// <returns>Normalized path</returns> internal static string Normalize(string path) { Span<char> initialBuffer = stackalloc char[PathInternal.MaxShortPath]; var builder = new ValueStringBuilder(initialBuffer); // Get the full path GetFullPathName(path.AsSpan(), ref builder); // If we have the exact same string we were passed in, don't allocate another string. // TryExpandShortName does this input identity check. string result = builder.AsSpan().IndexOf('~') >= 0 ? TryExpandShortFileName(ref builder, originalPath: path) : builder.AsSpan().Equals(path.AsSpan(), StringComparison.Ordinal) ? path : builder.ToString(); // Clear the buffer builder.Dispose(); return result; } /// <summary> /// Normalize the given path. /// </summary> /// <remarks> /// Exceptions are the same as the string overload. /// </remarks> internal static string Normalize(ref ValueStringBuilder path) { Span<char> initialBuffer = stackalloc char[PathInternal.MaxShortPath]; var builder = new ValueStringBuilder(initialBuffer); // Get the full path GetFullPathName(path.AsSpan(terminate: true), ref builder); string result = builder.AsSpan().IndexOf('~') >= 0 ? TryExpandShortFileName(ref builder, originalPath: null) : builder.ToString(); // Clear the buffer builder.Dispose(); return result; } /// <summary> /// Calls GetFullPathName on the given path. /// </summary> /// <param name="path">The path name. MUST be null terminated after the span.</param> /// <param name="builder">Builder that will store the result.</param> private static void GetFullPathName(ReadOnlySpan<char> path, ref ValueStringBuilder builder) { // If the string starts with an extended prefix we would need to remove it from the path before we call GetFullPathName as // it doesn't root extended paths correctly. We don't currently resolve extended paths, so we'll just assert here. Debug.Assert(PathInternal.IsPartiallyQualified(path) || !PathInternal.IsExtended(path)); uint result; while ((result = Interop.Kernel32.GetFullPathNameW(ref MemoryMarshal.GetReference(path), (uint)builder.Capacity, ref builder.GetPinnableReference(), IntPtr.Zero)) > builder.Capacity) { // Reported size is greater than the buffer size. Increase the capacity. builder.EnsureCapacity(checked((int)result)); } if (result == 0) { // Failure, get the error and throw int errorCode = Marshal.GetLastWin32Error(); if (errorCode == 0) errorCode = Interop.Errors.ERROR_BAD_PATHNAME; throw Win32Marshal.GetExceptionForWin32Error(errorCode, path.ToString()); } builder.Length = (int)result; } internal static int PrependDevicePathChars(ref ValueStringBuilder content, bool isDosUnc, ref ValueStringBuilder buffer) { int length = content.Length; length += isDosUnc ? PathInternal.UncExtendedPrefixLength - PathInternal.UncPrefixLength : PathInternal.DevicePrefixLength; buffer.EnsureCapacity(length + 1); buffer.Length = 0; if (isDosUnc) { // Is a \\Server\Share, put \\?\UNC\ in the front buffer.Append(PathInternal.UncExtendedPathPrefix); // Copy Server\Share\... over to the buffer buffer.Append(content.AsSpan(PathInternal.UncPrefixLength)); // Return the prefix difference return PathInternal.UncExtendedPrefixLength - PathInternal.UncPrefixLength; } else { // Not an UNC, put the \\?\ prefix in front, then the original string buffer.Append(PathInternal.ExtendedPathPrefix); buffer.Append(content.AsSpan()); return PathInternal.DevicePrefixLength; } } internal static string TryExpandShortFileName(ref ValueStringBuilder outputBuilder, string? originalPath) { // We guarantee we'll expand short names for paths that only partially exist. As such, we need to find the part of the path that actually does exist. To // avoid allocating a lot we'll create only one input array and modify the contents with embedded nulls. Debug.Assert(!PathInternal.IsPartiallyQualified(outputBuilder.AsSpan()), "should have resolved by now"); // We'll have one of a few cases by now (the normalized path will have already: // // 1. Dos path (C:\) // 2. Dos UNC (\\Server\Share) // 3. Dos device path (\\.\C:\, \\?\C:\) // // We want to put the extended syntax on the front if it doesn't already have it (for long path support and speed), which may mean switching from \\.\. // // Note that we will never get \??\ here as GetFullPathName() does not recognize \??\ and will return it as C:\??\ (or whatever the current drive is). int rootLength = PathInternal.GetRootLength(outputBuilder.AsSpan()); bool isDevice = PathInternal.IsDevice(outputBuilder.AsSpan()); // As this is a corner case we're not going to add a stackalloc here to keep the stack pressure down. var inputBuilder = new ValueStringBuilder(); bool isDosUnc = false; int rootDifference = 0; bool wasDotDevice = false; // Add the extended prefix before expanding to allow growth over MAX_PATH if (isDevice) { // We have one of the following (\\?\ or \\.\) inputBuilder.Append(outputBuilder.AsSpan()); if (outputBuilder[2] == '.') { wasDotDevice = true; inputBuilder[2] = '?'; } } else { isDosUnc = !PathInternal.IsDevice(outputBuilder.AsSpan()) && outputBuilder.Length > 1 && outputBuilder[0] == '\\' && outputBuilder[1] == '\\'; rootDifference = PrependDevicePathChars(ref outputBuilder, isDosUnc, ref inputBuilder); } rootLength += rootDifference; int inputLength = inputBuilder.Length; bool success = false; int foundIndex = inputBuilder.Length - 1; while (!success) { uint result = Interop.Kernel32.GetLongPathNameW( ref inputBuilder.GetPinnableReference(terminate: true), ref outputBuilder.GetPinnableReference(), (uint)outputBuilder.Capacity); // Replace any temporary null we added if (inputBuilder[foundIndex] == '\0') inputBuilder[foundIndex] = '\\'; if (result == 0) { // Look to see if we couldn't find the file int error = Marshal.GetLastWin32Error(); if (error != Interop.Errors.ERROR_FILE_NOT_FOUND && error != Interop.Errors.ERROR_PATH_NOT_FOUND) { // Some other failure, give up break; } // We couldn't find the path at the given index, start looking further back in the string. foundIndex--; for (; foundIndex > rootLength && inputBuilder[foundIndex] != '\\'; foundIndex--) ; if (foundIndex == rootLength) { // Can't trim the path back any further break; } else { // Temporarily set a null in the string to get Windows to look further up the path inputBuilder[foundIndex] = '\0'; } } else if (result > outputBuilder.Capacity) { // Not enough space. The result count for this API does not include the null terminator. outputBuilder.EnsureCapacity(checked((int)result)); } else { // Found the path success = true; outputBuilder.Length = checked((int)result); if (foundIndex < inputLength - 1) { // It was a partial find, put the non-existent part of the path back outputBuilder.Append(inputBuilder.AsSpan(foundIndex, inputBuilder.Length - foundIndex)); } } } // If we were able to expand the path, use it, otherwise use the original full path result ref ValueStringBuilder builderToUse = ref (success ? ref outputBuilder : ref inputBuilder); // Switch back from \\?\ to \\.\ if necessary if (wasDotDevice) builderToUse[2] = '.'; // Change from \\?\UNC\ to \\?\UN\\ if needed if (isDosUnc) builderToUse[PathInternal.UncExtendedPrefixLength - PathInternal.UncPrefixLength] = '\\'; // Strip out any added characters at the front of the string ReadOnlySpan<char> output = builderToUse.AsSpan(rootDifference); string returnValue = ((originalPath != null) && output.Equals(originalPath.AsSpan(), StringComparison.Ordinal)) ? originalPath : output.ToString(); inputBuilder.Dispose(); return returnValue; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; namespace UnityEditor.XCodeEditor { using Debug = UnityEngine.Debug; public class PBXFileReference : PBXObject { protected const string PATH_KEY = "path"; protected const string NAME_KEY = "name"; protected const string SOURCETREE_KEY = "sourceTree"; protected const string EXPLICIT_FILE_TYPE_KEY = "explicitFileType"; protected const string LASTKNOWN_FILE_TYPE_KEY = "lastKnownFileType"; protected const string ENCODING_KEY = "fileEncoding"; public string buildPhase; public readonly Dictionary<TreeEnum, string> trees = new Dictionary<TreeEnum, string> { { TreeEnum.ABSOLUTE, "<absolute>" }, { TreeEnum.GROUP, "<group>" }, { TreeEnum.BUILT_PRODUCTS_DIR, "BUILT_PRODUCTS_DIR" }, { TreeEnum.DEVELOPER_DIR, "DEVELOPER_DIR" }, { TreeEnum.SDKROOT, "SDKROOT" }, { TreeEnum.SOURCE_ROOT, "SOURCE_ROOT" } }; public static readonly Dictionary<string, string> typeNames = new Dictionary<string, string> { { ".a", "archive.ar" }, { ".app", "wrapper.application" }, { ".s", "sourcecode.asm" }, { ".c", "sourcecode.c.c" }, { ".cpp", "sourcecode.cpp.cpp" }, { ".framework", "wrapper.framework" }, { ".h", "sourcecode.c.h" }, { ".icns", "image.icns" }, { ".m", "sourcecode.c.objc" }, { ".mm", "sourcecode.cpp.objcpp" }, { ".nib", "wrapper.nib" }, { ".plist", "text.plist.xml" }, { ".png", "image.png" }, { ".rtf", "text.rtf" }, { ".tiff", "image.tiff" }, { ".txt", "text" }, { ".xcodeproj", "wrapper.pb-project" }, { ".xib", "file.xib" }, { ".strings", "text.plist.strings" }, { ".bundle", "wrapper.plug-in" }, { ".dylib", "compiled.mach-o.dylib" } }; public static readonly Dictionary<string, string> typePhases = new Dictionary<string, string> { { ".a", "PBXFrameworksBuildPhase" }, { ".app", null }, { ".s", "PBXSourcesBuildPhase" }, { ".c", "PBXSourcesBuildPhase" }, { ".cpp", "PBXSourcesBuildPhase" }, { ".framework", "PBXFrameworksBuildPhase" }, { ".h", null }, { ".icns", "PBXResourcesBuildPhase" }, { ".m", "PBXSourcesBuildPhase" }, { ".mm", "PBXSourcesBuildPhase" }, { ".nib", "PBXResourcesBuildPhase" }, { ".plist", "PBXResourcesBuildPhase" }, { ".png", "PBXResourcesBuildPhase" }, { ".rtf", "PBXResourcesBuildPhase" }, { ".tiff", "PBXResourcesBuildPhase" }, { ".txt", "PBXResourcesBuildPhase" }, { ".xcodeproj", null }, { ".xib", "PBXResourcesBuildPhase" }, { ".strings", "PBXResourcesBuildPhase" }, { ".bundle", "PBXResourcesBuildPhase" }, { ".dylib", "PBXFrameworksBuildPhase" } }; public PBXFileReference( string guid, PBXDictionary dictionary ) : base( guid, dictionary ) { } public PBXFileReference( string filePath, TreeEnum tree = TreeEnum.SOURCE_ROOT ) : base() { this.Add( PATH_KEY, filePath ); this.Add( NAME_KEY, System.IO.Path.GetFileName( filePath ) ); this.Add( SOURCETREE_KEY, (string)( System.IO.Path.IsPathRooted( filePath ) ? trees[TreeEnum.ABSOLUTE] : trees[tree] ) ); this.GuessFileType(); } public string name { get { if( !ContainsKey( NAME_KEY ) ) { return null; } return (string)_data[NAME_KEY]; } } private void GuessFileType() { this.Remove( EXPLICIT_FILE_TYPE_KEY ); this.Remove( LASTKNOWN_FILE_TYPE_KEY ); string extension = System.IO.Path.GetExtension( (string)_data[ PATH_KEY ] ); if( !PBXFileReference.typeNames.ContainsKey( extension ) ){ Debug.LogWarning( "Unknown file extension: " + extension + "\nPlease add extension and Xcode type to PBXFileReference.types" ); return; } this.Add( LASTKNOWN_FILE_TYPE_KEY, PBXFileReference.typeNames[ extension ] ); this.buildPhase = PBXFileReference.typePhases[ extension ]; } private void SetFileType( string fileType ) { this.Remove( EXPLICIT_FILE_TYPE_KEY ); this.Remove( LASTKNOWN_FILE_TYPE_KEY ); this.Add( EXPLICIT_FILE_TYPE_KEY, fileType ); } // class PBXFileReference(PBXType): // def __init__(self, d=None): // PBXType.__init__(self, d) // self.build_phase = None // // types = { // '.a':('archive.ar', 'PBXFrameworksBuildPhase'), // '.app': ('wrapper.application', None), // '.s': ('sourcecode.asm', 'PBXSourcesBuildPhase'), // '.c': ('sourcecode.c.c', 'PBXSourcesBuildPhase'), // '.cpp': ('sourcecode.cpp.cpp', 'PBXSourcesBuildPhase'), // '.framework': ('wrapper.framework','PBXFrameworksBuildPhase'), // '.h': ('sourcecode.c.h', None), // '.icns': ('image.icns','PBXResourcesBuildPhase'), // '.m': ('sourcecode.c.objc', 'PBXSourcesBuildPhase'), // '.mm': ('sourcecode.cpp.objcpp', 'PBXSourcesBuildPhase'), // '.nib': ('wrapper.nib', 'PBXResourcesBuildPhase'), // '.plist': ('text.plist.xml', 'PBXResourcesBuildPhase'), // '.png': ('image.png', 'PBXResourcesBuildPhase'), // '.rtf': ('text.rtf', 'PBXResourcesBuildPhase'), // '.tiff': ('image.tiff', 'PBXResourcesBuildPhase'), // '.txt': ('text', 'PBXResourcesBuildPhase'), // '.xcodeproj': ('wrapper.pb-project', None), // '.xib': ('file.xib', 'PBXResourcesBuildPhase'), // '.strings': ('text.plist.strings', 'PBXResourcesBuildPhase'), // '.bundle': ('wrapper.plug-in', 'PBXResourcesBuildPhase'), // '.dylib': ('compiled.mach-o.dylib', 'PBXFrameworksBuildPhase') // } // // trees = [ // '<absolute>', // '<group>', // 'BUILT_PRODUCTS_DIR', // 'DEVELOPER_DIR', // 'SDKROOT', // 'SOURCE_ROOT', // ] // // def guess_file_type(self): // self.remove('explicitFileType') // self.remove('lastKnownFileType') // ext = os.path.splitext(self.get('name', ''))[1] // // f_type, build_phase = PBXFileReference.types.get(ext, ('?', None)) // // self['lastKnownFileType'] = f_type // self.build_phase = build_phase // // if f_type == '?': // print 'unknown file extension: %s' % ext // print 'please add extension and Xcode type to PBXFileReference.types' // // return f_type // // def set_file_type(self, ft): // self.remove('explicitFileType') // self.remove('lastKnownFileType') // // self['explicitFileType'] = ft // // @classmethod // def Create(cls, os_path, tree='SOURCE_ROOT'): // if tree not in cls.trees: // print 'Not a valid sourceTree type: %s' % tree // return None // // fr = cls() // fr.id = cls.GenerateId() // fr['path'] = os_path // fr['name'] = os.path.split(os_path)[1] // fr['sourceTree'] = '<absolute>' if os.path.isabs(os_path) else tree // fr.guess_file_type() // // return fr } public enum TreeEnum { ABSOLUTE, GROUP, BUILT_PRODUCTS_DIR, DEVELOPER_DIR, SDKROOT, SOURCE_ROOT } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Redis { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// RedisOperations operations. /// </summary> public partial interface IRedisOperations { /// <summary> /// Create a redis cache, or replace (overwrite/recreate, with /// potential downtime) an existing cache /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='name'> /// The name of the redis cache. /// </param> /// <param name='parameters'> /// Parameters supplied to the CreateOrUpdate redis operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<RedisResourceWithAccessKey>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a redis cache. This operation takes a while to complete. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='name'> /// The name of the redis cache. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a redis cache (resource description). /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='name'> /// The name of the redis cache. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<RedisResource>> GetWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all redis caches in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<RedisResource>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all redis caches in the specified subscription. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<RedisResource>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Retrieve a redis cache's access keys. This operation requires /// write permission to the cache resource. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='name'> /// The name of the redis cache. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<RedisListKeysResult>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Regenerate redis cache's access keys. This operation requires /// write permission to the cache resource. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='name'> /// The name of the redis cache. /// </param> /// <param name='parameters'> /// Specifies which key to reset. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<RedisListKeysResult>> RegenerateKeyWithHttpMessagesAsync(string resourceGroupName, string name, RedisRegenerateKeyParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Reboot specified redis node(s). This operation requires write /// permission to the cache resource. There can be potential data /// loss. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='name'> /// The name of the redis cache. /// </param> /// <param name='parameters'> /// Specifies which redis node(s) to reboot. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> ForceRebootWithHttpMessagesAsync(string resourceGroupName, string name, RedisRebootParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Import data into redis cache. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='name'> /// The name of the redis cache. /// </param> /// <param name='parameters'> /// Parameters for redis import operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> ImportWithHttpMessagesAsync(string resourceGroupName, string name, ImportRDBParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Import data into redis cache. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='name'> /// The name of the redis cache. /// </param> /// <param name='parameters'> /// Parameters for redis import operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> BeginImportWithHttpMessagesAsync(string resourceGroupName, string name, ImportRDBParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Import data into redis cache. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='name'> /// The name of the redis cache. /// </param> /// <param name='parameters'> /// Parameters for redis export operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> ExportWithHttpMessagesAsync(string resourceGroupName, string name, ExportRDBParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Import data into redis cache. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='name'> /// The name of the redis cache. /// </param> /// <param name='parameters'> /// Parameters for redis export operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> BeginExportWithHttpMessagesAsync(string resourceGroupName, string name, ExportRDBParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all redis caches in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<RedisResource>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all redis caches in the specified subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<RedisResource>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using Xunit; namespace System.Security.Cryptography.X509Certificates.Tests { public static class FindTests { private static void RunTest(Action<X509Certificate2Collection> test) { RunTest((msCer, pfxCer, col1) => test(col1)); } private static void RunTest(Action<X509Certificate2, X509Certificate2, X509Certificate2Collection> test) { using (var msCer = new X509Certificate2(TestData.MsCertificate)) using (var pfxCer = new X509Certificate2(TestData.PfxData, TestData.PfxDataPassword)) { X509Certificate2Collection col1 = new X509Certificate2Collection(new[] { msCer, pfxCer }); test(msCer, pfxCer, col1); } } private static void RunExceptionTest<TException>(X509FindType findType, object findValue) where TException : Exception { RunTest( (msCer, pfxCer, col1) => { Assert.Throws<TException>(() => col1.Find(findType, findValue, validOnly: false)); }); } private static void RunZeroMatchTest(X509FindType findType, object findValue) { RunTest( (msCer, pfxCer, col1) => { X509Certificate2Collection col2 = col1.Find(findType, findValue, validOnly: false); Assert.Equal(0, col2.Count); }); } private static void RunSingleMatchTest_MsCer(X509FindType findType, object findValue) { RunTest( (msCer, pfxCer, col1) => { EvaluateSingleMatch(msCer, col1, findType, findValue); }); } private static void RunSingleMatchTest_PfxCer(X509FindType findType, object findValue) { RunTest( (msCer, pfxCer, col1) => { EvaluateSingleMatch(pfxCer, col1, findType, findValue); }); } private static void EvaluateSingleMatch( X509Certificate2 expected, X509Certificate2Collection col1, X509FindType findType, object findValue) { X509Certificate2Collection col2 = col1.Find(findType, findValue, validOnly: false); Assert.Equal(1, col2.Count); byte[] serialNumber; using (X509Certificate2 match = col2[0]) { Assert.Equal(expected, match); Assert.NotSame(expected, match); // FriendlyName is Windows-only. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // Verify that the find result and original are linked, not just equal. match.FriendlyName = "HAHA"; Assert.Equal("HAHA", expected.FriendlyName); } serialNumber = match.GetSerialNumber(); } // Check that disposing match didn't dispose expected Assert.Equal(serialNumber, expected.GetSerialNumber()); } [Theory] [MemberData("GenerateInvalidInputs")] public static void FindWithWrongTypeValue(X509FindType findType, Type badValueType) { object badValue; if (badValueType == typeof(object)) { badValue = new object(); } else if (badValueType == typeof(DateTime)) { badValue = DateTime.Now; } else if (badValueType == typeof(byte[])) { badValue = Array.Empty<byte>(); } else if (badValueType == typeof(string)) { badValue = "Hello, world"; } else { throw new InvalidOperationException("No creator exists for type " + badValueType); } RunExceptionTest<CryptographicException>(findType, badValue); } [Theory] [MemberData("GenerateInvalidOidInputs")] public static void FindWithBadOids(X509FindType findType, string badOid) { RunExceptionTest<ArgumentException>(findType, badOid); } [Fact] public static void FindByNullName() { RunExceptionTest<ArgumentNullException>(X509FindType.FindBySubjectName, null); } [Fact] public static void FindByInvalidThumbprint() { RunZeroMatchTest(X509FindType.FindByThumbprint, "Nothing"); } [Fact] public static void FindByInvalidThumbprint_RightLength() { RunZeroMatchTest(X509FindType.FindByThumbprint, "ffffffffffffffffffffffffffffffffffffffff"); } [Fact] public static void FindByValidThumbprint() { RunTest( (msCer, pfxCer, col1) => { EvaluateSingleMatch( pfxCer, col1, X509FindType.FindByThumbprint, pfxCer.Thumbprint); }); } [Theory] [InlineData(false)] [InlineData(true)] public static void FindByValidThumbprint_ValidOnly(bool validOnly) { using (var msCer = new X509Certificate2(TestData.MsCertificate)) { var col1 = new X509Certificate2Collection(msCer); X509Certificate2Collection col2 = col1.Find(X509FindType.FindByThumbprint, msCer.Thumbprint, validOnly); // The certificate is expired. Unless we invent time travel // (or roll the computer clock back significantly), the validOnly // criteria should filter it out. // // This test runs both ways to make sure that the precondition of // "would match otherwise" is met (in the validOnly=false case it is // effectively the same as FindByValidThumbprint, but does less inspection) int expectedMatchCount = validOnly ? 0 : 1; Assert.Equal(expectedMatchCount, col2.Count); if (!validOnly) { // Double check that turning on validOnly doesn't prevent the cloning // behavior of Find. using (X509Certificate2 match = col2[0]) { Assert.Equal(msCer, match); Assert.NotSame(msCer, match); } } } } [Theory] [InlineData("Nothing")] [InlineData("US, Redmond, Microsoft Corporation, MOPR, Microsoft Corporation")] public static void TestSubjectName_NoMatch(string subjectQualifier) { RunZeroMatchTest(X509FindType.FindBySubjectName, subjectQualifier); } [Theory] [InlineData("Microsoft Corporation")] [InlineData("MOPR")] [InlineData("Redmond")] [InlineData("Washington")] [InlineData("US")] [InlineData("US, Washington")] [InlineData("Washington, Redmond")] [InlineData("US, Washington, Redmond, Microsoft Corporation, MOPR, Microsoft Corporation")] [InlineData("us, washington, redmond, microsoft corporation, mopr, microsoft corporation")] public static void TestSubjectName_Match(string subjectQualifier) { RunSingleMatchTest_MsCer(X509FindType.FindBySubjectName, subjectQualifier); } [Theory] [InlineData("")] [InlineData("Nothing")] [InlineData("ou=mopr, o=microsoft corporation")] [InlineData("CN=Microsoft Corporation")] [InlineData("CN=Microsoft Corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("CN=Microsoft Corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US ")] [InlineData(" CN=Microsoft Corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] public static void TestDistinguishedSubjectName_NoMatch(string distinguishedSubjectName) { RunZeroMatchTest(X509FindType.FindBySubjectDistinguishedName, distinguishedSubjectName); } [Theory] [InlineData("CN=Microsoft Corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("CN=microsoft corporation, OU=MOPR, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("cn=microsoft corporation, ou=mopr, o=microsoft corporation, l=redmond, s=washington, c=us")] public static void TestDistinguishedSubjectName_Match(string distinguishedSubjectName) { RunSingleMatchTest_MsCer(X509FindType.FindBySubjectDistinguishedName, distinguishedSubjectName); } [Fact] public static void TestIssuerName_NoMatch() { RunZeroMatchTest(X509FindType.FindByIssuerName, "Nothing"); } [Theory] [InlineData("Microsoft Code Signing PCA")] [InlineData("Microsoft Corporation")] [InlineData("Redmond")] [InlineData("Washington")] [InlineData("US")] [InlineData("US, Washington")] [InlineData("Washington, Redmond")] [InlineData("US, Washington, Redmond, Microsoft Corporation, Microsoft Code Signing PCA")] [InlineData("us, washington, redmond, microsoft corporation, microsoft code signing pca")] public static void TestIssuerName_Match(string issuerQualifier) { RunSingleMatchTest_MsCer(X509FindType.FindByIssuerName, issuerQualifier); } [Theory] [InlineData("")] [InlineData("Nothing")] [InlineData("CN=Microsoft Code Signing PCA")] [InlineData("CN=Microsoft Code Signing PCA, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("CN=Microsoft Code Signing PCA, O=Microsoft Corporation, L=Redmond, S=Washington, C=US ")] [InlineData(" CN=Microsoft Code Signing PCA, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] public static void TestDistinguishedIssuerName_NoMatch(string issuerDistinguishedName) { RunZeroMatchTest(X509FindType.FindByIssuerDistinguishedName, issuerDistinguishedName); } [Theory] [InlineData("CN=Microsoft Code Signing PCA, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("CN=microsoft Code signing pca, O=Microsoft Corporation, L=Redmond, S=Washington, C=US")] [InlineData("cn=microsoft code signing pca, o=microsoft corporation, l=redmond, s=washington, c=us")] public static void TestDistinguishedIssuerName_Match(string issuerDistinguishedName) { RunSingleMatchTest_MsCer(X509FindType.FindByIssuerDistinguishedName, issuerDistinguishedName); } [Fact] public static void TestByTimeValid_Before() { RunTest( (msCer, pfxCer, col1) => { DateTime earliest = new[] { msCer.NotBefore, pfxCer.NotBefore }.Min(); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeValid, earliest - TimeSpan.FromSeconds(1), validOnly: false); Assert.Equal(0, col2.Count); }); } [Fact] public static void TestByTimeValid_After() { RunTest( (msCer, pfxCer, col1) => { DateTime latest = new[] { msCer.NotAfter, pfxCer.NotAfter }.Max(); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeValid, latest + TimeSpan.FromSeconds(1), validOnly: false); Assert.Equal(0, col2.Count); }); } [Fact] public static void TestByTimeValid_Between() { RunTest( (msCer, pfxCer, col1) => { DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min(); DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max(); TimeSpan gap = latestNotBefore - earliestNotAfter; // If this assert fails it means our test data was rebuilt and the constraint // can no longer be satisifed Assert.True(gap > TimeSpan.FromSeconds(1)); DateTime noMatchTime = earliestNotAfter + TimeSpan.FromSeconds(1); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeValid, noMatchTime, validOnly: false); Assert.Equal(0, col2.Count); }); } [Fact] public static void TestByTimeValid_Match() { RunTest( (msCer, pfxCer, col1) => { EvaluateSingleMatch( msCer, col1, X509FindType.FindByTimeValid, msCer.NotBefore + TimeSpan.FromSeconds(1)); }); } [Fact] public static void TestFindByTimeNotYetValid_Match() { RunTest( (msCer, pfxCer, col1) => { DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min(); DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max(); TimeSpan gap = latestNotBefore - earliestNotAfter; // If this assert fails it means our test data was rebuilt and the constraint // can no longer be satisifed Assert.True(gap > TimeSpan.FromSeconds(1)); // One second before the latest NotBefore, so one is valid, the other is not yet valid. DateTime matchTime = latestNotBefore - TimeSpan.FromSeconds(1); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeNotYetValid, matchTime, validOnly: false); Assert.Equal(1, col2.Count); }); } [Fact] public static void TestFindByTimeNotYetValid_NoMatch() { RunTest( (msCer, pfxCer, col1) => { DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min(); DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max(); TimeSpan gap = latestNotBefore - earliestNotAfter; // If this assert fails it means our test data was rebuilt and the constraint // can no longer be satisifed Assert.True(gap > TimeSpan.FromSeconds(1)); // One second after the latest NotBefore, both certificates are time-valid DateTime noMatchTime = latestNotBefore + TimeSpan.FromSeconds(1); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeNotYetValid, noMatchTime, validOnly: false); Assert.Equal(0, col2.Count); }); } [Fact] public static void TestFindByTimeExpired_Match() { RunTest( (msCer, pfxCer, col1) => { DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min(); DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max(); TimeSpan gap = latestNotBefore - earliestNotAfter; // If this assert fails it means our test data was rebuilt and the constraint // can no longer be satisifed Assert.True(gap > TimeSpan.FromSeconds(1)); // One second after the earliest NotAfter, so one is valid, the other is no longer valid. DateTime matchTime = earliestNotAfter + TimeSpan.FromSeconds(1); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeExpired, matchTime, validOnly: false); Assert.Equal(1, col2.Count); }); } [Fact] public static void TestFindByTimeExpired_NoMatch() { RunTest( (msCer, pfxCer, col1) => { DateTime earliestNotAfter = new[] { msCer.NotAfter, pfxCer.NotAfter }.Min(); DateTime latestNotBefore = new[] { msCer.NotBefore, pfxCer.NotBefore }.Max(); TimeSpan gap = latestNotBefore - earliestNotAfter; // If this assert fails it means our test data was rebuilt and the constraint // can no longer be satisifed Assert.True(gap > TimeSpan.FromSeconds(1)); // One second before the earliest NotAfter, so both certificates are valid DateTime noMatchTime = earliestNotAfter - TimeSpan.FromSeconds(1); X509Certificate2Collection col2 = col1.Find( X509FindType.FindByTimeExpired, noMatchTime, validOnly: false); Assert.Equal(0, col2.Count); }); } [Fact] public static void TestBySerialNumber_Decimal() { // Decimal string is an allowed input format. RunSingleMatchTest_PfxCer( X509FindType.FindBySerialNumber, "284069184166497622998429950103047369500"); } [Fact] public static void TestBySerialNumber_DecimalLeadingZeros() { // Checking that leading zeros are ignored. RunSingleMatchTest_PfxCer( X509FindType.FindBySerialNumber, "000" + "284069184166497622998429950103047369500"); } [Theory] [InlineData("1137338006039264696476027508428304567989436592")] // Leading zeroes are fine/ignored [InlineData("0001137338006039264696476027508428304567989436592")] // Compat: Minus signs are ignored [InlineData("-1137338006039264696476027508428304567989436592")] public static void TestBySerialNumber_Decimal_CertB(string serialNumber) { RunSingleMatchTest_MsCer(X509FindType.FindBySerialNumber, serialNumber); } [Fact] public static void TestBySerialNumber_Hex() { // Hex string is also an allowed input format. RunSingleMatchTest_PfxCer( X509FindType.FindBySerialNumber, "D5B5BC1C458A558845BFF51CB4DFF31C"); } [Fact] public static void TestBySerialNumber_HexIgnoreCase() { // Hex string is also an allowed input format and case-blind RunSingleMatchTest_PfxCer( X509FindType.FindBySerialNumber, "d5b5bc1c458a558845bff51cb4dff31c"); } [Fact] public static void TestBySerialNumber_HexLeadingZeros() { // Checking that leading zeros are ignored. RunSingleMatchTest_PfxCer( X509FindType.FindBySerialNumber, "0000" + "D5B5BC1C458A558845BFF51CB4DFF31C"); } [Fact] public static void TestBySerialNumber_NoMatch() { RunZeroMatchTest( X509FindType.FindBySerialNumber, "23000000B011AF0A8BD03B9FDD0001000000B0"); } [Theory] [MemberData("GenerateWorkingFauxSerialNumbers")] public static void TestBySerialNumber_Match_NonDecimalInput(string input) { RunSingleMatchTest_MsCer(X509FindType.FindBySerialNumber, input); } [Fact] public static void TestByExtension_FriendlyName() { // Cannot just say "Enhanced Key Usage" here because the extension name is localized. // Instead, look it up via the OID. RunSingleMatchTest_MsCer(X509FindType.FindByExtension, new Oid("2.5.29.37").FriendlyName); } [Fact] public static void TestByExtension_OidValue() { RunSingleMatchTest_MsCer(X509FindType.FindByExtension, "2.5.29.37"); } [Fact] // Compat: Non-ASCII digits don't throw, but don't match. public static void TestByExtension_OidValue_ArabicNumericChar() { // This uses the same OID as TestByExtension_OidValue, but uses "Arabic-Indic Digit Two" instead // of "Digit Two" in the third segment. This value can't possibly ever match, but it doesn't throw // as an illegal OID value. RunZeroMatchTest(X509FindType.FindByExtension, "2.5.\u06629.37"); } [Fact] public static void TestByExtension_UnknownFriendlyName() { RunExceptionTest<ArgumentException>(X509FindType.FindByExtension, "BOGUS"); } [Fact] public static void TestByExtension_NoMatch() { RunZeroMatchTest(X509FindType.FindByExtension, "2.9"); } [Fact] public static void TestBySubjectKeyIdentifier_UsingFallback() { RunSingleMatchTest_PfxCer( X509FindType.FindBySubjectKeyIdentifier, "B4D738B2D4978AFF290A0B02987BABD114FEE9C7"); } [Theory] [InlineData("5971A65A334DDA980780FF841EBE87F9723241F2")] // Whitespace is allowed [InlineData("59 71\tA6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 F9 72 32 41 F2")] // Lots of kinds of whitespace (does not include \u000b or \u000c, because those // produce a build warning (which becomes an error): // EXEC : warning : '(not included here)', hexadecimal value 0x0C, is an invalid character. [InlineData( "59\u000971\u000aA6\u30005A\u205f33\u000d4D\u0020DA\u008598\u00a007\u1680" + "80\u2000FF\u200184\u20021E\u2003BE\u200487\u2005F9\u200672\u200732\u2008" + "4\u20091\u200aF\u20282\u2029\u202f")] // Non-byte-aligned whitespace is allowed [InlineData("597 1A6 5A3 34D DA9 807 80F F84 1EB E87 F97 232 41F 2")] // Non-symmetric whitespace is allowed [InlineData(" 5971A65 A334DDA980780FF84 1EBE87F97 23241F 2")] public static void TestBySubjectKeyIdentifier_ExtensionPresent(string subjectKeyIdentifier) { RunSingleMatchTest_MsCer(X509FindType.FindBySubjectKeyIdentifier, subjectKeyIdentifier); } [Theory] // Compat: Lone trailing nybbles are ignored [InlineData("59 71 A6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 F9 72 32 41 F2 3")] // Compat: Lone trailing nybbles are ignored, even if not hex [InlineData("59 71 A6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 F9 72 32 41 F2 p")] // Compat: A non-hex character as the high nybble makes that nybble be F [InlineData("59 71 A6 5A 33 4D DA 98 07 80 FF 84 1E BE 87 p9 72 32 41 F2")] // Compat: A non-hex character as the low nybble makes the whole byte FF. [InlineData("59 71 A6 5A 33 4D DA 98 07 80 0p 84 1E BE 87 F9 72 32 41 F2")] public static void TestBySubjectKeyIdentifier_Compat(string subjectKeyIdentifier) { RunSingleMatchTest_MsCer(X509FindType.FindBySubjectKeyIdentifier, subjectKeyIdentifier); } [Fact] public static void TestBySubjectKeyIdentifier_NoMatch() { RunZeroMatchTest(X509FindType.FindBySubjectKeyIdentifier, ""); } [Fact] public static void TestBySubjectKeyIdentifier_NoMatch_RightLength() { RunZeroMatchTest( X509FindType.FindBySubjectKeyIdentifier, "5971A65A334DDA980780FF841EBE87F9723241F0"); } [Fact] public static void TestByApplicationPolicy_MatchAll() { RunTest( (msCer, pfxCer, col1) => { X509Certificate2Collection results = col1.Find(X509FindType.FindByApplicationPolicy, "1.3.6.1.5.5.7.3.3", false); Assert.Equal(2, results.Count); Assert.True(results.Contains(msCer)); Assert.True(results.Contains(pfxCer)); foreach (X509Certificate2 match in results) { match.Dispose(); } }); } [Fact] public static void TestByApplicationPolicy_NoPolicyAlwaysMatches() { // PfxCer doesn't have any application policies which means it's good for all usages (even nonsensical ones.) RunSingleMatchTest_PfxCer(X509FindType.FindByApplicationPolicy, "2.2"); } [Fact] public static void TestByApplicationPolicy_NoMatch() { RunTest( (msCer, pfxCer, col1) => { // Per TestByApplicationPolicy_NoPolicyAlwaysMatches we know that pfxCer will match, so remove it. col1.Remove(pfxCer); X509Certificate2Collection results = col1.Find(X509FindType.FindByApplicationPolicy, "2.2", false); Assert.Equal(0, results.Count); }); } [Fact] public static void TestByCertificatePolicies_MatchA() { using (var policyCert = new X509Certificate2(TestData.CertWithPolicies)) { EvaluateSingleMatch( policyCert, new X509Certificate2Collection(policyCert), X509FindType.FindByCertificatePolicy, "2.18.19"); } } [Fact] public static void TestByCertificatePolicies_MatchB() { using (var policyCert = new X509Certificate2(TestData.CertWithPolicies)) { EvaluateSingleMatch( policyCert, new X509Certificate2Collection(policyCert), X509FindType.FindByCertificatePolicy, "2.32.33"); } } [Fact] public static void TestByCertificatePolicies_NoMatch() { using (var policyCert = new X509Certificate2(TestData.CertWithPolicies)) { X509Certificate2Collection col1 = new X509Certificate2Collection(policyCert); X509Certificate2Collection results = col1.Find(X509FindType.FindByCertificatePolicy, "2.999", false); Assert.Equal(0, results.Count); } } [Fact] public static void TestByTemplate_MatchA() { using (var templatedCert = new X509Certificate2(TestData.CertWithTemplateData)) { EvaluateSingleMatch( templatedCert, new X509Certificate2Collection(templatedCert), X509FindType.FindByTemplateName, "Hello"); } } [Fact] public static void TestByTemplate_MatchB() { using (var templatedCert = new X509Certificate2(TestData.CertWithTemplateData)) { EvaluateSingleMatch( templatedCert, new X509Certificate2Collection(templatedCert), X509FindType.FindByTemplateName, "2.7.8.9"); } } [Fact] public static void TestByTemplate_NoMatch() { using (var templatedCert = new X509Certificate2(TestData.CertWithTemplateData)) { X509Certificate2Collection col1 = new X509Certificate2Collection(templatedCert); X509Certificate2Collection results = col1.Find(X509FindType.FindByTemplateName, "2.999", false); Assert.Equal(0, results.Count); } } [Theory] [InlineData((int)0x80)] [InlineData((uint)0x80)] [InlineData(X509KeyUsageFlags.DigitalSignature)] [InlineData("DigitalSignature")] [InlineData("digitalSignature")] public static void TestFindByKeyUsage_Match(object matchCriteria) { TestFindByKeyUsage(true, matchCriteria); } [Theory] [InlineData((int)0x20)] [InlineData((uint)0x20)] [InlineData(X509KeyUsageFlags.KeyEncipherment)] [InlineData("KeyEncipherment")] [InlineData("KEYEncipherment")] public static void TestFindByKeyUsage_NoMatch(object matchCriteria) { TestFindByKeyUsage(false, matchCriteria); } private static void TestFindByKeyUsage(bool shouldMatch, object matchCriteria) { using (var noKeyUsages = new X509Certificate2(TestData.MsCertificate)) using (var noKeyUsages2 = new X509Certificate2(Path.Combine("TestData", "test.cer"))) using (var keyUsages = new X509Certificate2(Path.Combine("TestData", "microsoft.cer"))) { var coll = new X509Certificate2Collection { noKeyUsages, noKeyUsages2, keyUsages, }; X509Certificate2Collection results = coll.Find(X509FindType.FindByKeyUsage, matchCriteria, false); // The two certificates with no KeyUsages extension will always match, the real question is about the third. int matchCount = shouldMatch ? 3 : 2; Assert.Equal(matchCount, results.Count); if (shouldMatch) { bool found = false; foreach (X509Certificate2 cert in results) { if (keyUsages.Equals(cert)) { Assert.NotSame(cert, keyUsages); found = true; break; } } Assert.True(found, "Certificate with key usages was found in the collection"); } else { Assert.False(results.Contains(keyUsages), "KeyUsages certificate is not present in the collection"); } } } public static IEnumerable<object[]> GenerateWorkingFauxSerialNumbers { get { const string seedDec = "1137338006039264696476027508428304567989436592"; string[] nonHexWords = { "wow", "its", "tough", "using", "only", "high", "lttr", "vlus" }; string gluedTogether = string.Join("", nonHexWords); string withSpaces = string.Join(" ", nonHexWords); yield return new object[] { gluedTogether + seedDec }; yield return new object[] { seedDec + gluedTogether }; yield return new object[] { withSpaces + seedDec }; yield return new object[] { seedDec + withSpaces }; StringBuilder builderDec = new StringBuilder(512); int offsetDec = 0; for (int i = 0; i < nonHexWords.Length; i++) { if (offsetDec < seedDec.Length) { int appendLen = Math.Max(1, seedDec.Length / nonHexWords.Length); appendLen = Math.Min(appendLen, seedDec.Length - offsetDec); builderDec.Append(seedDec, offsetDec, appendLen); offsetDec += appendLen; } builderDec.Append(nonHexWords[i]); } builderDec.Append(seedDec, offsetDec, seedDec.Length - offsetDec); yield return new object[] { builderDec.ToString() }; builderDec.Length = 0; offsetDec = 0; for (int i = 0; i < nonHexWords.Length; i++) { if (offsetDec < seedDec.Length) { int appendLen = Math.Max(1, seedDec.Length / nonHexWords.Length); appendLen = Math.Min(appendLen, seedDec.Length - offsetDec); builderDec.Append(seedDec, offsetDec, appendLen); offsetDec += appendLen; builderDec.Append(' '); } builderDec.Append(nonHexWords[i]); builderDec.Append(' '); } builderDec.Append(seedDec, offsetDec, seedDec.Length - offsetDec); yield return new object[] { builderDec.ToString() }; } } public static IEnumerable<object[]> GenerateInvalidOidInputs { get { X509FindType[] oidTypes = { X509FindType.FindByApplicationPolicy, }; string[] invalidOids = { "", "This Is Not An Oid", "1", "95.22", ".1", "1..1", "1.", "1.2.", }; List<object[]> combinations = new List<object[]>(oidTypes.Length * invalidOids.Length); for (int findTypeIndex = 0; findTypeIndex < oidTypes.Length; findTypeIndex++) { for (int oidIndex = 0; oidIndex < invalidOids.Length; oidIndex++) { combinations.Add(new object[] { oidTypes[findTypeIndex], invalidOids[oidIndex] }); } } return combinations; } } public static IEnumerable<object[]> GenerateInvalidInputs { get { Type[] allTypes = { typeof(object), typeof(DateTime), typeof(byte[]), typeof(string), }; Tuple<X509FindType, Type>[] legalInputs = { Tuple.Create(X509FindType.FindByThumbprint, typeof(string)), Tuple.Create(X509FindType.FindBySubjectName, typeof(string)), Tuple.Create(X509FindType.FindBySubjectDistinguishedName, typeof(string)), Tuple.Create(X509FindType.FindByIssuerName, typeof(string)), Tuple.Create(X509FindType.FindByIssuerDistinguishedName, typeof(string)), Tuple.Create(X509FindType.FindBySerialNumber, typeof(string)), Tuple.Create(X509FindType.FindByTimeValid, typeof(DateTime)), Tuple.Create(X509FindType.FindByTimeNotYetValid, typeof(DateTime)), Tuple.Create(X509FindType.FindByTimeExpired, typeof(DateTime)), Tuple.Create(X509FindType.FindByTemplateName, typeof(string)), Tuple.Create(X509FindType.FindByApplicationPolicy, typeof(string)), Tuple.Create(X509FindType.FindByCertificatePolicy, typeof(string)), Tuple.Create(X509FindType.FindByExtension, typeof(string)), // KeyUsage supports int/uint/KeyUsage/string, but only one of those is in allTypes. Tuple.Create(X509FindType.FindByKeyUsage, typeof(string)), Tuple.Create(X509FindType.FindBySubjectKeyIdentifier, typeof(string)), }; List<object[]> invalidCombinations = new List<object[]>(); for (int findTypesIndex = 0; findTypesIndex < legalInputs.Length; findTypesIndex++) { Tuple<X509FindType, Type> tuple = legalInputs[findTypesIndex]; for (int typeIndex = 0; typeIndex < allTypes.Length; typeIndex++) { Type t = allTypes[typeIndex]; if (t != tuple.Item2) { invalidCombinations.Add(new object[] { tuple.Item1, t }); } } } return invalidCombinations; } } } }
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> /// Controller class for MAM_EstudiosHospitalProvincial /// </summary> [System.ComponentModel.DataObject] public partial class MamEstudiosHospitalProvincialController { // Preload our schema.. MamEstudiosHospitalProvincial thisSchemaLoad = new MamEstudiosHospitalProvincial(); private string userName = String.Empty; protected string UserName { get { if (userName.Length == 0) { if (System.Web.HttpContext.Current != null) { userName=System.Web.HttpContext.Current.User.Identity.Name; } else { userName=System.Threading.Thread.CurrentPrincipal.Identity.Name; } } return userName; } } [DataObjectMethod(DataObjectMethodType.Select, true)] public MamEstudiosHospitalProvincialCollection FetchAll() { MamEstudiosHospitalProvincialCollection coll = new MamEstudiosHospitalProvincialCollection(); Query qry = new Query(MamEstudiosHospitalProvincial.Schema); coll.LoadAndCloseReader(qry.ExecuteReader()); return coll; } [DataObjectMethod(DataObjectMethodType.Select, false)] public MamEstudiosHospitalProvincialCollection FetchByID(object IdMamografiaHP) { MamEstudiosHospitalProvincialCollection coll = new MamEstudiosHospitalProvincialCollection().Where("idMamografiaHP", IdMamografiaHP).Load(); return coll; } [DataObjectMethod(DataObjectMethodType.Select, false)] public MamEstudiosHospitalProvincialCollection FetchByQuery(Query qry) { MamEstudiosHospitalProvincialCollection coll = new MamEstudiosHospitalProvincialCollection(); coll.LoadAndCloseReader(qry.ExecuteReader()); return coll; } [DataObjectMethod(DataObjectMethodType.Delete, true)] public bool Delete(object IdMamografiaHP) { return (MamEstudiosHospitalProvincial.Delete(IdMamografiaHP) == 1); } [DataObjectMethod(DataObjectMethodType.Delete, false)] public bool Destroy(object IdMamografiaHP) { return (MamEstudiosHospitalProvincial.Destroy(IdMamografiaHP) == 1); } /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> [DataObjectMethod(DataObjectMethodType.Insert, true)] public void Insert(int? IdHistoria,string TipoDocumento,int? Documento,string Apellido,string Nombre,DateTime? FechaNacimiento,string ObraSocial,string InformacionContacto,string Direccion,int? SolicitudProfesional,int? SolicitudCentroSalud,int? BiradIzquierdo,int? BiradDerecho,int? BiradDefinitivo,DateTime? FechaPlaca,DateTime? FechaInforme,string Informe,int? IdMotivo,string Motivo,int? IdMotivoSitam,int? IdTipoEstudio,int? IdTipoEstudioSitam,string Observaciones,bool PasadoSips,bool Activo,string CreatedBy,DateTime? CreatedOn,string ModifiedBy,DateTime? ModifiedOn,int? InformeProfesional,string Localidad,string InformacionCelular,int? SolicitudProfesionalSSS,int? SolicitudProfesionalDNI,int? InformeProfesionalSSS,int? InformeProfesionalDNI,string Equipo,string MotivoConsulta,int? Protocolo,string ProtocoloPrefijo) { MamEstudiosHospitalProvincial item = new MamEstudiosHospitalProvincial(); item.IdHistoria = IdHistoria; item.TipoDocumento = TipoDocumento; item.Documento = Documento; item.Apellido = Apellido; item.Nombre = Nombre; item.FechaNacimiento = FechaNacimiento; item.ObraSocial = ObraSocial; item.InformacionContacto = InformacionContacto; item.Direccion = Direccion; item.SolicitudProfesional = SolicitudProfesional; item.SolicitudCentroSalud = SolicitudCentroSalud; item.BiradIzquierdo = BiradIzquierdo; item.BiradDerecho = BiradDerecho; item.BiradDefinitivo = BiradDefinitivo; item.FechaPlaca = FechaPlaca; item.FechaInforme = FechaInforme; item.Informe = Informe; item.IdMotivo = IdMotivo; item.Motivo = Motivo; item.IdMotivoSitam = IdMotivoSitam; item.IdTipoEstudio = IdTipoEstudio; item.IdTipoEstudioSitam = IdTipoEstudioSitam; item.Observaciones = Observaciones; item.PasadoSips = PasadoSips; item.Activo = Activo; item.CreatedBy = CreatedBy; item.CreatedOn = CreatedOn; item.ModifiedBy = ModifiedBy; item.ModifiedOn = ModifiedOn; item.InformeProfesional = InformeProfesional; item.Localidad = Localidad; item.InformacionCelular = InformacionCelular; item.SolicitudProfesionalSSS = SolicitudProfesionalSSS; item.SolicitudProfesionalDNI = SolicitudProfesionalDNI; item.InformeProfesionalSSS = InformeProfesionalSSS; item.InformeProfesionalDNI = InformeProfesionalDNI; item.Equipo = Equipo; item.MotivoConsulta = MotivoConsulta; item.Protocolo = Protocolo; item.ProtocoloPrefijo = ProtocoloPrefijo; item.Save(UserName); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> [DataObjectMethod(DataObjectMethodType.Update, true)] public void Update(int IdMamografiaHP,int? IdHistoria,string TipoDocumento,int? Documento,string Apellido,string Nombre,DateTime? FechaNacimiento,string ObraSocial,string InformacionContacto,string Direccion,int? SolicitudProfesional,int? SolicitudCentroSalud,int? BiradIzquierdo,int? BiradDerecho,int? BiradDefinitivo,DateTime? FechaPlaca,DateTime? FechaInforme,string Informe,int? IdMotivo,string Motivo,int? IdMotivoSitam,int? IdTipoEstudio,int? IdTipoEstudioSitam,string Observaciones,bool PasadoSips,bool Activo,string CreatedBy,DateTime? CreatedOn,string ModifiedBy,DateTime? ModifiedOn,int? InformeProfesional,string Localidad,string InformacionCelular,int? SolicitudProfesionalSSS,int? SolicitudProfesionalDNI,int? InformeProfesionalSSS,int? InformeProfesionalDNI,string Equipo,string MotivoConsulta,int? Protocolo,string ProtocoloPrefijo) { MamEstudiosHospitalProvincial item = new MamEstudiosHospitalProvincial(); item.MarkOld(); item.IsLoaded = true; item.IdMamografiaHP = IdMamografiaHP; item.IdHistoria = IdHistoria; item.TipoDocumento = TipoDocumento; item.Documento = Documento; item.Apellido = Apellido; item.Nombre = Nombre; item.FechaNacimiento = FechaNacimiento; item.ObraSocial = ObraSocial; item.InformacionContacto = InformacionContacto; item.Direccion = Direccion; item.SolicitudProfesional = SolicitudProfesional; item.SolicitudCentroSalud = SolicitudCentroSalud; item.BiradIzquierdo = BiradIzquierdo; item.BiradDerecho = BiradDerecho; item.BiradDefinitivo = BiradDefinitivo; item.FechaPlaca = FechaPlaca; item.FechaInforme = FechaInforme; item.Informe = Informe; item.IdMotivo = IdMotivo; item.Motivo = Motivo; item.IdMotivoSitam = IdMotivoSitam; item.IdTipoEstudio = IdTipoEstudio; item.IdTipoEstudioSitam = IdTipoEstudioSitam; item.Observaciones = Observaciones; item.PasadoSips = PasadoSips; item.Activo = Activo; item.CreatedBy = CreatedBy; item.CreatedOn = CreatedOn; item.ModifiedBy = ModifiedBy; item.ModifiedOn = ModifiedOn; item.InformeProfesional = InformeProfesional; item.Localidad = Localidad; item.InformacionCelular = InformacionCelular; item.SolicitudProfesionalSSS = SolicitudProfesionalSSS; item.SolicitudProfesionalDNI = SolicitudProfesionalDNI; item.InformeProfesionalSSS = InformeProfesionalSSS; item.InformeProfesionalDNI = InformeProfesionalDNI; item.Equipo = Equipo; item.MotivoConsulta = MotivoConsulta; item.Protocolo = Protocolo; item.ProtocoloPrefijo = ProtocoloPrefijo; item.Save(UserName); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.Globalization { using System; using System.Diagnostics.Contracts; //////////////////////////////////////////////////////////////////////////// // // Notes about JapaneseLunisolarCalendar // //////////////////////////////////////////////////////////////////////////// /* ** Calendar support range: ** Calendar Minimum Maximum ** ========== ========== ========== ** Gregorian 1960/01/28 2050/01/22 ** JapaneseLunisolar 1960/01/01 2049/12/29 */ [Serializable] public class JapaneseLunisolarCalendar : EastAsianLunisolarCalendar { // // The era value for the current era. // public const int JapaneseEra = 1; internal GregorianCalendarHelper helper; internal const int MIN_LUNISOLAR_YEAR = 1960; internal const int MAX_LUNISOLAR_YEAR = 2049; internal const int MIN_GREGORIAN_YEAR = 1960; internal const int MIN_GREGORIAN_MONTH = 1; internal const int MIN_GREGORIAN_DAY = 28; internal const int MAX_GREGORIAN_YEAR = 2050; internal const int MAX_GREGORIAN_MONTH = 1; internal const int MAX_GREGORIAN_DAY = 22; internal static DateTime minDate = new DateTime(MIN_GREGORIAN_YEAR, MIN_GREGORIAN_MONTH, MIN_GREGORIAN_DAY); internal static DateTime maxDate = new DateTime((new DateTime(MAX_GREGORIAN_YEAR, MAX_GREGORIAN_MONTH, MAX_GREGORIAN_DAY, 23, 59, 59, 999)).Ticks + 9999); public override DateTime MinSupportedDateTime { get { return (minDate); } } public override DateTime MaxSupportedDateTime { get { return (maxDate); } } protected override int DaysInYearBeforeMinSupportedYear { get { // 1959 from ChineseLunisolarCalendar return 354; } } static readonly int [,] yinfo = { /*Y LM Lmon Lday DaysPerMonth D1 D2 D3 D4 D5 D6 D7 D8 D9 D10 D11 D12 D13 #Days 1960 */{ 6 , 1 , 28 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 29 384 1961 */{ 0 , 2 , 15 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 0 355 1962 */{ 0 , 2 , 5 , 19808 },/* 29 30 29 29 30 30 29 30 29 30 30 29 0 354 1963 */{ 4 , 1 , 25 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384 1964 */{ 0 , 2 , 13 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355 1965 */{ 0 , 2 , 2 , 21104 },/* 29 30 29 30 29 29 30 29 29 30 30 30 0 354 1966 */{ 3 , 1 , 22 , 26928 },/* 29 30 30 29 30 29 29 30 29 29 30 30 29 383 1967 */{ 0 , 2 , 9 , 55632 },/* 30 30 29 30 30 29 29 30 29 30 29 30 0 355 1968 */{ 7 , 1 , 30 , 27304 },/* 29 30 30 29 30 29 30 29 30 29 30 29 30 384 1969 */{ 0 , 2 , 17 , 22176 },/* 29 30 29 30 29 30 30 29 30 29 30 29 0 354 1970 */{ 0 , 2 , 6 , 39632 },/* 30 29 29 30 30 29 30 29 30 30 29 30 0 355 1971 */{ 5 , 1 , 27 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 1972 */{ 0 , 2 , 15 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354 1973 */{ 0 , 2 , 3 , 42208 },/* 30 29 30 29 29 30 29 29 30 30 30 29 0 354 1974 */{ 4 , 1 , 23 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384 1975 */{ 0 , 2 , 11 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 1976 */{ 8 , 1 , 31 , 54600 },/* 30 30 29 30 29 30 29 30 29 30 29 29 30 384 1977 */{ 0 , 2 , 18 , 46400 },/* 30 29 30 30 29 30 29 30 29 30 29 29 0 354 1978 */{ 0 , 2 , 7 , 54944 },/* 30 30 29 30 29 30 30 29 30 29 30 29 0 355 1979 */{ 6 , 1 , 28 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 29 384 1980 */{ 0 , 2 , 16 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355 1981 */{ 0 , 2 , 5 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354 1982 */{ 4 , 1 , 25 , 42200 },/* 30 29 30 29 29 30 29 29 30 30 29 30 30 384 1983 */{ 0 , 2 , 13 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 1984 */{ 10 , 2 , 2 , 45656 },/* 30 29 30 30 29 29 30 29 29 30 29 30 30 384 1985 */{ 0 , 2 , 20 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 0 354 1986 */{ 0 , 2 , 9 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354 1987 */{ 6 , 1 , 29 , 46504 },/* 30 29 30 30 29 30 29 30 30 29 30 29 30 385 1988 */{ 0 , 2 , 18 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354 1989 */{ 0 , 2 , 6 , 38320 },/* 30 29 29 30 29 30 29 30 30 29 30 30 0 355 1990 */{ 5 , 1 , 27 , 18872 },/* 29 30 29 29 30 29 29 30 30 29 30 30 30 384 1991 */{ 0 , 2 , 15 , 18800 },/* 29 30 29 29 30 29 29 30 29 30 30 30 0 354 1992 */{ 0 , 2 , 4 , 25776 },/* 29 30 30 29 29 30 29 29 30 29 30 30 0 354 1993 */{ 3 , 1 , 23 , 27216 },/* 29 30 30 29 30 29 30 29 29 30 29 30 29 383 1994 */{ 0 , 2 , 10 , 59984 },/* 30 30 30 29 30 29 30 29 29 30 29 30 0 355 1995 */{ 8 , 1 , 31 , 27976 },/* 29 30 30 29 30 30 29 30 29 30 29 29 30 384 1996 */{ 0 , 2 , 19 , 23248 },/* 29 30 29 30 30 29 30 29 30 30 29 30 0 355 1997 */{ 0 , 2 , 8 , 11104 },/* 29 29 30 29 30 29 30 30 29 30 30 29 0 354 1998 */{ 5 , 1 , 28 , 37744 },/* 30 29 29 30 29 29 30 30 29 30 30 30 29 384 1999 */{ 0 , 2 , 16 , 37600 },/* 30 29 29 30 29 29 30 29 30 30 30 29 0 354 2000 */{ 0 , 2 , 5 , 51552 },/* 30 30 29 29 30 29 29 30 29 30 30 29 0 354 2001 */{ 4 , 1 , 24 , 58536 },/* 30 30 30 29 29 30 29 29 30 29 30 29 30 384 2002 */{ 0 , 2 , 12 , 54432 },/* 30 30 29 30 29 30 29 29 30 29 30 29 0 354 2003 */{ 0 , 2 , 1 , 55888 },/* 30 30 29 30 30 29 30 29 29 30 29 30 0 355 2004 */{ 2 , 1 , 22 , 23208 },/* 29 30 29 30 30 29 30 29 30 29 30 29 30 384 2005 */{ 0 , 2 , 9 , 22208 },/* 29 30 29 30 29 30 30 29 30 30 29 29 0 354 2006 */{ 7 , 1 , 29 , 43736 },/* 30 29 30 29 30 29 30 29 30 30 29 30 30 385 2007 */{ 0 , 2 , 18 , 9680 },/* 29 29 30 29 29 30 29 30 30 30 29 30 0 354 2008 */{ 0 , 2 , 7 , 37584 },/* 30 29 29 30 29 29 30 29 30 30 29 30 0 354 2009 */{ 5 , 1 , 26 , 51544 },/* 30 30 29 29 30 29 29 30 29 30 29 30 30 384 2010 */{ 0 , 2 , 14 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354 2011 */{ 0 , 2 , 3 , 46240 },/* 30 29 30 30 29 30 29 29 30 29 30 29 0 354 2012 */{ 3 , 1 , 23 , 47696 },/* 30 29 30 30 30 29 30 29 29 30 29 30 29 384 2013 */{ 0 , 2 , 10 , 46416 },/* 30 29 30 30 29 30 29 30 29 30 29 30 0 355 2014 */{ 9 , 1 , 31 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384 2015 */{ 0 , 2 , 19 , 19360 },/* 29 30 29 29 30 29 30 30 30 29 30 29 0 354 2016 */{ 0 , 2 , 8 , 42416 },/* 30 29 30 29 29 30 29 30 30 29 30 30 0 355 2017 */{ 5 , 1 , 28 , 21176 },/* 29 30 29 30 29 29 30 29 30 29 30 30 30 384 2018 */{ 0 , 2 , 16 , 21168 },/* 29 30 29 30 29 29 30 29 30 29 30 30 0 354 2019 */{ 0 , 2 , 5 , 43344 },/* 30 29 30 29 30 29 29 30 29 30 29 30 0 354 2020 */{ 4 , 1 , 25 , 46248 },/* 30 29 30 30 29 30 29 29 30 29 30 29 30 384 2021 */{ 0 , 2 , 12 , 27296 },/* 29 30 30 29 30 29 30 29 30 29 30 29 0 354 2022 */{ 0 , 2 , 1 , 44368 },/* 30 29 30 29 30 30 29 30 29 30 29 30 0 355 2023 */{ 2 , 1 , 22 , 21928 },/* 29 30 29 30 29 30 29 30 30 29 30 29 30 384 2024 */{ 0 , 2 , 10 , 19296 },/* 29 30 29 29 30 29 30 30 29 30 30 29 0 354 2025 */{ 6 , 1 , 29 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 29 384 2026 */{ 0 , 2 , 17 , 42352 },/* 30 29 30 29 29 30 29 30 29 30 30 30 0 355 2027 */{ 0 , 2 , 7 , 21104 },/* 29 30 29 30 29 29 30 29 29 30 30 30 0 354 2028 */{ 5 , 1 , 27 , 26928 },/* 29 30 30 29 30 29 29 30 29 29 30 30 29 383 2029 */{ 0 , 2 , 13 , 55600 },/* 30 30 29 30 30 29 29 30 29 29 30 30 0 355 2030 */{ 0 , 2 , 3 , 23200 },/* 29 30 29 30 30 29 30 29 30 29 30 29 0 354 2031 */{ 3 , 1 , 23 , 43856 },/* 30 29 30 29 30 29 30 30 29 30 29 30 29 384 2032 */{ 0 , 2 , 11 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355 2033 */{ 11 , 1 , 31 , 19176 },/* 29 30 29 29 30 29 30 29 30 30 30 29 30 384 2034 */{ 0 , 2 , 19 , 19168 },/* 29 30 29 29 30 29 30 29 30 30 30 29 0 354 2035 */{ 0 , 2 , 8 , 42192 },/* 30 29 30 29 29 30 29 29 30 30 29 30 0 354 2036 */{ 6 , 1 , 28 , 53864 },/* 30 30 29 30 29 29 30 29 29 30 30 29 30 384 2037 */{ 0 , 2 , 15 , 53840 },/* 30 30 29 30 29 29 30 29 29 30 29 30 0 354 2038 */{ 0 , 2 , 4 , 54560 },/* 30 30 29 30 29 30 29 30 29 29 30 29 0 354 2039 */{ 5 , 1 , 24 , 55968 },/* 30 30 29 30 30 29 30 29 30 29 30 29 29 384 2040 */{ 0 , 2 , 12 , 46752 },/* 30 29 30 30 29 30 30 29 30 29 30 29 0 355 2041 */{ 0 , 2 , 1 , 38608 },/* 30 29 29 30 29 30 30 29 30 30 29 30 0 355 2042 */{ 2 , 1 , 22 , 19160 },/* 29 30 29 29 30 29 30 29 30 30 29 30 30 384 2043 */{ 0 , 2 , 10 , 18864 },/* 29 30 29 29 30 29 29 30 30 29 30 30 0 354 2044 */{ 7 , 1 , 30 , 42168 },/* 30 29 30 29 29 30 29 29 30 29 30 30 30 384 2045 */{ 0 , 2 , 17 , 42160 },/* 30 29 30 29 29 30 29 29 30 29 30 30 0 354 2046 */{ 0 , 2 , 6 , 45648 },/* 30 29 30 30 29 29 30 29 29 30 29 30 0 354 2047 */{ 5 , 1 , 26 , 46376 },/* 30 29 30 30 29 30 29 30 29 29 30 29 30 384 2048 */{ 0 , 2 , 14 , 27968 },/* 29 30 30 29 30 30 29 30 29 30 29 29 0 354 2049 */{ 0 , 2 , 2 , 44448 },/* 30 29 30 29 30 30 29 30 30 29 30 29 0 355 */ }; internal override int MinCalendarYear { get { return (MIN_LUNISOLAR_YEAR); } } internal override int MaxCalendarYear { get { return (MAX_LUNISOLAR_YEAR); } } internal override DateTime MinDate { get { return (minDate); } } internal override DateTime MaxDate { get { return (maxDate); } } internal override EraInfo[] CalEraInfo { get { return (JapaneseCalendar.GetEraInfo()); } } internal override int GetYearInfo(int LunarYear, int Index) { if ((LunarYear < MIN_LUNISOLAR_YEAR) || (LunarYear > MAX_LUNISOLAR_YEAR)) { throw new ArgumentOutOfRangeException( "year", String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("ArgumentOutOfRange_Range"), MIN_LUNISOLAR_YEAR, MAX_LUNISOLAR_YEAR )); } Contract.EndContractBlock(); return yinfo[LunarYear - MIN_LUNISOLAR_YEAR, Index]; } internal override int GetYear(int year, DateTime time) { return helper.GetYear(year, time); } internal override int GetGregorianYear(int year, int era) { return helper.GetGregorianYear(year, era); } // Trim off the eras that are before our date range private static EraInfo[] TrimEras(EraInfo[] baseEras) { EraInfo[] newEras = new EraInfo[baseEras.Length]; int newIndex = 0; // Eras have most recent first, so start with that for (int i = 0; i < baseEras.Length; i++) { // If this one's minimum year is bigger than our maximum year // then we can't use it. if (baseEras[i].yearOffset + baseEras[i].minEraYear >= MAX_LUNISOLAR_YEAR) { // skip this one. continue; } // If this one's maximum era is less than our minimum era // then we've gotten too low in the era #s, so we're done if (baseEras[i].yearOffset + baseEras[i].maxEraYear < MIN_LUNISOLAR_YEAR) { break; } // Wasn't too large or too small, can use this one newEras[newIndex] = baseEras[i]; newIndex++; } // If we didn't copy any then something was wrong, just return base if (newIndex == 0) return baseEras; // Resize the output array Array.Resize(ref newEras, newIndex); return newEras; } // Construct an instance of JapaneseLunisolar calendar. public JapaneseLunisolarCalendar() { helper = new GregorianCalendarHelper(this, TrimEras(JapaneseCalendar.GetEraInfo())); } public override int GetEra(DateTime time) { return (helper.GetEra(time)); } internal override int BaseCalendarID { get { return (CAL_JAPAN); } } internal override int ID { get { return (CAL_JAPANESELUNISOLAR); } } public override int[] Eras { get { return (helper.Eras); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Microsoft.Win32.SafeHandles; internal static partial class Interop { internal static partial class Crypto { internal delegate int X509StoreVerifyCallback(int ok, IntPtr ctx); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509EvpPublicKey")] internal static extern SafeEvpPKeyHandle GetX509EvpPublicKey(SafeX509Handle x509); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_DecodeX509Crl")] internal static extern SafeX509CrlHandle DecodeX509Crl(byte[] buf, int len); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_DecodeX509")] internal static extern SafeX509Handle DecodeX509(byte[] buf, int len); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509DerSize")] internal static extern int GetX509DerSize(SafeX509Handle x); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EncodeX509")] internal static extern int EncodeX509(SafeX509Handle x, byte[] buf); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509Destroy")] internal static extern void X509Destroy(IntPtr a); /// <summary> /// Clone the input certificate into a new object. /// </summary> [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509Duplicate")] internal static extern SafeX509Handle X509Duplicate(IntPtr handle); /// <summary> /// Clone the input certificate into a new object. /// </summary> [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509Duplicate")] internal static extern SafeX509Handle X509Duplicate(SafeX509Handle handle); /// <summary> /// Increment the native reference count of the certificate to protect against /// a free from another pointer-holder. /// </summary> [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509UpRef")] internal static extern SafeX509Handle X509UpRef(IntPtr handle); /// <summary> /// Increment the native reference count of the certificate to protect against /// a free from another pointer-holder. /// </summary> [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509UpRef")] internal static extern SafeX509Handle X509UpRef(SafeX509Handle handle); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_PemReadX509FromBio")] internal static extern SafeX509Handle PemReadX509FromBio(SafeBioHandle bio); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_PemReadX509FromBioAux")] internal static extern SafeX509Handle PemReadX509FromBioAux(SafeBioHandle bio); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509GetSerialNumber")] private static extern SafeSharedAsn1IntegerHandle X509GetSerialNumber_private(SafeX509Handle x); internal static SafeSharedAsn1IntegerHandle X509GetSerialNumber(SafeX509Handle x) { CheckValidOpenSslHandle(x); return SafeInteriorHandle.OpenInteriorHandle( handle => X509GetSerialNumber_private(handle), x); } [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509GetIssuerName")] internal static extern IntPtr X509GetIssuerName(SafeX509Handle x); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509GetSubjectName")] internal static extern IntPtr X509GetSubjectName(SafeX509Handle x); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509CheckPurpose")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool X509CheckPurpose(SafeX509Handle x, int id, int ca); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509IssuerNameHash")] internal static extern ulong X509IssuerNameHash(SafeX509Handle x); [DllImport(Libraries.CryptoNative)] private static extern SafeSharedAsn1OctetStringHandle CryptoNative_X509FindExtensionData( SafeX509Handle x, int extensionNid); internal static SafeSharedAsn1OctetStringHandle X509FindExtensionData(SafeX509Handle x, int extensionNid) { CheckValidOpenSslHandle(x); return SafeInteriorHandle.OpenInteriorHandle( (handle, arg) => CryptoNative_X509FindExtensionData(handle, arg), x, extensionNid); } [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509GetExtCount")] internal static extern int X509GetExtCount(SafeX509Handle x); // Returns a pointer already being tracked by the SafeX509Handle, shouldn't be SafeHandle tracked/freed. // Bounds checking is in place for "loc", IntPtr.Zero is returned on violations. [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509GetExt")] internal static extern IntPtr X509GetExt(SafeX509Handle x, int loc); // Returns a pointer already being tracked by a SafeX509Handle, shouldn't be SafeHandle tracked/freed. [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509ExtensionGetOid")] internal static extern IntPtr X509ExtensionGetOid(IntPtr ex); // Returns a pointer already being tracked by a SafeX509Handle, shouldn't be SafeHandle tracked/freed. [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509ExtensionGetData")] internal static extern IntPtr X509ExtensionGetData(IntPtr ex); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509ExtensionGetCritical")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool X509ExtensionGetCritical(IntPtr ex); [DllImport(Libraries.CryptoNative)] private static extern SafeX509StoreHandle CryptoNative_X509ChainNew(SafeX509StackHandle systemTrust, SafeX509StackHandle userTrust); internal static SafeX509StoreHandle X509ChainNew(SafeX509StackHandle systemTrust, SafeX509StackHandle userTrust) { SafeX509StoreHandle store = CryptoNative_X509ChainNew(systemTrust, userTrust); if (store.IsInvalid) { throw CreateOpenSslCryptographicException(); } return store; } [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreDestory")] internal static extern void X509StoreDestory(IntPtr v); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreAddCrl")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool X509StoreAddCrl(SafeX509StoreHandle ctx, SafeX509CrlHandle x); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreSetRevocationFlag")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool CryptoNative_X509StoreSetRevocationFlag(SafeX509StoreHandle ctx, X509RevocationFlag revocationFlag); internal static void X509StoreSetRevocationFlag(SafeX509StoreHandle ctx, X509RevocationFlag revocationFlag) { if (!CryptoNative_X509StoreSetRevocationFlag(ctx, revocationFlag)) { throw CreateOpenSslCryptographicException(); } } [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreCtxInit")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool X509StoreCtxInit( SafeX509StoreCtxHandle ctx, SafeX509StoreHandle store, SafeX509Handle x509, SafeX509StackHandle extraCerts); [DllImport(Libraries.CryptoNative)] private static extern int CryptoNative_X509VerifyCert(SafeX509StoreCtxHandle ctx); internal static bool X509VerifyCert(SafeX509StoreCtxHandle ctx) { int result = CryptoNative_X509VerifyCert(ctx); if (result < 0) { throw CreateOpenSslCryptographicException(); } return result != 0; } [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreCtxGetError")] internal static extern X509VerifyStatusCode X509StoreCtxGetError(SafeX509StoreCtxHandle ctx); [DllImport(Libraries.CryptoNative)] private static extern int CryptoNative_X509StoreCtxReset(SafeX509StoreCtxHandle ctx); internal static void X509StoreCtxReset(SafeX509StoreCtxHandle ctx) { if (CryptoNative_X509StoreCtxReset(ctx) != 1) { throw CreateOpenSslCryptographicException(); } } [DllImport(Libraries.CryptoNative)] private static extern int CryptoNative_X509StoreCtxRebuildChain(SafeX509StoreCtxHandle ctx); internal static bool X509StoreCtxRebuildChain(SafeX509StoreCtxHandle ctx) { int result = CryptoNative_X509StoreCtxRebuildChain(ctx); if (result < 0) { throw CreateOpenSslCryptographicException(); } return result != 0; } [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreCtxGetErrorDepth")] internal static extern int X509StoreCtxGetErrorDepth(SafeX509StoreCtxHandle ctx); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509StoreCtxSetVerifyCallback")] internal static extern void X509StoreCtxSetVerifyCallback(SafeX509StoreCtxHandle ctx, X509StoreVerifyCallback callback); internal static string GetX509VerifyCertErrorString(X509VerifyStatusCode n) { return Marshal.PtrToStringAnsi(X509VerifyCertErrorString(n)); } [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509VerifyCertErrorString")] private static extern IntPtr X509VerifyCertErrorString(X509VerifyStatusCode n); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_X509CrlDestroy")] internal static extern void X509CrlDestroy(IntPtr a); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_PemWriteBioX509Crl")] internal static extern int PemWriteBioX509Crl(SafeBioHandle bio, SafeX509CrlHandle crl); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_PemReadBioX509Crl")] internal static extern SafeX509CrlHandle PemReadBioX509Crl(SafeBioHandle bio); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509SubjectPublicKeyInfoDerSize")] internal static extern int GetX509SubjectPublicKeyInfoDerSize(SafeX509Handle x509); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EncodeX509SubjectPublicKeyInfo")] internal static extern int EncodeX509SubjectPublicKeyInfo(SafeX509Handle x509, byte[] buf); internal enum X509VerifyStatusCode : int { X509_V_OK = 0, X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT = 2, X509_V_ERR_UNABLE_TO_GET_CRL = 3, X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE = 5, X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY = 6, X509_V_ERR_CERT_SIGNATURE_FAILURE = 7, X509_V_ERR_CRL_SIGNATURE_FAILURE = 8, X509_V_ERR_CERT_NOT_YET_VALID = 9, X509_V_ERR_CERT_HAS_EXPIRED = 10, X509_V_ERR_CRL_NOT_YET_VALID = 11, X509_V_ERR_CRL_HAS_EXPIRED = 12, X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD = 13, X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD = 14, X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD = 15, X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD = 16, X509_V_ERR_OUT_OF_MEM = 17, X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT = 18, X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN = 19, X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY = 20, X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE = 21, X509_V_ERR_CERT_CHAIN_TOO_LONG = 22, X509_V_ERR_CERT_REVOKED = 23, X509_V_ERR_INVALID_CA = 24, X509_V_ERR_PATH_LENGTH_EXCEEDED = 25, X509_V_ERR_INVALID_PURPOSE = 26, X509_V_ERR_CERT_UNTRUSTED = 27, X509_V_ERR_CERT_REJECTED = 28, X509_V_ERR_KEYUSAGE_NO_CERTSIGN = 32, X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER = 33, X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION = 34, X509_V_ERR_KEYUSAGE_NO_CRL_SIGN = 35, X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION = 36, X509_V_ERR_INVALID_NON_CA = 37, X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE = 39, X509_V_ERR_INVALID_EXTENSION = 41, X509_V_ERR_INVALID_POLICY_EXTENSION = 42, X509_V_ERR_NO_EXPLICIT_POLICY = 43, X509_V_ERR_DIFFERENT_CRL_SCOPE = 44, X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE = 45, X509_V_ERR_UNNESTED_RESOURCE = 46, X509_V_ERR_PERMITTED_VIOLATION = 47, X509_V_ERR_EXCLUDED_VIOLATION = 48, X509_V_ERR_SUBTREE_MINMAX = 49, X509_V_ERR_APPLICATION_VERIFICATION = 50, X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE = 51, X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX = 52, X509_V_ERR_UNSUPPORTED_NAME_SYNTAX = 53, X509_V_ERR_CRL_PATH_VALIDATION_ERROR = 54, X509_V_ERR_PATH_LOOP = 55, X509_V_ERR_SUITE_B_INVALID_VERSION = 56, X509_V_ERR_SUITE_B_INVALID_ALGORITHM = 57, X509_V_ERR_SUITE_B_INVALID_CURVE = 58, X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM = 59, X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED = 60, X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256 = 61, X509_V_ERR_HOSTNAME_MISMATCH = 62, X509_V_ERR_EMAIL_MISMATCH = 63, X509_V_ERR_IP_ADDRESS_MISMATCH = 64, X509_V_ERR_DANE_NO_MATCH = 65, X509_V_ERR_EE_KEY_TOO_SMALL = 66, X509_V_ERR_CA_KEY_TOO_SMALL = 67, X509_V_ERR_CA_MD_TOO_WEAK = 68, X509_V_ERR_INVALID_CALL = 69, X509_V_ERR_STORE_LOOKUP = 70, X509_V_ERR_NO_VALID_SCTS = 71, X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION = 72, X509_V_ERR_OCSP_VERIFY_NEEDED = 73, X509_V_ERR_OCSP_VERIFY_FAILED = 74, X509_V_ERR_OCSP_CERT_UNKNOWN = 75, } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Net.Mail; using System.Text; namespace System.Net.Http.Headers { internal static class HeaderUtilities { private const string qualityName = "q"; internal const string ConnectionClose = "close"; internal static readonly TransferCodingHeaderValue TransferEncodingChunked = new TransferCodingHeaderValue("chunked"); internal static readonly NameValueWithParametersHeaderValue ExpectContinue = new NameValueWithParametersHeaderValue("100-continue"); internal const string BytesUnit = "bytes"; // Validator internal static readonly Action<HttpHeaderValueCollection<string>, string> TokenValidator = ValidateToken; internal static void SetQuality(ObjectCollection<NameValueHeaderValue> parameters, double? value) { Contract.Requires(parameters != null); NameValueHeaderValue qualityParameter = NameValueHeaderValue.Find(parameters, qualityName); if (value.HasValue) { // Note that even if we check the value here, we can't prevent a user from adding an invalid quality // value using Parameters.Add(). Even if we would prevent the user from adding an invalid value // using Parameters.Add() he could always add invalid values using HttpHeaders.AddWithoutValidation(). // So this check is really for convenience to show users that they're trying to add an invalid // value. if ((value < 0) || (value > 1)) { throw new ArgumentOutOfRangeException("value"); } string qualityString = ((double)value).ToString("0.0##", NumberFormatInfo.InvariantInfo); if (qualityParameter != null) { qualityParameter.Value = qualityString; } else { parameters.Add(new NameValueHeaderValue(qualityName, qualityString)); } } else { // Remove quality parameter if (qualityParameter != null) { parameters.Remove(qualityParameter); } } } internal static double? GetQuality(ObjectCollection<NameValueHeaderValue> parameters) { Contract.Requires(parameters != null); NameValueHeaderValue qualityParameter = NameValueHeaderValue.Find(parameters, qualityName); if (qualityParameter != null) { // Note that the RFC requires decimal '.' regardless of the culture. I.e. using ',' as decimal // separator is considered invalid (even if the current culture would allow it). double qualityValue = 0; if (double.TryParse(qualityParameter.Value, NumberStyles.AllowDecimalPoint, NumberFormatInfo.InvariantInfo, out qualityValue)) { return qualityValue; } // If the stored value is an invalid quality value, just return null and log a warning. if (Logging.On) Logging.PrintError(Logging.Http, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_log_headers_invalid_quality, qualityParameter.Value)); } return null; } internal static void CheckValidToken(string value, string parameterName) { if (string.IsNullOrEmpty(value)) { throw new ArgumentException(SR.net_http_argument_empty_string, parameterName); } if (HttpRuleParser.GetTokenLength(value, 0) != value.Length) { throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value)); } } internal static void CheckValidComment(string value, string parameterName) { if (string.IsNullOrEmpty(value)) { throw new ArgumentException(SR.net_http_argument_empty_string, parameterName); } int length = 0; if ((HttpRuleParser.GetCommentLength(value, 0, out length) != HttpParseResult.Parsed) || (length != value.Length)) // no trailing spaces allowed { throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value)); } } internal static void CheckValidQuotedString(string value, string parameterName) { if (string.IsNullOrEmpty(value)) { throw new ArgumentException(SR.net_http_argument_empty_string, parameterName); } int length = 0; if ((HttpRuleParser.GetQuotedStringLength(value, 0, out length) != HttpParseResult.Parsed) || (length != value.Length)) // no trailing spaces allowed { throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, value)); } } internal static bool AreEqualCollections<T>(ObjectCollection<T> x, ObjectCollection<T> y) where T : class { return AreEqualCollections(x, y, null); } internal static bool AreEqualCollections<T>(ObjectCollection<T> x, ObjectCollection<T> y, IEqualityComparer<T> comparer) where T : class { if (x == null) { return (y == null) || (y.Count == 0); } if (y == null) { return (x.Count == 0); } if (x.Count != y.Count) { return false; } if (x.Count == 0) { return true; } // We have two unordered lists. So comparison is an O(n*m) operation which is expensive. Usually // headers have 1-2 parameters (if any), so this comparison shouldn't be too expensive. bool[] alreadyFound = new bool[x.Count]; int i = 0; foreach (var xItem in x) { Debug.Assert(xItem != null); i = 0; bool found = false; foreach (var yItem in y) { if (!alreadyFound[i]) { if (((comparer == null) && xItem.Equals(yItem)) || ((comparer != null) && comparer.Equals(xItem, yItem))) { alreadyFound[i] = true; found = true; break; } } i++; } if (!found) { return false; } } // Since we never re-use a "found" value in 'y', we expect 'alreadyFound' to have all fields set to 'true'. // Otherwise the two collections can't be equal and we should not get here. Debug.Assert(Contract.ForAll(alreadyFound, value => { return value; }), "Expected all values in 'alreadyFound' to be true since collections are considered equal."); return true; } internal static int GetNextNonEmptyOrWhitespaceIndex(string input, int startIndex, bool skipEmptyValues, out bool separatorFound) { Contract.Requires(input != null); Contract.Requires(startIndex <= input.Length); // it's OK if index == value.Length. separatorFound = false; int current = startIndex + HttpRuleParser.GetWhitespaceLength(input, startIndex); if ((current == input.Length) || (input[current] != ',')) { return current; } // If we have a separator, skip the separator and all following whitespaces. If we support // empty values, continue until the current character is neither a separator nor a whitespace. separatorFound = true; current++; // skip delimiter. current = current + HttpRuleParser.GetWhitespaceLength(input, current); if (skipEmptyValues) { while ((current < input.Length) && (input[current] == ',')) { current++; // skip delimiter. current = current + HttpRuleParser.GetWhitespaceLength(input, current); } } return current; } internal static DateTimeOffset? GetDateTimeOffsetValue(string headerName, HttpHeaders store) { Contract.Requires(store != null); object storedValue = store.GetParsedValues(headerName); if (storedValue != null) { return (DateTimeOffset)storedValue; } return null; } internal static TimeSpan? GetTimeSpanValue(string headerName, HttpHeaders store) { Contract.Requires(store != null); object storedValue = store.GetParsedValues(headerName); if (storedValue != null) { return (TimeSpan)storedValue; } return null; } internal static bool TryParseInt32(string value, out int result) { return int.TryParse(value, NumberStyles.None, NumberFormatInfo.InvariantInfo, out result); } internal static bool TryParseInt64(string value, out long result) { return long.TryParse(value, NumberStyles.None, NumberFormatInfo.InvariantInfo, out result); } internal static string DumpHeaders(params HttpHeaders[] headers) { // Return all headers as string similar to: // { // HeaderName1: Value1 // HeaderName1: Value2 // HeaderName2: Value1 // ... // } StringBuilder sb = new StringBuilder(); sb.Append("{\r\n"); for (int i = 0; i < headers.Length; i++) { if (headers[i] != null) { foreach (var header in headers[i]) { foreach (var headerValue in header.Value) { sb.Append(" "); sb.Append(header.Key); sb.Append(": "); sb.Append(headerValue); sb.Append("\r\n"); } } } } sb.Append('}'); return sb.ToString(); } internal static bool IsValidEmailAddress(string value) { try { #if NETNative new MailAddress(value); #else MailAddressParser.ParseAddress(value); #endif return true; } catch (FormatException e) { if (Logging.On) Logging.PrintError(Logging.Http, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_log_headers_wrong_email_format, value, e.Message)); } return false; } private static void ValidateToken(HttpHeaderValueCollection<string> collection, string value) { CheckValidToken(value, "item"); } } }
// Copyright: Hemanth Kapila (2016). // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Text; using Xunit; using CShark.Lexer; namespace CSharkTests.Lexer { public class CharTests { [Fact] public void RandomlyChosenChars_As4DigitHexStr_CharLexer_Match() { Random random = new Random(); ILexer lexer = new CharLexer(); for (int i=0; i<1000; i++) { char c = Convert.ToChar(random.Next(Char.MaxValue)); string inpStr = Convert.ToInt32(c).ToString("x"); while (inpStr.Length < 4) { inpStr = "0" + inpStr; } Assert.Equal(4, inpStr.Length); using (IReader reader = new Reader(new StringReader($"'\\u{inpStr}'"))) { Assert.True(reader.MoveNext()); var token = lexer.Scan(reader); Assert.Equal(TokenType.CharConstant, token.TokenType); Assert.Equal(c, token.Text); Assert.False(reader.MoveNext()); } } } [Fact] public void RandomlyChosenChars_As8DigitHexStr_CharLexer_Match() { Random random = new Random(); ILexer lexer = new CharLexer(); for (int i=0; i<1000; i++) { char c = Convert.ToChar(random.Next(Char.MaxValue)); string inpStr = Convert.ToInt32(c).ToString("x"); while (inpStr.Length < 8) { inpStr = "0" + inpStr; } Assert.Equal(8, inpStr.Length); using (IReader reader = new Reader(new StringReader($"'\\U{inpStr}'"))) { Assert.True(reader.MoveNext()); var token = lexer.Scan(reader); Assert.Equal(TokenType.CharConstant, token.TokenType); Assert.Equal(c, token.Text); Assert.False(reader.MoveNext()); } } } [Fact] public void EscapedChars_CharLexer_Match() { ILexer lexer = new CharLexer(); for(int i=0; i<CharLexer.EscapedChars.Length; i++) { char c = CharLexer.EscapedChars[i]; var expected = CharLexer.EscapedVals[i]; using (IReader reader = new Reader(new StringReader($"'\\{c}'"))) { Assert.True(reader.MoveNext()); var token = lexer.Scan(reader); Assert.Equal(TokenType.CharConstant, token.TokenType); Assert.Equal(expected, token.Text); Assert.False(reader.MoveNext()); } } } [Fact] public void RandomlyChosenChars_CharLexer_Match() { Random random = new Random(); ILexer lexer = new CharLexer(); for (int i=0; i<1000; i++) { char c = Convert.ToChar(random.Next(Char.MaxValue)); while (c == '\\' || c == '\'') { c = Convert.ToChar(random.Next(Char.MaxValue)); } using (IReader reader = new Reader(new StringReader($"'{c}'"))) { Assert.True(reader.MoveNext()); var token = lexer.Scan(reader); Assert.Equal(TokenType.CharConstant, token.TokenType); Assert.Equal(c, token.Text); Assert.False(reader.MoveNext()); } } } [Fact] public void EmptyChar_CharLexer_Throws() { var lexer = new CharLexer(); using (IReader reader = new Reader(new StringReader($"''"))) { Assert.True(reader.MoveNext()); Assert.Throws<ScannerException>(() => lexer.Scan(reader)); } } [Fact] public void UnescapedBackSlash_CharLexer_Throws() { var lexer = new CharLexer(); using (IReader reader = new Reader(new StringReader($"'\\'"))) { Assert.True(reader.MoveNext()); Assert.Throws<ScannerException>(() => lexer.Scan(reader)); } } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(5)] public void WrongNumOfHexDigitsFollowing_u_CharLexer_Throws(int count) { string digits = "0123456789ABCDEFabcdef"; var random = new Random(); var lexer = new CharLexer(); for (int i=0; i<1000; i++) { var strb = new StringBuilder("'\\u"); for (int j=0; j < count; j++) { strb.Append(digits[random.Next(digits.Length)]); } using (IReader reader = new Reader(new StringReader(strb.ToString()))) { Assert.True(reader.MoveNext()); Assert.Throws<ScannerException>(() => lexer.Scan(reader)); } } } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(4)] [InlineData(5)] [InlineData(6)] [InlineData(7)] [InlineData(9)] public void WrongNumOfHexDigitsFollowing_U_CharLexer_Throws(int count) { string digits = "0123456789ABCDEFabcdef"; var random = new Random(); var lexer = new CharLexer(); for (int i=0; i<10; i++) { var strb = new StringBuilder("'\\U"); for (int j=0; j < count; j++) { strb.Append(digits[random.Next(digits.Length)]); } using (IReader reader = new Reader(new StringReader(strb.ToString()))) { Assert.True(reader.MoveNext()); Assert.Throws<ScannerException>(() => lexer.Scan(reader)); } } } [Fact] public void EmptyString_StringLexer_Success() { var lexer = new StringLexer(); using (IReader reader = new Reader(new StringReader("\"\""))) { Assert.True(reader.MoveNext()); Token t = lexer.Scan(reader); Assert.NotNull(t); Assert.Equal(TokenType.StringConstant, t.TokenType); Assert.Equal(string.Empty, t.Text); Assert.False(reader.MoveNext()); } } [Fact] public void StringWithSlashR_StringLexer_Throws() { var lexer = new StringLexer(); using (IReader reader = new Reader(new StringReader("\"\r\""))) { Assert.True(reader.MoveNext()); Assert.Throws<ScannerException>(() => lexer.Scan(reader)); } } [Fact] public void StringWithSlashN_StringLexer_Throws() { var lexer = new StringLexer(); using (IReader reader = new Reader(new StringReader("\"\n\""))) { Assert.True(reader.MoveNext()); Assert.Throws<ScannerException>(() => lexer.Scan(reader)); } } [Fact] public void HundredCharString_StringLexer_Match() { var random = new Random(); var lexer = new StringLexer(); var strb = new StringBuilder("\""); for (int i=0; i<100; i++) { char c = Convert.ToChar(random.Next(Char.MaxValue)); while (c == '\\' || c == '\r' || c == '\n' || c == '"') { c = Convert.ToChar(random.Next(Char.MaxValue)); } strb.Append(c); } strb.Append('\"'); using (IReader reader = new Reader(new StringReader(strb.ToString()))) { Assert.True(reader.MoveNext()); Token t = lexer.Scan(reader); Assert.NotNull(t); Assert.Equal(TokenType.StringConstant, t.TokenType); Assert.Equal(strb.ToString(), "\"" + t.Text + "\""); Assert.False(reader.MoveNext()); } } } }
using System; using System.Collections.Generic; using System.Text; using System.IO; using gView.Framework.FDB; using gView.Framework.Data; using gView.Framework.Geometry; namespace gView.DataSources.Shape { [gView.Framework.system.RegisterPlugIn("BC0F0E24-075D-437c-ACBF-48BA74906009")] public class ShapeDatabase : IFileFeatureDatabase { private string _errMsg = ""; private string _name = ""; private string _directoryName = String.Empty; internal string DirectoryName { set { _directoryName = value; } } #region IFeatureDatabase Member public int CreateDataset(string name, ISpatialReference sRef) { return Create(name) ? 0 : -1; } public int CreateFeatureClass(string dsname, string fcname, IGeometryDef geomDef, IFields fields) { if (geomDef == null || fields == null) return -1; string filename = _directoryName + @"\" + fcname; Fields f = new Fields(); foreach (IField field in fields.ToEnumerable()) f.Add(field); if (!SHPFile.Create(filename, geomDef, f)) return -1; return 0; } public IFeatureDataset this[string name] { get { if (name.ToLower() == _directoryName.ToLower() || name.ToLower() == "esri shapefile") { ShapeDataset dataset = new ShapeDataset(); dataset.ConnectionString = _directoryName; dataset.Open(); return dataset; } else { ShapeDataset dataset = new ShapeDataset(); dataset.ConnectionString = name; dataset.Open(); return dataset; } return null; } } public string[] DatasetNames { get { throw new Exception("The method or operation is not implemented."); } } public bool DeleteDataset(string dsName) { try { DirectoryInfo di = new DirectoryInfo(dsName); if (!di.Exists) di.Delete(); return true; } catch (Exception ex) { _errMsg = ex.Message; return false; } } public bool DeleteFeatureClass(string fcName) { if(_name=="") return false; SHPFile file = new SHPFile(_name + @"\" + fcName + ".shp"); return file.Delete(); } public bool RenameDataset(string name, string newName) { throw new Exception("The method or operation is not implemented."); } public bool RenameFeatureClass(string name, string newName) { throw new Exception("The method or operation is not implemented."); } public IFeatureCursor Query(IFeatureClass fc, IQueryFilter filter) { return fc.GetFeatures(filter); } #endregion #region IDatabase Member public bool Create(string name) { try { DirectoryInfo di = new DirectoryInfo(name); if (!di.Exists) di.Create(); return true; } catch (Exception ex) { _errMsg = ex.Message; return false; } } public bool Open(string name) { try { DirectoryInfo di = new DirectoryInfo(name); if (di.Exists) { _name = _directoryName = name; return true; } else { _name = name; _errMsg = "Directory not exists!"; return false; } } catch(Exception ex) { _errMsg = ex.Message; _name = ""; return false; } } public string lastErrorMsg { get { return _errMsg; } } public Exception lastException { get { return null; } } #endregion #region IDisposable Member public void Dispose() { } #endregion #region IFeatureUpdater Member public bool Insert(IFeatureClass fClass, IFeature feature) { if (fClass == null || feature == null) return false; List<IFeature> features = new List<IFeature>(); features.Add(feature); return Insert(fClass, features); } public bool Insert(IFeatureClass fClass, List<IFeature> features) { if (fClass == null || !(fClass.Dataset is ShapeDataset) || features == null) return false; if (features.Count == 0) return true; SHPFile shpFile = new SHPFile(fClass.Dataset.ConnectionString + @"\" + fClass.Name + ".shp"); foreach (IFeature feature in features) { if (!shpFile.WriteShape(feature)) return false; } return true; } public bool Update(IFeatureClass fClass, IFeature feature) { throw new Exception("The method or operation is not implemented."); } public bool Update(IFeatureClass fClass, List<IFeature> features) { throw new Exception("The method or operation is not implemented."); } public bool Delete(IFeatureClass fClass, int oid) { throw new Exception("The method or operation is not implemented."); } public bool Delete(IFeatureClass fClass, string where) { throw new Exception("The method or operation is not implemented."); } public int SuggestedInsertFeatureCountPerTransaction { get { return 50; } } #endregion #region IFileFeatureDatabase Member public bool Flush(IFeatureClass fc) { return true; } public string DatabaseName { get { return "ESRI Shape file"; } } public int MaxFieldNameLength { get { return 10; } } #endregion } }
/* *************************************************************************** * This file is part of SharpNEAT - Evolution of Neural Networks. * * Copyright 2004-2006, 2009-2010 Colin Green (sharpneat@gmail.com) * * SharpNEAT is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SharpNEAT is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with SharpNEAT. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Collections.Generic; using System.Drawing; namespace SharpNeat.View.Graph { /// <summary> /// Paints IOGraphs to a GDI+ Graphics object. /// </summary> public class IOGraphPainter { /// <summary>Diameter of a node in the model coordinate space.</summary> const float NodeDiameterModel = 10; /// <summary>Font for drawing text on the viewport.</summary> protected static readonly Font __fontNodeTag = new Font("Microsoft Sans Serif", 7.0F); /// <summary>Black brush</summary> protected static readonly Brush __brushBlack = new SolidBrush(Color.Black); /// <summary>Brush for node fill color.</summary> protected static readonly Brush __brushNodeFill = new SolidBrush(Color.GhostWhite); /// <summary>Black pen for node borders.</summary> protected static readonly Pen __penBlack = new Pen(Color.Black, 2F); /// <summary>Pen for drawing connections with positive connection weight.</summary> protected static readonly Color _connectionPositive = Color.Red; /// <summary>Pen for drawing connections with negative connection weight.</summary> protected static readonly Color _connectionNegative = Color.Blue; #region Painting Methods / High Level /// <summary> /// Paints the provided IOGraph onto the provided GDI+ Graphics drawing surface. /// </summary> public void PaintNetwork(IOGraph graph, Graphics g, Rectangle viewportArea, float zoomFactor) { // Create a PaintState object. This holds all temporary state info for the painting routines. // Pass the call on to the virtual PaintNetwork. This allows us to override a version of PaintNetwork // that has access to a PaintState object. PaintState state = new PaintState(g, viewportArea, zoomFactor, graph.ConnectionWeightRange); PaintNetwork(graph, state); } /// <summary> /// Paints the provided IOGraph onto the current GDI+ Graphics drawing surface. /// </summary> protected virtual void PaintNetwork(IOGraph graph, PaintState state) { // Create per-node state info. int hiddenNodeCount = graph.HiddenNodeList.Count; int inputNodeCount = graph.InputNodeList.Count; int outputNodeCount = graph.OutputNodeList.Count; state._nodeStateDict = new Dictionary<GraphNode,ConnectionPointInfo>(hiddenNodeCount + inputNodeCount + outputNodeCount); // Paint all connections. We do this first and paint nodes on top of the connections. This allows the // slightly messy ends of the connections to be painted over by the nodes. PaintConnections(graph.InputNodeList, state); PaintConnections(graph.HiddenNodeList, state); PaintConnections(graph.OutputNodeList, state); // Paint all nodes. Painted over the top of connection endpoints. PaintNodes(graph.InputNodeList, state); PaintNodes(graph.HiddenNodeList, state); PaintNodes(graph.OutputNodeList, state); } #endregion #region Painting Methods / Model Element Painting private void PaintNodes(IList<GraphNode> nodeList, PaintState state) { int nodeCount = nodeList.Count; for(int i=0; i<nodeCount; i++) { PaintNode(nodeList[i], state); } } private void PaintConnections(IList<GraphNode> nodeList, PaintState state) { int nodeCount = nodeList.Count; for(int i=0; i<nodeCount; i++) { List<GraphConnection> conList = nodeList[i].OutConnectionList; int conCount = conList.Count; for(int j=0; j<conCount; j++) { PaintConnection(conList[j], state); } } } /// <summary> /// Paints a single graph node. /// </summary> protected virtual void PaintNode(GraphNode node, PaintState state) { Point nodePos = ModelToViewport(node.Position, state); if(!IsPointWithinViewport(nodePos, state)) { // Skip node. It's outside the viewport area. return; } // Paint the node as a square. Create a Rectangle that represents the square's position and size. Point p = new Point(nodePos.X - state._nodeDiameterHalf, nodePos.Y - state._nodeDiameterHalf); Size s = new Size(state._nodeDiameter, state._nodeDiameter); Rectangle r = new Rectangle(p, s); // Paint the node. Fill first and then border, this gives a clean border. Graphics g = state._g; g.FillRectangle(__brushNodeFill, r); g.DrawRectangle(__penBlack, r); // Draw the node tag. nodePos.X += state._nodeDiameterHalf+1; nodePos.Y -= state._nodeDiameterHalf/2; g.DrawString(node.Tag, __fontNodeTag, __brushBlack, nodePos); } private void PaintConnection(GraphConnection con, PaintState state) { Point srcPos = ModelToViewport(con.SourceNode.Position, state); Point tgtPos = ModelToViewport(con.TargetNode.Position, state); // Connections leave from the base of the source node and enter the top of the target node. // Adjust end points to make them neatly terminate just underneath the edge of the endpoint nodes. srcPos.Y += (int)(state._nodeDiameterHalf * 0.9f); tgtPos.Y -= (int)(state._nodeDiameterHalf * 0.9f); // Is any part of the connection within the viewport area? if(!IsPointWithinViewport(srcPos, state) && !IsPointWithinViewport(tgtPos, state)) { // Skip connection. It's outside the viewport area. return; } // Create a pen for painting the connection. // Width is related to connection strength/magnitude. float width = (float)(con.Weight < 0.0 ? -Math.Log10(1.0 - con.Weight) : Math.Log10(1.0 + con.Weight)); width = width * state._connectionWeightToWidth * state._zoomFactor; width = Math.Max(1f, Math.Abs(width)); Pen pen = new Pen(con.Weight < 0f ? _connectionNegative : _connectionPositive, width); // Draw the connection line. if(tgtPos.Y > srcPos.Y) { // Target is below the source. Draw a straight line. state._g.DrawLine(pen, srcPos, tgtPos); } else { // Target is above source. Draw a back-connection. PaintBackConnection(pen, srcPos, tgtPos, state.GetNodeStateInfo(con.SourceNode), state.GetNodeStateInfo(con.TargetNode), state); } } private void PaintBackConnection(Pen pen, Point srcPos, Point tgtPos, ConnectionPointInfo srcInfo, ConnectionPointInfo tgtInfo, PaintState state) { const float SlopeInit = 0.25f; const float SlopeIncr = 0.23f; // This is the maximum slope value we get before exceeding the slope threshold of 1. float slopeMax = SlopeInit + (SlopeIncr * (float)Math.Floor((1f-SlopeInit) / SlopeIncr)); // Back connection is described by the line ABCDEF. A = srcPos and F = tgtPos. int srcConIdx, tgtConIdx; int srcSide, tgtSide; // If the source and target nodes are close on the X-axis then connect to the same side on both // nodes. Otherwise connect nodes on their facing sides. if(Math.Abs(tgtPos.X - srcPos.X) <= NodeDiameterModel) { srcConIdx = srcInfo._lowerLeft++; tgtConIdx = tgtInfo._upperLeft++; srcSide = -1; tgtSide = -1; } else if(tgtPos.X > srcPos.X) { srcConIdx = srcInfo._lowerRight++; tgtConIdx = tgtInfo._upperLeft++; srcSide = 1; tgtSide = -1; } else { srcConIdx = srcInfo._lowerLeft++; tgtConIdx = tgtInfo._upperRight++; srcSide = -1; tgtSide = 1; } //--- Point B. // The line AB is a connection leg emerging from the base of a node. To visually seperate multiple legs // the first leg has a gentle gradient (almost horizontal) and each successive leg has a steeper gradient. // Once a vertical gradient has been reached each sucessive leg is made longer. // Calculate leg slope: 0=horizontal, 1=vertical. Hence this is value is not a gradient. // Slope pre-trimming back to maximum of 1.0. float slopePre = SlopeInit + (SlopeIncr * srcConIdx); // Leg length. float lenAB = state._backConnectionLegLength; float slope = slopePre; if(slope > slopeMax) { // Increase length in fractions of _backConnectionLegLength. lenAB += (slopePre-slopeMax) * state._backConnectionLegLength; slope = 1f; } // Calculate position of B as relative to A. // Note. Length is taken to be L1 length (Manhatten distance). This means that the successive B positions // describe a straight line (rather than the circle you get with L2/Euclidean distance) which in turn // ensures that the BC segments of successive connections are evenly spaced out. int xDelta = (int)(lenAB * (1f - slope)) * srcSide; int yDelta = (int)(lenAB * slope); Point b = new Point(srcPos.X + xDelta, srcPos.Y + yDelta); //--- Point C. // Line BC is a horizontal line from the end of the leg AB. int lenBC = (int)(2f * slopePre * state._backConnectionLegLength); xDelta = lenBC * srcSide; Point c = new Point(b.X + xDelta, b.Y); //--- Point E. Equivalent to point B but emerging from the target node. slopePre = SlopeInit + (SlopeIncr * tgtConIdx); // Leg length. float lenEF = state._backConnectionLegLength; slope = slopePre; if(slope > slopeMax) { // Increase length in fractions of _backConnectionLegLength. lenEF += (slopePre-slopeMax) * state._backConnectionLegLength; slope = 1f; } xDelta = (int)(lenEF * (1f - slope)) * tgtSide; yDelta = -(int)(lenEF * slope); Point e = new Point(tgtPos.X + xDelta, tgtPos.Y + yDelta); //--- Point D. Equivalent to point C but on the target end of the connection. int lenDE = (int)(2f * slopePre * state._backConnectionLegLength); xDelta = lenDE * tgtSide; Point d = new Point(e.X + xDelta, e.Y); state._g.DrawLines(pen, new Point[]{srcPos,b,c,d,e,tgtPos}); } #endregion #region Low Level Helper Methods /// <summary> /// Converts from a model coordinate to a viewport coordinate. /// </summary> protected Point ModelToViewport(Point p, PaintState state) { p.X = (int)((float)p.X * state._zoomFactor) - state._viewportArea.X; p.Y = (int)((float)p.Y * state._zoomFactor) - state._viewportArea.Y; return p; } /// <summary> /// Indicates if a point is within the graphics area represented by the viewport. /// That is, does an element at this position need to be painted. /// </summary> protected bool IsPointWithinViewport(Point p, PaintState state) { return (p.X >= 0) && (p.Y >= 0) && (p.X < state._viewportArea.Width) && (p.Y < state._viewportArea.Height); } #endregion #region Inner Classes /// <summary> /// Represents data required for by painting routines. /// </summary> public class PaintState { // State variables. /// <summary>The current GDI+ painting surface.</summary> public readonly Graphics _g; /// <summary>The area being painted to. Any elements outside of this area are not visible.</summary> public readonly Rectangle _viewportArea; /// <summary>Scales the elements being drawn.</summary> public readonly float _zoomFactor; /// <summary>Range of connections weights. Used to determine width of drawn connections.</summary> public readonly float _connectionWeightRange; /// <summary>Use in conjunction with _connectionWeightRange to draw connections.</summary> public readonly float _connectionWeightRangeHalf; /// <summary>Uses in conjunction with _connectionWeightRange to draw connections.</summary> public readonly float _connectionWeightToWidth; // Useful derived values. /// <summary>Diameter of drawn nodes.</summary> public readonly int _nodeDiameter; /// <summary>Used in conjunction with _nodeDiameter to draw nodes.</summary> public readonly int _nodeDiameterHalf; /// <summary>Length of connection legs eminating from the base of nodes when drawing conenctions /// to nodes above the source node.</summary> public readonly float _backConnectionLegLength; /// <summary> /// Dictionary containing temporary painting related state for each graph node. /// </summary> public Dictionary<GraphNode,ConnectionPointInfo> _nodeStateDict; /// <summary> /// Construct with the provided Graphics painting surface and state data. /// </summary> public PaintState(Graphics g, Rectangle viewportArea, float zoomFactor, float connectionWeightRange) { // Store state variables. _g = g; _viewportArea = viewportArea; _zoomFactor = zoomFactor; _connectionWeightRange = connectionWeightRange; _connectionWeightRangeHalf = connectionWeightRange * 0.5f; _connectionWeightToWidth = (float)(2.0 / Math.Log10(connectionWeightRange + 1.0)); // Precalculate some useful derived values. _nodeDiameter = (int)(NodeDiameterModel * zoomFactor); _nodeDiameterHalf = (int)((NodeDiameterModel * zoomFactor) * 0.5f); _backConnectionLegLength = _nodeDiameter * 1.6f; } /// <summary> /// Gets the state object for a given graph node. Creates the object if it does not yet exist. /// </summary> public ConnectionPointInfo GetNodeStateInfo(GraphNode node) { ConnectionPointInfo info; if(!_nodeStateDict.TryGetValue(node, out info)) { info = new ConnectionPointInfo(); _nodeStateDict.Add(node, info); } return info; } } /// <summary> /// Class used for tracking connection point on nodes when drawing backwards directed /// connections (target node higher than the source node). /// </summary> public class ConnectionPointInfo { /// <summary>Running connection count for top left of node.</summary> public int _upperLeft = 0; /// <summary>Running connection count for top right of node.</summary> public int _upperRight = 0; /// <summary>Running connection count for bottom left of node.</summary> public int _lowerLeft = 0; /// <summary>Running connection count for bottom right of node.</summary> public int _lowerRight = 0; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void CompareEqualInt64() { var test = new SimpleBinaryOpTest__CompareEqualInt64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareEqualInt64 { private const int VectorSize = 32; private const int Op1ElementCount = VectorSize / sizeof(Int64); private const int Op2ElementCount = VectorSize / sizeof(Int64); private const int RetElementCount = VectorSize / sizeof(Int64); private static Int64[] _data1 = new Int64[Op1ElementCount]; private static Int64[] _data2 = new Int64[Op2ElementCount]; private static Vector256<Int64> _clsVar1; private static Vector256<Int64> _clsVar2; private Vector256<Int64> _fld1; private Vector256<Int64> _fld2; private SimpleBinaryOpTest__DataTable<Int64, Int64, Int64> _dataTable; static SimpleBinaryOpTest__CompareEqualInt64() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__CompareEqualInt64() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<Int64, Int64, Int64>(_data1, _data2, new Int64[RetElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.CompareEqual( Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.CompareEqual( Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.CompareEqual( Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.CompareEqual), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.CompareEqual( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr); var result = Avx2.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)); var result = Avx2.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)); var result = Avx2.CompareEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__CompareEqualInt64(); var result = Avx2.CompareEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.CompareEqual(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Int64> left, Vector256<Int64> right, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[Op1ElementCount]; Int64[] inArray2 = new Int64[Op2ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "") { if (result[0] != ((left[0] == right[0]) ? unchecked((long)(-1)) : 0)) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != ((left[i] == right[i]) ? unchecked((long)(-1)) : 0)) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.CompareEqual)}<Int64>(Vector256<Int64>, Vector256<Int64>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.Mvc.ViewFeatures.Infrastructure; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; using Microsoft.Net.Http.Headers; using Xunit; namespace Microsoft.AspNetCore.Mvc.FunctionalTests { public class TempDataInCookiesTest : TempDataTestBase, IClassFixture<MvcTestFixture<BasicWebSite.StartupWithoutEndpointRouting>> { private IServiceCollection _serviceCollection; public TempDataInCookiesTest(MvcTestFixture<BasicWebSite.StartupWithoutEndpointRouting> fixture) { var factory = fixture.Factories.FirstOrDefault() ?? fixture.WithWebHostBuilder(b => b.UseStartup<BasicWebSite.StartupWithoutEndpointRouting>()); factory = factory.WithWebHostBuilder(b => b.ConfigureTestServices(serviceCollection => _serviceCollection = serviceCollection)); Client = factory.CreateDefaultClient(); } protected override HttpClient Client { get; } [Fact] public void VerifyNewtonsoftJsonTempDataSerializer() { // Arrange // This test could provide some diagnostics for the test failure reported in https://github.com/dotnet/aspnetcore-internal/issues/1803. // AddNewtonsoftJson attempts to replace the DefaultTempDataSerializer. The test failure indicates this failed but it's not clear why. // We'll capture the application's ServiceCollection and inspect the instance of ITempDataSerializer instances here. It might give us some // clues if the test fails again in the future. // Intentionally avoiding using Xunit.Assert to get more diagnostics. var tempDataSerializers = _serviceCollection.Where(f => f.ServiceType == typeof(TempDataSerializer)).ToList(); if (tempDataSerializers.Count == 1 && tempDataSerializers[0].ImplementationType.FullName == "Microsoft.AspNetCore.Mvc.NewtonsoftJson.BsonTempDataSerializer") { return; } var builder = new StringBuilder(); foreach (var serializer in tempDataSerializers) { var type = serializer.ImplementationType; builder.Append(serializer.ImplementationType.AssemblyQualifiedName); } throw new Exception($"Expected exactly one instance of TempDataSerializer based on NewtonsoftJson, but found {tempDataSerializers.Count} instance(s):" + Environment.NewLine + builder); } [Theory] [InlineData(ChunkingCookieManager.DefaultChunkSize)] [InlineData(ChunkingCookieManager.DefaultChunkSize * 1.5)] [InlineData(ChunkingCookieManager.DefaultChunkSize * 2)] [InlineData(ChunkingCookieManager.DefaultChunkSize * 3)] public async Task RoundTripLargeData_WorksWithChunkingCookies(int size) { // Arrange var character = 'a'; var expected = new string(character, size); // Act 1 var response = await Client.GetAsync($"/TempData/SetLargeValueInTempData?size={size}&character={character}"); // Assert 1 Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.True(response.Headers.TryGetValues(HeaderNames.SetCookie, out IEnumerable<string> setCookieValues)); setCookieValues = setCookieValues.Where(cookie => cookie.Contains(CookieTempDataProvider.CookieName)); Assert.NotEmpty(setCookieValues); // Verify that all the cookies from CookieTempDataProvider are within the maximum size foreach (var cookie in setCookieValues) { Assert.True(cookie.Length <= ChunkingCookieManager.DefaultChunkSize); } var cookieTempDataProviderCookies = setCookieValues .Select(setCookieValue => SetCookieHeaderValue.Parse(setCookieValue)); foreach (var cookieTempDataProviderCookie in cookieTempDataProviderCookies) { Assert.NotNull(cookieTempDataProviderCookie.Value.Value); Assert.Equal("/", cookieTempDataProviderCookie.Path); Assert.Null(cookieTempDataProviderCookie.Domain.Value); Assert.False(cookieTempDataProviderCookie.Secure); } // Act 2 response = await Client.SendAsync(GetRequest("/TempData/GetLargeValueFromTempData", response)); // Assert 2 Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); Assert.Equal(expected, body); Assert.True(response.Headers.TryGetValues(HeaderNames.SetCookie, out setCookieValues)); var setCookieHeaderValue = setCookieValues .Select(setCookieValue => SetCookieHeaderValue.Parse(setCookieValue)) .FirstOrDefault(setCookieHeader => setCookieHeader.Name == CookieTempDataProvider.CookieName); Assert.NotNull(setCookieHeaderValue); Assert.Equal(string.Empty, setCookieHeaderValue.Value); Assert.Equal("/", setCookieHeaderValue.Path); Assert.Null(setCookieHeaderValue.Domain.Value); Assert.NotNull(setCookieHeaderValue.Expires); Assert.True(setCookieHeaderValue.Expires < DateTimeOffset.Now); // expired cookie // Act 3 response = await Client.SendAsync(GetRequest("/TempData/GetLargeValueFromTempData", response)); // Assert 3 Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); } [Fact] public async Task Redirect_RetainsTempData_EvenIfAccessed_AndSetsAppropriateCookieValues() { // Arrange var nameValueCollection = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("value", "Foo"), }; var content = new FormUrlEncodedContent(nameValueCollection); // Act 1 var response = await Client.PostAsync("/TempData/SetTempData", content); // Assert 1 Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.True(response.Headers.TryGetValues(HeaderNames.SetCookie, out IEnumerable<string> setCookieValues)); var setCookieHeader = setCookieValues .Select(setCookieValue => SetCookieHeaderValue.Parse(setCookieValue)) .FirstOrDefault(setCookieHeaderValue => setCookieHeaderValue.Name == CookieTempDataProvider.CookieName); Assert.NotNull(setCookieHeader); Assert.Equal("/", setCookieHeader.Path); Assert.Null(setCookieHeader.Domain.Value); Assert.False(setCookieHeader.Secure); Assert.Null(setCookieHeader.Expires); // Act 2 var redirectResponse = await Client.SendAsync(GetRequest("/TempData/GetTempDataAndRedirect", response)); // Assert 2 Assert.Equal(HttpStatusCode.Redirect, redirectResponse.StatusCode); // Act 3 response = await Client.SendAsync(GetRequest(redirectResponse.Headers.Location.ToString(), response)); // Assert 3 Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); Assert.Equal("Foo", body); Assert.True(response.Headers.TryGetValues(HeaderNames.SetCookie, out setCookieValues)); setCookieHeader = setCookieValues .Select(setCookieValue => SetCookieHeaderValue.Parse(setCookieValue)) .FirstOrDefault(setCookieHeaderValue => setCookieHeaderValue.Name == CookieTempDataProvider.CookieName); Assert.NotNull(setCookieHeader); Assert.Equal(string.Empty, setCookieHeader.Value); Assert.Equal("/", setCookieHeader.Path); Assert.Null(setCookieHeader.Domain.Value); Assert.NotNull(setCookieHeader.Expires); Assert.True(setCookieHeader.Expires < DateTimeOffset.Now); // expired cookie } [Theory] [InlineData(true)] [InlineData(false)] public async Task CookieTempDataProviderCookie_DoesNotSetsSecureAttributeOnCookie(bool secureRequest) { // Arrange var protocol = secureRequest ? "https" : "http"; var nameValueCollection = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("value", "Foo"), }; var content = new FormUrlEncodedContent(nameValueCollection); // Act var response = await Client.PostAsync($"{protocol}://localhost/TempData/SetTempData", content); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.True(response.Headers.TryGetValues(HeaderNames.SetCookie, out IEnumerable<string> setCookieValues)); var setCookieHeader = setCookieValues .Select(setCookieValue => SetCookieHeaderValue.Parse(setCookieValue)) .FirstOrDefault(setCookieHeaderValue => setCookieHeaderValue.Name == CookieTempDataProvider.CookieName); Assert.NotNull(setCookieHeader); Assert.Equal("/", setCookieHeader.Path); Assert.Null(setCookieHeader.Domain.Value); Assert.False(setCookieHeader.Secure); Assert.Null(setCookieHeader.Expires); } } }
// 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. // File System.ServiceModel.Syndication.SyndicationLink.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.ServiceModel.Syndication { public partial class SyndicationLink : IExtensibleSyndicationObject { #region Methods and constructors public virtual new System.ServiceModel.Syndication.SyndicationLink Clone() { return default(System.ServiceModel.Syndication.SyndicationLink); } public static System.ServiceModel.Syndication.SyndicationLink CreateAlternateLink(Uri uri) { Contract.Ensures(Contract.Result<System.ServiceModel.Syndication.SyndicationLink>() != null); return default(System.ServiceModel.Syndication.SyndicationLink); } public static System.ServiceModel.Syndication.SyndicationLink CreateAlternateLink(Uri uri, string mediaType) { Contract.Ensures(Contract.Result<System.ServiceModel.Syndication.SyndicationLink>() != null); return default(System.ServiceModel.Syndication.SyndicationLink); } public static System.ServiceModel.Syndication.SyndicationLink CreateMediaEnclosureLink(Uri uri, string mediaType, long length) { Contract.Ensures(Contract.Result<System.ServiceModel.Syndication.SyndicationLink>() != null); return default(System.ServiceModel.Syndication.SyndicationLink); } public static System.ServiceModel.Syndication.SyndicationLink CreateSelfLink(Uri uri) { Contract.Ensures(Contract.Result<System.ServiceModel.Syndication.SyndicationLink>() != null); return default(System.ServiceModel.Syndication.SyndicationLink); } public static System.ServiceModel.Syndication.SyndicationLink CreateSelfLink(Uri uri, string mediaType) { Contract.Ensures(Contract.Result<System.ServiceModel.Syndication.SyndicationLink>() != null); return default(System.ServiceModel.Syndication.SyndicationLink); } public Uri GetAbsoluteUri() { return default(Uri); } public SyndicationLink(Uri uri) { } public SyndicationLink(Uri uri, string relationshipType, string title, string mediaType, long length) { } public SyndicationLink() { } protected SyndicationLink(System.ServiceModel.Syndication.SyndicationLink source) { } protected internal virtual new bool TryParseAttribute(string name, string ns, string value, string version) { return default(bool); } protected internal virtual new bool TryParseElement(System.Xml.XmlReader reader, string version) { return default(bool); } protected internal virtual new void WriteAttributeExtensions(System.Xml.XmlWriter writer, string version) { } protected internal virtual new void WriteElementExtensions(System.Xml.XmlWriter writer, string version) { } #endregion #region Properties and indexers public Dictionary<System.Xml.XmlQualifiedName, string> AttributeExtensions { get { return default(Dictionary<System.Xml.XmlQualifiedName, string>); } } public Uri BaseUri { get { return default(Uri); } set { } } public SyndicationElementExtensionCollection ElementExtensions { get { return default(SyndicationElementExtensionCollection); } } public long Length { get { return default(long); } set { } } public string MediaType { get { return default(string); } set { } } public string RelationshipType { get { return default(string); } set { } } public string Title { get { return default(string); } set { } } public Uri Uri { get { return default(Uri); } set { } } #endregion } }
using EIDSS.Reports.Parameterized.Uni.EventLog; namespace EIDSS.Reports.Parameterized.Human.TH.Reports { partial class NumberOfCasesDeathsMorbidityMortalityTHReport { #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(NumberOfCasesDeathsMorbidityMortalityTHReport)); this.HeaderTable = new DevExpress.XtraReports.UI.XRTable(); this.rowHeader1 = new DevExpress.XtraReports.UI.XRTableRow(); this.cellDateTime = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell(); this.DeathsHeaderCell = new DevExpress.XtraReports.UI.XRTableCell(); this.cellType = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell(); this.cellPerson = new DevExpress.XtraReports.UI.XRTableCell(); this.DetailReport = new DevExpress.XtraReports.UI.DetailReportBand(); this.Detail1 = new DevExpress.XtraReports.UI.DetailBand(); this.xrTable1 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow(); this.ReportingAreaCell = new DevExpress.XtraReports.UI.XRTableCell(); this.CasesCell = new DevExpress.XtraReports.UI.XRTableCell(); this.MorbidityRateCell = new DevExpress.XtraReports.UI.XRTableCell(); this.DeathsCell = new DevExpress.XtraReports.UI.XRTableCell(); this.CFRCell = new DevExpress.XtraReports.UI.XRTableCell(); this.MortalityRateCell = new DevExpress.XtraReports.UI.XRTableCell(); this.PopulationCell = new DevExpress.XtraReports.UI.XRTableCell(); this.GroupHeaderLine = new DevExpress.XtraReports.UI.GroupHeaderBand(); this.xrLine2 = new DevExpress.XtraReports.UI.XRLine(); this.m_Adapter = new EIDSS.Reports.Parameterized.Human.TH.DataSets.NumberOfCasesDeathsMorbidityMortalityTHDataSetTableAdapters.NumberOfCasesAdapter(); this.m_DataSet = new EIDSS.Reports.Parameterized.Human.TH.DataSets.NumberOfCasesDeathsMorbidityMortalityTHDataSet(); this.ReportHeaderTable = new DevExpress.XtraReports.UI.XRTable(); this.HeaderRow1 = new DevExpress.XtraReports.UI.XRTableRow(); this.HeaderCell1 = new DevExpress.XtraReports.UI.XRTableCell(); this.HeaderRow2 = new DevExpress.XtraReports.UI.XRTableRow(); this.HeaderCell2 = new DevExpress.XtraReports.UI.XRTableCell(); this.HeaderRow3 = new DevExpress.XtraReports.UI.XRTableRow(); this.HeaderCell3 = new DevExpress.XtraReports.UI.XRTableCell(); this.ReportFooter = new DevExpress.XtraReports.UI.ReportFooterBand(); this.SignatureTable = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow7 = new DevExpress.XtraReports.UI.XRTableRow(); this.OrganizationNameCell = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell(); this.DateTimeCell = new DevExpress.XtraReports.UI.XRTableCell(); ((System.ComponentModel.ISupportInitialize)(this.tableInterval)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.HeaderTable)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.m_DataSet)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.ReportHeaderTable)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.SignatureTable)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); // // tableInterval // resources.ApplyResources(this.tableInterval, "tableInterval"); this.tableInterval.StylePriority.UseBorders = false; this.tableInterval.StylePriority.UseFont = false; this.tableInterval.StylePriority.UsePadding = false; // // cellInputStartDate // this.cellInputStartDate.StylePriority.UseFont = false; this.cellInputStartDate.StylePriority.UseTextAlignment = false; // // cellInputEndDate // this.cellInputEndDate.StylePriority.UseFont = false; this.cellInputEndDate.StylePriority.UseTextAlignment = false; // // cellDefis // this.cellDefis.StylePriority.UseFont = false; this.cellDefis.StylePriority.UseTextAlignment = false; // // cellLanguage // this.cellLanguage.StylePriority.UseTextAlignment = false; // // lblReportName // resources.ApplyResources(this.lblReportName, "lblReportName"); this.lblReportName.StylePriority.UseBorders = false; this.lblReportName.StylePriority.UseBorderWidth = false; this.lblReportName.StylePriority.UseFont = false; this.lblReportName.StylePriority.UseTextAlignment = false; // // Detail // resources.ApplyResources(this.Detail, "Detail"); this.Detail.StylePriority.UseFont = false; this.Detail.StylePriority.UsePadding = false; // // PageHeader // resources.ApplyResources(this.PageHeader, "PageHeader"); this.PageHeader.StylePriority.UseFont = false; this.PageHeader.StylePriority.UsePadding = false; // // PageFooter // this.PageFooter.StylePriority.UseBorders = false; // // ReportHeader // this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.ReportHeaderTable, this.HeaderTable}); resources.ApplyResources(this.ReportHeader, "ReportHeader"); this.ReportHeader.Controls.SetChildIndex(this.HeaderTable, 0); this.ReportHeader.Controls.SetChildIndex(this.tableBaseHeader, 0); this.ReportHeader.Controls.SetChildIndex(this.ReportHeaderTable, 0); // // xrPageInfo1 // resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1"); this.xrPageInfo1.StylePriority.UseBorders = false; // // cellReportHeader // this.cellReportHeader.StylePriority.UseBorders = false; this.cellReportHeader.StylePriority.UseFont = false; this.cellReportHeader.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.cellReportHeader, "cellReportHeader"); // // cellBaseSite // this.cellBaseSite.StylePriority.UseBorders = false; this.cellBaseSite.StylePriority.UseFont = false; this.cellBaseSite.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.cellBaseSite, "cellBaseSite"); // // cellBaseCountry // this.cellBaseCountry.StylePriority.UseFont = false; resources.ApplyResources(this.cellBaseCountry, "cellBaseCountry"); // // cellBaseLeftHeader // resources.ApplyResources(this.cellBaseLeftHeader, "cellBaseLeftHeader"); // // tableBaseHeader // resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader"); this.tableBaseHeader.StylePriority.UseBorders = false; this.tableBaseHeader.StylePriority.UseBorderWidth = false; this.tableBaseHeader.StylePriority.UseFont = false; this.tableBaseHeader.StylePriority.UsePadding = false; this.tableBaseHeader.StylePriority.UseTextAlignment = false; // // HeaderTable // this.HeaderTable.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right))); resources.ApplyResources(this.HeaderTable, "HeaderTable"); this.HeaderTable.Name = "HeaderTable"; this.HeaderTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.rowHeader1}); this.HeaderTable.StylePriority.UseBorders = false; this.HeaderTable.StylePriority.UseFont = false; this.HeaderTable.StylePriority.UseTextAlignment = false; // // rowHeader1 // this.rowHeader1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.cellDateTime, this.xrTableCell5, this.xrTableCell3, this.DeathsHeaderCell, this.cellType, this.xrTableCell4, this.cellPerson}); this.rowHeader1.Name = "rowHeader1"; this.rowHeader1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.rowHeader1.StylePriority.UseFont = false; this.rowHeader1.StylePriority.UsePadding = false; this.rowHeader1.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.rowHeader1, "rowHeader1"); // // cellDateTime // resources.ApplyResources(this.cellDateTime, "cellDateTime"); this.cellDateTime.Name = "cellDateTime"; this.cellDateTime.StylePriority.UseFont = false; // // xrTableCell5 // resources.ApplyResources(this.xrTableCell5, "xrTableCell5"); this.xrTableCell5.Name = "xrTableCell5"; this.xrTableCell5.StylePriority.UseFont = false; this.xrTableCell5.StylePriority.UseTextAlignment = false; // // xrTableCell3 // resources.ApplyResources(this.xrTableCell3, "xrTableCell3"); this.xrTableCell3.Name = "xrTableCell3"; this.xrTableCell3.StylePriority.UseFont = false; this.xrTableCell3.StylePriority.UseTextAlignment = false; // // DeathsHeaderCell // resources.ApplyResources(this.DeathsHeaderCell, "DeathsHeaderCell"); this.DeathsHeaderCell.Name = "DeathsHeaderCell"; this.DeathsHeaderCell.StylePriority.UseFont = false; this.DeathsHeaderCell.StylePriority.UseTextAlignment = false; // // cellType // resources.ApplyResources(this.cellType, "cellType"); this.cellType.Name = "cellType"; this.cellType.StylePriority.UseFont = false; this.cellType.StylePriority.UseTextAlignment = false; // // xrTableCell4 // resources.ApplyResources(this.xrTableCell4, "xrTableCell4"); this.xrTableCell4.Multiline = true; this.xrTableCell4.Name = "xrTableCell4"; this.xrTableCell4.StylePriority.UseFont = false; this.xrTableCell4.StylePriority.UseTextAlignment = false; // // cellPerson // resources.ApplyResources(this.cellPerson, "cellPerson"); this.cellPerson.Name = "cellPerson"; this.cellPerson.StylePriority.UseFont = false; this.cellPerson.StylePriority.UseTextAlignment = false; // // DetailReport // this.DetailReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail1, this.GroupHeaderLine}); this.DetailReport.DataAdapter = this.m_Adapter; this.DetailReport.DataMember = "NumberOfCasesTable"; this.DetailReport.DataSource = this.m_DataSet; this.DetailReport.Level = 0; this.DetailReport.Name = "DetailReport"; // // Detail1 // this.Detail1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable1}); resources.ApplyResources(this.Detail1, "Detail1"); this.Detail1.Name = "Detail1"; // // xrTable1 // this.xrTable1.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); resources.ApplyResources(this.xrTable1, "xrTable1"); this.xrTable1.Name = "xrTable1"; this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow1}); this.xrTable1.StylePriority.UseBorders = false; this.xrTable1.StylePriority.UseFont = false; this.xrTable1.StylePriority.UseTextAlignment = false; // // xrTableRow1 // this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.ReportingAreaCell, this.CasesCell, this.MorbidityRateCell, this.DeathsCell, this.CFRCell, this.MortalityRateCell, this.PopulationCell}); this.xrTableRow1.Name = "xrTableRow1"; this.xrTableRow1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrTableRow1.StylePriority.UseFont = false; this.xrTableRow1.StylePriority.UsePadding = false; this.xrTableRow1.StylePriority.UseTextAlignment = false; resources.ApplyResources(this.xrTableRow1, "xrTableRow1"); // // ReportingAreaCell // this.ReportingAreaCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "NumberOfCasesTable.strReportingArea")}); resources.ApplyResources(this.ReportingAreaCell, "ReportingAreaCell"); this.ReportingAreaCell.Name = "ReportingAreaCell"; this.ReportingAreaCell.StylePriority.UseFont = false; this.ReportingAreaCell.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.ReportingAreaCell_BeforePrint); // // CasesCell // this.CasesCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "NumberOfCasesTable.intCases")}); resources.ApplyResources(this.CasesCell, "CasesCell"); this.CasesCell.Name = "CasesCell"; this.CasesCell.StylePriority.UseFont = false; this.CasesCell.StylePriority.UseTextAlignment = false; this.CasesCell.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CasesCell_BeforePrint); // // MorbidityRateCell // resources.ApplyResources(this.MorbidityRateCell, "MorbidityRateCell"); this.MorbidityRateCell.Name = "MorbidityRateCell"; this.MorbidityRateCell.StylePriority.UseFont = false; this.MorbidityRateCell.StylePriority.UseTextAlignment = false; this.MorbidityRateCell.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.MorbidityRateCell_BeforePrint); // // DeathsCell // this.DeathsCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "NumberOfCasesTable.intDeath")}); resources.ApplyResources(this.DeathsCell, "DeathsCell"); this.DeathsCell.Name = "DeathsCell"; this.DeathsCell.StylePriority.UseFont = false; this.DeathsCell.StylePriority.UseTextAlignment = false; this.DeathsCell.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.DeathsCell_BeforePrint); // // CFRCell // resources.ApplyResources(this.CFRCell, "CFRCell"); this.CFRCell.Name = "CFRCell"; this.CFRCell.StylePriority.UseFont = false; this.CFRCell.StylePriority.UseTextAlignment = false; this.CFRCell.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.CFRCell_BeforePrint); // // MortalityRateCell // resources.ApplyResources(this.MortalityRateCell, "MortalityRateCell"); this.MortalityRateCell.Multiline = true; this.MortalityRateCell.Name = "MortalityRateCell"; this.MortalityRateCell.StylePriority.UseFont = false; this.MortalityRateCell.StylePriority.UseTextAlignment = false; this.MortalityRateCell.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.MortalityRateCell_BeforePrint); // // PopulationCell // this.PopulationCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "NumberOfCasesTable.intPopulation")}); resources.ApplyResources(this.PopulationCell, "PopulationCell"); this.PopulationCell.Name = "PopulationCell"; this.PopulationCell.StylePriority.UseFont = false; this.PopulationCell.StylePriority.UseTextAlignment = false; this.PopulationCell.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.PopulationCell_BeforePrint); this.PopulationCell.AfterPrint += new System.EventHandler(this.PopulationCell_AfterPrint); // // GroupHeaderLine // this.GroupHeaderLine.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrLine2}); resources.ApplyResources(this.GroupHeaderLine, "GroupHeaderLine"); this.GroupHeaderLine.Name = "GroupHeaderLine"; this.GroupHeaderLine.RepeatEveryPage = true; // // xrLine2 // this.xrLine2.BorderWidth = 0F; this.xrLine2.LineWidth = 0; resources.ApplyResources(this.xrLine2, "xrLine2"); this.xrLine2.Name = "xrLine2"; this.xrLine2.StylePriority.UseBorderWidth = false; // // m_Adapter // this.m_Adapter.ClearBeforeFill = true; // // m_DataSet // this.m_DataSet.DataSetName = "EventLogDataSet"; this.m_DataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; // // ReportHeaderTable // resources.ApplyResources(this.ReportHeaderTable, "ReportHeaderTable"); this.ReportHeaderTable.Name = "ReportHeaderTable"; this.ReportHeaderTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.HeaderRow1, this.HeaderRow2, this.HeaderRow3}); this.ReportHeaderTable.StylePriority.UseTextAlignment = false; // // HeaderRow1 // this.HeaderRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.HeaderCell1}); this.HeaderRow1.Name = "HeaderRow1"; resources.ApplyResources(this.HeaderRow1, "HeaderRow1"); // // HeaderCell1 // resources.ApplyResources(this.HeaderCell1, "HeaderCell1"); this.HeaderCell1.Name = "HeaderCell1"; this.HeaderCell1.StylePriority.UseFont = false; // // HeaderRow2 // this.HeaderRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.HeaderCell2}); this.HeaderRow2.Name = "HeaderRow2"; resources.ApplyResources(this.HeaderRow2, "HeaderRow2"); // // HeaderCell2 // resources.ApplyResources(this.HeaderCell2, "HeaderCell2"); this.HeaderCell2.Name = "HeaderCell2"; this.HeaderCell2.StylePriority.UseFont = false; // // HeaderRow3 // this.HeaderRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.HeaderCell3}); this.HeaderRow3.Name = "HeaderRow3"; resources.ApplyResources(this.HeaderRow3, "HeaderRow3"); // // HeaderCell3 // resources.ApplyResources(this.HeaderCell3, "HeaderCell3"); this.HeaderCell3.Name = "HeaderCell3"; this.HeaderCell3.StylePriority.UseFont = false; // // ReportFooter // this.ReportFooter.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.SignatureTable}); resources.ApplyResources(this.ReportFooter, "ReportFooter"); this.ReportFooter.Name = "ReportFooter"; // // SignatureTable // resources.ApplyResources(this.SignatureTable, "SignatureTable"); this.SignatureTable.Name = "SignatureTable"; this.SignatureTable.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F); this.SignatureTable.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow7}); this.SignatureTable.StylePriority.UseFont = false; this.SignatureTable.StylePriority.UsePadding = false; this.SignatureTable.StylePriority.UseTextAlignment = false; // // xrTableRow7 // this.xrTableRow7.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.OrganizationNameCell, this.xrTableCell1, this.DateTimeCell}); this.xrTableRow7.Name = "xrTableRow7"; resources.ApplyResources(this.xrTableRow7, "xrTableRow7"); // // OrganizationNameCell // this.OrganizationNameCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] { new DevExpress.XtraReports.UI.XRBinding("Text", null, "sprepGetBaseParameters.SiteName", "{0}, Ministry of Public Health")}); resources.ApplyResources(this.OrganizationNameCell, "OrganizationNameCell"); this.OrganizationNameCell.Name = "OrganizationNameCell"; this.OrganizationNameCell.StylePriority.UseFont = false; // // xrTableCell1 // resources.ApplyResources(this.xrTableCell1, "xrTableCell1"); this.xrTableCell1.Name = "xrTableCell1"; this.xrTableCell1.StylePriority.UseFont = false; this.xrTableCell1.StylePriority.UseTextAlignment = false; // // DateTimeCell // resources.ApplyResources(this.DateTimeCell, "DateTimeCell"); this.DateTimeCell.Name = "DateTimeCell"; this.DateTimeCell.StylePriority.UseFont = false; // // NumberOfCasesDeathsMorbidityMortalityTHReport // this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail, this.PageHeader, this.PageFooter, this.DetailReport, this.ReportHeader, this.ReportFooter}); resources.ApplyResources(this, "$this"); this.Version = "15.1"; this.Controls.SetChildIndex(this.ReportFooter, 0); this.Controls.SetChildIndex(this.ReportHeader, 0); this.Controls.SetChildIndex(this.DetailReport, 0); this.Controls.SetChildIndex(this.PageFooter, 0); this.Controls.SetChildIndex(this.PageHeader, 0); this.Controls.SetChildIndex(this.Detail, 0); ((System.ComponentModel.ISupportInitialize)(this.tableInterval)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.HeaderTable)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.m_DataSet)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.ReportHeaderTable)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.SignatureTable)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); } #endregion private DevExpress.XtraReports.UI.XRTable HeaderTable; private DevExpress.XtraReports.UI.XRTableRow rowHeader1; private DevExpress.XtraReports.UI.XRTableCell cellType; private DevExpress.XtraReports.UI.XRTableCell cellPerson; private DevExpress.XtraReports.UI.DetailReportBand DetailReport; private DevExpress.XtraReports.UI.DetailBand Detail1; private DevExpress.XtraReports.UI.XRTableCell cellDateTime; private EIDSS.Reports.Parameterized.Human.TH.DataSets.NumberOfCasesDeathsMorbidityMortalityTHDataSet m_DataSet; private EIDSS.Reports.Parameterized.Human.TH.DataSets.NumberOfCasesDeathsMorbidityMortalityTHDataSetTableAdapters.NumberOfCasesAdapter m_Adapter; private DevExpress.XtraReports.UI.XRTable ReportHeaderTable; private DevExpress.XtraReports.UI.XRTableRow HeaderRow1; private DevExpress.XtraReports.UI.XRTableCell HeaderCell1; private DevExpress.XtraReports.UI.XRTableRow HeaderRow2; private DevExpress.XtraReports.UI.XRTableCell HeaderCell2; private DevExpress.XtraReports.UI.XRTableRow HeaderRow3; private DevExpress.XtraReports.UI.XRTableCell HeaderCell3; private DevExpress.XtraReports.UI.XRTableCell xrTableCell5; private DevExpress.XtraReports.UI.XRTableCell xrTableCell3; private DevExpress.XtraReports.UI.XRTableCell DeathsHeaderCell; private DevExpress.XtraReports.UI.XRTableCell xrTableCell4; private DevExpress.XtraReports.UI.XRTable xrTable1; private DevExpress.XtraReports.UI.XRTableRow xrTableRow1; private DevExpress.XtraReports.UI.XRTableCell ReportingAreaCell; private DevExpress.XtraReports.UI.XRTableCell CasesCell; private DevExpress.XtraReports.UI.XRTableCell MorbidityRateCell; private DevExpress.XtraReports.UI.XRTableCell DeathsCell; private DevExpress.XtraReports.UI.XRTableCell CFRCell; private DevExpress.XtraReports.UI.XRTableCell MortalityRateCell; private DevExpress.XtraReports.UI.XRTableCell PopulationCell; private DevExpress.XtraReports.UI.GroupHeaderBand GroupHeaderLine; private DevExpress.XtraReports.UI.XRLine xrLine2; private DevExpress.XtraReports.UI.ReportFooterBand ReportFooter; private DevExpress.XtraReports.UI.XRTable SignatureTable; private DevExpress.XtraReports.UI.XRTableRow xrTableRow7; private DevExpress.XtraReports.UI.XRTableCell OrganizationNameCell; private DevExpress.XtraReports.UI.XRTableCell xrTableCell1; private DevExpress.XtraReports.UI.XRTableCell DateTimeCell; } }
using System.Buffers.Text; using System.Runtime.InteropServices; using System.Text; using MySqlConnector.Protocol; using MySqlConnector.Protocol.Payloads; using MySqlConnector.Protocol.Serialization; using MySqlConnector.Utilities; namespace MySqlConnector.Core; internal sealed class BinaryRow : Row { public BinaryRow(ResultSet resultSet) : base(resultSet) { } protected override Row CloneCore() => new BinaryRow(ResultSet); protected override void GetDataOffsets(ReadOnlySpan<byte> data, int[] dataOffsets, int[] dataLengths) { Array.Clear(dataOffsets, 0, dataOffsets.Length); for (var column = 0; column < dataOffsets.Length; column++) { if ((data[(column + 2) / 8 + 1] & (1 << ((column + 2) % 8))) != 0) { // column is NULL dataOffsets[column] = -1; } } var reader = new ByteArrayReader(data); // skip packet header (1 byte) and NULL bitmap (formula for length at https://dev.mysql.com/doc/internals/en/null-bitmap.html) reader.Offset += 1 + (dataOffsets.Length + 7 + 2) / 8; for (var column = 0; column < dataOffsets.Length; column++) { if (dataOffsets[column] == -1) { dataLengths[column] = 0; } else { var columnDefinition = ResultSet.ColumnDefinitions![column]; var length = columnDefinition.ColumnType switch { ColumnType.Longlong or ColumnType.Double => 8, ColumnType.Long or ColumnType.Int24 or ColumnType.Float => 4, ColumnType.Short or ColumnType.Year => 2, ColumnType.Tiny => 1, ColumnType.Date or ColumnType.DateTime or ColumnType.NewDate or ColumnType.Timestamp or ColumnType.Time => reader.ReadByte(), ColumnType.DateTime2 or ColumnType.Timestamp2 => throw new NotSupportedException("ColumnType {0} is not supported".FormatInvariant(columnDefinition.ColumnType)), _ => checked((int) reader.ReadLengthEncodedInteger()), }; dataLengths[column] = length; dataOffsets[column] = reader.Offset; } reader.Offset += dataLengths[column]; } } protected override int GetInt32Core(ReadOnlySpan<byte> data, ColumnDefinitionPayload columnDefinition) { var isUnsigned = (columnDefinition.ColumnFlags & ColumnFlags.Unsigned) != 0; return columnDefinition.ColumnType switch { ColumnType.Tiny => isUnsigned ? (int) data[0] : (sbyte) data[0], ColumnType.Decimal or ColumnType.NewDecimal => Utf8Parser.TryParse(data, out decimal decimalValue, out int bytesConsumed) && bytesConsumed == data.Length ? checked((int) decimalValue) : throw new FormatException(), ColumnType.Int24 or ColumnType.Long => isUnsigned ? checked((int) MemoryMarshal.Read<uint>(data)) : MemoryMarshal.Read<int>(data), ColumnType.Longlong => isUnsigned ? checked((int) MemoryMarshal.Read<ulong>(data)) : checked((int) MemoryMarshal.Read<long>(data)), ColumnType.Short => isUnsigned ? (int) MemoryMarshal.Read<ushort>(data) : MemoryMarshal.Read<short>(data), ColumnType.Year => MemoryMarshal.Read<short>(data), _ => throw new FormatException(), }; } protected override object GetValueCore(ReadOnlySpan<byte> data, ColumnDefinitionPayload columnDefinition) { var isUnsigned = (columnDefinition.ColumnFlags & ColumnFlags.Unsigned) != 0; switch (columnDefinition.ColumnType) { case ColumnType.Tiny: if (Connection.TreatTinyAsBoolean && columnDefinition.ColumnLength == 1 && !isUnsigned) return data[0] != 0; return isUnsigned ? (object) data[0] : (sbyte) data[0]; case ColumnType.Int24: case ColumnType.Long: return isUnsigned ? (object) MemoryMarshal.Read<uint>(data) : MemoryMarshal.Read<int>(data); case ColumnType.Longlong: return isUnsigned ? (object) MemoryMarshal.Read<ulong>(data) : MemoryMarshal.Read<long>(data); case ColumnType.Bit: return ReadBit(data, columnDefinition); case ColumnType.String: if (Connection.GuidFormat == MySqlGuidFormat.Char36 && columnDefinition.ColumnLength / ProtocolUtility.GetBytesPerCharacter(columnDefinition.CharacterSet) == 36) return Utf8Parser.TryParse(data, out Guid guid, out int guid36BytesConsumed, 'D') && guid36BytesConsumed == 36 ? guid : throw new FormatException("Could not parse CHAR(36) value as Guid: {0}".FormatInvariant(Encoding.UTF8.GetString(data))); if (Connection.GuidFormat == MySqlGuidFormat.Char32 && columnDefinition.ColumnLength / ProtocolUtility.GetBytesPerCharacter(columnDefinition.CharacterSet) == 32) return Utf8Parser.TryParse(data, out Guid guid, out int guid32BytesConsumed, 'N') && guid32BytesConsumed == 32 ? guid : throw new FormatException("Could not parse CHAR(32) value as Guid: {0}".FormatInvariant(Encoding.UTF8.GetString(data))); goto case ColumnType.VarString; case ColumnType.VarString: case ColumnType.VarChar: case ColumnType.TinyBlob: case ColumnType.Blob: case ColumnType.MediumBlob: case ColumnType.LongBlob: case ColumnType.Enum: case ColumnType.Set: if (columnDefinition.CharacterSet == CharacterSet.Binary) { var guidFormat = Connection.GuidFormat; if ((guidFormat is MySqlGuidFormat.Binary16 or MySqlGuidFormat.TimeSwapBinary16 or MySqlGuidFormat.LittleEndianBinary16) && columnDefinition.ColumnLength == 16) return CreateGuidFromBytes(guidFormat, data); return data.ToArray(); } return Encoding.UTF8.GetString(data); case ColumnType.Json: return Encoding.UTF8.GetString(data); case ColumnType.Short: return isUnsigned ? (object) MemoryMarshal.Read<ushort>(data) : MemoryMarshal.Read<short>(data); case ColumnType.Date: case ColumnType.DateTime: case ColumnType.NewDate: case ColumnType.Timestamp: return ReadDateTime(data); case ColumnType.Time: return ReadTimeSpan(data); case ColumnType.Year: return (int) MemoryMarshal.Read<short>(data); case ColumnType.Float: return MemoryMarshal.Read<float>(data); case ColumnType.Double: return MemoryMarshal.Read<double>(data); case ColumnType.Decimal: case ColumnType.NewDecimal: return Utf8Parser.TryParse(data, out decimal decimalValue, out int bytesConsumed) && bytesConsumed == data.Length ? decimalValue : throw new FormatException(); case ColumnType.Geometry: return data.ToArray(); default: throw new NotImplementedException("Reading {0} not implemented".FormatInvariant(columnDefinition.ColumnType)); } } private object ReadDateTime(ReadOnlySpan<byte> value) { if (value.Length == 0) { if (Connection.ConvertZeroDateTime) return DateTime.MinValue; if (Connection.AllowZeroDateTime) return default(MySqlDateTime); throw new InvalidCastException("Unable to convert MySQL date/time to System.DateTime."); } int year = value[0] + value[1] * 256; int month = value[2]; int day = value[3]; int hour, minute, second; if (value.Length <= 4) { hour = 0; minute = 0; second = 0; } else { hour = value[4]; minute = value[5]; second = value[6]; } var microseconds = value.Length <= 7 ? 0 : MemoryMarshal.Read<int>(value.Slice(7)); try { return Connection.AllowZeroDateTime ? (object) new MySqlDateTime(year, month, day, hour, minute, second, microseconds) : new DateTime(year, month, day, hour, minute, second, microseconds / 1000, Connection.DateTimeKind).AddTicks(microseconds % 1000 * 10); } catch (Exception ex) { throw new FormatException("Couldn't interpret value as a valid DateTime".FormatInvariant(Encoding.UTF8.GetString(value)), ex); } } private static TimeSpan ReadTimeSpan(ReadOnlySpan<byte> value) { if (value.Length == 0) return TimeSpan.Zero; var isNegative = value[0]; var days = MemoryMarshal.Read<int>(value.Slice(1)); var hours = (int) value[5]; var minutes = (int) value[6]; var seconds = (int) value[7]; var microseconds = value.Length == 8 ? 0 : MemoryMarshal.Read<int>(value.Slice(8)); if (isNegative != 0) { days = -days; hours = -hours; minutes = -minutes; seconds = -seconds; microseconds = -microseconds; } return new TimeSpan(days, hours, minutes, seconds) + TimeSpan.FromTicks(microseconds * 10); } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmStockTransfer { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmStockTransfer() : base() { FormClosed += frmStockTransfer_FormClosed; KeyPress += frmStockTransfer_KeyPress; Resize += frmStockTransfer_Resize; Load += frmStockTransfer_Load; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; private System.Windows.Forms.Button withEventsField_cmdSelComp; public System.Windows.Forms.Button cmdSelComp { get { return withEventsField_cmdSelComp; } set { if (withEventsField_cmdSelComp != null) { withEventsField_cmdSelComp.Click -= cmdSelComp_Click; } withEventsField_cmdSelComp = value; if (withEventsField_cmdSelComp != null) { withEventsField_cmdSelComp.Click += cmdSelComp_Click; } } } private System.Windows.Forms.Button withEventsField_cmdDelete; public System.Windows.Forms.Button cmdDelete { get { return withEventsField_cmdDelete; } set { if (withEventsField_cmdDelete != null) { withEventsField_cmdDelete.Click -= cmdDelete_Click; } withEventsField_cmdDelete = value; if (withEventsField_cmdDelete != null) { withEventsField_cmdDelete.Click += cmdDelete_Click; } } } private System.Windows.Forms.Button withEventsField_cmdAdd; public System.Windows.Forms.Button cmdAdd { get { return withEventsField_cmdAdd; } set { if (withEventsField_cmdAdd != null) { withEventsField_cmdAdd.Click -= cmdAdd_Click; } withEventsField_cmdAdd = value; if (withEventsField_cmdAdd != null) { withEventsField_cmdAdd.Click += cmdAdd_Click; } } } private System.Windows.Forms.ListView withEventsField_lvStockT; public System.Windows.Forms.ListView lvStockT { get { return withEventsField_lvStockT; } set { if (withEventsField_lvStockT != null) { withEventsField_lvStockT.DoubleClick -= lvStockT_DoubleClick; withEventsField_lvStockT.KeyPress -= lvStockT_KeyPress; } withEventsField_lvStockT = value; if (withEventsField_lvStockT != null) { withEventsField_lvStockT.DoubleClick += lvStockT_DoubleClick; withEventsField_lvStockT.KeyPress += lvStockT_KeyPress; } } } private System.Windows.Forms.Button withEventsField_cmdTransfer; public System.Windows.Forms.Button cmdTransfer { get { return withEventsField_cmdTransfer; } set { if (withEventsField_cmdTransfer != null) { withEventsField_cmdTransfer.Click -= cmdTransfer_Click; } withEventsField_cmdTransfer = value; if (withEventsField_cmdTransfer != null) { withEventsField_cmdTransfer.Click += cmdTransfer_Click; } } } private System.Windows.Forms.Button withEventsField_cmdPrint; public System.Windows.Forms.Button cmdPrint { get { return withEventsField_cmdPrint; } set { if (withEventsField_cmdPrint != null) { withEventsField_cmdPrint.Click -= cmdPrint_Click; } withEventsField_cmdPrint = value; if (withEventsField_cmdPrint != null) { withEventsField_cmdPrint.Click += cmdPrint_Click; } } } private System.Windows.Forms.Button withEventsField_cmdClose; public System.Windows.Forms.Button cmdClose { get { return withEventsField_cmdClose; } set { if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click -= cmdClose_Click; } withEventsField_cmdClose = value; if (withEventsField_cmdClose != null) { withEventsField_cmdClose.Click += cmdClose_Click; } } } private System.Windows.Forms.Button withEventsField_cmdCancel; public System.Windows.Forms.Button cmdCancel { get { return withEventsField_cmdCancel; } set { if (withEventsField_cmdCancel != null) { withEventsField_cmdCancel.Click -= cmdCancel_Click; } withEventsField_cmdCancel = value; if (withEventsField_cmdCancel != null) { withEventsField_cmdCancel.Click += cmdCancel_Click; } } } public System.Windows.Forms.Panel picButtons; public System.Windows.Forms.Label lblSComp; public System.Windows.Forms.Label _lbl_0; public System.Windows.Forms.Label lblPComp; public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_2; public System.Windows.Forms.Label _lbl_5; //Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray public RectangleShapeArray Shape1; public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmStockTransfer)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer(); this.cmdSelComp = new System.Windows.Forms.Button(); this.cmdDelete = new System.Windows.Forms.Button(); this.cmdAdd = new System.Windows.Forms.Button(); this.lvStockT = new System.Windows.Forms.ListView(); this.picButtons = new System.Windows.Forms.Panel(); this.cmdTransfer = new System.Windows.Forms.Button(); this.cmdPrint = new System.Windows.Forms.Button(); this.cmdClose = new System.Windows.Forms.Button(); this.cmdCancel = new System.Windows.Forms.Button(); this.lblSComp = new System.Windows.Forms.Label(); this._lbl_0 = new System.Windows.Forms.Label(); this.lblPComp = new System.Windows.Forms.Label(); this._Shape1_2 = new Microsoft.VisualBasic.PowerPacks.RectangleShape(); this._lbl_5 = new System.Windows.Forms.Label(); //Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) this.Shape1 = new RectangleShapeArray(components); this.picButtons.SuspendLayout(); this.SuspendLayout(); this.ToolTip1.Active = true; //CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit() ((System.ComponentModel.ISupportInitialize)this.Shape1).BeginInit(); this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Text = "Stock Transfer Details"; this.ClientSize = new System.Drawing.Size(453, 406); this.Location = new System.Drawing.Point(73, 22); this.ControlBox = false; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Enabled = true; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.ShowInTaskbar = true; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmStockTransfer"; this.cmdSelComp.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdSelComp.Text = "&Select Company to Transfer"; this.cmdSelComp.Size = new System.Drawing.Size(161, 25); this.cmdSelComp.Location = new System.Drawing.Point(280, 120); this.cmdSelComp.TabIndex = 9; this.cmdSelComp.TabStop = false; this.cmdSelComp.BackColor = System.Drawing.SystemColors.Control; this.cmdSelComp.CausesValidation = true; this.cmdSelComp.Enabled = true; this.cmdSelComp.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdSelComp.Cursor = System.Windows.Forms.Cursors.Default; this.cmdSelComp.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdSelComp.Name = "cmdSelComp"; this.cmdDelete.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdDelete.Text = "&Delete"; this.cmdDelete.Enabled = false; this.cmdDelete.Size = new System.Drawing.Size(94, 25); this.cmdDelete.Location = new System.Drawing.Point(112, 120); this.cmdDelete.TabIndex = 7; this.cmdDelete.TabStop = false; this.cmdDelete.BackColor = System.Drawing.SystemColors.Control; this.cmdDelete.CausesValidation = true; this.cmdDelete.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdDelete.Cursor = System.Windows.Forms.Cursors.Default; this.cmdDelete.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdDelete.Name = "cmdDelete"; this.cmdAdd.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdAdd.Text = "&Add"; this.cmdAdd.Enabled = false; this.cmdAdd.Size = new System.Drawing.Size(94, 25); this.cmdAdd.Location = new System.Drawing.Point(8, 120); this.cmdAdd.TabIndex = 6; this.cmdAdd.TabStop = false; this.cmdAdd.BackColor = System.Drawing.SystemColors.Control; this.cmdAdd.CausesValidation = true; this.cmdAdd.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdAdd.Cursor = System.Windows.Forms.Cursors.Default; this.cmdAdd.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdAdd.Name = "cmdAdd"; this.lvStockT.Size = new System.Drawing.Size(445, 250); this.lvStockT.Location = new System.Drawing.Point(2, 150); this.lvStockT.TabIndex = 4; this.lvStockT.View = System.Windows.Forms.View.Details; this.lvStockT.LabelEdit = false; this.lvStockT.LabelWrap = true; this.lvStockT.HideSelection = false; this.lvStockT.FullRowSelect = true; this.lvStockT.GridLines = true; this.lvStockT.ForeColor = System.Drawing.SystemColors.WindowText; this.lvStockT.BackColor = System.Drawing.SystemColors.Window; this.lvStockT.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lvStockT.Name = "lvStockT"; this.picButtons.Dock = System.Windows.Forms.DockStyle.Top; this.picButtons.BackColor = System.Drawing.Color.Blue; this.picButtons.Size = new System.Drawing.Size(453, 39); this.picButtons.Location = new System.Drawing.Point(0, 0); this.picButtons.TabIndex = 3; this.picButtons.TabStop = false; this.picButtons.CausesValidation = true; this.picButtons.Enabled = true; this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText; this.picButtons.Cursor = System.Windows.Forms.Cursors.Default; this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No; this.picButtons.Visible = true; this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.picButtons.Name = "picButtons"; this.cmdTransfer.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdTransfer.Text = "&Transfer"; this.cmdTransfer.Size = new System.Drawing.Size(73, 29); this.cmdTransfer.Location = new System.Drawing.Point(368, 3); this.cmdTransfer.TabIndex = 12; this.cmdTransfer.TabStop = false; this.cmdTransfer.BackColor = System.Drawing.SystemColors.Control; this.cmdTransfer.CausesValidation = true; this.cmdTransfer.Enabled = true; this.cmdTransfer.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdTransfer.Cursor = System.Windows.Forms.Cursors.Default; this.cmdTransfer.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdTransfer.Name = "cmdTransfer"; this.cmdPrint.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdPrint.Text = "&Print"; this.cmdPrint.Size = new System.Drawing.Size(73, 29); this.cmdPrint.Location = new System.Drawing.Point(80, 3); this.cmdPrint.TabIndex = 8; this.cmdPrint.TabStop = false; this.cmdPrint.Visible = false; this.cmdPrint.BackColor = System.Drawing.SystemColors.Control; this.cmdPrint.CausesValidation = true; this.cmdPrint.Enabled = true; this.cmdPrint.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdPrint.Cursor = System.Windows.Forms.Cursors.Default; this.cmdPrint.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdPrint.Name = "cmdPrint"; this.cmdClose.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdClose.Text = "E&xit"; this.cmdClose.Size = new System.Drawing.Size(73, 29); this.cmdClose.Location = new System.Drawing.Point(161, 3); this.cmdClose.TabIndex = 5; this.cmdClose.TabStop = false; this.cmdClose.Visible = false; this.cmdClose.BackColor = System.Drawing.SystemColors.Control; this.cmdClose.CausesValidation = true; this.cmdClose.Enabled = true; this.cmdClose.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdClose.Cursor = System.Windows.Forms.Cursors.Default; this.cmdClose.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdClose.Name = "cmdClose"; this.cmdCancel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdCancel.Text = "&Undo"; this.cmdCancel.Size = new System.Drawing.Size(73, 29); this.cmdCancel.Location = new System.Drawing.Point(5, 3); this.cmdCancel.TabIndex = 2; this.cmdCancel.TabStop = false; this.cmdCancel.BackColor = System.Drawing.SystemColors.Control; this.cmdCancel.CausesValidation = true; this.cmdCancel.Enabled = true; this.cmdCancel.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdCancel.Cursor = System.Windows.Forms.Cursors.Default; this.cmdCancel.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdCancel.Name = "cmdCancel"; this.lblSComp.Text = "Promotion Name:"; this.lblSComp.Size = new System.Drawing.Size(192, 48); this.lblSComp.Location = new System.Drawing.Point(248, 64); this.lblSComp.TabIndex = 11; this.lblSComp.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.lblSComp.BackColor = System.Drawing.Color.Transparent; this.lblSComp.Enabled = true; this.lblSComp.ForeColor = System.Drawing.SystemColors.ControlText; this.lblSComp.Cursor = System.Windows.Forms.Cursors.Default; this.lblSComp.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblSComp.UseMnemonic = true; this.lblSComp.Visible = true; this.lblSComp.AutoSize = false; this.lblSComp.BorderStyle = System.Windows.Forms.BorderStyle.None; this.lblSComp.Name = "lblSComp"; this._lbl_0.BackColor = System.Drawing.Color.Transparent; this._lbl_0.Text = "&Transfer To"; this._lbl_0.Size = new System.Drawing.Size(67, 13); this._lbl_0.Location = new System.Drawing.Point(248, 45); this._lbl_0.TabIndex = 10; this._lbl_0.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._lbl_0.Enabled = true; this._lbl_0.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_0.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_0.UseMnemonic = true; this._lbl_0.Visible = true; this._lbl_0.AutoSize = true; this._lbl_0.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_0.Name = "_lbl_0"; this.lblPComp.Text = "Promotion Name:"; this.lblPComp.Size = new System.Drawing.Size(216, 48); this.lblPComp.Location = new System.Drawing.Point(16, 64); this.lblPComp.TabIndex = 1; this.lblPComp.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.lblPComp.BackColor = System.Drawing.Color.Transparent; this.lblPComp.Enabled = true; this.lblPComp.ForeColor = System.Drawing.SystemColors.ControlText; this.lblPComp.Cursor = System.Windows.Forms.Cursors.Default; this.lblPComp.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblPComp.UseMnemonic = true; this.lblPComp.Visible = true; this.lblPComp.AutoSize = false; this.lblPComp.BorderStyle = System.Windows.Forms.BorderStyle.None; this.lblPComp.Name = "lblPComp"; this._Shape1_2.BackColor = System.Drawing.Color.FromArgb(192, 192, 255); this._Shape1_2.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque; this._Shape1_2.Size = new System.Drawing.Size(439, 56); this._Shape1_2.Location = new System.Drawing.Point(8, 60); this._Shape1_2.BorderColor = System.Drawing.SystemColors.WindowText; this._Shape1_2.BorderStyle = System.Drawing.Drawing2D.DashStyle.Solid; this._Shape1_2.BorderWidth = 1; this._Shape1_2.FillColor = System.Drawing.Color.Black; this._Shape1_2.FillStyle = Microsoft.VisualBasic.PowerPacks.FillStyle.Transparent; this._Shape1_2.Visible = true; this._Shape1_2.Name = "_Shape1_2"; this._lbl_5.BackColor = System.Drawing.Color.Transparent; this._lbl_5.Text = "&Transfer From"; this._lbl_5.Size = new System.Drawing.Size(79, 13); this._lbl_5.Location = new System.Drawing.Point(8, 45); this._lbl_5.TabIndex = 0; this._lbl_5.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._lbl_5.Enabled = true; this._lbl_5.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_5.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_5.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_5.UseMnemonic = true; this._lbl_5.Visible = true; this._lbl_5.AutoSize = true; this._lbl_5.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_5.Name = "_lbl_5"; this.Controls.Add(cmdSelComp); this.Controls.Add(cmdDelete); this.Controls.Add(cmdAdd); this.Controls.Add(lvStockT); this.Controls.Add(picButtons); this.Controls.Add(lblSComp); this.Controls.Add(_lbl_0); this.Controls.Add(lblPComp); this.ShapeContainer1.Shapes.Add(_Shape1_2); this.Controls.Add(_lbl_5); this.Controls.Add(ShapeContainer1); this.picButtons.Controls.Add(cmdTransfer); this.picButtons.Controls.Add(cmdPrint); this.picButtons.Controls.Add(cmdClose); this.picButtons.Controls.Add(cmdCancel); //Me.lbl.SetIndex(_lbl_0, CType(0, Short)) //Me.lbl.SetIndex(_lbl_5, CType(5, Short)) this.Shape1.SetIndex(_Shape1_2, Convert.ToInt16(2)); ((System.ComponentModel.ISupportInitialize)this.Shape1).EndInit(); //CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit() this.picButtons.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Globalization; using System.Management.Automation; using Microsoft.WindowsAzure.Commands.Common; using Microsoft.WindowsAzure.Commands.SqlDatabase.Properties; using Microsoft.WindowsAzure.Commands.SqlDatabase.Services.Common; using Microsoft.WindowsAzure.Commands.SqlDatabase.Services.Server; using Microsoft.WindowsAzure.Commands.Utilities.Common; namespace Microsoft.WindowsAzure.Commands.SqlDatabase.Database.Cmdlet { using DatabaseCopyModel = Model.DatabaseCopy; using Microsoft.Azure.Common.Extensions; /// <summary> /// Start a copy operation for a Microsoft Azure SQL Database in the given server context. /// </summary> [Cmdlet(VerbsLifecycle.Start, "AzureSqlDatabaseCopy", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Low)] public class StartAzureSqlDatabaseCopy : AzurePSCmdlet { #region ParameterSets internal const string ByInputObjectContinuous = "ByInputObjectContinuous"; internal const string ByDatabaseNameContinuous = "ByDatabaseNameContinuous"; internal const string ByInputObject = "ByInputObject"; internal const string ByDatabaseName = "ByDatabaseName"; #endregion #region Parameters /// <summary> /// Gets or sets the name of the server upon which to operate /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The name of the server to operate on.")] [ValidateNotNullOrEmpty] public string ServerName { get; set; } /// <summary> /// Gets or sets the database to copy. /// </summary> [Parameter(Mandatory = true, Position = 1, ParameterSetName = ByInputObject, ValueFromPipeline = true, HelpMessage = "The database object to copy.")] [Parameter(Mandatory = true, Position = 1, ParameterSetName = ByInputObjectContinuous, ValueFromPipeline = true, HelpMessage = "The database object to copy.")] [ValidateNotNull] public Services.Server.Database Database { get; set; } /// <summary> /// Gets or sets the name of the database to copy. /// </summary> [Parameter(Mandatory = true, Position = 1, ParameterSetName = ByDatabaseName, HelpMessage = "The name of the database to copy.")] [Parameter(Mandatory = true, Position = 1, ParameterSetName = ByDatabaseNameContinuous, HelpMessage = "The name of the database to copy.")] [ValidateNotNullOrEmpty] public string DatabaseName { get; set; } /// <summary> /// Gets or sets the name of the partner server. /// </summary> [Parameter(Mandatory = false, ParameterSetName = ByInputObject, HelpMessage = "The name of the partner server.")] [Parameter(Mandatory = false, ParameterSetName = ByDatabaseName, HelpMessage = "The name of the partner server.")] [Parameter(Mandatory = true, ParameterSetName = ByInputObjectContinuous, HelpMessage = "The name of the partner server.")] [Parameter(Mandatory = true, ParameterSetName = ByDatabaseNameContinuous, HelpMessage = "The name of the partner server.")] [ValidateNotNullOrEmpty] public string PartnerServer { get; set; } /// <summary> /// Gets or sets the name of the partner database. /// </summary> [Parameter(Mandatory = true, ParameterSetName = ByInputObject, HelpMessage = "The name of the partner database.")] [Parameter(Mandatory = true, ParameterSetName = ByDatabaseName, HelpMessage = "The name of the partner database.")] [Parameter(Mandatory = false, ParameterSetName = ByInputObjectContinuous, HelpMessage = "The name of the partner database.")] [Parameter(Mandatory = false, ParameterSetName = ByDatabaseNameContinuous, HelpMessage = "The name of the partner database.")] [ValidateNotNullOrEmpty] public string PartnerDatabase { get; set; } /// <summary> /// Gets or sets a value indicating whether to make this a continuous copy. /// </summary> [Parameter(Mandatory = true, ParameterSetName = ByInputObjectContinuous, HelpMessage = "Whether to make this a continuous copy.")] [Parameter(Mandatory = true, ParameterSetName = ByDatabaseNameContinuous, HelpMessage = "Whether to make this a continuous copy.")] public SwitchParameter ContinuousCopy { get; set; } /// <summary> /// Gets or sets a value indicating whether this is an offline secondary copy. /// </summary> [Parameter(Mandatory = false, ParameterSetName = ByInputObjectContinuous, HelpMessage = "Whether this is an offline secondary copy.")] [Parameter(Mandatory = false, ParameterSetName = ByDatabaseNameContinuous, HelpMessage = "Whether this is an offline secondary copy.")] public SwitchParameter OfflineSecondary { get; set; } /// <summary> /// Gets or sets the switch to not confirm on the start of the database copy. /// </summary> [Parameter(HelpMessage = "Do not confirm on the start of the database copy.")] public SwitchParameter Force { get; set; } #endregion /// <summary> /// Execute the command. /// </summary> public override void ExecuteCmdlet() { // Obtain the database name from the given parameters. string databaseName = null; if (this.MyInvocation.BoundParameters.ContainsKey("Database")) { databaseName = this.Database.Name; } else if (this.MyInvocation.BoundParameters.ContainsKey("DatabaseName")) { databaseName = this.DatabaseName; } string partnerServerName = this.PartnerServer; string partnerDatabaseName = this.PartnerDatabase; if (this.ContinuousCopy.IsPresent) { // Default partnerDatabaseName to the only allowed value for continuous copies. partnerDatabaseName = partnerDatabaseName ?? databaseName; } else { // Default partnerServerName to the only allowed value for normal copies. partnerServerName = partnerServerName ?? this.ServerName; } // Do nothing if force is not specified and user cancelled the operation string actionDescription = string.Format( CultureInfo.InvariantCulture, Resources.StartAzureSqlDatabaseCopyDescription, this.ServerName, databaseName, partnerServerName, partnerDatabaseName); string actionWarning = string.Format( CultureInfo.InvariantCulture, Resources.StartAzureSqlDatabaseCopyWarning, this.ServerName, databaseName, partnerServerName, partnerDatabaseName); this.WriteVerbose(actionDescription); if (!this.Force.IsPresent && !this.ShouldProcess( actionDescription, actionWarning, Resources.ShouldProcessCaption)) { return; } // Use the provided ServerDataServiceContext or create one from the // provided ServerName and the active subscription. IServerDataServiceContext context = ServerDataServiceCertAuth.Create(this.ServerName, AzureSession.CurrentContext.Subscription); try { // Update the database with the specified name DatabaseCopyModel databaseCopy = context.StartDatabaseCopy( databaseName, partnerServerName, partnerDatabaseName, this.ContinuousCopy.IsPresent, this.OfflineSecondary.IsPresent); this.WriteObject(databaseCopy, true); } catch (Exception ex) { SqlDatabaseExceptionHandler.WriteErrorDetails( this, context.ClientRequestId, ex); } } } }
// // 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 System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.DataFactories.Common.Models; using Microsoft.Azure.Management.DataFactories.Core; using Microsoft.Azure.Management.DataFactories.Models; namespace Microsoft.Azure.Management.DataFactories.Core { public static partial class HubOperationsExtensions { /// <summary> /// Create a new hub instance or update an existing instance. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.Core.IHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. The name of the data factory. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a hub. /// </param> /// <returns> /// The create or update hub operation response. /// </returns> public static HubCreateOrUpdateResponse BeginCreateOrUpdate(this IHubOperations operations, string resourceGroupName, string dataFactoryName, HubCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IHubOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, dataFactoryName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create a new hub instance or update an existing instance. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.Core.IHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. The name of the data factory. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a hub. /// </param> /// <returns> /// The create or update hub operation response. /// </returns> public static Task<HubCreateOrUpdateResponse> BeginCreateOrUpdateAsync(this IHubOperations operations, string resourceGroupName, string dataFactoryName, HubCreateOrUpdateParameters parameters) { return operations.BeginCreateOrUpdateAsync(resourceGroupName, dataFactoryName, parameters, CancellationToken.None); } /// <summary> /// Delete a hub instance. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.Core.IHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. The name of the data factory. /// </param> /// <param name='hubName'> /// Required. The name of the hub. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse BeginDelete(this IHubOperations operations, string resourceGroupName, string dataFactoryName, string hubName) { return Task.Factory.StartNew((object s) => { return ((IHubOperations)s).BeginDeleteAsync(resourceGroupName, dataFactoryName, hubName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete a hub instance. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.Core.IHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. The name of the data factory. /// </param> /// <param name='hubName'> /// Required. The name of the hub. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> BeginDeleteAsync(this IHubOperations operations, string resourceGroupName, string dataFactoryName, string hubName) { return operations.BeginDeleteAsync(resourceGroupName, dataFactoryName, hubName, CancellationToken.None); } /// <summary> /// Create a new hub instance or update an existing instance. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.Core.IHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. The name of the data factory. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a hub. /// </param> /// <returns> /// The create or update hub operation response. /// </returns> public static HubCreateOrUpdateResponse CreateOrUpdate(this IHubOperations operations, string resourceGroupName, string dataFactoryName, HubCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IHubOperations)s).CreateOrUpdateAsync(resourceGroupName, dataFactoryName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create a new hub instance or update an existing instance. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.Core.IHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. The name of the data factory. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a hub. /// </param> /// <returns> /// The create or update hub operation response. /// </returns> public static Task<HubCreateOrUpdateResponse> CreateOrUpdateAsync(this IHubOperations operations, string resourceGroupName, string dataFactoryName, HubCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, dataFactoryName, parameters, CancellationToken.None); } /// <summary> /// Create a new hub instance or update an existing instance. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.Core.IHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. The name of the data factory. /// </param> /// <param name='hubName'> /// Required. The name of the data factory hub to be created or updated. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a hub. /// </param> /// <returns> /// The create or update hub operation response. /// </returns> public static HubCreateOrUpdateResponse CreateOrUpdateWithRawJsonContent(this IHubOperations operations, string resourceGroupName, string dataFactoryName, string hubName, HubCreateOrUpdateWithRawJsonContentParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IHubOperations)s).CreateOrUpdateWithRawJsonContentAsync(resourceGroupName, dataFactoryName, hubName, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create a new hub instance or update an existing instance. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.Core.IHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. The name of the data factory. /// </param> /// <param name='hubName'> /// Required. The name of the data factory hub to be created or updated. /// </param> /// <param name='parameters'> /// Required. The parameters required to create or update a hub. /// </param> /// <returns> /// The create or update hub operation response. /// </returns> public static Task<HubCreateOrUpdateResponse> CreateOrUpdateWithRawJsonContentAsync(this IHubOperations operations, string resourceGroupName, string dataFactoryName, string hubName, HubCreateOrUpdateWithRawJsonContentParameters parameters) { return operations.CreateOrUpdateWithRawJsonContentAsync(resourceGroupName, dataFactoryName, hubName, parameters, CancellationToken.None); } /// <summary> /// Delete a hub instance. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.Core.IHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. The name of the data factory. /// </param> /// <param name='hubName'> /// Required. The name of the hub. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static LongRunningOperationResponse Delete(this IHubOperations operations, string resourceGroupName, string dataFactoryName, string hubName) { return Task.Factory.StartNew((object s) => { return ((IHubOperations)s).DeleteAsync(resourceGroupName, dataFactoryName, hubName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete a hub instance. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.Core.IHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. The name of the data factory. /// </param> /// <param name='hubName'> /// Required. The name of the hub. /// </param> /// <returns> /// A standard service response for long running operations. /// </returns> public static Task<LongRunningOperationResponse> DeleteAsync(this IHubOperations operations, string resourceGroupName, string dataFactoryName, string hubName) { return operations.DeleteAsync(resourceGroupName, dataFactoryName, hubName, CancellationToken.None); } /// <summary> /// Gets a hub instance. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.Core.IHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. The name of the data factory. /// </param> /// <param name='hubName'> /// Required. The name of the hub. /// </param> /// <returns> /// The get hub operation response. /// </returns> public static HubGetResponse Get(this IHubOperations operations, string resourceGroupName, string dataFactoryName, string hubName) { return Task.Factory.StartNew((object s) => { return ((IHubOperations)s).GetAsync(resourceGroupName, dataFactoryName, hubName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets a hub instance. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.Core.IHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. The name of the data factory. /// </param> /// <param name='hubName'> /// Required. The name of the hub. /// </param> /// <returns> /// The get hub operation response. /// </returns> public static Task<HubGetResponse> GetAsync(this IHubOperations operations, string resourceGroupName, string dataFactoryName, string hubName) { return operations.GetAsync(resourceGroupName, dataFactoryName, hubName, CancellationToken.None); } /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.Core.IHubOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// The create or update hub operation response. /// </returns> public static HubCreateOrUpdateResponse GetCreateOrUpdateStatus(this IHubOperations operations, string operationStatusLink) { return Task.Factory.StartNew((object s) => { return ((IHubOperations)s).GetCreateOrUpdateStatusAsync(operationStatusLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.Core.IHubOperations. /// </param> /// <param name='operationStatusLink'> /// Required. Location value returned by the Begin operation. /// </param> /// <returns> /// The create or update hub operation response. /// </returns> public static Task<HubCreateOrUpdateResponse> GetCreateOrUpdateStatusAsync(this IHubOperations operations, string operationStatusLink) { return operations.GetCreateOrUpdateStatusAsync(operationStatusLink, CancellationToken.None); } /// <summary> /// Gets the first page of data factory hub instances with the link to /// the next page. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.Core.IHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. The name of the data factory. /// </param> /// <returns> /// The list hub operation response. /// </returns> public static HubListResponse List(this IHubOperations operations, string resourceGroupName, string dataFactoryName) { return Task.Factory.StartNew((object s) => { return ((IHubOperations)s).ListAsync(resourceGroupName, dataFactoryName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the first page of data factory hub instances with the link to /// the next page. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.Core.IHubOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The resource group name of the data factory. /// </param> /// <param name='dataFactoryName'> /// Required. The name of the data factory. /// </param> /// <returns> /// The list hub operation response. /// </returns> public static Task<HubListResponse> ListAsync(this IHubOperations operations, string resourceGroupName, string dataFactoryName) { return operations.ListAsync(resourceGroupName, dataFactoryName, CancellationToken.None); } /// <summary> /// Gets the next page of data factory hub instances with the link to /// the next page. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.Core.IHubOperations. /// </param> /// <param name='nextLink'> /// Required. The url to the next data factory hubs page. /// </param> /// <returns> /// The list hub operation response. /// </returns> public static HubListResponse ListNext(this IHubOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IHubOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the next page of data factory hub instances with the link to /// the next page. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.DataFactories.Core.IHubOperations. /// </param> /// <param name='nextLink'> /// Required. The url to the next data factory hubs page. /// </param> /// <returns> /// The list hub operation response. /// </returns> public static Task<HubListResponse> ListNextAsync(this IHubOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } } }
using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net.NetworkInformation; using System.Xml.Linq; using HealthCheck; using HealthCheck.Plugins; using Xunit; namespace UnitTests.Plugins { [SuppressMessage( "StyleCop.CSharp.DocumentationRules", "SA1600:ElementsMustBeDocumented", Justification = "Test Suites do not need XML Documentation.")] public class PingCheckTests { [Fact] public void Execute_Should_ReturnError_When_PingingHostThatDoesNotExist() { // Arrange var plugin = new PingCheckPlugin(); var xml = new XElement("Settings"); xml.Add(new XElement("HostName", "169.254.0.1")); xml.Add(new XElement("Retries", "1")); plugin.SetTaskConfiguration(xml); // Act var status = plugin.Execute(); // Assert Assert.Equal(CheckResult.Error, status.Status); } [Fact] public void Execute_Should_ReturnError_When_PingingInvalidHost() { // Arrange var plugin = new PingCheckPlugin(); plugin.SetTaskConfiguration(SettingsWithMinimum()); plugin.HostName = "Invalid"; // Act var status = plugin.Execute(); // Assert Assert.Equal(CheckResult.Error, status.Status); } [Fact] public void Execute_Should_ReturnPluginStatusToIdle() { // Arrange var plugin = CreatePingCheck(); plugin.SetTaskConfiguration(SettingsWithMinimum()); // Act _ = plugin.Execute(); // Assert Assert.Equal(PluginStatus.Idle, plugin.PluginStatus); } [Fact] public void Execute_Should_ReturnSuccess_When_PingingLocalHost() { // Arrange var plugin = CreatePingCheck(); plugin.SetTaskConfiguration(SettingsWithMinimum()); // Act var status = plugin.Execute(); // Assert Assert.Equal(CheckResult.Success, status.Status); } [Fact] public void Execute_Should_SetPluginStatusFailed_When_PingingInvalidHost() { // Arrange var plugin = new PingCheckPlugin(); plugin.SetTaskConfiguration(SettingsWithMinimum()); plugin.HostName = "Invalid"; // Act _ = plugin.Execute(); // Assert Assert.Equal(PluginStatus.TaskExecutionFailure, plugin.PluginStatus); } [Fact] public void HostName_Should_ReturnWhatItWasSetToDuringCreation() { // Arrange var plugin = CreatePingCheck(); // Act var actual = plugin.HostName; // Assert Assert.Equal("127.0.0.1", actual); } [Fact] public void ProcessPingResponse_Should_ReturnError_When_ErrorResponse() { // Arrange var plugin = new PingCheckPlugin(); plugin.SetTaskConfiguration(SettingsWithEverything()); // Act var status = plugin.ProcessPingResponse(IPStatus.Success, 3500); // Assert Assert.Equal(CheckResult.Error, status.Status); } [Fact] public void ProcessPingResponse_Should_ReturnError_When_PingFailed() { // Arrange var plugin = new PingCheckPlugin(); plugin.SetTaskConfiguration(SettingsWithEverything()); // Act var status = plugin.ProcessPingResponse(IPStatus.Unknown, 0); // Assert Assert.Equal(CheckResult.Error, status.Status); } [Fact] public void ProcessPingResponse_Should_ReturnSuccess_When_GoodResponse() { // Arrange var plugin = new PingCheckPlugin(); // Act var status = plugin.ProcessPingResponse(IPStatus.Success, 1); // Assert Assert.Equal(CheckResult.Success, status.Status); } [Fact] public void ProcessPingResponse_Should_ReturnWarning_When_WarnResponse() { // Arrange var plugin = new PingCheckPlugin(); plugin.SetTaskConfiguration(SettingsWithEverything()); // Act var status = plugin.ProcessPingResponse(IPStatus.Success, 501); // Assert Assert.Equal(CheckResult.Warning, status.Status); } [Fact] public void ResponseTimeError_Should_ReturnCorrectValue_When_SettingIsProvided() { // Arrange var plugin = new PingCheckPlugin(); // Act plugin.SetTaskConfiguration(SettingsWithEverything()); // Assert Assert.Equal(1500, plugin.ResponseTimeError); } [Fact] public void ResponseTimeError_Should_ReturnDefault_When_SettingDoesNotExist() { // Arrange var plugin = new PingCheckPlugin(); // Act plugin.SetTaskConfiguration(SettingsWithMinimum()); // Assert Assert.Equal(3000, plugin.ResponseTimeError); } [Fact] public void ResponseTimeWarn_Should_ReturnCorrectValue_When_SettingIsProvided() { // Arrange var plugin = new PingCheckPlugin(); // Act plugin.SetTaskConfiguration(SettingsWithEverything()); // Assert Assert.Equal(250, plugin.ResponseTimeWarn); } [Fact] public void ResponseTimeWarn_Should_ReturnDefault_When_SettingDoesNotExist() { // Arrange var plugin = new PingCheckPlugin(); // Act plugin.SetTaskConfiguration(SettingsWithMinimum()); // Assert Assert.Equal(500, plugin.ResponseTimeWarn); } [Fact] public void Retries_Should_ReturnCorrectValue_When_SettingIsProvided() { // Arrange var plugin = new PingCheckPlugin(); // Act plugin.SetTaskConfiguration(SettingsWithEverything()); // Assert Assert.Equal(10, plugin.Retries); } [Fact] public void Retries_Should_ReturnDefault_When_SettingDoesNotExist() { // Arrange var plugin = new PingCheckPlugin(); // Act plugin.SetTaskConfiguration(SettingsWithMinimum()); // Assert Assert.Equal(3, plugin.Retries); } [Fact] public void RetryDelay_Should_ReturnCorrectValue_When_SettingIsProvided() { // Arrange var plugin = new PingCheckPlugin(); // Act plugin.SetTaskConfiguration(SettingsWithEverything()); // Assert Assert.Equal(5000, plugin.RetryDelay); } [Fact] public void RetryDelay_Should_ReturnDefault_When_SettingDoesNotExist() { // Arrange var plugin = new PingCheckPlugin(); // Act plugin.SetTaskConfiguration(SettingsWithMinimum()); // Assert Assert.Equal(2500, plugin.RetryDelay); } [Fact] public void SetTaskConfiguration_Should_ThrowException_When_HostNameIsMissing() { // Arrange var plugin = new PingCheckPlugin(); var xml = new XElement("Settings"); // Act & Assert Assert.Throws<MissingRequiredSettingException>(() => plugin.SetTaskConfiguration(xml)); } [Fact] public void Shutdown_Should_ReturnNothing() { // Arrange var plugin = new PingCheckPlugin(); // Act & Assert plugin.Shutdown(); Assert.IsAssignableFrom<IHealthCheckPlugin>(plugin); } [Fact] public void Startup_Should_SetPluginStatusToIdle() { // Arrange var plugin = new PingCheckPlugin(); // Act plugin.Startup(); // Assert Assert.Equal(PluginStatus.Idle, plugin.PluginStatus); } [Fact] public void TimeOut_Should_ReturnCorrectValue_When_SettingIsProvided() { // Arrange var plugin = new PingCheckPlugin(); // Act plugin.SetTaskConfiguration(SettingsWithEverything()); // Assert Assert.Equal(200, plugin.TimeOut); } [Fact] public void TimeOut_Should_ReturnDefault_When_SettingDoesNotExist() { // Arrange var plugin = new PingCheckPlugin(); // Act plugin.SetTaskConfiguration(SettingsWithMinimum()); // Assert Assert.Equal(5000, plugin.TimeOut); } private PingCheckPlugin CreatePingCheck() { return new PingCheckPlugin() { GroupName = "UnitTest", HostName = "127.0.0.1" }; } private XElement SettingsWithEverything() { var xml = new XElement("Settings"); xml.Add(new XElement("HostName", "127.0.0.1")); xml.Add(new XElement("Retries", "10")); xml.Add(new XElement("RetryDelay", "5000")); xml.Add(new XElement("TimeOut", "200")); xml.Add(new XElement("ResponseTimeWarn", "250")); xml.Add(new XElement("ResponseTimeError", "1500")); return xml; } private XElement SettingsWithMinimum() { var xml = new XElement("Settings"); xml.Add(new XElement("HostName", "127.0.0.1")); return xml; } } }
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 settings4net.TestWebApp.Areas.HelpPage.ModelDescriptions; using settings4net.TestWebApp.Areas.HelpPage.Models; namespace settings4net.TestWebApp.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); } } } }