context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Internal.NativeFormat; using Internal.Runtime.Augments; using Internal.Runtime.CallInterceptor; using Internal.Runtime.CompilerServices; using Internal.TypeSystem; namespace Internal.Runtime.TypeLoader { [McgIntrinsics] internal static class AddrofIntrinsics { // This method is implemented elsewhere in the toolchain internal static IntPtr AddrOf<T>(T ftn) { throw new PlatformNotSupportedException(); } } internal class DebugFuncEval { private static void HighLevelDebugFuncEvalHelperWithVariables(ref TypesAndValues param, ref LocalVariableSet arguments) { for (int i = 0; i < param.parameterValues.Length; i++) { arguments.SetVar<int>(i + 1, param.parameterValues[i]); } // Obtain the target method address from the runtime IntPtr targetAddress = RuntimeAugments.RhpGetFuncEvalTargetAddress(); LocalVariableType[] returnAndArgumentTypes = new LocalVariableType[param.types.Length]; for (int i = 0; i < returnAndArgumentTypes.Length; i++) { returnAndArgumentTypes[i] = new LocalVariableType(param.types[i], false, false); } // Hard coding static here DynamicCallSignature dynamicCallSignature = new DynamicCallSignature(Internal.Runtime.CallConverter.CallingConvention.ManagedStatic, returnAndArgumentTypes, returnAndArgumentTypes.Length); // Invoke the target method Internal.Runtime.CallInterceptor.CallInterceptor.MakeDynamicCall(targetAddress, dynamicCallSignature, arguments); unsafe { // Box the return IntPtr input = arguments.GetAddressOfVarData(0); object returnValue = RuntimeAugments.RhBoxAny(input, (IntPtr)param.types[0].ToEETypePtr()); GCHandle returnValueHandle = GCHandle.Alloc(returnValue); IntPtr returnValueHandlePointer = GCHandle.ToIntPtr(returnValueHandle); uint identifier = RuntimeAugments.RhpRecordDebuggeeInitiatedHandle(returnValueHandlePointer); // Signal to the debugger the func eval completes FuncEvalCompleteCommand* funcEvalCompleteCommand = stackalloc FuncEvalCompleteCommand[1]; funcEvalCompleteCommand->commandCode = 0; funcEvalCompleteCommand->returnAddress = (long)returnValueHandlePointer; IntPtr funcEvalCompleteCommandPointer = new IntPtr(funcEvalCompleteCommand); RuntimeAugments.RhpSendCustomEventToDebugger(funcEvalCompleteCommandPointer, Unsafe.SizeOf<FuncEvalCompleteCommand>()); } // debugger magic will make sure this function never returns, instead control will be transferred back to the point where the FuncEval begins } [StructLayout(LayoutKind.Explicit, Size=16)] struct WriteParameterCommand { [FieldOffset(0)] public int commandCode; [FieldOffset(4)] public int unused; [FieldOffset(8)] public long bufferAddress; } [StructLayout(LayoutKind.Explicit, Size=16)] struct FuncEvalCompleteCommand { [FieldOffset(0)] public int commandCode; [FieldOffset(4)] public int unused; [FieldOffset(8)] public long returnAddress; } struct TypesAndValues { public RuntimeTypeHandle[] types; // TODO: We should support arguments of *any* type public int[] parameterValues; } private static void HighLevelDebugFuncEvalHelper() { uint parameterBufferSize = RuntimeAugments.RhpGetFuncEvalParameterBufferSize(); IntPtr writeParameterCommandPointer; IntPtr debuggerBufferPointer; unsafe { byte* debuggerBufferRawPointer = stackalloc byte[(int)parameterBufferSize]; debuggerBufferPointer = new IntPtr(debuggerBufferRawPointer); WriteParameterCommand writeParameterCommand = new WriteParameterCommand { commandCode = 1, bufferAddress = debuggerBufferPointer.ToInt64() }; writeParameterCommandPointer = new IntPtr(&writeParameterCommand); RuntimeAugments.RhpSendCustomEventToDebugger(writeParameterCommandPointer, Unsafe.SizeOf<WriteParameterCommand>()); // .. debugger magic ... the debuggerBuffer will be filled with parameter data TypesAndValues typesAndValues = new TypesAndValues(); uint trash; uint parameterCount; uint parameterValue; uint eeTypeCount; ulong eeType; uint offset = 0; NativeReader reader = new NativeReader(debuggerBufferRawPointer, parameterBufferSize); offset = reader.DecodeUnsigned(offset, out trash); // The VertexSequence always generate a length, I don't really need it. offset = reader.DecodeUnsigned(offset, out parameterCount); typesAndValues.parameterValues = new int[parameterCount]; for (int i = 0; i < parameterCount; i++) { offset = reader.DecodeUnsigned(offset, out parameterValue); typesAndValues.parameterValues[i] = (int)parameterValue; } offset = reader.DecodeUnsigned(offset, out eeTypeCount); for (int i = 0; i < eeTypeCount; i++) { // TODO: Stuff these eeType values into the external reference table offset = reader.DecodeUnsignedLong(offset, out eeType); } TypeSystemContext typeSystemContext = TypeSystemContextFactory.Create(); bool hasThis; TypeDesc[] parameters; bool[] parametersWithGenericDependentLayout; bool result = TypeLoaderEnvironment.Instance.GetCallingConverterDataFromMethodSignature_NativeLayout_Debugger(typeSystemContext, RuntimeSignature.CreateFromNativeLayoutSignatureForDebugger(offset), Instantiation.Empty, Instantiation.Empty, out hasThis, out parameters, out parametersWithGenericDependentLayout, reader); typesAndValues.types = new RuntimeTypeHandle[parameters.Length]; bool needToDynamicallyLoadTypes = false; for (int i = 0; i < typesAndValues.types.Length; i++) { if (!parameters[i].RetrieveRuntimeTypeHandleIfPossible()) { needToDynamicallyLoadTypes = true; break; } typesAndValues.types[i] = parameters[i].GetRuntimeTypeHandle(); } if (needToDynamicallyLoadTypes) { TypeLoaderEnvironment.Instance.RunUnderTypeLoaderLock(() => { typeSystemContext.FlushTypeBuilderStates(); GenericDictionaryCell[] cells = new GenericDictionaryCell[parameters.Length]; for (int i = 0; i < cells.Length; i++) { cells[i] = GenericDictionaryCell.CreateTypeHandleCell(parameters[i]); } IntPtr[] eetypePointers; TypeBuilder.ResolveMultipleCells(cells, out eetypePointers); for (int i = 0; i < parameters.Length; i++) { typesAndValues.types[i] = ((EEType*)eetypePointers[i])->ToRuntimeTypeHandle(); } }); } TypeSystemContextFactory.Recycle(typeSystemContext); LocalVariableType[] argumentTypes = new LocalVariableType[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { // TODO: What these false really means? Need to make sure our format contains those information argumentTypes[i] = new LocalVariableType(typesAndValues.types[i], false, false); } LocalVariableSet.SetupArbitraryLocalVariableSet<TypesAndValues>(HighLevelDebugFuncEvalHelperWithVariables, ref typesAndValues, argumentTypes); } } public static void Initialize() { // We needed this function only because the McgIntrinsics attribute cannot be applied on the static constructor RuntimeAugments.RhpSetHighLevelDebugFuncEvalHelper(AddrofIntrinsics.AddrOf<Action>(HighLevelDebugFuncEvalHelper)); } } }
// 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; using System.Globalization; using System.Net.NetworkInformation; using System.Runtime.Serialization; using System.Text.RegularExpressions; namespace System.Net { [Serializable] public class WebProxy : IWebProxy, ISerializable { private ArrayList _bypassList; private Regex[] _regExBypassList; public WebProxy() : this((Uri)null, false, null, null) { } public WebProxy(Uri Address) : this(Address, false, null, null) { } public WebProxy(Uri Address, bool BypassOnLocal) : this(Address, BypassOnLocal, null, null) { } public WebProxy(Uri Address, bool BypassOnLocal, string[] BypassList) : this(Address, BypassOnLocal, BypassList, null) { } public WebProxy(Uri Address, bool BypassOnLocal, string[] BypassList, ICredentials Credentials) { this.Address = Address; this.Credentials = Credentials; this.BypassProxyOnLocal = BypassOnLocal; if (BypassList != null) { _bypassList = new ArrayList(BypassList); UpdateRegExList(true); } } public WebProxy(string Host, int Port) : this(new Uri("http://" + Host + ":" + Port.ToString(CultureInfo.InvariantCulture)), false, null, null) { } public WebProxy(string Address) : this(CreateProxyUri(Address), false, null, null) { } public WebProxy(string Address, bool BypassOnLocal) : this(CreateProxyUri(Address), BypassOnLocal, null, null) { } public WebProxy(string Address, bool BypassOnLocal, string[] BypassList) : this(CreateProxyUri(Address), BypassOnLocal, BypassList, null) { } public WebProxy(string Address, bool BypassOnLocal, string[] BypassList, ICredentials Credentials) : this(CreateProxyUri(Address), BypassOnLocal, BypassList, Credentials) { } public Uri Address { get; set; } public bool BypassProxyOnLocal { get; set; } public string[] BypassList { get { return _bypassList != null ? (string[])_bypassList.ToArray(typeof(string)) : Array.Empty<string>(); } set { _bypassList = new ArrayList(value); UpdateRegExList(true); } } public ArrayList BypassArrayList => _bypassList ?? (_bypassList = new ArrayList()); public ICredentials Credentials { get; set; } public bool UseDefaultCredentials { get { return Credentials == CredentialCache.DefaultCredentials; } set { Credentials = value ? CredentialCache.DefaultCredentials : null; } } public Uri GetProxy(Uri destination) { if (destination == null) { throw new ArgumentNullException(nameof(destination)); } return IsBypassed(destination) ? destination : Address; } private static Uri CreateProxyUri(string address) => address == null ? null : address.IndexOf("://") == -1 ? new Uri("http://" + address) : new Uri(address); private void UpdateRegExList(bool canThrow) { Regex[] regExBypassList = null; ArrayList bypassList = _bypassList; try { if (bypassList != null && bypassList.Count > 0) { regExBypassList = new Regex[bypassList.Count]; for (int i = 0; i < bypassList.Count; i++) { regExBypassList[i] = new Regex((string)bypassList[i], RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); } } } catch { if (!canThrow) { _regExBypassList = null; return; } throw; } // Update field here, as it could throw earlier in the loop _regExBypassList = regExBypassList; } private bool IsMatchInBypassList(Uri input) { UpdateRegExList(false); if (_regExBypassList != null) { string matchUriString = input.IsDefaultPort ? input.Scheme + "://" + input.Host : input.Scheme + "://" + input.Host + ":" + input.Port.ToString(); foreach (Regex r in _regExBypassList) { if (r.IsMatch(matchUriString)) { return true; } } } return false; } private bool IsLocal(Uri host) { string hostString = host.Host; IPAddress hostAddress; if (IPAddress.TryParse(hostString, out hostAddress)) { return IPAddress.IsLoopback(hostAddress) || IsAddressLocal(hostAddress); } // No dot? Local. int dot = hostString.IndexOf('.'); if (dot == -1) { return true; } // If it matches the primary domain, it's local. (Whether or not the hostname matches.) string local = "." + IPGlobalProperties.GetIPGlobalProperties().DomainName; return local.Length == (hostString.Length - dot) && string.Compare(local, 0, hostString, dot, local.Length, StringComparison.OrdinalIgnoreCase) == 0; } private static bool IsAddressLocal(IPAddress ipAddress) { // Perf note: The .NET Framework caches this and then uses network change notifications to track // whether the set should be recomputed. We could consider doing the same if this is observed as // a bottleneck, but that tracking has its own costs. IPAddress[] localAddresses = Dns.GetHostEntryAsync(Dns.GetHostName()).GetAwaiter().GetResult().AddressList; // TODO: Use synchronous GetHostEntry when available for (int i = 0; i < localAddresses.Length; i++) { if (ipAddress.Equals(localAddresses[i])) { return true; } } return false; } public bool IsBypassed(Uri host) { if (host == null) { throw new ArgumentNullException(nameof(host)); } return Address == null || host.IsLoopback || (BypassProxyOnLocal && IsLocal(host)) || IsMatchInBypassList(host); } protected WebProxy(SerializationInfo serializationInfo, StreamingContext streamingContext) { BypassProxyOnLocal = serializationInfo.GetBoolean("_BypassOnLocal"); Address = (Uri)serializationInfo.GetValue("_ProxyAddress", typeof(Uri)); _bypassList = (ArrayList)serializationInfo.GetValue("_BypassList", typeof(ArrayList)); UseDefaultCredentials = serializationInfo.GetBoolean("_UseDefaultCredentials"); } void ISerializable.GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext) { GetObjectData(serializationInfo, streamingContext); } protected virtual void GetObjectData(SerializationInfo serializationInfo, StreamingContext streamingContext) { serializationInfo.AddValue("_BypassOnLocal", BypassProxyOnLocal); serializationInfo.AddValue("_ProxyAddress", Address); serializationInfo.AddValue("_BypassList", _bypassList); serializationInfo.AddValue("_UseDefaultCredentials", UseDefaultCredentials); } [Obsolete("This method has been deprecated. Please use the proxy selected for you by default. http://go.microsoft.com/fwlink/?linkid=14202")] public static WebProxy GetDefaultProxy() { // The .NET Framework here returns a proxy that fetches IE settings and // executes JavaScript to determine the correct proxy. throw new PlatformNotSupportedException(); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // namespace System.Reflection { using System; using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Text; using System.Threading; // // Invocation cached flags. Those are used in unmanaged code as well // so be careful if you change them // [Flags] internal enum INVOCATION_FLAGS : uint { INVOCATION_FLAGS_UNKNOWN = 0x00000000, INVOCATION_FLAGS_INITIALIZED = 0x00000001, // it's used for both method and field to signify that no access is allowed INVOCATION_FLAGS_NO_INVOKE = 0x00000002, INVOCATION_FLAGS_NEED_SECURITY = 0x00000004, // Set for static ctors and ctors on abstract types, which // can be invoked only if the "this" object is provided (even if it's null). INVOCATION_FLAGS_NO_CTOR_INVOKE = 0x00000008, // because field and method are different we can reuse the same bits // method INVOCATION_FLAGS_IS_CTOR = 0x00000010, INVOCATION_FLAGS_RISKY_METHOD = 0x00000020, INVOCATION_FLAGS_NON_W8P_FX_API = 0x00000040, INVOCATION_FLAGS_IS_DELEGATE_CTOR = 0x00000080, INVOCATION_FLAGS_CONTAINS_STACK_POINTERS = 0x00000100, // field INVOCATION_FLAGS_SPECIAL_FIELD = 0x00000010, INVOCATION_FLAGS_FIELD_SPECIAL_CAST = 0x00000020, // temporary flag used for flagging invocation of method vs ctor // this flag never appears on the instance m_invocationFlag and is simply // passed down from within ConstructorInfo.Invoke() INVOCATION_FLAGS_CONSTRUCTOR_INVOKE = 0x10000000, } [Serializable] [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_MethodBase))] #pragma warning disable 618 [PermissionSetAttribute(SecurityAction.InheritanceDemand, Name = "FullTrust")] #pragma warning restore 618 [System.Runtime.InteropServices.ComVisible(true)] public abstract class MethodBase : MemberInfo, _MethodBase { #region Static Members public static MethodBase GetMethodFromHandle(RuntimeMethodHandle handle) { if (handle.IsNullHandle()) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle")); MethodBase m = RuntimeType.GetMethodBase(handle.GetMethodInfo()); Type declaringType = m.DeclaringType; if (declaringType != null && declaringType.IsGenericType) throw new ArgumentException(String.Format( CultureInfo.CurrentCulture, Environment.GetResourceString("Argument_MethodDeclaringTypeGeneric"), m, declaringType.GetGenericTypeDefinition())); return m; } [System.Runtime.InteropServices.ComVisible(false)] public static MethodBase GetMethodFromHandle(RuntimeMethodHandle handle, RuntimeTypeHandle declaringType) { if (handle.IsNullHandle()) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidHandle")); return RuntimeType.GetMethodBase(declaringType.GetRuntimeType(), handle.GetMethodInfo()); } [System.Security.DynamicSecurityMethod] // Specify DynamicSecurityMethod attribute to prevent inlining of the caller. [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var has to be marked non-inlineable public static MethodBase GetCurrentMethod() { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return RuntimeMethodInfo.InternalGetCurrentMethod(ref stackMark); } #endregion #region Constructor protected MethodBase() { } #endregion #if !FEATURE_CORECLR public static bool operator ==(MethodBase left, MethodBase right) { if (ReferenceEquals(left, right)) return true; if ((object)left == null || (object)right == null) return false; MethodInfo method1, method2; ConstructorInfo constructor1, constructor2; if ((method1 = left as MethodInfo) != null && (method2 = right as MethodInfo) != null) return method1 == method2; else if ((constructor1 = left as ConstructorInfo) != null && (constructor2 = right as ConstructorInfo) != null) return constructor1 == constructor2; return false; } public static bool operator !=(MethodBase left, MethodBase right) { return !(left == right); } #endif // !FEATURE_CORECLR public override bool Equals(object obj) { return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } #region Internal Members // used by EE [System.Security.SecurityCritical] private IntPtr GetMethodDesc() { return MethodHandle.Value; } #if FEATURE_APPX // The C# dynamic and VB late bound binders need to call this API. Since we don't have time to make this // public in Dev11, the C# and VB binders currently call this through a delegate. // When we make this API public (hopefully) in Dev12 we need to change the C# and VB binders to call this // probably statically. The code is located in: // C#: ndp\fx\src\CSharp\Microsoft\CSharp\SymbolTable.cs - Microsoft.CSharp.RuntimeBinder.SymbolTable..cctor // VB: vb\runtime\msvbalib\helpers\Symbols.vb - Microsoft.VisualBasic.CompilerServices.Symbols..cctor internal virtual bool IsDynamicallyInvokable { get { return true; } } #endif #endregion #region Public Abstract\Virtual Members internal virtual ParameterInfo[] GetParametersNoCopy() { return GetParameters (); } [System.Diagnostics.Contracts.Pure] public abstract ParameterInfo[] GetParameters(); public virtual MethodImplAttributes MethodImplementationFlags { get { return GetMethodImplementationFlags(); } } public abstract MethodImplAttributes GetMethodImplementationFlags(); public abstract RuntimeMethodHandle MethodHandle { get; } public abstract MethodAttributes Attributes { get; } public abstract Object Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture); public virtual CallingConventions CallingConvention { get { return CallingConventions.Standard; } } [System.Runtime.InteropServices.ComVisible(true)] public virtual Type[] GetGenericArguments() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_SubclassOverride")); } public virtual bool IsGenericMethodDefinition { get { return false; } } public virtual bool ContainsGenericParameters { get { return false; } } public virtual bool IsGenericMethod { get { return false; } } public virtual bool IsSecurityCritical { get { throw new NotImplementedException(); } } public virtual bool IsSecuritySafeCritical { get { throw new NotImplementedException(); } } public virtual bool IsSecurityTransparent { get { throw new NotImplementedException(); } } #endregion #region Public Members [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] public Object Invoke(Object obj, Object[] parameters) { // Theoretically we should set up a LookForMyCaller stack mark here and pass that along. // But to maintain backward compatibility we can't switch to calling an // internal overload that takes a stack mark. // Fortunately the stack walker skips all the reflection invocation frames including this one. // So this method will never be returned by the stack walker as the caller. // See SystemDomain::CallersMethodCallbackWithStackMark in AppDomain.cpp. return Invoke(obj, BindingFlags.Default, null, parameters, null); } public bool IsPublic { get { return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Public; } } public bool IsPrivate { get { return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Private; } } public bool IsFamily { get { return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Family; } } public bool IsAssembly { get { return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.Assembly; } } public bool IsFamilyAndAssembly { get { return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.FamANDAssem; } } public bool IsFamilyOrAssembly { get {return(Attributes & MethodAttributes.MemberAccessMask) == MethodAttributes.FamORAssem; } } public bool IsStatic { get { return(Attributes & MethodAttributes.Static) != 0; } } public bool IsFinal { get { return(Attributes & MethodAttributes.Final) != 0; } } public bool IsVirtual { get { return(Attributes & MethodAttributes.Virtual) != 0; } } public bool IsHideBySig { get { return(Attributes & MethodAttributes.HideBySig) != 0; } } public bool IsAbstract { get { return(Attributes & MethodAttributes.Abstract) != 0; } } public bool IsSpecialName { get { return(Attributes & MethodAttributes.SpecialName) != 0; } } [System.Runtime.InteropServices.ComVisible(true)] public bool IsConstructor { get { // To be backward compatible we only return true for instance RTSpecialName ctors. return (this is ConstructorInfo && !IsStatic && ((Attributes & MethodAttributes.RTSpecialName) == MethodAttributes.RTSpecialName)); } } [System.Security.SecuritySafeCritical] #pragma warning disable 618 [ReflectionPermissionAttribute(SecurityAction.Demand, Flags=ReflectionPermissionFlag.MemberAccess)] #pragma warning restore 618 public virtual MethodBody GetMethodBody() { throw new InvalidOperationException(); } #endregion #region Internal Methods // helper method to construct the string representation of the parameter list internal static string ConstructParameters(Type[] parameterTypes, CallingConventions callingConvention, bool serialization) { StringBuilder sbParamList = new StringBuilder(); string comma = ""; for (int i = 0; i < parameterTypes.Length; i++) { Type t = parameterTypes[i]; sbParamList.Append(comma); string typeName = t.FormatTypeName(serialization); // Legacy: Why use "ByRef" for by ref parameters? What language is this? // VB uses "ByRef" but it should precede (not follow) the parameter name. // Why don't we just use "&"? if (t.IsByRef && !serialization) { sbParamList.Append(typeName.TrimEnd(new char[] { '&' })); sbParamList.Append(" ByRef"); } else { sbParamList.Append(typeName); } comma = ", "; } if ((callingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) { sbParamList.Append(comma); sbParamList.Append("..."); } return sbParamList.ToString(); } internal string FullName { get { return String.Format("{0}.{1}", DeclaringType.FullName, FormatNameAndSig()); } } internal string FormatNameAndSig() { return FormatNameAndSig(false); } internal virtual string FormatNameAndSig(bool serialization) { // Serialization uses ToString to resolve MethodInfo overloads. StringBuilder sbName = new StringBuilder(Name); sbName.Append("("); sbName.Append(ConstructParameters(GetParameterTypes(), CallingConvention, serialization)); sbName.Append(")"); return sbName.ToString(); } internal virtual Type[] GetParameterTypes() { ParameterInfo[] paramInfo = GetParametersNoCopy(); Type[] parameterTypes = new Type[paramInfo.Length]; for (int i = 0; i < paramInfo.Length; i++) parameterTypes[i] = paramInfo[i].ParameterType; return parameterTypes; } [System.Security.SecuritySafeCritical] internal Object[] CheckArguments(Object[] parameters, Binder binder, BindingFlags invokeAttr, CultureInfo culture, Signature sig) { // copy the arguments in a different array so we detach from any user changes Object[] copyOfParameters = new Object[parameters.Length]; ParameterInfo[] p = null; for (int i = 0; i < parameters.Length; i++) { Object arg = parameters[i]; RuntimeType argRT = sig.Arguments[i]; if (arg == Type.Missing) { if (p == null) p = GetParametersNoCopy(); if (p[i].DefaultValue == System.DBNull.Value) throw new ArgumentException(Environment.GetResourceString("Arg_VarMissNull"),"parameters"); arg = p[i].DefaultValue; } copyOfParameters[i] = argRT.CheckValue(arg, binder, culture, invokeAttr); } return copyOfParameters; } #endregion #region _MethodBase Implementation #if !FEATURE_CORECLR Type _MethodBase.GetType() { return base.GetType(); } bool _MethodBase.IsPublic { get { return IsPublic; } } bool _MethodBase.IsPrivate { get { return IsPrivate; } } bool _MethodBase.IsFamily { get { return IsFamily; } } bool _MethodBase.IsAssembly { get { return IsAssembly; } } bool _MethodBase.IsFamilyAndAssembly { get { return IsFamilyAndAssembly; } } bool _MethodBase.IsFamilyOrAssembly { get { return IsFamilyOrAssembly; } } bool _MethodBase.IsStatic { get { return IsStatic; } } bool _MethodBase.IsFinal { get { return IsFinal; } } bool _MethodBase.IsVirtual { get { return IsVirtual; } } bool _MethodBase.IsHideBySig { get { return IsHideBySig; } } bool _MethodBase.IsAbstract { get { return IsAbstract; } } bool _MethodBase.IsSpecialName { get { return IsSpecialName; } } bool _MethodBase.IsConstructor { get { return IsConstructor; } } void _MethodBase.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _MethodBase.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _MethodBase.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } // If you implement this method, make sure to include _MethodBase.Invoke in VM\DangerousAPIs.h and // include _MethodBase in SystemDomain::IsReflectionInvocationMethod in AppDomain.cpp. void _MethodBase.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } #endif #endregion } }
// 32feet.NET - Personal Area Networking for .NET // // InTheHand.Net.Widcomm.WidcommSocketExceptions // // Copyright (c) 2008-2013 In The Hand Ltd, All rights reserved. // Copyright (c) 2008-2013 Alan J. McFarlane, All rights reserved. // This source code is licensed under the MIT License using System; using System.Collections.Generic; using System.Text; using System.Net.Sockets; using InTheHand.Net.Sockets; using System.Diagnostics; using Microsoft.Win32; using System.Diagnostics.CodeAnalysis; using InTheHand.Net.Bluetooth.Factory; using List_IBluetoothDeviceInfo = System.Collections.Generic.List<InTheHand.Net.Bluetooth.Factory.IBluetoothDeviceInfo>; using AR_Inquiry = InTheHand.Net.AsyncResult<System.Collections.Generic.List<InTheHand.Net.Bluetooth.Factory.IBluetoothDeviceInfo>>; using System.Threading; using AsyncResultDD = InTheHand.Net.AsyncResult< System.Collections.Generic.List<InTheHand.Net.Bluetooth.Factory.IBluetoothDeviceInfo>, InTheHand.Net.Bluetooth.Factory.DiscoDevsParams>; using System.Globalization; using System.IO; namespace InTheHand.Net.Bluetooth.Widcomm { internal sealed class WidcommBtInterface : IDisposable { volatile bool _disposed; readonly WidcommBluetoothFactoryBase m_factory; readonly IBtIf m_btIf; readonly WidcommInquiry _inquiryHandler; internal WidcommBtInterface(IBtIf btIf, WidcommBluetoothFactoryBase factory) { m_factory = factory; _inquiryHandler = new WidcommInquiry(m_factory, StopInquiry); bool created = false; try { m_btIf = btIf; m_btIf.SetParent(this); // "An object of this class must be instantiated before any other DK classes are used" m_btIf.Create(); created = true; } finally { if (!created) { GC.SuppressFinalize(this); } } } private void EnsureLoaded() { if (!_disposed) // All is good. return; m_factory.EnsureLoaded(); } //---- void IDisposable.Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~WidcommBtInterface() { Dispose(false); } [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "disposing")] void Dispose(bool disposing) { _disposed = true; m_btIf.Destroy(disposing); } //----------------------------- //---------- internal IAsyncResult BeginInquiry(int maxDevices, TimeSpan inquiryLength, AsyncCallback asyncCallback, Object state, BluetoothClient.LiveDiscoveryCallback liveDiscoHandler, object liveDiscoState, DiscoDevsParams args) { return _inquiryHandler.BeginInquiry(maxDevices, inquiryLength, asyncCallback, state, liveDiscoHandler, liveDiscoState, StartInquiry, args); } private void StartInquiry() // We are inside the lock. { // BTW InquiryLength is set-up in BeginInquiry. Debug.WriteLine(WidcommUtils.GetTime4Log() + ": calling StartInquiry."); bool success = m_btIf.StartInquiry(); Debug.WriteLine(WidcommUtils.GetTime4Log() + ": StartInquiry ret: " + success); if (!success) throw CommonSocketExceptions.Create_StartInquiry("StartInquiry"); } void StopInquiry() { Utils.MiscUtils.Trace_WriteLine("StopInquiry"); Debug.WriteLine(WidcommUtils.GetTime4Log() + ": StopInquiry done"); m_btIf.StopInquiry(); } class WidcommInquiry : CommonBluetoothInquiry<IBluetoothDeviceInfo> { readonly WidcommBluetoothFactoryBase m_factory; ThreadStart _stopInquiry; //---- internal WidcommInquiry(WidcommBluetoothFactoryBase factory, ThreadStart stopInquiry) { m_factory = factory; _stopInquiry = stopInquiry; } //---- protected override IBluetoothDeviceInfo CreateDeviceInfo(IBluetoothDeviceInfo item) { return item; } //---- internal void HandleDeviceResponded(byte[] bdAddr, byte[] devClass, byte[] deviceName, bool connected) { Utils.MiscUtils.Trace_WriteLine("HandleDeviceResponded"); var bdi = WidcommBluetoothDeviceInfo.CreateFromHandleDeviceResponded( bdAddr, deviceName, devClass, connected, m_factory); Utils.MiscUtils.Trace_WriteLine("HDR: {0} {1} {2} {3}", ToStringQuotedOrNull(bdAddr), ToStringQuotedOrNull(devClass), ToStringQuotedOrNull(deviceName), connected); HandleInquiryResultInd(bdi); Utils.MiscUtils.Trace_WriteLine("exit HDR"); } private static string ToStringQuotedOrNull(byte[] array) { if (array == null) return "(null)"; else return "\"" + BitConverter.ToString(array) + "\""; } internal void HandleInquiryComplete(bool success, UInt16 numResponses) { Utils.MiscUtils.Trace_WriteLine("HandleInquiryComplete"); HandleInquiryComplete(numResponses); Utils.MiscUtils.Trace_WriteLine("exit HandleInquiryComplete"); } protected override void StopInquiry() { _stopInquiry(); } }//class internal List_IBluetoothDeviceInfo EndInquiry(IAsyncResult ar) { // (Can't lock here as that would block the callback methods). // Check is one of queued ar. However this function is only called from // inside BluetoothClient.DiscoverDevices so we can be less careful/helpful!! AR_Inquiry ar2 = (AR_Inquiry)ar; return ar2.EndInvoke(); } internal void HandleDeviceResponded(byte[] bdAddr, byte[] devClass, byte[] deviceName, bool connected) { _inquiryHandler.HandleDeviceResponded(bdAddr, devClass, deviceName, connected); } internal void HandleInquiryComplete(bool success, UInt16 numResponses) { _inquiryHandler.HandleInquiryComplete(success, numResponses); } //---------- const int MaxNumberSdpRecords = 10; // object lockServiceDiscovery = new object(); AsyncResult<ISdpDiscoveryRecordsBuffer, ServiceDiscoveryParams> m_arServiceDiscovery; public IAsyncResult BeginServiceDiscovery(BluetoothAddress address, Guid serviceGuid, SdpSearchScope searchScope, AsyncCallback asyncCallback, Object state) { BeginServiceDiscoveryKillInquiry(); // Just in case the user modifies the original address!!! BluetoothAddress addr2 = (BluetoothAddress)address.Clone(); AsyncResult<ISdpDiscoveryRecordsBuffer, ServiceDiscoveryParams> ar = new AsyncResult<ISdpDiscoveryRecordsBuffer, ServiceDiscoveryParams>(asyncCallback, state, new ServiceDiscoveryParams(addr2, serviceGuid, searchScope)); lock (lockServiceDiscovery) { if (m_arServiceDiscovery != null) throw new NotSupportedException("Currently support only one concurrent Service Lookup operation."); bool success = false; try { m_arServiceDiscovery = ar; bool ret = m_btIf.StartDiscovery(addr2, serviceGuid); Debug.WriteLine(WidcommUtils.GetTime4Log() + ": StartDiscovery ret: " + ret); if (!ret) { WBtRc ee = GetExtendedError(); throw WidcommSocketExceptions.Create_StartDiscovery(ee); } success = true; } finally { if (!success) m_arServiceDiscovery = null; } } return ar; } private void BeginServiceDiscoveryKillInquiry() { Utils.MiscUtils.Trace_WriteLine("BeginServiceDiscovery gonna call StopInquiry."); //IAsyncResult arDD = m_arInquiry; //var whDD = arDD == null ? null : arDD.AsyncWaitHandle; StopInquiry(); //if (whDD != null) { // We NEVER saw the Inquiry Complete event come from Widcomm no // matter how long we waited, so don't bother with this wait. // Leave the StopInquiry in case it is doing some good... //const int KillInquiryWaitTimeout = 5 * 1000; //bool completed = whDD.WaitOne(KillInquiryWaitTimeout, false); //Utils.MiscUtils.Trace_WriteLine("BeginServiceDiscovery saw _arInquiry complete: {0}.", completed); //} } public ISdpDiscoveryRecordsBuffer EndServiceDiscovery(IAsyncResult asyncResult) { AsyncResult<ISdpDiscoveryRecordsBuffer, ServiceDiscoveryParams> checkTypeMatches = m_arServiceDiscovery; AsyncResult<ISdpDiscoveryRecordsBuffer, ServiceDiscoveryParams> ar2 = (AsyncResult<ISdpDiscoveryRecordsBuffer, ServiceDiscoveryParams>)asyncResult; return ar2.EndInvoke(); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "will rethrow")] internal void HandleDiscoveryComplete() { Utils.MiscUtils.Trace_WriteLine("HandleDiscoveryComplete"); AsyncResult<ISdpDiscoveryRecordsBuffer, ServiceDiscoveryParams> sacAr = null; ISdpDiscoveryRecordsBuffer recBuf = null; Exception sacEx = null; try { lock (lockServiceDiscovery) { Debug.Assert(m_arServiceDiscovery != null, "NOT m_arServiceDiscovery != null"); if (m_arServiceDiscovery == null) { return; } // Nothing we can do then! sacAr = m_arServiceDiscovery; m_arServiceDiscovery = null; BluetoothAddress addr; ushort numRecords0; DISCOVERY_RESULT result = m_btIf.GetLastDiscoveryResult(out addr, out numRecords0); if (result != DISCOVERY_RESULT.SUCCESS) { sacEx = WidcommSocketExceptions.Create(result, "ServiceRecordsGetResult"); return; } if (!addr.Equals(sacAr.BeginParameters.address)) { sacEx = new InvalidOperationException("Internal error -- different DiscoveryComplete address."); return; } // Get the records recBuf = m_btIf.ReadDiscoveryRecords(addr, MaxNumberSdpRecords, sacAr.BeginParameters); }//lock } catch (Exception ex) { sacEx = ex; } finally { Debug.Assert(sacAr != null, "out: NOT sacAr != null"); Debug.Assert(m_arServiceDiscovery == null, "out: NOT m_arServiceDiscovery == null"); WaitCallback dlgt = delegate { RaiseDiscoveryComplete(sacAr, recBuf, sacEx); }; ThreadPool.QueueUserWorkItem(dlgt); } } static void RaiseDiscoveryComplete( AsyncResult<ISdpDiscoveryRecordsBuffer, ServiceDiscoveryParams> sacAr, ISdpDiscoveryRecordsBuffer recBuf, Exception sacEx) { if (sacAr != null) { // will always be true! if (sacEx != null) { sacAr.SetAsCompleted(sacEx, false); } else { sacAr.SetAsCompleted(recBuf, false); } } } //---------- public List_IBluetoothDeviceInfo GetKnownRemoteDeviceEntries() { List<REM_DEV_INFO> list = new List<REM_DEV_INFO>(); REM_DEV_INFO info = new REM_DEV_INFO(); int cb = System.Runtime.InteropServices.Marshal.SizeOf(typeof(REM_DEV_INFO)); IntPtr pBuf = System.Runtime.InteropServices.Marshal.AllocHGlobal(cb); try { REM_DEV_INFO_RETURN_CODE ret = m_btIf.GetRemoteDeviceInfo(ref info, pBuf, cb); Utils.MiscUtils.Trace_WriteLine("GRDI: ret: {0}=0x{0:X}", ret); while (ret == REM_DEV_INFO_RETURN_CODE.SUCCESS) { list.Add(info); // COPY it into the list ret = m_btIf.GetNextRemoteDeviceInfo(ref info, pBuf, cb); Utils.MiscUtils.Trace_WriteLine("GnRDI: ret: {0}=0x{0:X}", ret); }//while if (ret != REM_DEV_INFO_RETURN_CODE.EOF) throw WidcommSocketExceptions.Create(ret, "Get[Next]RemoteDeviceInfo"); // List_IBluetoothDeviceInfo bdiList = new List_IBluetoothDeviceInfo(list.Count); foreach (REM_DEV_INFO cur in list) { IBluetoothDeviceInfo bdi = WidcommBluetoothDeviceInfo.CreateFromStoredRemoteDeviceInfo(cur, m_factory); bdiList.Add(bdi); } return bdiList; } finally { System.Runtime.InteropServices.Marshal.FreeHGlobal(pBuf); } } //---------- const string DevicesRegPath = @"Software\WIDCOMM\BTConfig\Devices\"; // "HKEY_LOCAL_MACHINE\..." [SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")] private static string GetWidcommDeviceKeyName(BluetoothAddress device) { // See ReadDeviceFromRegistryAndCheckAndSetIfPaired_ return device.ToString("C").ToLower(CultureInfo.InvariantCulture); } public List_IBluetoothDeviceInfo ReadKnownDevicesFromRegistry() { // Multiple keys, one per device, named with address e.g. 00:11:22:33:44:55 // Each with values: BRCMStack DWORD, Code DWORD, DevClass DWORD, etc etc // List_IBluetoothDeviceInfo devices = new List_IBluetoothDeviceInfo(); using (RegistryKey rkDevices = Registry.LocalMachine.OpenSubKey(DevicesRegPath)) { if (rkDevices == null) { // The Registry key is created when the first device is stored, // so on a new device it doesn't exist. So return an empty list. return devices; // IOException is what GetValueKind throws. //throw new System.IO.IOException("Widcomm 'Devices' key not found in the Registry."); } foreach (string itemName in rkDevices.GetSubKeyNames()) { using (RegistryKey rkItem = rkDevices.OpenSubKey(itemName)) { WidcommBluetoothDeviceInfo bdi = ReadDeviceFromRegistryAndCheckAndSetIfPaired_( itemName, rkItem, m_factory); devices.Add(bdi); } }//for } return devices; } private WidcommBluetoothDeviceInfo ReadDeviceFromRegistryAndCheckAndSetIfPaired_( string itemName, RegistryKey rkItem, WidcommBluetoothFactoryBase factory) { BluetoothAddress address = BluetoothAddress.Parse(itemName); Debug.Assert(GetWidcommDeviceKeyName(address).Equals(itemName, StringComparison.OrdinalIgnoreCase), "itemName not colons?: " + itemName); // byte[] devName, devClass ; try { devName = Registry_ReadBinaryValue(rkItem, "Name"); devClass = Registry_ReadBinaryValue(rkItem, "DevClass"); } catch (IOException) { // "The specified registry key does not exist." Debug.WriteLine("Partial device info in Registry for: {0}.", itemName); return null; } Int32? trusted = Registry_ReadDwordValue_Optional(rkItem, "TrustedMask"); WidcommBluetoothDeviceInfo bdi = CreateFromStoredRemoteDeviceInfo(address, devName, devClass, factory); WidcommBluetoothDeviceInfo.CheckAndSetIfPaired(bdi, factory); return bdi; } internal WidcommBluetoothDeviceInfo ReadDeviceFromRegistryAndCheckAndSetIfPaired(BluetoothAddress address, WidcommBluetoothFactoryBase factory) { using (RegistryKey rkDevices = Registry.LocalMachine.OpenSubKey(DevicesRegPath)) { if (rkDevices == null) { // The Registry key is created when the first device is stored, // so on a new device it doesn't exist. So return an empty list. return null; } string itemName = address.ToString("C"); using (RegistryKey rkItem = rkDevices.OpenSubKey(itemName)) { if (rkItem == null) { return null; } WidcommBluetoothDeviceInfo bdi = ReadDeviceFromRegistryAndCheckAndSetIfPaired_(itemName, rkItem, factory); return bdi; } } } private static WidcommBluetoothDeviceInfo CreateFromStoredRemoteDeviceInfo( BluetoothAddress devAddress, byte[] devName, byte[] devClass, WidcommBluetoothFactoryBase factory) { REM_DEV_INFO rdi = new REM_DEV_INFO(); rdi.bda = WidcommUtils.FromBluetoothAddress(devAddress); rdi.bd_name = devName; rdi.dev_class = devClass; // rdi.b_connected = ... // rdi.b_paired = ... WidcommBluetoothDeviceInfo bdi = WidcommBluetoothDeviceInfo.CreateFromStoredRemoteDeviceInfo(rdi, factory); string nameStr = bdi.DeviceName; Debug.Assert(nameStr.Length == 0 || nameStr[nameStr.Length - 1] != 0, "null terminator!!"); int idxDbg; Debug.Assert((idxDbg = nameStr.IndexOf((char)0)) == -1, "null terminator!! at: " + idxDbg); return bdi; } private static byte[] Registry_ReadBinaryValue(RegistryKey rkItem, string name) { Registry_CheckIsKind(rkItem, name, RegistryValueKind.Binary); byte[] raw = (byte[])rkItem.GetValue(name); return raw; } private static Int32? Registry_ReadDwordValue_Optional(RegistryKey rkItem, string name) { object val = rkItem.GetValue(name); if (val == null) return null; Registry_CheckIsKind(rkItem, name, RegistryValueKind.DWord); return (Int32)val; } private static void Registry_CheckIsKind(RegistryKey rkItem, string name, RegistryValueKind expectedKind) { if (PlatformVerification.IsMonoRuntime) { Utils.MiscUtils.Trace_WriteLine("Skipping Registry_CheckIsKind check on Mono as it's not supported."); return; } RegistryValueKind kind = rkItem.GetValueKind(name); if (kind != expectedKind) { string msg = string.Format(System.Globalization.CultureInfo.InvariantCulture, "Expected '{0}':'{1}', to be '{2}' but was '{3}'.", rkItem.Name, name, expectedKind, kind); throw new FormatException(msg); } } /// <summary> /// Remove the device by deleting it from the Registry. /// </summary> /// <param name="device">The device address.</param> /// <returns>Whether the device is deleted -- it is no longer a remembered device. /// </returns> internal static bool DeleteKnownDevice(BluetoothAddress device) { string itemName = GetWidcommDeviceKeyName(device); using (RegistryKey rkDevices = Registry.LocalMachine.OpenSubKey(DevicesRegPath, true)) { using (RegistryKey theOne = rkDevices.OpenSubKey(itemName, false)) { if (theOne == null) // Isn't present. return true; } try { rkDevices.DeleteSubKeyTree(itemName); return true; } catch (System.Security.SecurityException ex) { Utils.MiscUtils.Trace_WriteLine("DeleteKnownDevice DeleteSubKeyTree(" + itemName + "): " + ExceptionExtension.ToStringNoStackTrace(ex)); } catch (UnauthorizedAccessException ex) { Utils.MiscUtils.Trace_WriteLine("DeleteKnownDevice DeleteSubKeyTree(" + itemName + "): " + ExceptionExtension.ToStringNoStackTrace(ex)); } return false; } } //---------- internal bool GetLocalDeviceVersionInfo(ref DEV_VER_INFO m_dvi) { return m_btIf.GetLocalDeviceVersionInfo(ref m_dvi); } internal bool GetLocalDeviceInfoBdAddr(byte[] bdAddr) { return m_btIf.GetLocalDeviceInfoBdAddr(bdAddr); } internal bool GetLocalDeviceName(byte[] bdName) { return m_btIf.GetLocalDeviceName(bdName); } internal void IsStackUpAndRadioReady(out bool stackServerUp, out bool deviceReady) { m_btIf.IsStackUpAndRadioReady(out stackServerUp, out deviceReady); } internal void IsDeviceConnectableDiscoverable(out bool conno, out bool disco) { m_btIf.IsDeviceConnectableDiscoverable(out conno, out disco); } internal void SetDeviceConnectableDiscoverable(bool connectable, bool forPairedOnly, bool discoverable) { if (connectable || discoverable) { EnsureLoaded(); } m_btIf.SetDeviceConnectableDiscoverable(connectable, forPairedOnly, discoverable); } internal int GetRssi(byte[] bd_addr) { return m_btIf.GetRssi(bd_addr); } internal bool BondQuery(byte[] bd_addr) { return m_btIf.BondQuery(bd_addr); } internal BOND_RETURN_CODE Bond(BluetoothAddress address, string passphrase) { return m_btIf.Bond(address, passphrase); } internal bool UnBond(BluetoothAddress address) { return m_btIf.UnBond(address); } //---------- /// <summary> /// Call CBtIf::GetExtendedError. /// </summary> /// - /// <remarks> /// <para>Is not currently used anywhere... /// </para> /// <para>Not supported on Widcomm WCE WM/WinCE, we (natively) return -1. /// </para> /// </remarks> /// - /// <returns>A <see cref="T:InTheHand.Net.Bluetooth.Widcomm.WBtRc"/> value.</returns> private WBtRc GetExtendedError() { return m_btIf.GetExtendedError(); } /// <summary> /// CBtIf::IsRemoteDevicePresent /// </summary> /// - /// <remarks> /// <note>"added BTW and SDK 5.0.1.1000"</note> /// <note>"added BTW-CE and SDK 1.7.1.2700"</note> /// </remarks> internal SDK_RETURN_CODE IsRemoteDevicePresent(byte[] bd_addr) { return m_btIf.IsRemoteDevicePresent(bd_addr); } /// <summary> /// CBtIf::IsRemoteDeviceConnected /// </summary> /// - /// <remarks> /// <note>"added BTW 5.0.1.300, SDK 5.0"</note> /// <note>"added BTW-CE and SDK 1.7.1.2700"</note> /// </remarks> internal bool IsRemoteDeviceConnected(byte[] bd_addr) { return m_btIf.IsRemoteDeviceConnected(bd_addr); } //---------- [DebuggerStepThrough] public static bool IsWidcommSingleThread(WidcommPortSingleThreader st) { return WidcommPortSingleThreader.IsWidcommSingleThread(st); } static T GetStaticData<T>(LocalDataStoreSlot slot) where T : struct { object o = Thread.GetData(slot); T v = o == null ? default(T) : (T)o; return v; } }//class internal enum SdpSearchScope { Anywhere, ServiceClassOnly } sealed class ServiceDiscoveryParams { readonly internal BluetoothAddress address; readonly internal Guid serviceGuid; readonly internal SdpSearchScope searchScope; internal ServiceDiscoveryParams(BluetoothAddress address, Guid serviceGuid, SdpSearchScope searchScope) { this.address = address; this.serviceGuid = serviceGuid; if (searchScope != SdpSearchScope.Anywhere && searchScope != SdpSearchScope.ServiceClassOnly) throw new ArgumentException("Unrecognized value for SdpSearchScope enum.", "searchScope"); this.searchScope = searchScope; } } }
namespace AdMaiora.AppKit { using System; using System.Collections.Generic; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Gms.Common; using Android.Support.V4.App; using Android.Media; using Firebase.Iid; using Firebase.Messaging; using AdMaiora.AppKit.Data; using AdMaiora.AppKit.Notifications; using Firebase; [Service] [IntentFilter(new[] { "com.google.firebase.INSTANCE_ID_EVENT" })] class AppKitFirebaseIdService : FirebaseInstanceIdService { #region Service Methods public override void OnTokenRefresh() { string token = FirebaseInstanceId.Instance.Token; AppKitApplication.Current?.OnRegisteredForRemoteNotifications(token); } #endregion } [Service] [IntentFilter(new[] { "com.google.firebase.MESSAGING_EVENT" })] class AppKitFirebaseMessagingService : FirebaseMessagingService { #region Constants and Fields private static PushNotificationData _launchNotification; #endregion #region Helper Methods public static bool HasStartUpNotification(out PushNotificationData launchNotification) { launchNotification = null; if (_launchNotification == null) return false; launchNotification = _launchNotification; _launchNotification = null; return true; } public static PushNotificationData GetNotificationData(RemoteMessage message) { /* * JSON Sample for notifications * * * { "data": { "title": "", "body": "", "action": 0, // Default value 0 stands for plain message (title and body) "payload": { // Optional. A custom JSON payload to be used in conjunction with the action } } } * */ if (message == null) return null; var data = new PushNotificationData(); data.Add("title", message.Data.ContainsKey("title") ? message.Data["title"] : null); data.Add("body", message.Data.ContainsKey("body") ? message.Data["body"] : null); data.Add("action", message.Data.ContainsKey("action") ? Int32.Parse(message.Data["action"]) : 0); data.Add("payload", message.Data.ContainsKey("payload") ? message.Data["payload"] : null); return data; } #endregion #region Service Methods public override void OnMessageReceived(RemoteMessage message) { if(AppKitApplication.Current == null || !AppKitApplication.Current.IsApplicationInForeground) { var data = GetNotificationData(message); string title = (string)data["title"]; string text = (string)data["body"]; if(AppKitApplication.Current == null) _launchNotification = data; Intent intent = new Intent(); intent.AddFlags(ActivityFlags.ReorderToFront); intent.SetComponent(GetRootActivityComponentName()); PendingIntent pendingIntent = PendingIntent.GetActivity(this, 0, intent, PendingIntentFlags.UpdateCurrent); var notificationBuilder = new NotificationCompat.Builder(this) .SetSmallIcon(GetSmallIconResourceId()) .SetContentIntent(pendingIntent) .SetContentTitle(title) .SetContentText(text) .SetSound(RingtoneManager.GetDefaultUri(RingtoneType.Notification)) .SetAutoCancel(true); if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop) { notificationBuilder.SetDefaults(NotificationCompat.DefaultVibrate); notificationBuilder.SetPriority(NotificationCompat.PriorityDefault); notificationBuilder.SetVibrate(new long[] { 50, 50 }); } string channelID = "PushMainChannel"; if(Build.VERSION.SdkInt >= BuildVersionCodes.O) { NotificationChannel channel = new NotificationChannel(channelID, "PushMainChannel", NotificationImportance.High); notificationBuilder.SetChannelId(channelID); var notificationManager = NotificationManager.FromContext(this); notificationManager.CreateNotificationChannel(channel); notificationManager.Notify(0, notificationBuilder.Build()); } else { var notificationManager = NotificationManager.FromContext(this); notificationManager.Notify(0, notificationBuilder.Build()); } } AppKitApplication.Current?.OnReceivedRemoteNotification(message); } #endregion #region Methods private ComponentName GetRootActivityComponentName() { string packageName = Application.Context.PackageName; Intent intent = Application.Context.PackageManager.GetLaunchIntentForPackage(packageName); return intent.Component; } private int GetSmallIconResourceId() { string packageName = Application.Context.PackageName; int id = -1; string[] names = { "icon_push", "ic_push", "ic_notification", "ic_launcher", "icon" }; foreach (string name in names) { id = Application.Context.Resources.GetIdentifier(name, "drawable", packageName); if (id != -1) return id; } return id; } #endregion } public class AppKitApplication : Application { #region Inner Classes public class LifecycleManager : Java.Lang.Object, Android.App.Application.IActivityLifecycleCallbacks { #region Constants and Fields private int _resumed; private int _paused; private int _started; private int _stopped; private bool _inPause; private Stack<Activity> _activities; #endregion #region Events public event EventHandler Resumed; public event EventHandler Paused; #endregion #region Properties public Activity CurrentActivity { get { if (_activities == null) return null; return _activities.Peek(); } } public bool IsApplicationRunning { get { return _started > _stopped; } } public bool IsApplicationInForeground { get { return _resumed > _paused; } } #endregion #region IActivityLifecycleCallbacks Methods public void OnActivityCreated(Activity activity, Bundle savedInstanceState) { //Android.Util.Log.Info(GlobalSettings.AppLogTag, activity.GetType().Name + " Created"); } public void OnActivityStarted(Activity activity) { ++_started; //Android.Util.Log.Info(GlobalSettings.AppLogTag, activity.GetType().Name + " Started"); } public void OnActivityResumed(Activity activity) { ++_resumed; if (_inPause) { _inPause = false; if (Resumed != null) Resumed(this, EventArgs.Empty); } if (_activities == null) _activities = new Stack<Activity>(); _activities.Push(activity); //Android.Util.Log.Info(GlobalSettings.AppLogTag, activity.GetType().Name + " Resumed"); } public void OnActivityPaused(Activity activity) { ++_paused; if (!this.IsApplicationInForeground) { _inPause = true; if (Paused != null) Paused(this, EventArgs.Empty); } if (_activities != null) _activities.Pop(); //Android.Util.Log.Info(GlobalSettings.AppLogTag, activity.GetType().Name + " Paused"); } public void OnActivitySaveInstanceState(Activity activity, Bundle outState) { } public void OnActivityStopped(Activity activity) { ++_stopped; //Android.Util.Log.Info(GlobalSettings.AppLogTag, activity.GetType().Name + " Stopped"); } public void OnActivityDestroyed(Activity activity) { //Android.Util.Log.Info(GlobalSettings.AppLogTag, activity.GetType().Name + " Destroyed"); } #endregion } #endregion #region Constants and Fields private LifecycleManager _lfcb; #endregion #region Constructors public AppKitApplication(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer) { AppKitApplication.Current = this; // Handle activities lifecycle _lfcb = new AppKitApplication.LifecycleManager(); _lfcb.Resumed += App_Resumed; _lfcb.Paused += App_Paused; RegisterActivityLifecycleCallbacks(_lfcb); } #endregion #region Properties public static AppKitApplication Current { get; private set; } public bool IsApplicationRunning { get { return _lfcb.IsApplicationRunning; } } public bool IsApplicationInForeground { get { return _lfcb.IsApplicationInForeground; } } #endregion #region Application Methods public override void OnCreate() { base.OnCreate(); PushNotificationData notification = null; if (AppKitFirebaseMessagingService.HasStartUpNotification(out notification)) PushNotificationManager.Current.StorePendingNotification(notification); } public virtual void OnRegisteredForRemoteNotifications(string token) { } public virtual void OnFailedToRegisterForRemoteNotifications(Exception ex) { } public virtual void OnReceivedRemoteNotification(RemoteMessage message) { PushNotificationData notification = AppKitFirebaseMessagingService.GetNotificationData(message); OnReceivedRemoteNotification(notification); } public virtual void OnReceivedRemoteNotification(PushNotificationData data) { } public virtual void OnResume() { } public virtual void OnPause() { } #endregion #region Methods protected override void Dispose(bool disposing) { base.Dispose(disposing); if (_lfcb != null) { UnregisterActivityLifecycleCallbacks(_lfcb); _lfcb.Resumed -= App_Resumed; _lfcb.Paused -= App_Paused; } } protected void RegisterForRemoteNotifications() { // Configure Push Notifications int resultCode = GoogleApiAvailability.Instance.IsGooglePlayServicesAvailable(this.ApplicationContext); if (resultCode == ConnectionResult.Success) { // Everything is fine! } else { OnFailedToRegisterForRemoteNotifications(new GooglePlayServicesNotAvailableException(resultCode)); } } #endregion #region Event Handlers private void App_Resumed(object sender, EventArgs e) { OnResume(); } private void App_Paused(object sender, EventArgs e) { OnPause(); } #endregion } }
using System.IO; using System; using Aspose.Pdf.Facades; using Aspose.Pdf.Devices; using Aspose.Pdf.Annotations; using System.Drawing; namespace Aspose.Pdf.Examples.CSharp.AsposePDFFacades.TechnicalArticles { public class PDFToTIFFConversion { public static void Run() { // ExStart:PDFToTIFFConversion // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdfFacades_TechnicalArticles(); // Create PdfConverter object and bind input PDF file PdfConverter pdfConverter = new PdfConverter(); pdfConverter.Resolution = new Aspose.Pdf.Devices.Resolution(300); pdfConverter.BindPdf(dataDir + "inFile.pdf"); pdfConverter.DoConvert(); // Create TiffSettings object and set ColorDepth TiffSettings tiffSettings = new TiffSettings(); tiffSettings.Depth = ColorDepth.Format1bpp; // Convert to TIFF image pdfConverter.SaveAsTIFF(dataDir + "PDFToTIFFConversion_out.tif", 300, 300, tiffSettings); pdfConverter.Close(); // ExEnd:PDFToTIFFConversion } public static void NewApproach() { // ExStart:NewApproach // The path to the documents directory. string dataDir = RunExamples.GetDataDir_AsposePdfFacades_TechnicalArticles(); // Create PdfConverter object and bind input PDF file PdfConverter pdfConverter = new PdfConverter(); pdfConverter.BindPdf(dataDir + "inFile.pdf"); pdfConverter.DoConvert(); // Create TiffSettings object and set CompressionType TiffSettings tiffSettings = new TiffSettings(); // Convert to TIFF image pdfConverter.SaveAsTIFF(dataDir + "PDFToTIFFConversion_out.tif", 300, 300, tiffSettings, new WinAPIIndexBitmapConverter()); pdfConverter.Close(); // ExEnd:NewApproach } } // ExStart:IIndexBitmapConverter public class WinAPIIndexBitmapConverter : IIndexBitmapConverter { public Bitmap Get1BppImage(Bitmap src) { return CopyToBpp(src, 1); } public Bitmap Get4BppImage(Bitmap src) { return CopyToBpp(src, 4); } public Bitmap Get8BppImage(Bitmap src) { return CopyToBpp(src, 8); } [System.Runtime.InteropServices.DllImport("gdi32.dll")] public static extern bool DeleteObject(IntPtr hObject); [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern IntPtr GetDC(IntPtr hwnd); [System.Runtime.InteropServices.DllImport("gdi32.dll")] public static extern IntPtr CreateCompatibleDC(IntPtr hdc); [System.Runtime.InteropServices.DllImport("user32.dll")] public static extern int ReleaseDC(IntPtr hwnd, IntPtr hdc); [System.Runtime.InteropServices.DllImport("gdi32.dll")] public static extern int DeleteDC(IntPtr hdc); [System.Runtime.InteropServices.DllImport("gdi32.dll")] public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj); [System.Runtime.InteropServices.DllImport("gdi32.dll")] public static extern int BitBlt(IntPtr hdcDst, int xDst, int yDst, int w, int h, IntPtr hdcSrc, int xSrc, int ySrc, int rop); static int SRCCOPY = 0x00CC0020; [System.Runtime.InteropServices.DllImport("gdi32.dll")] static extern IntPtr CreateDIBSection(IntPtr hdc, ref BITMAPINFO bmi, uint Usage, out IntPtr bits, IntPtr hSection, uint dwOffset); static uint BI_RGB = 0; static uint DIB_RGB_COLORS = 0; [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)] public struct BITMAPINFO { public uint biSize; public int biWidth, biHeight; public short biPlanes, biBitCount; public uint biCompression, biSizeImage; public int biXPelsPerMeter, biYPelsPerMeter; public uint biClrUsed, biClrImportant; [System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst = 256)] public uint[] cols; } static uint MAKERGB(int r, int g, int b) { return ((uint)(b & 255)) | ((uint)((r & 255) << 8)) | ((uint)((g & 255) << 16)); } //////////// /// <summary> /// Copies a bitmap into a 1bpp/8bpp bitmap of the same dimensions, fast /// </summary> /// <param name="b">original bitmap</param> /// <param name="bpp">1 or 8, target bpp</param> /// <returns>a 1bpp copy of the bitmap</returns> private Bitmap CopyToBpp(System.Drawing.Bitmap b, int bpp) { if (bpp != 1 && bpp != 8 && bpp != 4) throw new System.ArgumentException("1 or 4 or 8 ", "bpp"); // Plan: built into Windows GDI is the ability to convert // Bitmaps from one format to another. Most of the time, this // Job is actually done by the graphics hardware accelerator card // And so is extremely fast. The rest of the time, the job is done by // Very fast native code. // We will call into this GDI functionality from C#. Our plan: // (1) Convert our Bitmap into a GDI hbitmap (ie. copy unmanaged->managed) // (2) Create a GDI monochrome hbitmap // (3) Use GDI "BitBlt" function to copy from hbitmap into monochrome (as above) // (4) Convert the monochrone hbitmap into a Bitmap (ie. copy unmanaged->managed) int w = b.Width, h = b.Height; IntPtr hbm = b.GetHbitmap(); // This is step (1) // // Step (2): create the monochrome bitmap. // "BITMAPINFO" is an interop-struct which we define below. // In GDI terms, it's a BITMAPHEADERINFO followed by an array of two RGBQUADs BITMAPINFO bmi = new BITMAPINFO(); bmi.biSize = 40; // The size of the BITMAPHEADERINFO struct bmi.biWidth = w; bmi.biHeight = h; bmi.biPlanes = 1; // "planes" are confusing. We always use just 1. Read MSDN for more info. bmi.biBitCount = (short)bpp; // Ie. 1bpp or 8bpp bmi.biCompression = BI_RGB; // Ie. the pixels in our RGBQUAD table are stored as RGBs, not palette indexes bmi.biSizeImage = (uint)(((w + 7) & 0xFFFFFFF8) * h / 8); bmi.biXPelsPerMeter = 1000000; // Not really important bmi.biYPelsPerMeter = 1000000; // Not really important // Now for the colour table. uint ncols = (uint)1 << bpp; // 2 colours for 1bpp; 256 colours for 8bpp bmi.biClrUsed = ncols; bmi.biClrImportant = ncols; bmi.cols = new uint[256]; // The structure always has fixed size 256, even if we end up using fewer colours if (bpp == 1) { bmi.cols[0] = MAKERGB(0, 0, 0); bmi.cols[1] = MAKERGB(255, 255, 255); } else if (bpp == 4) { // For 8bpp we've created an palette with just greyscale colours. // You can set up any palette you want here. Here are some possibilities: // Rainbow: bmi.biClrUsed = 16; bmi.biClrImportant = 16; int[] colv = new int[16] { 8, 24, 38, 56, 72, 88, 104, 120, 136, 152, 168, 184, 210, 216, 232, 248 }; // for (int i = 0; i < 16; i++) bmi.cols[i] = MAKERGB(colv[i], colv[i], colv[i]); } else if (bpp == 8) { // For 8bpp we've created an palette with just greyscale colours. // You can set up any palette you want here. Here are some possibilities: // Rainbow: bmi.biClrUsed = 216; bmi.biClrImportant = 216; int[] colv = new int[6] { 0, 51, 102, 153, 204, 255 }; for (int i = 0; i < 216; i++) bmi.cols[i] = MAKERGB(colv[i / 36], colv[(i / 6) % 6], colv[i % 6]); // Optimal: a difficult topic: http:// En.wikipedia.org/wiki/Color_quantization } // // Now create the indexed bitmap "hbm0" IntPtr bits0; // Not used for our purposes. It returns a pointer to the raw bits that make up the bitmap. IntPtr hbm0 = CreateDIBSection(IntPtr.Zero, ref bmi, DIB_RGB_COLORS, out bits0, IntPtr.Zero, 0); // // Step (3): use GDI's BitBlt function to copy from original hbitmap into monocrhome bitmap // GDI programming is kind of confusing... nb. The GDI equivalent of "Graphics" is called a "DC". IntPtr sdc = GetDC(IntPtr.Zero); // First we obtain the DC for the screen // Next, create a DC for the original hbitmap IntPtr hdc = CreateCompatibleDC(sdc); SelectObject(hdc, hbm); // And create a DC for the monochrome hbitmap IntPtr hdc0 = CreateCompatibleDC(sdc); SelectObject(hdc0, hbm0); // Now we can do the BitBlt: BitBlt(hdc0, 0, 0, w, h, hdc, 0, 0, SRCCOPY); // Step (4): convert this monochrome hbitmap back into a Bitmap: Bitmap b0 = System.Drawing.Image.FromHbitmap(hbm0); // // Finally some cleanup. DeleteDC(hdc); DeleteDC(hdc0); ReleaseDC(IntPtr.Zero, sdc); DeleteObject(hbm); DeleteObject(hbm0); // return b0; } } // ExEnd:IIndexBitmapConverter }
using System.Collections.Generic; using System.Collections; using System.Text.RegularExpressions; using System.IO; using System.Linq; using System; namespace UnityEditor.iOS.Xcode.PBX { class PBXElement { protected PBXElement() {} // convenience methods public string AsString() { return ((PBXElementString)this).value; } public PBXElementArray AsArray() { return (PBXElementArray)this; } public PBXElementDict AsDict() { return (PBXElementDict)this; } public PBXElement this[string key] { get { return AsDict()[key]; } set { AsDict()[key] = value; } } } class PBXElementString : PBXElement { public PBXElementString(string v) { value = v; } public string value; } class PBXElementDict : PBXElement { public PBXElementDict() : base() {} private SortedDictionary<string, PBXElement> m_PrivateValue = new SortedDictionary<string, PBXElement>(); public IDictionary<string, PBXElement> values { get { return m_PrivateValue; }} new public PBXElement this[string key] { get { if (values.ContainsKey(key)) return values[key]; return null; } set { this.values[key] = value; } } public bool Contains(string key) { return values.ContainsKey(key); } public void Remove(string key) { values.Remove(key); } public void SetString(string key, string val) { values[key] = new PBXElementString(val); } public PBXElementArray CreateArray(string key) { var v = new PBXElementArray(); values[key] = v; return v; } public PBXElementDict CreateDict(string key) { var v = new PBXElementDict(); values[key] = v; return v; } } class PBXElementArray : PBXElement { public PBXElementArray() : base() {} public List<PBXElement> values = new List<PBXElement>(); // convenience methods public void AddString(string val) { values.Add(new PBXElementString(val)); } public PBXElementArray AddArray() { var v = new PBXElementArray(); values.Add(v); return v; } public PBXElementDict AddDict() { var v = new PBXElementDict(); values.Add(v); return v; } } internal class PBXObject { public string guid; protected PBXElementDict m_Properties = new PBXElementDict(); internal void SetPropertiesWhenSerializing(PBXElementDict props) { m_Properties = props; } internal PBXElementDict GetPropertiesWhenSerializing() { return m_Properties; } // returns null if it does not exist protected string GetPropertyString(string name) { var prop = m_Properties[name]; if (prop == null) return null; return prop.AsString(); } protected void SetPropertyString(string name, string value) { if (value == null) m_Properties.Remove(name); else m_Properties.SetString(name, value); } protected List<string> GetPropertyList(string name) { var prop = m_Properties[name]; if (prop == null) return null; var list = new List<string>(); foreach (var el in prop.AsArray().values) list.Add(el.AsString()); return list; } protected void SetPropertyList(string name, List<string> value) { if (value == null) m_Properties.Remove(name); else { var array = m_Properties.CreateArray(name); foreach (string val in value) array.AddString(val); } } private static PropertyCommentChecker checkerData = new PropertyCommentChecker(); internal virtual PropertyCommentChecker checker { get { return checkerData; } } internal virtual bool shouldCompact { get { return false; } } public virtual void UpdateProps() {} // Updates the props from cached variables public virtual void UpdateVars() {} // Updates the cached variables from underlying props } internal class PBXBuildFile : PBXObject { public string fileRef; public string compileFlags; public bool weak; private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "fileRef/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } internal override bool shouldCompact { get { return true; } } public static PBXBuildFile CreateFromFile(string fileRefGUID, bool weak, string compileFlags) { PBXBuildFile buildFile = new PBXBuildFile(); buildFile.guid = PBXGUID.Generate(); buildFile.SetPropertyString("isa", "PBXBuildFile"); buildFile.fileRef = fileRefGUID; buildFile.compileFlags = compileFlags; buildFile.weak = weak; return buildFile; } PBXElementDict GetSettingsDict() { if (m_Properties.Contains("settings")) return m_Properties["settings"].AsDict(); else return m_Properties.CreateDict("settings"); } public override void UpdateProps() { SetPropertyString("fileRef", fileRef); if (compileFlags != null && compileFlags != "") { GetSettingsDict().SetString("COMPILER_FLAGS", compileFlags); } if (weak) { var dict = GetSettingsDict(); PBXElementArray attrs = null; if (dict.Contains("ATTRIBUTES")) attrs = dict["ATTRIBUTES"].AsArray(); else attrs = dict.CreateArray("ATTRIBUTES"); bool exists = false; foreach (var value in attrs.values) { if (value is PBXElementString && value.AsString() == "Weak") exists = true; } if (!exists) attrs.AddString("Weak"); } } public override void UpdateVars() { fileRef = GetPropertyString("fileRef"); compileFlags = null; weak = false; if (m_Properties.Contains("settings")) { var dict = m_Properties["settings"].AsDict(); if (dict.Contains("COMPILER_FLAGS")) compileFlags = dict["COMPILER_FLAGS"].AsString(); if (dict.Contains("ATTRIBUTES")) { var attrs = dict["ATTRIBUTES"].AsArray(); foreach (var value in attrs.values) { if (value is PBXElementString && value.AsString() == "Weak") weak = true; } } } } } internal class PBXFileReference : PBXObject { public string path; public string name; public PBXSourceTree tree; internal override bool shouldCompact { get { return true; } } public static PBXFileReference CreateFromFile(string path, string projectFileName, PBXSourceTree tree) { string guid = PBXGUID.Generate(); PBXFileReference fileRef = new PBXFileReference(); fileRef.SetPropertyString("isa", "PBXFileReference"); fileRef.guid = guid; fileRef.path = path; fileRef.name = projectFileName; fileRef.tree = tree; return fileRef; } public override void UpdateProps() { string ext = null; if (name != null) ext = Path.GetExtension(name); else if (path != null) ext = Path.GetExtension(path); if (ext != null) { if (FileTypeUtils.IsFileTypeExplicit(ext)) SetPropertyString("explicitFileType", FileTypeUtils.GetTypeName(ext)); else SetPropertyString("lastKnownFileType", FileTypeUtils.GetTypeName(ext)); } if (path == name) SetPropertyString("name", null); else SetPropertyString("name", name); if (path == null) SetPropertyString("path", ""); else SetPropertyString("path", path); SetPropertyString("sourceTree", FileTypeUtils.SourceTreeDesc(tree)); } public override void UpdateVars() { name = GetPropertyString("name"); path = GetPropertyString("path"); if (name == null) name = path; if (path == null) path = ""; tree = FileTypeUtils.ParseSourceTree(GetPropertyString("sourceTree")); } } class GUIDList : IEnumerable<string> { private List<string> m_List = new List<string>(); public GUIDList() {} public GUIDList(List<string> data) { m_List = data; } public static implicit operator List<string>(GUIDList list) { return list.m_List; } public static implicit operator GUIDList(List<string> data) { return new GUIDList(data); } public void AddGUID(string guid) { m_List.Add(guid); } public void RemoveGUID(string guid) { m_List.RemoveAll(x => x == guid); } public bool Contains(string guid) { return m_List.Contains(guid); } public int Count { get { return m_List.Count; } } public void Clear() { m_List.Clear(); } IEnumerator<string> IEnumerable<string>.GetEnumerator() { return m_List.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return m_List.GetEnumerator(); } } internal class XCConfigurationList : PBXObject { public GUIDList buildConfigs; private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "buildConfigurations/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } public static XCConfigurationList Create() { var res = new XCConfigurationList(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "XCConfigurationList"); res.buildConfigs = new GUIDList(); res.SetPropertyString("defaultConfigurationIsVisible", "0"); return res; } public override void UpdateProps() { SetPropertyList("buildConfigurations", buildConfigs); } public override void UpdateVars() { buildConfigs = GetPropertyList("buildConfigurations"); } } internal class PBXGroup : PBXObject { public GUIDList children; public PBXSourceTree tree; public string name, path; private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "children/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } // name must not contain '/' public static PBXGroup Create(string name, string path, PBXSourceTree tree) { if (name.Contains("/")) throw new Exception("Group name must not contain '/'"); PBXGroup gr = new PBXGroup(); gr.guid = PBXGUID.Generate(); gr.SetPropertyString("isa", "PBXGroup"); gr.name = name; gr.path = path; gr.tree = PBXSourceTree.Group; gr.children = new GUIDList(); return gr; } public static PBXGroup CreateRelative(string name) { return Create(name, name, PBXSourceTree.Group); } public override void UpdateProps() { // The name property is set only if it is different from the path property SetPropertyList("children", children); if (name == path) SetPropertyString("name", null); else SetPropertyString("name", name); if (path == "") SetPropertyString("path", null); else SetPropertyString("path", path); SetPropertyString("sourceTree", FileTypeUtils.SourceTreeDesc(tree)); } public override void UpdateVars() { children = GetPropertyList("children"); path = GetPropertyString("path"); name = GetPropertyString("name"); if (name == null) name = path; if (path == null) path = ""; tree = FileTypeUtils.ParseSourceTree(GetPropertyString("sourceTree")); } } internal class PBXVariantGroup : PBXGroup { } internal class PBXNativeTarget : PBXObject { public GUIDList phases; public string buildConfigList; // guid public string name; public GUIDList dependencies; private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "buildPhases/*", "buildRules/*", "dependencies/*", "productReference/*", "buildConfigurationList/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } public static PBXNativeTarget Create(string name, string productRef, string productType, string buildConfigList) { var res = new PBXNativeTarget(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXNativeTarget"); res.buildConfigList = buildConfigList; res.phases = new GUIDList(); res.SetPropertyList("buildRules", new List<string>()); res.dependencies = new GUIDList(); res.name = name; res.SetPropertyString("productName", name); res.SetPropertyString("productReference", productRef); res.SetPropertyString("productType", productType); return res; } public override void UpdateProps() { SetPropertyString("buildConfigurationList", buildConfigList); SetPropertyString("name", name); SetPropertyList("buildPhases", phases); SetPropertyList("dependencies", dependencies); } public override void UpdateVars() { buildConfigList = GetPropertyString("buildConfigurationList"); name = GetPropertyString("name"); phases = GetPropertyList("buildPhases"); dependencies = GetPropertyList("dependencies"); } } internal class FileGUIDListBase : PBXObject { public GUIDList files; private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "files/*", }); internal override PropertyCommentChecker checker { get { return checkerData; } } public override void UpdateProps() { SetPropertyList("files", files); } public override void UpdateVars() { files = GetPropertyList("files"); } } internal class PBXSourcesBuildPhase : FileGUIDListBase { public static PBXSourcesBuildPhase Create() { var res = new PBXSourcesBuildPhase(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXSourcesBuildPhase"); res.SetPropertyString("buildActionMask", "2147483647"); res.files = new List<string>(); res.SetPropertyString("runOnlyForDeploymentPostprocessing", "0"); return res; } } internal class PBXFrameworksBuildPhase : FileGUIDListBase { public static PBXFrameworksBuildPhase Create() { var res = new PBXFrameworksBuildPhase(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXFrameworksBuildPhase"); res.SetPropertyString("buildActionMask", "2147483647"); res.files = new List<string>(); res.SetPropertyString("runOnlyForDeploymentPostprocessing", "0"); return res; } } internal class PBXResourcesBuildPhase : FileGUIDListBase { public static PBXResourcesBuildPhase Create() { var res = new PBXResourcesBuildPhase(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXResourcesBuildPhase"); res.SetPropertyString("buildActionMask", "2147483647"); res.files = new List<string>(); res.SetPropertyString("runOnlyForDeploymentPostprocessing", "0"); return res; } } internal class PBXCopyFilesBuildPhase : FileGUIDListBase { private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "files/*", }); internal override PropertyCommentChecker checker { get { return checkerData; } } public string name; // name may be null public static PBXCopyFilesBuildPhase Create(string name, string subfolderSpec) { var res = new PBXCopyFilesBuildPhase(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXCopyFilesBuildPhase"); res.SetPropertyString("buildActionMask", "2147483647"); res.SetPropertyString("dstPath", ""); res.SetPropertyString("dstSubfolderSpec", subfolderSpec); res.files = new List<string>(); res.SetPropertyString("runOnlyForDeploymentPostprocessing", "0"); res.name = name; return res; } public override void UpdateProps() { SetPropertyList("files", files); SetPropertyString("name", name); } public override void UpdateVars() { files = GetPropertyList("files"); name = GetPropertyString("name"); } } internal class PBXShellScriptBuildPhase : PBXObject { public GUIDList files; private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "files/*", }); internal override PropertyCommentChecker checker { get { return checkerData; } } public override void UpdateProps() { SetPropertyList("files", files); } public override void UpdateVars() { files = GetPropertyList("files"); } } internal class BuildConfigEntry { public string name; public List<string> val = new List<string>(); public static string ExtractValue(string src) { return PBXStream.UnquoteString(src.Trim().TrimEnd(',')); } public void AddValue(string value) { if (!val.Contains(value)) val.Add(value); } public static BuildConfigEntry FromNameValue(string name, string value) { BuildConfigEntry ret = new BuildConfigEntry(); ret.name = name; ret.AddValue(value); return ret; } } internal class XCBuildConfiguration : PBXObject { protected SortedDictionary<string, BuildConfigEntry> entries = new SortedDictionary<string, BuildConfigEntry>(); public string name { get { return GetPropertyString("name"); } } // Note that QuoteStringIfNeeded does its own escaping. Double-escaping with quotes is // required to please Xcode that does not handle paths with spaces if they are not // enclosed in quotes. static string EscapeWithQuotesIfNeeded(string name, string value) { if (name != "LIBRARY_SEARCH_PATHS") return value; if (!value.Contains(" ")) return value; if (value.First() == '\"' && value.Last() == '\"') return value; return "\"" + value + "\""; } public void SetProperty(string name, string value) { entries[name] = BuildConfigEntry.FromNameValue(name, EscapeWithQuotesIfNeeded(name, value)); } public void AddProperty(string name, string value) { if (entries.ContainsKey(name)) entries[name].AddValue(EscapeWithQuotesIfNeeded(name, value)); else SetProperty(name, value); } public void UpdateProperties(string name, string[] addValues, string[] removeValues) { if (entries.ContainsKey(name)) { HashSet<string> valSet = new HashSet<string>(entries[name].val); if (removeValues != null) { foreach (string val in removeValues) valSet.Remove(EscapeWithQuotesIfNeeded(name, val)); } if (addValues != null) { foreach (string val in addValues) valSet.Add(EscapeWithQuotesIfNeeded(name, val)); } entries[name].val = new List<string>(valSet); } } // name should be either release or debug public static XCBuildConfiguration Create(string name) { var res = new XCBuildConfiguration(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "XCBuildConfiguration"); res.SetPropertyString("name", name); return res; } public override void UpdateProps() { var dict = m_Properties.CreateDict("buildSettings"); foreach (var kv in entries) { if (kv.Value.val.Count == 0) continue; else if (kv.Value.val.Count == 1) dict.SetString(kv.Key, kv.Value.val[0]); else // kv.Value.val.Count > 1 { var array = dict.CreateArray(kv.Key); foreach (var value in kv.Value.val) array.AddString(value); } } } public override void UpdateVars() { entries = new SortedDictionary<string, BuildConfigEntry>(); if (m_Properties.Contains("buildSettings")) { var dict = m_Properties["buildSettings"].AsDict(); foreach (var key in dict.values.Keys) { var value = dict[key]; if (value is PBXElementString) { if (entries.ContainsKey(key)) entries[key].val.Add(value.AsString()); else entries.Add(key, BuildConfigEntry.FromNameValue(key, value.AsString())); } else if (value is PBXElementArray) { foreach (var pvalue in value.AsArray().values) { if (pvalue is PBXElementString) { if (entries.ContainsKey(key)) entries[key].val.Add(pvalue.AsString()); else entries.Add(key, BuildConfigEntry.FromNameValue(key, pvalue.AsString())); } } } } } } } internal class PBXContainerItemProxy : PBXObject { private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "containerPortal/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } public static PBXContainerItemProxy Create(string containerRef, string proxyType, string remoteGlobalGUID, string remoteInfo) { var res = new PBXContainerItemProxy(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXContainerItemProxy"); res.SetPropertyString("containerPortal", containerRef); // guid res.SetPropertyString("proxyType", proxyType); res.SetPropertyString("remoteGlobalIDString", remoteGlobalGUID); // guid res.SetPropertyString("remoteInfo", remoteInfo); return res; } } internal class PBXReferenceProxy : PBXObject { private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "remoteRef/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } public string path { get { return GetPropertyString("path"); } } public static PBXReferenceProxy Create(string path, string fileType, string remoteRef, string sourceTree) { var res = new PBXReferenceProxy(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXReferenceProxy"); res.SetPropertyString("path", path); res.SetPropertyString("fileType", fileType); res.SetPropertyString("remoteRef", remoteRef); res.SetPropertyString("sourceTree", sourceTree); return res; } } internal class PBXTargetDependency : PBXObject { private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "target/*", "targetProxy/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } public static PBXTargetDependency Create(string target, string targetProxy) { var res = new PBXTargetDependency(); res.guid = PBXGUID.Generate(); res.SetPropertyString("isa", "PBXTargetDependency"); res.SetPropertyString("target", target); res.SetPropertyString("targetProxy", targetProxy); return res; } } internal class ProjectReference { public string group; // guid public string projectRef; // guid public static ProjectReference Create(string group, string projectRef) { var res = new ProjectReference(); res.group = group; res.projectRef = projectRef; return res; } } internal class PBXProjectObject : PBXObject { private static PropertyCommentChecker checkerData = new PropertyCommentChecker(new string[]{ "buildConfigurationList/*", "mainGroup/*", "projectReferences/*/ProductGroup/*", "projectReferences/*/ProjectRef/*", "targets/*" }); internal override PropertyCommentChecker checker { get { return checkerData; } } public List<ProjectReference> projectReferences = new List<ProjectReference>(); public string mainGroup { get { return GetPropertyString("mainGroup"); } } public List<string> targets { get { return GetPropertyList("targets"); } } public string buildConfigList; public void AddReference(string productGroup, string projectRef) { projectReferences.Add(ProjectReference.Create(productGroup, projectRef)); } public override void UpdateProps() { m_Properties.values.Remove("projectReferences"); if (projectReferences.Count > 0) { var array = m_Properties.CreateArray("projectReferences"); foreach (var value in projectReferences) { var dict = array.AddDict(); dict.SetString("ProductGroup", value.group); dict.SetString("ProjectRef", value.projectRef); } }; SetPropertyString("buildConfigurationList", buildConfigList); } public override void UpdateVars() { projectReferences = new List<ProjectReference>(); if (m_Properties.Contains("projectReferences")) { var el = m_Properties["projectReferences"].AsArray(); foreach (var value in el.values) { PBXElementDict dict = value.AsDict(); if (dict.Contains("ProductGroup") && dict.Contains("ProjectRef")) { string group = dict["ProductGroup"].AsString(); string projectRef = dict["ProjectRef"].AsString(); projectReferences.Add(ProjectReference.Create(group, projectRef)); } } } buildConfigList = GetPropertyString("buildConfigurationList"); } } } // namespace UnityEditor.iOS.Xcode
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.Text; using System.Web; using ASC.Core; using ASC.Core.Common.Configuration; using ASC.Core.Users; using ASC.FederatedLogin.LoginProviders; using ASC.Files.Core; using ASC.Web.Core.Files; using ASC.Web.Core.WhiteLabel; using ASC.Web.Files.Classes; using ASC.Web.Files.Helpers; using ASC.Web.Files.Resources; using ASC.Web.Files.Services.WCFService; using ASC.Web.Files.ThirdPartyApp; using ASC.Web.Files.Utils; using ASC.Web.Studio.Utility; using File = ASC.Files.Core.File; namespace ASC.Web.Files.Services.DocumentService { [DataContract(Name = "editorConfig", Namespace = "")] public class Configuration { public static readonly Dictionary<FileType, string> DocType = new Dictionary<FileType, string> { { FileType.Document, "text" }, { FileType.Spreadsheet, "spreadsheet" }, { FileType.Presentation, "presentation" } }; public enum EditorType { Desktop, Mobile, Embedded, External, } private FileType _fileTypeCache = FileType.Unknown; public Configuration(File file) { Document = new DocumentConfig { Info = { File = file, }, }; EditorConfig = new EditorConfiguration(this); } public EditorType Type { set { Document.Info.Type = value; } get { return Document.Info.Type; } } #region Property [DataMember(Name = "document")] public DocumentConfig Document; [DataMember(Name = "documentType")] public string DocumentType { set { } get { string documentType; DocType.TryGetValue(GetFileType, out documentType); return documentType; } } [DataMember(Name = "editorConfig")] public EditorConfiguration EditorConfig; [DataMember(Name = "token", EmitDefaultValue = false)] public string Token; [DataMember(Name = "type")] public string TypeString { set { Type = (EditorType)Enum.Parse(typeof(EditorType), value, true); } get { return Type.ToString().ToLower(); } } private FileType GetFileType { set { } get { if (_fileTypeCache == FileType.Unknown) _fileTypeCache = FileUtility.GetFileTypeByFileName(Document.Info.File.Title); return _fileTypeCache; } } [DataMember(Name = "error", EmitDefaultValue = false)] public string ErrorMessage; #endregion public static string Serialize(Configuration configuration) { using (var ms = new MemoryStream()) { var serializer = new DataContractJsonSerializer(typeof(Configuration)); serializer.WriteObject(ms, configuration); ms.Seek(0, SeekOrigin.Begin); return Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length); } } #region Nested Classes [DataContract(Name = "document", Namespace = "")] public class DocumentConfig { public string SharedLinkKey; public DocumentConfig() { Info = new InfoConfig(); Permissions = new PermissionsConfig(); } private string _key = string.Empty; private string _fileUri; private string _title; [DataMember(Name = "fileType")] public string FileType { set { } get { return Info.File.ConvertedExtension.Trim('.'); } } [DataMember(Name = "info")] public InfoConfig Info; [DataMember(Name = "key")] public string Key { set { _key = value; } get { return DocumentServiceConnector.GenerateRevisionId(_key); } } [DataMember(Name = "permissions")] public PermissionsConfig Permissions; [DataMember(Name = "title")] public string Title { set { _title = value; } get { return _title ?? Info.File.Title; } } [DataMember(Name = "url")] public string Url { set { _fileUri = DocumentServiceConnector.ReplaceCommunityAdress(value); } get { if (!string.IsNullOrEmpty(_fileUri)) return _fileUri; var last = Permissions.Edit || Permissions.Review || Permissions.Comment; _fileUri = DocumentServiceConnector.ReplaceCommunityAdress(PathProvider.GetFileStreamUrl(Info.File, SharedLinkKey, last)); return _fileUri; } } #region Nested Classes [DataContract(Name = "info", Namespace = "")] public class InfoConfig { public File File; public EditorType Type = EditorType.Desktop; private string _breadCrumbs; [DataMember(Name = "favorite", EmitDefaultValue = false)] public bool? Favorite { set { } get { if (!SecurityContext.IsAuthenticated || CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor()) return null; if (File.Encrypted) return null; return File.IsFavorite; } } [DataMember(Name = "folder", EmitDefaultValue = false)] public string Folder { set { } get { if (Type == EditorType.Embedded || Type == EditorType.External) return null; if (string.IsNullOrEmpty(_breadCrumbs)) { const string crumbsSeporator = " \\ "; var breadCrumbsList = EntryManager.GetBreadCrumbs(File.FolderID); _breadCrumbs = String.Join(crumbsSeporator, breadCrumbsList.Select(folder => folder.Title).ToArray()); } return _breadCrumbs; } } [DataMember(Name = "owner")] public string Owner { set { } get { return File.CreateByString; } } [DataMember(Name = "uploaded")] public string Uploaded { set { } get { return File.CreateOnString; } } [DataMember(Name = "sharingSettings", EmitDefaultValue = false)] public ItemList<AceShortWrapper> SharingSettings { set { } get { if (Type == EditorType.Embedded || Type == EditorType.External || !FileSharing.CanSetAccess(File)) return null; try { return Global.FileStorageService.GetSharedInfoShort(File.UniqID); } catch { return null; } } } } [DataContract(Name = "permissions", Namespace = "")] public class PermissionsConfig { //todo: obsolete since DS v5.5 [DataMember(Name = "changeHistory")] public bool ChangeHistory = false; [DataMember(Name = "comment")] public bool Comment = true; [DataMember(Name = "download")] public bool Download = true; [DataMember(Name = "edit")] public bool Edit = true; [DataMember(Name = "fillForms")] public bool FillForms = true; [DataMember(Name = "print")] public bool Print = true; [DataMember(Name = "modifyFilter")] public bool ModifyFilter = true; //todo: obsolete since DS v6.0 [DataMember(Name = "rename")] public bool Rename = false; [DataMember(Name = "review")] public bool Review = true; } #endregion } [DataContract(Name = "editorConfig", Namespace = "")] public class EditorConfiguration { public EditorConfiguration(Configuration configuration) { _configuration = configuration; Customization = new CustomizationConfig(_configuration); Plugins = new PluginsConfig(); Embedded = new EmbeddedConfig(); _userInfo = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID); if (!_userInfo.ID.Equals(ASC.Core.Configuration.Constants.Guest.ID)) { User = new UserConfig { Id = _userInfo.ID.ToString(), Name = _userInfo.DisplayUserName(false), }; } } public bool ModeWrite = false; private readonly Configuration _configuration; private readonly UserInfo _userInfo; private EmbeddedConfig _embeddedConfig; [DataMember(Name = "actionLink", EmitDefaultValue = false)] public ActionLinkConfig ActionLink; public string ActionLinkString { get { return null; } set { try { using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(value))) { var serializer = new DataContractJsonSerializer(typeof(ActionLinkConfig)); ActionLink = (ActionLinkConfig)serializer.ReadObject(ms); } } catch (Exception) { ActionLink = null; } } } [DataMember(Name = "templates", EmitDefaultValue = false)] public List<TemplatesConfig> Templates { set { } get { if (!SecurityContext.IsAuthenticated || CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor()) return null; if (!FilesSettings.TemplatesSection) return null; var extension = FileUtility.GetInternalExtension(_configuration.Document.Title).TrimStart('.'); var filter = FilterType.FilesOnly; switch (_configuration.GetFileType) { case FileType.Document: filter = FilterType.DocumentsOnly; break; case FileType.Spreadsheet: filter = FilterType.SpreadsheetsOnly; break; case FileType.Presentation: filter = FilterType.PresentationsOnly; break; } using (var folderDao = Global.DaoFactory.GetFolderDao()) using (var fileDao = Global.DaoFactory.GetFileDao()) { var files = EntryManager.GetTemplates(folderDao, fileDao, filter, false, Guid.Empty, string.Empty, false); var listTemplates = from file in files select new TemplatesConfig { Image = CommonLinkUtility.GetFullAbsolutePath("skins/default/images/filetype/thumb/" + extension + ".png"), Name = file.Title, Title = file.Title, Url = CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorUrl(file.ID)) }; return listTemplates.ToList(); } } } [DataMember(Name = "callbackUrl", EmitDefaultValue = false)] public string CallbackUrl; [DataMember(Name = "createUrl", EmitDefaultValue = false)] public string CreateUrl { set { } get { if (_configuration.Document.Info.Type != EditorType.Desktop) return null; if (!SecurityContext.IsAuthenticated || CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor()) return null; return GetCreateUrl(_configuration.GetFileType); } } [DataMember(Name = "plugins", EmitDefaultValue = false)] public PluginsConfig Plugins; [DataMember(Name = "customization", EmitDefaultValue = false)] public CustomizationConfig Customization; [DataMember(Name = "embedded", EmitDefaultValue = false)] public EmbeddedConfig Embedded { set { _embeddedConfig = value; } get { return _configuration.Document.Info.Type == EditorType.Embedded ? _embeddedConfig : null; } } [DataMember(Name = "encryptionKeys", EmitDefaultValue = false)] public EncryptionKeysConfig EncryptionKeys; [DataMember(Name = "fileChoiceUrl", EmitDefaultValue = false)] public string FileChoiceUrl; [DataMember(Name = "lang")] public string Lang { set { } get { return _userInfo.GetCulture().Name; } } [DataMember(Name = "mode")] public string Mode { set { } get { return ModeWrite ? "edit" : "view"; } } [DataMember(Name = "saveAsUrl", EmitDefaultValue = false)] public string SaveAsUrl; [DataMember(Name = "recent", EmitDefaultValue = false)] public List<RecentConfig> Recent { set { } get { if (!SecurityContext.IsAuthenticated || CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor()) return null; if (!FilesSettings.RecentSection) return null; var filter = FilterType.FilesOnly; switch (_configuration.GetFileType) { case FileType.Document: filter = FilterType.DocumentsOnly; break; case FileType.Spreadsheet: filter = FilterType.SpreadsheetsOnly; break; case FileType.Presentation: filter = FilterType.PresentationsOnly; break; } using (var folderDao = Global.DaoFactory.GetFolderDao()) using (var fileDao = Global.DaoFactory.GetFileDao()) { var files = EntryManager.GetRecent(folderDao, fileDao, filter, false, Guid.Empty, string.Empty, false); var listRecent = from file in files where !Equals(_configuration.Document.Info.File.ID, file.ID) select new RecentConfig { Folder = folderDao.GetFolder(file.FolderID).Title, Title = file.Title, Url = CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorUrl(file.ID)) }; return listRecent.ToList(); } } } [DataMember(Name = "sharingSettingsUrl", EmitDefaultValue = false)] public string SharingSettingsUrl; [DataMember(Name = "user")] public UserConfig User; private static string GetCreateUrl(FileType fileType) { String title; switch (fileType) { case FileType.Document: title = FilesJSResource.TitleNewFileText; break; case FileType.Spreadsheet: title = FilesJSResource.TitleNewFileSpreadsheet; break; case FileType.Presentation: title = FilesJSResource.TitleNewFilePresentation; break; default: return null; } string documentType; DocType.TryGetValue(fileType, out documentType); return CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FileHandlerPath) + "?" + FilesLinkUtility.Action + "=create" + "&doctype=" + documentType + "&" + FilesLinkUtility.FileTitle + "=" + HttpUtility.UrlEncode(title); } #region Nested Classes [DataContract(Name = "actionLink", Namespace = "")] public class ActionLinkConfig { [DataMember(Name = "action", EmitDefaultValue = false)] public ActionConfig Action; [DataContract(Name = "action", Namespace = "")] public class ActionConfig { [DataMember(Name = "type", EmitDefaultValue = false)] public string Type; [DataMember(Name = "data", EmitDefaultValue = false)] public string Data; } public static string Serialize(ActionLinkConfig actionLinkConfig) { using (var ms = new MemoryStream()) { var serializer = new DataContractJsonSerializer(typeof(ActionLinkConfig)); serializer.WriteObject(ms, actionLinkConfig); ms.Seek(0, SeekOrigin.Begin); return Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length); } } } [DataContract(Name = "embedded", Namespace = "")] public class EmbeddedConfig { public string ShareLinkParam; [DataMember(Name = "embedUrl", EmitDefaultValue = false)] public string EmbedUrl { set { } get { return CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FilesBaseAbsolutePath + FilesLinkUtility.EditorPage + "?" + FilesLinkUtility.Action + "=embedded" + ShareLinkParam); } } [DataMember(Name = "saveUrl", EmitDefaultValue = false)] public string SaveUrl { set { } get { return CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FileHandlerPath + "?" + FilesLinkUtility.Action + "=download" + ShareLinkParam); } } [DataMember(Name = "shareUrl", EmitDefaultValue = false)] public string ShareUrl { set { } get { return CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FilesBaseAbsolutePath + FilesLinkUtility.EditorPage + "?" + FilesLinkUtility.Action + "=view" + ShareLinkParam); } } [DataMember(Name = "toolbarDocked")] public string ToolbarDocked = "top"; } [DataContract(Name = "encryptionKeys", Namespace = "")] public class EncryptionKeysConfig { [DataMember(Name = "cryptoEngineId", EmitDefaultValue = false)] public string CryptoEngineId = "{FFF0E1EB-13DB-4678-B67D-FF0A41DBBCEF}"; [DataMember(Name = "privateKeyEnc", EmitDefaultValue = false)] public string PrivateKeyEnc; [DataMember(Name = "publicKey", EmitDefaultValue = false)] public string PublicKey; } [DataContract(Name = "plugins", Namespace = "")] public class PluginsConfig { [DataMember(Name = "pluginsData", EmitDefaultValue = false)] public string[] PluginsData { set { } get { var plugins = new List<string>(); if (CoreContext.Configuration.Standalone || !TenantExtra.GetTenantQuota().Free) { var easyBibHelper = ConsumerFactory.Get<EasyBibHelper>(); if (!string.IsNullOrEmpty(easyBibHelper.AppKey)) { plugins.Add(CommonLinkUtility.GetFullAbsolutePath("ThirdParty/plugin/easybib/config.json")); } var wordpressLoginProvider = ConsumerFactory.Get<WordpressLoginProvider>(); if (!string.IsNullOrEmpty(wordpressLoginProvider.ClientID) && !string.IsNullOrEmpty(wordpressLoginProvider.ClientSecret) && !string.IsNullOrEmpty(wordpressLoginProvider.RedirectUri)) { plugins.Add(CommonLinkUtility.GetFullAbsolutePath("ThirdParty/plugin/wordpress/config.json")); } } return plugins.ToArray(); } } } [DataContract(Name = "customization", Namespace = "")] public class CustomizationConfig { public CustomizationConfig(Configuration configuration) { _configuration = configuration; Customer = new CustomerConfig(_configuration); Logo = new LogoConfig(_configuration); } private readonly Configuration _configuration; public string GobackUrl; public bool IsRetina = false; [DataMember(Name = "about")] public bool About { set { } get { return !CoreContext.Configuration.Standalone || CoreContext.Configuration.CustomMode; } } [DataMember(Name = "customer")] public CustomerConfig Customer; [DataMember(Name = "feedback", EmitDefaultValue = false)] public FeedbackConfig Feedback { set { } get { if (CoreContext.Configuration.Standalone) return null; if (!AdditionalWhiteLabelSettings.Instance.FeedbackAndSupportEnabled) return null; return new FeedbackConfig { Url = CommonLinkUtility.GetRegionalUrl( AdditionalWhiteLabelSettings.Instance.FeedbackAndSupportUrl, CultureInfo.CurrentCulture.TwoLetterISOLanguageName), }; } } [DataMember(Name = "forcesave", EmitDefaultValue = false)] public bool Forcesave { set { } get { return FileUtility.CanForcesave && !_configuration.Document.Info.File.ProviderEntry && ThirdPartySelector.GetAppByFileId(_configuration.Document.Info.File.ID.ToString()) == null && FilesSettings.Forcesave; } } [DataMember(Name = "goback", EmitDefaultValue = false)] public GobackConfig Goback { set { } get { if (_configuration.Type == EditorType.Embedded || _configuration.Type == EditorType.External) return null; if (!SecurityContext.IsAuthenticated) return null; if (GobackUrl != null) { return new GobackConfig { Url = GobackUrl, }; } using (var folderDao = Global.DaoFactory.GetFolderDao()) { try { var parent = folderDao.GetFolder(_configuration.Document.Info.File.FolderID); var fileSecurity = Global.GetFilesSecurity(); if (_configuration.Document.Info.File.RootFolderType == FolderType.USER && !Equals(_configuration.Document.Info.File.RootFolderId, Global.FolderMy) && !fileSecurity.CanRead(parent)) { if (fileSecurity.CanRead(_configuration.Document.Info.File)) { return new GobackConfig { Url = PathProvider.GetFolderUrl(Global.FolderShare), }; } return null; } if(_configuration.Document.Info.File.Encrypted && _configuration.Document.Info.File.RootFolderType == FolderType.Privacy && !fileSecurity.CanRead(parent)) { parent = folderDao.GetFolder(Global.FolderPrivacy); } return new GobackConfig { Url = PathProvider.GetFolderUrl(parent), }; } catch (Exception) { return null; } } } } [DataMember(Name = "logo")] public LogoConfig Logo; [DataMember(Name = "mentionShare")] public bool MentionShare { set { } get { return SecurityContext.IsAuthenticated && !_configuration.Document.Info.File.Encrypted && FileSharing.CanSetAccess(_configuration.Document.Info.File); } } [DataMember(Name = "reviewDisplay", EmitDefaultValue = false)] public string ReviewDisplay { set { } get { return _configuration.EditorConfig.ModeWrite ? null : "markup"; } } [DataContract(Name = "customer", Namespace = "")] public class CustomerConfig { public CustomerConfig(Configuration configuration) { _configuration = configuration; } private readonly Configuration _configuration; [DataMember(Name = "logo")] public string Logo { set { } get { return CommonLinkUtility.GetFullAbsolutePath(TenantLogoHelper.GetLogo(WhiteLabelLogoTypeEnum.Dark, !_configuration.EditorConfig.Customization.IsRetina)); } } [DataMember(Name = "name")] public string Name { set { } get { return (TenantWhiteLabelSettings.Load().LogoText ?? "") .Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("/", "\\/"); } } } [DataContract(Name = "feedback", Namespace = "")] public class FeedbackConfig { [DataMember(Name = "url")] public string Url; [DataMember(Name = "visible")] public bool Visible = true; } [DataContract(Name = "goback", Namespace = "")] public class GobackConfig { [DataMember(Name = "url", EmitDefaultValue = false)] public string Url; } [DataContract(Name = "logo", Namespace = "")] public class LogoConfig { public LogoConfig(Configuration configuration) { _configuration = configuration; } private readonly Configuration _configuration; [DataMember(Name = "image")] public string Image { set { } get { var fillingForm = FileUtility.CanWebRestrictedEditing(_configuration.Document.Title); return _configuration.Type == EditorType.Embedded || fillingForm ? CommonLinkUtility.GetFullAbsolutePath(TenantLogoHelper.GetLogo(WhiteLabelLogoTypeEnum.DocsEditorEmbed, !_configuration.EditorConfig.Customization.IsRetina)) : CommonLinkUtility.GetFullAbsolutePath(TenantLogoHelper.GetLogo(WhiteLabelLogoTypeEnum.DocsEditor, !_configuration.EditorConfig.Customization.IsRetina)); } } [DataMember(Name = "imageDark")] public string ImageDark { set { } get { return CommonLinkUtility.GetFullAbsolutePath(TenantLogoHelper.GetLogo(WhiteLabelLogoTypeEnum.DocsEditor, !_configuration.EditorConfig.Customization.IsRetina)); } } [DataMember(Name = "imageEmbedded", EmitDefaultValue = false)] public string ImageEmbedded { set { } get { return _configuration.Type != EditorType.Embedded ? null : CommonLinkUtility.GetFullAbsolutePath(TenantLogoHelper.GetLogo(WhiteLabelLogoTypeEnum.DocsEditorEmbed, !_configuration.EditorConfig.Customization.IsRetina)); } } [DataMember(Name = "url")] public string Url { set { } get { return CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.GetDefault()); } } } } [DataContract(Name = "recentconfig", Namespace = "")] public class RecentConfig { [DataMember(Name = "folder", EmitDefaultValue = false)] public string Folder; [DataMember(Name = "title", EmitDefaultValue = false)] public string Title; [DataMember(Name = "url", EmitDefaultValue = false)] public string Url; } [DataContract(Name = "templatesconfig", Namespace = "")] public class TemplatesConfig { [DataMember(Name = "image", EmitDefaultValue = false)] public string Image; //todo: obsolete since DS v6.0 [DataMember(Name = "name", EmitDefaultValue = false)] public string Name; [DataMember(Name = "title", EmitDefaultValue = false)] public string Title; [DataMember(Name = "url", EmitDefaultValue = false)] public string Url; } [DataContract(Name = "user", Namespace = "")] public class UserConfig { [DataMember(Name = "id", EmitDefaultValue = false)] public string Id; [DataMember(Name = "name", EmitDefaultValue = false)] public string Name; } #endregion } #endregion } }
using System; using System.IO; using System.Collections; namespace TableClothKernel { public class Token { public int kind; // token kind public int pos; // token position in bytes in the source text (starting at 0) public int charPos; // token position in characters in the source text (starting at 0) public int col; // token column (starting at 1) public int line; // token line (starting at 1) public string val; // token value public Token next; // ML 2005-03-11 Tokens are kept in linked list } //----------------------------------------------------------------------------------- // Buffer //----------------------------------------------------------------------------------- public class Buffer { // This Buffer supports the following cases: // 1) seekable stream (file) // a) whole stream in buffer // b) part of stream in buffer // 2) non seekable stream (network, console) public const int EOF = char.MaxValue + 1; const int MIN_BUFFER_LENGTH = 1024; // 1KB const int MAX_BUFFER_LENGTH = MIN_BUFFER_LENGTH * 64; // 64KB byte[] buf; // input buffer int bufStart; // position of first byte in buffer relative to input stream int bufLen; // length of buffer int fileLen; // length of input stream (may change if the stream is no file) int bufPos; // current position in buffer Stream stream; // input stream (seekable) bool isUserStream; // was the stream opened by the user? public Buffer (Stream s, bool isUserStream) { stream = s; this.isUserStream = isUserStream; if (stream.CanSeek) { fileLen = (int) stream.Length; bufLen = Math.Min(fileLen, MAX_BUFFER_LENGTH); bufStart = Int32.MaxValue; // nothing in the buffer so far } else { fileLen = bufLen = bufStart = 0; } buf = new byte[(bufLen>0) ? bufLen : MIN_BUFFER_LENGTH]; if (fileLen > 0) Pos = 0; // setup buffer to position 0 (start) else bufPos = 0; // index 0 is already after the file, thus Pos = 0 is invalid if (bufLen == fileLen && stream.CanSeek) Close(); } protected Buffer(Buffer b) { // called in UTF8Buffer constructor buf = b.buf; bufStart = b.bufStart; bufLen = b.bufLen; fileLen = b.fileLen; bufPos = b.bufPos; stream = b.stream; // keep destructor from closing the stream b.stream = null; isUserStream = b.isUserStream; } ~Buffer() { Close(); } protected void Close() { if (!isUserStream && stream != null) { stream.Close(); stream = null; } } public virtual int Read () { if (bufPos < bufLen) { return buf[bufPos++]; } else if (Pos < fileLen) { Pos = Pos; // shift buffer start to Pos return buf[bufPos++]; } else if (stream != null && !stream.CanSeek && ReadNextStreamChunk() > 0) { return buf[bufPos++]; } else { return EOF; } } public int Peek () { int curPos = Pos; int ch = Read(); Pos = curPos; return ch; } // beg .. begin, zero-based, inclusive, in byte // end .. end, zero-based, exclusive, in byte public string GetString (int beg, int end) { int len = 0; char[] buf = new char[end - beg]; int oldPos = Pos; Pos = beg; while (Pos < end) buf[len++] = (char) Read(); Pos = oldPos; return new String(buf, 0, len); } public int Pos { get { return bufPos + bufStart; } set { if (value >= fileLen && stream != null && !stream.CanSeek) { // Wanted position is after buffer and the stream // is not seek-able e.g. network or console, // thus we have to read the stream manually till // the wanted position is in sight. while (value >= fileLen && ReadNextStreamChunk() > 0); } if (value < 0 || value > fileLen) { throw new FatalError("buffer out of bounds access, position: " + value); } if (value >= bufStart && value < bufStart + bufLen) { // already in buffer bufPos = value - bufStart; } else if (stream != null) { // must be swapped in stream.Seek(value, SeekOrigin.Begin); bufLen = stream.Read(buf, 0, buf.Length); bufStart = value; bufPos = 0; } else { // set the position to the end of the file, Pos will return fileLen. bufPos = fileLen - bufStart; } } } // Read the next chunk of bytes from the stream, increases the buffer // if needed and updates the fields fileLen and bufLen. // Returns the number of bytes read. private int ReadNextStreamChunk() { int free = buf.Length - bufLen; if (free == 0) { // in the case of a growing input stream // we can neither seek in the stream, nor can we // foresee the maximum length, thus we must adapt // the buffer size on demand. byte[] newBuf = new byte[bufLen * 2]; Array.Copy(buf, newBuf, bufLen); buf = newBuf; free = bufLen; } int read = stream.Read(buf, bufLen, free); if (read > 0) { fileLen = bufLen = (bufLen + read); return read; } // end of stream reached return 0; } } //----------------------------------------------------------------------------------- // UTF8Buffer //----------------------------------------------------------------------------------- public class UTF8Buffer : Buffer { public UTF8Buffer(Buffer b): base(b) { } public override int Read() { int ch; do { ch = base.Read(); // until we find a utf8 start (0xxxxxxx or 11xxxxxx) } while ((ch >= 128) && ((ch & 0xC0) != 0xC0) && (ch != EOF)); if (ch < 128 || ch == EOF) { // nothing to do, first 127 chars are the same in ascii and utf8 // 0xxxxxxx or end of file character } else if ((ch & 0xF0) == 0xF0) { // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx int c1 = ch & 0x07; ch = base.Read(); int c2 = ch & 0x3F; ch = base.Read(); int c3 = ch & 0x3F; ch = base.Read(); int c4 = ch & 0x3F; ch = (((((c1 << 6) | c2) << 6) | c3) << 6) | c4; } else if ((ch & 0xE0) == 0xE0) { // 1110xxxx 10xxxxxx 10xxxxxx int c1 = ch & 0x0F; ch = base.Read(); int c2 = ch & 0x3F; ch = base.Read(); int c3 = ch & 0x3F; ch = (((c1 << 6) | c2) << 6) | c3; } else if ((ch & 0xC0) == 0xC0) { // 110xxxxx 10xxxxxx int c1 = ch & 0x1F; ch = base.Read(); int c2 = ch & 0x3F; ch = (c1 << 6) | c2; } return ch; } } //----------------------------------------------------------------------------------- // Scanner //----------------------------------------------------------------------------------- public class Scanner { const char EOL = '\n'; const int eofSym = 0; /* pdt */ const int maxT = 25; const int noSym = 25; public Buffer buffer; // scanner buffer Token t; // current token int ch; // current input character int pos; // byte position of current character int charPos; // position by unicode characters starting with 0 int col; // column number of current character int line; // line number of current character int oldEols; // EOLs that appeared in a comment; static readonly Hashtable start; // maps first token character to start state Token tokens; // list of tokens already peeked (first token is a dummy) Token pt; // current peek token char[] tval = new char[128]; // text of current token int tlen; // length of current token static Scanner() { start = new Hashtable(128); for (int i = 65; i <= 90; ++i) start[i] = 1; for (int i = 97; i <= 122; ++i) start[i] = 1; start[49] = 2; start[48] = 3; start[61] = 47; start[33] = 7; start[91] = 48; start[38] = 8; start[124] = 13; start[94] = 20; start[40] = 41; start[41] = 42; start[123] = 43; start[125] = 44; start[59] = 45; start[44] = 46; start[Buffer.EOF] = -1; } public Scanner (string inputString) { MemoryStream stream = new MemoryStream(System.Text.Encoding.Default.GetBytes(inputString)); buffer = new Buffer(stream, false); Init(); } public Scanner (Stream s) { buffer = new Buffer(s, true); Init(); } void Init() { pos = -1; line = 1; col = 0; charPos = -1; oldEols = 0; NextCh(); if (ch == 0xEF) { // check optional byte order mark for UTF-8 NextCh(); int ch1 = ch; NextCh(); int ch2 = ch; if (ch1 != 0xBB || ch2 != 0xBF) { throw new FatalError(String.Format("illegal byte order mark: EF {0,2:X} {1,2:X}", ch1, ch2)); } buffer = new UTF8Buffer(buffer); col = 0; charPos = -1; NextCh(); } pt = tokens = new Token(); // first token is a dummy } void NextCh() { if (oldEols > 0) { ch = EOL; oldEols--; } else { pos = buffer.Pos; // buffer reads unicode chars, if UTF8 has been detected ch = buffer.Read(); col++; charPos++; // replace isolated '\r' by '\n' in order to make // eol handling uniform across Windows, Unix and Mac if (ch == '\r' && buffer.Peek() != '\n') ch = EOL; if (ch == EOL) { line++; col = 0; } } } void AddCh() { if (tlen >= tval.Length) { char[] newBuf = new char[2 * tval.Length]; Array.Copy(tval, 0, newBuf, 0, tval.Length); tval = newBuf; } if (ch != Buffer.EOF) { tval[tlen++] = (char) ch; NextCh(); } } bool Comment0() { int level = 1, pos0 = pos, line0 = line, col0 = col, charPos0 = charPos; NextCh(); if (ch == '/') { NextCh(); for(;;) { if (ch == 10) { level--; if (level == 0) { oldEols = line - line0; NextCh(); return true; } NextCh(); } else if (ch == Buffer.EOF) return false; else NextCh(); } } else { buffer.Pos = pos0; NextCh(); line = line0; col = col0; charPos = charPos0; } return false; } bool Comment1() { int level = 1, pos0 = pos, line0 = line, col0 = col, charPos0 = charPos; NextCh(); if (ch == '*') { NextCh(); for(;;) { if (ch == '*') { NextCh(); if (ch == '/') { level--; if (level == 0) { oldEols = line - line0; NextCh(); return true; } NextCh(); } } else if (ch == '/') { NextCh(); if (ch == '*') { level++; NextCh(); } } else if (ch == Buffer.EOF) return false; else NextCh(); } } else { buffer.Pos = pos0; NextCh(); line = line0; col = col0; charPos = charPos0; } return false; } void CheckLiteral() { switch (t.val) { case "true": t.kind = 4; break; case "false": t.kind = 5; break; case "True": t.kind = 6; break; case "False": t.kind = 7; break; case "new": t.kind = 8; break; case "clear": t.kind = 9; break; default: break; } } Token NextToken() { while (ch == ' ' || ch == 0 || ch >= 9 && ch <= 10 || ch == 13 ) NextCh(); if (ch == '/' && Comment0() ||ch == '/' && Comment1()) return NextToken(); int recKind = noSym; int recEnd = pos; t = new Token(); t.pos = pos; t.col = col; t.line = line; t.charPos = charPos; int state; if (start.ContainsKey(ch)) { state = (int) start[ch]; } else { state = 0; } tlen = 0; AddCh(); switch (state) { case -1: { t.kind = eofSym; break; } // NextCh already done case 0: { if (recKind != noSym) { tlen = recEnd - t.pos; SetScannerBehindT(); } t.kind = recKind; break; } // NextCh already done case 1: recEnd = pos; recKind = 1; if (ch >= '0' && ch <= '9' || ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z') {AddCh(); goto case 1;} else {t.kind = 1; t.val = new String(tval, 0, tlen); CheckLiteral(); return t;} case 2: {t.kind = 2; break;} case 3: {t.kind = 3; break;} case 4: if (ch == 'o') {AddCh(); goto case 5;} else {goto case 0;} case 5: if (ch == 't') {AddCh(); goto case 6;} else {goto case 0;} case 6: if (ch == ']') {AddCh(); goto case 7;} else {goto case 0;} case 7: {t.kind = 11; break;} case 8: if (ch == '&') {AddCh(); goto case 12;} else {goto case 0;} case 9: if (ch == 'n') {AddCh(); goto case 10;} else {goto case 0;} case 10: if (ch == 'd') {AddCh(); goto case 11;} else {goto case 0;} case 11: if (ch == ']') {AddCh(); goto case 12;} else {goto case 0;} case 12: {t.kind = 12; break;} case 13: if (ch == '|') {AddCh(); goto case 16;} else {goto case 0;} case 14: if (ch == 'r') {AddCh(); goto case 15;} else {goto case 0;} case 15: if (ch == ']') {AddCh(); goto case 16;} else {goto case 0;} case 16: {t.kind = 13; break;} case 17: if (ch == 'o') {AddCh(); goto case 18;} else {goto case 0;} case 18: if (ch == 'r') {AddCh(); goto case 19;} else {goto case 0;} case 19: if (ch == ']') {AddCh(); goto case 20;} else {goto case 0;} case 20: {t.kind = 14; break;} case 21: if (ch == 'q') {AddCh(); goto case 22;} else {goto case 0;} case 22: if (ch == 'u') {AddCh(); goto case 23;} else {goto case 0;} case 23: if (ch == ']') {AddCh(); goto case 24;} else {goto case 0;} case 24: {t.kind = 15; break;} case 25: if (ch == 'm') {AddCh(); goto case 26;} else {goto case 0;} case 26: if (ch == 'p') {AddCh(); goto case 27;} else {goto case 0;} case 27: if (ch == 'l') {AddCh(); goto case 28;} else {goto case 0;} case 28: if (ch == ']') {AddCh(); goto case 29;} else {goto case 0;} case 29: {t.kind = 16; break;} case 30: if (ch == 'h') {AddCh(); goto case 31;} else {goto case 0;} case 31: if (ch == 'e') {AddCh(); goto case 32;} else {goto case 0;} case 32: if (ch == 'f') {AddCh(); goto case 33;} else {goto case 0;} case 33: if (ch == ']') {AddCh(); goto case 34;} else {goto case 0;} case 34: {t.kind = 17; break;} case 35: if (ch == 'i') {AddCh(); goto case 36;} else {goto case 0;} case 36: if (ch == 'r') {AddCh(); goto case 37;} else {goto case 0;} case 37: if (ch == 's') {AddCh(); goto case 38;} else {goto case 0;} case 38: if (ch == 'e') {AddCh(); goto case 39;} else {goto case 0;} case 39: if (ch == ']') {AddCh(); goto case 40;} else {goto case 0;} case 40: {t.kind = 18; break;} case 41: {t.kind = 19; break;} case 42: {t.kind = 20; break;} case 43: {t.kind = 21; break;} case 44: {t.kind = 22; break;} case 45: {t.kind = 23; break;} case 46: {t.kind = 24; break;} case 47: recEnd = pos; recKind = 10; if (ch == '=') {AddCh(); goto case 24;} else if (ch == '>') {AddCh(); goto case 29;} else {t.kind = 10; break;} case 48: if (ch == 'n') {AddCh(); goto case 4;} else if (ch == 'a') {AddCh(); goto case 9;} else if (ch == 'o') {AddCh(); goto case 14;} else if (ch == 'x') {AddCh(); goto case 17;} else if (ch == 'e') {AddCh(); goto case 21;} else if (ch == 'i') {AddCh(); goto case 25;} else if (ch == 's') {AddCh(); goto case 30;} else if (ch == 'p') {AddCh(); goto case 35;} else {goto case 0;} } t.val = new String(tval, 0, tlen); return t; } private void SetScannerBehindT() { buffer.Pos = t.pos; NextCh(); line = t.line; col = t.col; charPos = t.charPos; for (int i = 0; i < tlen; i++) NextCh(); } // get the next token (possibly a token already seen during peeking) public Token Scan () { if (tokens.next == null) { return NextToken(); } else { pt = tokens = tokens.next; return tokens; } } // peek for the next token, ignore pragmas public Token Peek () { do { if (pt.next == null) { pt.next = NextToken(); } pt = pt.next; } while (pt.kind > maxT); // skip pragmas return pt; } // make sure that peeking starts at the current scan position public void ResetPeek () { pt = tokens; } } }
// 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.IO; using System.Net.Http; using System.Net.Test.Common; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Tests { public partial class HttpWebRequestTest { private const string RequestBody = "This is data to POST."; private readonly byte[] _requestBodyBytes = Encoding.UTF8.GetBytes(RequestBody); private readonly NetworkCredential _explicitCredential = new NetworkCredential("user", "password", "domain"); private readonly ITestOutputHelper _output; public static readonly object[][] EchoServers = System.Net.Test.Common.Configuration.Http.EchoServers; public HttpWebRequestTest(ITestOutputHelper output) { _output = output; } [Theory, MemberData(nameof(EchoServers))] public void Ctor_VerifyDefaults_Success(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.Null(request.Accept); Assert.False(request.AllowReadStreamBuffering); Assert.True(request.AllowWriteStreamBuffering); Assert.Null(request.ContentType); Assert.Equal(350, request.ContinueTimeout); Assert.Null(request.CookieContainer); Assert.Null(request.Credentials); Assert.False(request.HaveResponse); Assert.NotNull(request.Headers); Assert.Equal(0, request.Headers.Count); Assert.Equal("GET", request.Method); Assert.NotNull(request.Proxy); Assert.Equal(remoteServer, request.RequestUri); Assert.True(request.SupportsCookieContainer); Assert.False(request.UseDefaultCredentials); } [Theory, MemberData(nameof(EchoServers))] public void Ctor_CreateHttpWithString_ExpectNotNull(Uri remoteServer) { string remoteServerString = remoteServer.ToString(); HttpWebRequest request = WebRequest.CreateHttp(remoteServerString); Assert.NotNull(request); } [Theory, MemberData(nameof(EchoServers))] public void Ctor_CreateHttpWithUri_ExpectNotNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.NotNull(request); } [Theory, MemberData(nameof(EchoServers))] public void Accept_SetThenGetValidValue_ExpectSameValue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); string acceptType = "*/*"; request.Accept = acceptType; Assert.Equal(acceptType, request.Accept); } [Theory, MemberData(nameof(EchoServers))] public void Accept_SetThenGetEmptyValue_ExpectNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Accept = string.Empty; Assert.Null(request.Accept); } [Theory, MemberData(nameof(EchoServers))] public void Accept_SetThenGetNullValue_ExpectNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Accept = null; Assert.Null(request.Accept); } [Theory, MemberData(nameof(EchoServers))] public void AllowReadStreamBuffering_SetFalseThenGet_ExpectFalse(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.AllowReadStreamBuffering = false; Assert.False(request.AllowReadStreamBuffering); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "not supported on .NET Framework")] [Theory, MemberData(nameof(EchoServers))] public void AllowReadStreamBuffering_SetTrueThenGet_ExpectTrue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.AllowReadStreamBuffering = true; Assert.True(request.AllowReadStreamBuffering); } [Theory, MemberData(nameof(EchoServers))] public async Task ContentLength_Get_ExpectSameAsGetResponseStream(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); WebResponse response = await request.GetResponseAsync(); Stream myStream = response.GetResponseStream(); String strContent; using (var sr = new StreamReader(myStream)) { strContent = sr.ReadToEnd(); } long length = response.ContentLength; Assert.Equal(strContent.Length, length); } [Theory, MemberData(nameof(EchoServers))] public void ContentType_SetThenGet_ExpectSameValue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); string myContent = "application/x-www-form-urlencoded"; request.ContentType = myContent; Assert.Equal(myContent, request.ContentType); } [Theory, MemberData(nameof(EchoServers))] public void ContentType_SetThenGetEmptyValue_ExpectNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.ContentType = string.Empty; Assert.Null(request.ContentType); } [Theory, MemberData(nameof(EchoServers))] public void ContinueTimeout_SetThenGetZero_ExpectZero(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.ContinueTimeout = 0; Assert.Equal(0, request.ContinueTimeout); } [Theory, MemberData(nameof(EchoServers))] public void ContinueTimeout_SetNegativeOne_Success(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.ContinueTimeout = -1; } [Theory, MemberData(nameof(EchoServers))] public void ContinueTimeout_SetNegativeTwo_ThrowsArgumentOutOfRangeException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.Throws<ArgumentOutOfRangeException>(() => request.ContinueTimeout = -2); } [Theory, MemberData(nameof(EchoServers))] public void Credentials_SetDefaultCredentialsThenGet_ValuesMatch(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Credentials = CredentialCache.DefaultCredentials; Assert.Equal(CredentialCache.DefaultCredentials, request.Credentials); } [Theory, MemberData(nameof(EchoServers))] public void Credentials_SetExplicitCredentialsThenGet_ValuesMatch(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Credentials = _explicitCredential; Assert.Equal(_explicitCredential, request.Credentials); } [Theory, MemberData(nameof(EchoServers))] public void UseDefaultCredentials_SetTrue_CredentialsEqualsDefaultCredentials(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Credentials = _explicitCredential; request.UseDefaultCredentials = true; Assert.Equal(CredentialCache.DefaultCredentials, request.Credentials); } [Theory, MemberData(nameof(EchoServers))] public void UseDefaultCredentials_SetFalse_CredentialsNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Credentials = _explicitCredential; request.UseDefaultCredentials = false; Assert.Equal(null, request.Credentials); } [Theory, MemberData(nameof(EchoServers))] public void BeginGetRequestStream_UseGETVerb_ThrowsProtocolViolationException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.Throws<ProtocolViolationException>(() => { request.BeginGetRequestStream(null, null); }); } [Theory, MemberData(nameof(EchoServers))] public void BeginGetRequestStream_UseHEADVerb_ThrowsProtocolViolationException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Head.Method; Assert.Throws<ProtocolViolationException>(() => { request.BeginGetRequestStream(null, null); }); } [Theory, MemberData(nameof(EchoServers))] public void BeginGetRequestStream_UseCONNECTVerb_ThrowsProtocolViolationException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = "CONNECT"; Assert.Throws<ProtocolViolationException>(() => { request.BeginGetRequestStream(null, null); }); } [Theory, MemberData(nameof(EchoServers))] public void BeginGetRequestStream_CreatePostRequestThenAbort_ThrowsWebException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; request.Abort(); WebException ex = Assert.Throws<WebException>(() => request.BeginGetRequestStream(null, null)); Assert.Equal(WebExceptionStatus.RequestCanceled, ex.Status); } [Theory, MemberData(nameof(EchoServers))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "no exception thrown on netfx")] public void BeginGetRequestStream_CreatePostRequestThenCallTwice_ThrowsInvalidOperationException(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); request.Method = "POST"; IAsyncResult asyncResult = request.BeginGetRequestStream(null, null); Assert.Throws<InvalidOperationException>(() => { request.BeginGetRequestStream(null, null); }); } [Theory, MemberData(nameof(EchoServers))] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "request stream not allowed for GET on netfx")] public void BeginGetRequestStream_CreateRequestThenBeginGetResponsePrior_ThrowsInvalidOperationException(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); IAsyncResult asyncResult = request.BeginGetResponse(null, null); Assert.Throws<InvalidOperationException>(() => { request.BeginGetRequestStream(null, null); }); } [Theory, MemberData(nameof(EchoServers))] public void BeginGetResponse_CreateRequestThenCallTwice_ThrowsInvalidOperationException(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); IAsyncResult asyncResult = request.BeginGetResponse(null, null); Assert.Throws<InvalidOperationException>(() => { request.BeginGetResponse(null, null); }); } [Theory, MemberData(nameof(EchoServers))] public void BeginGetResponse_CreatePostRequestThenAbort_ThrowsWebException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; request.Abort(); WebException ex = Assert.Throws<WebException>(() => request.BeginGetResponse(null, null)); Assert.Equal(WebExceptionStatus.RequestCanceled, ex.Status); } [Theory, MemberData(nameof(EchoServers))] public async Task GetRequestStreamAsync_WriteAndDisposeRequestStreamThenOpenRequestStream_ThrowsArgumentException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; Stream requestStream; using (requestStream = await request.GetRequestStreamAsync()) { requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length); } Assert.Throws<ArgumentException>(() => { var sr = new StreamReader(requestStream); }); } [Theory, MemberData(nameof(EchoServers))] public async Task GetRequestStreamAsync_SetPOSTThenGet_ExpectNotNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; Stream requestStream = await request.GetRequestStreamAsync(); Assert.NotNull(requestStream); } [Theory, MemberData(nameof(EchoServers))] public async Task GetResponseAsync_GetResponseStream_ExpectNotNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); WebResponse response = await request.GetResponseAsync(); Assert.NotNull(response.GetResponseStream()); } [Theory, MemberData(nameof(EchoServers))] public async Task GetResponseAsync_GetResponseStream_ContainsHost(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Get.Method; WebResponse response = await request.GetResponseAsync(); Stream myStream = response.GetResponseStream(); Assert.NotNull(myStream); String strContent; using (var sr = new StreamReader(myStream)) { strContent = sr.ReadToEnd(); } Assert.True(strContent.Contains("\"Host\": \"" + System.Net.Test.Common.Configuration.Http.Host + "\"")); } [Theory, MemberData(nameof(EchoServers))] public async Task GetResponseAsync_PostRequestStream_ContainsData(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; using (Stream requestStream = await request.GetRequestStreamAsync()) { requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length); } WebResponse response = await request.GetResponseAsync(); Stream myStream = response.GetResponseStream(); String strContent; using (var sr = new StreamReader(myStream)) { strContent = sr.ReadToEnd(); } Assert.True(strContent.Contains(RequestBody)); } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotFedoraOrRedHatOrCentos))] // #16201 [MemberData(nameof(EchoServers))] public async Task GetResponseAsync_UseDefaultCredentials_ExpectSuccess(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.UseDefaultCredentials = true; await request.GetResponseAsync(); } [OuterLoop] // fails on networks with DNS servers that provide a dummy page for invalid addresses [Fact] public void GetResponseAsync_ServerNameNotInDns_ThrowsWebException() { string serverUrl = string.Format("http://www.{0}.com/", Guid.NewGuid().ToString()); HttpWebRequest request = WebRequest.CreateHttp(serverUrl); WebException ex = Assert.Throws<WebException>(() => request.GetResponseAsync().GetAwaiter().GetResult()); Assert.Equal(WebExceptionStatus.NameResolutionFailure, ex.Status); } public static object[][] StatusCodeServers = { new object[] { System.Net.Test.Common.Configuration.Http.StatusCodeUri(false, 404) }, new object[] { System.Net.Test.Common.Configuration.Http.StatusCodeUri(true, 404) }, }; [Theory, MemberData(nameof(StatusCodeServers))] public async Task GetResponseAsync_ResourceNotFound_ThrowsWebException(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); WebException ex = await Assert.ThrowsAsync<WebException>(() => request.GetResponseAsync()); Assert.Equal(WebExceptionStatus.ProtocolError, ex.Status); } [Theory, MemberData(nameof(EchoServers))] public async Task HaveResponse_GetResponseAsync_ExpectTrue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); WebResponse response = await request.GetResponseAsync(); Assert.True(request.HaveResponse); } [ConditionalTheory(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotFedoraOrRedHatOrCentos))] // #16201 [MemberData(nameof(EchoServers))] public async Task Headers_GetResponseHeaders_ContainsExpectedValue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); HttpWebResponse response = (HttpWebResponse) await request.GetResponseAsync(); String headersString = response.Headers.ToString(); string headersPartialContent = "Content-Type: application/json"; Assert.True(headersString.Contains(headersPartialContent)); } [Theory, MemberData(nameof(EchoServers))] public void Method_SetThenGetToGET_ExpectSameValue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Get.Method; Assert.Equal(HttpMethod.Get.Method, request.Method); } [Theory, MemberData(nameof(EchoServers))] public void Method_SetThenGetToPOST_ExpectSameValue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; Assert.Equal(HttpMethod.Post.Method, request.Method); } [Theory, MemberData(nameof(EchoServers))] public void Proxy_GetDefault_ExpectNotNull(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.NotNull(request.Proxy); } [Theory, MemberData(nameof(EchoServers))] public void RequestUri_CreateHttpThenGet_ExpectSameUri(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.Equal(remoteServer, request.RequestUri); } [Theory, MemberData(nameof(EchoServers))] public async Task ResponseUri_GetResponseAsync_ExpectSameUri(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); WebResponse response = await request.GetResponseAsync(); Assert.Equal(remoteServer, response.ResponseUri); } [Theory, MemberData(nameof(EchoServers))] public void SupportsCookieContainer_GetDefault_ExpectTrue(Uri remoteServer) { HttpWebRequest request = WebRequest.CreateHttp(remoteServer); Assert.True(request.SupportsCookieContainer); } [Theory, MemberData(nameof(EchoServers))] public async Task SimpleScenario_UseGETVerb_Success(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync(); Stream responseStream = response.GetResponseStream(); String responseBody; using (var sr = new StreamReader(responseStream)) { responseBody = sr.ReadToEnd(); } Assert.Equal(HttpStatusCode.OK, response.StatusCode); } [Theory, MemberData(nameof(EchoServers))] public async Task SimpleScenario_UsePOSTVerb_Success(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); request.Method = HttpMethod.Post.Method; using (Stream requestStream = await request.GetRequestStreamAsync()) { requestStream.Write(_requestBodyBytes, 0, _requestBodyBytes.Length); } HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync(); Stream responseStream = response.GetResponseStream(); String responseBody; using (var sr = new StreamReader(responseStream)) { responseBody = sr.ReadToEnd(); } Assert.Equal(HttpStatusCode.OK, response.StatusCode); } [Theory, MemberData(nameof(EchoServers))] public async Task ContentType_AddHeaderWithNoContent_SendRequest_HeaderGetsSent(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); request.ContentType = "application/json"; HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync(); Stream responseStream = response.GetResponseStream(); String responseBody; using (var sr = new StreamReader(responseStream)) { responseBody = sr.ReadToEnd(); } _output.WriteLine(responseBody); Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.True(responseBody.Contains("Content-Type")); } [Theory, MemberData(nameof(EchoServers))] public void Abort_BeginGetRequestStreamThenAbort_EndGetRequestStreamThrowsWebException(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); request.Method = "POST"; RequestState state = new RequestState(); state.Request = request; request.BeginGetResponse(new AsyncCallback(RequestStreamCallback), state); request.Abort(); Assert.Equal(1, state.RequestStreamCallbackCallCount); WebException wex = state.SavedRequestStreamException as WebException; Assert.Equal(WebExceptionStatus.RequestCanceled, wex.Status); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "ResponseCallback not called after Abort on netfx")] [Theory, MemberData(nameof(EchoServers))] public void Abort_BeginGetResponseThenAbort_ResponseCallbackCalledBeforeAbortReturns(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); RequestState state = new RequestState(); state.Request = request; request.BeginGetResponse(new AsyncCallback(ResponseCallback), state); request.Abort(); Assert.Equal(1, state.ResponseCallbackCallCount); } [ActiveIssue(18800)] [Theory, MemberData(nameof(EchoServers))] public void Abort_BeginGetResponseThenAbort_EndGetResponseThrowsWebException(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); RequestState state = new RequestState(); state.Request = request; request.BeginGetResponse(new AsyncCallback(ResponseCallback), state); request.Abort(); WebException wex = state.SavedResponseException as WebException; Assert.Equal(WebExceptionStatus.RequestCanceled, wex.Status); } [Theory, MemberData(nameof(EchoServers))] public void Abort_BeginGetResponseUsingNoCallbackThenAbort_Success(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); request.BeginGetResponse(null, null); request.Abort(); } [Theory, MemberData(nameof(EchoServers))] public void Abort_CreateRequestThenAbort_Success(Uri remoteServer) { HttpWebRequest request = HttpWebRequest.CreateHttp(remoteServer); request.Abort(); } private void RequestStreamCallback(IAsyncResult asynchronousResult) { RequestState state = (RequestState) asynchronousResult.AsyncState; state.RequestStreamCallbackCallCount++; try { HttpWebRequest request = state.Request; state.Response = (HttpWebResponse) request.EndGetResponse(asynchronousResult); Stream stream = (Stream) request.EndGetRequestStream(asynchronousResult); stream.Dispose(); } catch (Exception ex) { state.SavedRequestStreamException = ex; } } private void ResponseCallback(IAsyncResult asynchronousResult) { RequestState state = (RequestState) asynchronousResult.AsyncState; state.ResponseCallbackCallCount++; try { using (HttpWebResponse response = (HttpWebResponse) state.Request.EndGetResponse(asynchronousResult)) { state.SavedResponseHeaders = response.Headers; } } catch (Exception ex) { state.SavedResponseException = ex; } } [Fact] public void HttpWebRequest_Serialize_Fails() { using (MemoryStream fs = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); var hwr = HttpWebRequest.CreateHttp("http://localhost"); if (PlatformDetection.IsFullFramework) { // .NET Framework throws a more detailed exception. // System.Runtime.Serialization.SerializationException): // Type 'System.Net.WebRequest+WebProxyWrapper' in Assembly 'System, Version=4.0.0. // 0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable. Assert.Throws<System.Runtime.Serialization.SerializationException>(() => formatter.Serialize(fs, hwr)); } else { // TODO: Issue #18850. Change HttpWebRquest to throw SerializationException similar to .NET Framework. Assert.Throws<PlatformNotSupportedException>(() => formatter.Serialize(fs, hwr)); } } } } public class RequestState { public HttpWebRequest Request; public HttpWebResponse Response; public WebHeaderCollection SavedResponseHeaders; public int RequestStreamCallbackCallCount; public int ResponseCallbackCallCount; public Exception SavedRequestStreamException; public Exception SavedResponseException; } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; namespace ServiceStack.OrmLite.Dapper { /// <summary> /// A bag of parameters that can be passed to the Dapper Query and Execute methods /// </summary> public partial class DynamicParameters : SqlMapper.IDynamicParameters, SqlMapper.IParameterLookup, SqlMapper.IParameterCallbacks { internal const DbType EnumerableMultiParameter = (DbType)(-1); private static readonly Dictionary<SqlMapper.Identity, Action<IDbCommand, object>> paramReaderCache = new Dictionary<SqlMapper.Identity, Action<IDbCommand, object>>(); private readonly Dictionary<string, ParamInfo> parameters = new Dictionary<string, ParamInfo>(); private List<object> templates; object SqlMapper.IParameterLookup.this[string name] => parameters.TryGetValue(name, out ParamInfo param) ? param.Value : null; /// <summary> /// construct a dynamic parameter bag /// </summary> public DynamicParameters() { RemoveUnused = true; } /// <summary> /// construct a dynamic parameter bag /// </summary> /// <param name="template">can be an anonymous type or a DynamicParameters bag</param> public DynamicParameters(object template) { RemoveUnused = true; AddDynamicParams(template); } /// <summary> /// Append a whole object full of params to the dynamic /// EG: AddDynamicParams(new {A = 1, B = 2}) // will add property A and B to the dynamic /// </summary> /// <param name="param"></param> public void AddDynamicParams(object param) { var obj = param; if (obj != null) { var subDynamic = obj as DynamicParameters; if (subDynamic == null) { var dictionary = obj as IEnumerable<KeyValuePair<string, object>>; if (dictionary == null) { templates = templates ?? new List<object>(); templates.Add(obj); } else { foreach (var kvp in dictionary) { Add(kvp.Key, kvp.Value, null, null, null); } } } else { if (subDynamic.parameters != null) { foreach (var kvp in subDynamic.parameters) { parameters.Add(kvp.Key, kvp.Value); } } if (subDynamic.templates != null) { templates = templates ?? new List<object>(); foreach (var t in subDynamic.templates) { templates.Add(t); } } } } } /// <summary> /// Add a parameter to this dynamic parameter list. /// </summary> /// <param name="name">The name of the parameter.</param> /// <param name="value">The value of the parameter.</param> /// <param name="dbType">The type of the parameter.</param> /// <param name="direction">The in or out direction of the parameter.</param> /// <param name="size">The size of the parameter.</param> public void Add(string name, object value, DbType? dbType, ParameterDirection? direction, int? size) { parameters[Clean(name)] = new ParamInfo { Name = name, Value = value, ParameterDirection = direction ?? ParameterDirection.Input, DbType = dbType, Size = size }; } /// <summary> /// Add a parameter to this dynamic parameter list. /// </summary> /// <param name="name">The name of the parameter.</param> /// <param name="value">The value of the parameter.</param> /// <param name="dbType">The type of the parameter.</param> /// <param name="direction">The in or out direction of the parameter.</param> /// <param name="size">The size of the parameter.</param> /// <param name="precision">The precision of the parameter.</param> /// <param name="scale">The scale of the parameter.</param> public void Add(string name, object value = null, DbType? dbType = null, ParameterDirection? direction = null, int? size = null, byte? precision = null, byte? scale = null) { parameters[Clean(name)] = new ParamInfo { Name = name, Value = value, ParameterDirection = direction ?? ParameterDirection.Input, DbType = dbType, Size = size, Precision = precision, Scale = scale }; } private static string Clean(string name) { if (!string.IsNullOrEmpty(name)) { switch (name[0]) { case '@': case ':': case '?': return name.Substring(1); } } return name; } void SqlMapper.IDynamicParameters.AddParameters(IDbCommand command, SqlMapper.Identity identity) { AddParameters(command, identity); } /// <summary> /// If true, the command-text is inspected and only values that are clearly used are included on the connection /// </summary> public bool RemoveUnused { get; set; } /// <summary> /// Add all the parameters needed to the command just before it executes /// </summary> /// <param name="command">The raw command prior to execution</param> /// <param name="identity">Information about the query</param> protected void AddParameters(IDbCommand command, SqlMapper.Identity identity) { var literals = SqlMapper.GetLiteralTokens(identity.sql); if (templates != null) { foreach (var template in templates) { var newIdent = identity.ForDynamicParameters(template.GetType()); Action<IDbCommand, object> appender; lock (paramReaderCache) { if (!paramReaderCache.TryGetValue(newIdent, out appender)) { appender = SqlMapper.CreateParamInfoGenerator(newIdent, true, RemoveUnused, literals); paramReaderCache[newIdent] = appender; } } appender(command, template); } // The parameters were added to the command, but not the // DynamicParameters until now. foreach (IDbDataParameter param in command.Parameters) { // If someone makes a DynamicParameters with a template, // then explicitly adds a parameter of a matching name, // it will already exist in 'parameters'. if (!parameters.ContainsKey(param.ParameterName)) { parameters.Add(param.ParameterName, new ParamInfo { AttachedParam = param, CameFromTemplate = true, DbType = param.DbType, Name = param.ParameterName, ParameterDirection = param.Direction, Size = param.Size, Value = param.Value }); } } // Now that the parameters are added to the command, let's place our output callbacks var tmp = outputCallbacks; if (tmp != null) { foreach (var generator in tmp) { generator(); } } } foreach (var param in parameters.Values) { if (param.CameFromTemplate) continue; var dbType = param.DbType; var val = param.Value; string name = Clean(param.Name); var isCustomQueryParameter = val is SqlMapper.ICustomQueryParameter; SqlMapper.ITypeHandler handler = null; if (dbType == null && val != null && !isCustomQueryParameter) { #pragma warning disable 618 dbType = SqlMapper.LookupDbType(val.GetType(), name, true, out handler); #pragma warning disable 618 } if (isCustomQueryParameter) { ((SqlMapper.ICustomQueryParameter)val).AddParameter(command, name); } else if (dbType == EnumerableMultiParameter) { #pragma warning disable 612, 618 SqlMapper.PackListParameters(command, name, val); #pragma warning restore 612, 618 } else { bool add = !command.Parameters.Contains(name); IDbDataParameter p; if (add) { p = command.CreateParameter(); p.ParameterName = name; } else { p = (IDbDataParameter)command.Parameters[name]; } p.Direction = param.ParameterDirection; if (handler == null) { #pragma warning disable 0618 p.Value = SqlMapper.SanitizeParameterValue(val); #pragma warning restore 0618 if (dbType != null && p.DbType != dbType) { p.DbType = dbType.Value; } var s = val as string; if (s?.Length <= DbString.DefaultLength) { p.Size = DbString.DefaultLength; } if (param.Size != null) p.Size = param.Size.Value; if (param.Precision != null) p.Precision = param.Precision.Value; if (param.Scale != null) p.Scale = param.Scale.Value; } else { if (dbType != null) p.DbType = dbType.Value; if (param.Size != null) p.Size = param.Size.Value; if (param.Precision != null) p.Precision = param.Precision.Value; if (param.Scale != null) p.Scale = param.Scale.Value; handler.SetValue(p, val ?? DBNull.Value); } if (add) { command.Parameters.Add(p); } param.AttachedParam = p; } } // note: most non-priveleged implementations would use: this.ReplaceLiterals(command); if (literals.Count != 0) SqlMapper.ReplaceLiterals(this, command, literals); } /// <summary> /// All the names of the param in the bag, use Get to yank them out /// </summary> public IEnumerable<string> ParameterNames => parameters.Select(p => p.Key); /// <summary> /// Get the value of a parameter /// </summary> /// <typeparam name="T"></typeparam> /// <param name="name"></param> /// <returns>The value, note DBNull.Value is not returned, instead the value is returned as null</returns> public T Get<T>(string name) { var paramInfo = parameters[Clean(name)]; var attachedParam = paramInfo.AttachedParam; object val = attachedParam == null ? paramInfo.Value : attachedParam.Value; if (val == DBNull.Value) { if (default(T) != null) { throw new ApplicationException("Attempting to cast a DBNull to a non nullable type! Note that out/return parameters will not have updated values until the data stream completes (after the 'foreach' for Query(..., buffered: false), or after the GridReader has been disposed for QueryMultiple)"); } return default(T); } return (T)val; } /// <summary> /// Allows you to automatically populate a target property/field from output parameters. It actually /// creates an InputOutput parameter, so you can still pass data in. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="target">The object whose property/field you wish to populate.</param> /// <param name="expression">A MemberExpression targeting a property/field of the target (or descendant thereof.)</param> /// <param name="dbType"></param> /// <param name="size">The size to set on the parameter. Defaults to 0, or DbString.DefaultLength in case of strings.</param> /// <returns>The DynamicParameters instance</returns> public DynamicParameters Output<T>(T target, Expression<Func<T, object>> expression, DbType? dbType = null, int? size = null) { var failMessage = "Expression must be a property/field chain off of a(n) {0} instance"; failMessage = string.Format(failMessage, typeof(T).Name); Action @throw = () => throw new InvalidOperationException(failMessage); // Is it even a MemberExpression? var lastMemberAccess = expression.Body as MemberExpression; if (lastMemberAccess == null || (!(lastMemberAccess.Member is PropertyInfo) && !(lastMemberAccess.Member is FieldInfo))) { if (expression.Body.NodeType == ExpressionType.Convert && expression.Body.Type == typeof(object) && ((UnaryExpression)expression.Body).Operand is MemberExpression) { // It's got to be unboxed lastMemberAccess = (MemberExpression)((UnaryExpression)expression.Body).Operand; } else { @throw(); } } // Does the chain consist of MemberExpressions leading to a ParameterExpression of type T? MemberExpression diving = lastMemberAccess; // Retain a list of member names and the member expressions so we can rebuild the chain. List<string> names = new List<string>(); List<MemberExpression> chain = new List<MemberExpression>(); do { // Insert the names in the right order so expression // "Post.Author.Name" becomes parameter "PostAuthorName" names.Insert(0, diving?.Member.Name); chain.Insert(0, diving); var constant = diving?.Expression as ParameterExpression; diving = diving?.Expression as MemberExpression; if (constant != null && constant.Type == typeof(T)) { break; } else if (diving == null || (!(diving.Member is PropertyInfo) && !(diving.Member is FieldInfo))) { @throw(); } } while (diving != null); var dynamicParamName = string.Concat(names.ToArray()); // Before we get all emitty... var lookup = string.Join("|", names.ToArray()); var cache = CachedOutputSetters<T>.Cache; var setter = (Action<object, DynamicParameters>)cache[lookup]; if (setter != null) goto MAKECALLBACK; // Come on let's build a method, let's build it, let's build it now! var dm = new DynamicMethod("ExpressionParam" + Guid.NewGuid().ToString(), null, new[] { typeof(object), GetType() }, true); var il = dm.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); // [object] il.Emit(OpCodes.Castclass, typeof(T)); // [T] // Count - 1 to skip the last member access for (var i = 0; i < chain.Count - 1; i++) { var member = chain[i].Member; if (member is PropertyInfo) { var get = ((PropertyInfo)member).GetGetMethod(true); il.Emit(OpCodes.Callvirt, get); // [Member{i}] } else // Else it must be a field! { il.Emit(OpCodes.Ldfld, (FieldInfo)member); // [Member{i}] } } var paramGetter = GetType().GetMethod("Get", new Type[] { typeof(string) }).MakeGenericMethod(lastMemberAccess.Type); il.Emit(OpCodes.Ldarg_1); // [target] [DynamicParameters] il.Emit(OpCodes.Ldstr, dynamicParamName); // [target] [DynamicParameters] [ParamName] il.Emit(OpCodes.Callvirt, paramGetter); // [target] [value], it's already typed thanks to generic method // GET READY var lastMember = lastMemberAccess.Member; if (lastMember is PropertyInfo) { var set = ((PropertyInfo)lastMember).GetSetMethod(true); il.Emit(OpCodes.Callvirt, set); // SET } else { il.Emit(OpCodes.Stfld, (FieldInfo)lastMember); // SET } il.Emit(OpCodes.Ret); // GO setter = (Action<object, DynamicParameters>)dm.CreateDelegate(typeof(Action<object, DynamicParameters>)); lock (cache) { cache[lookup] = setter; } // Queue the preparation to be fired off when adding parameters to the DbCommand MAKECALLBACK: (outputCallbacks ?? (outputCallbacks = new List<Action>())).Add(() => { // Finally, prep the parameter and attach the callback to it var targetMemberType = lastMemberAccess?.Type; int sizeToSet = (!size.HasValue && targetMemberType == typeof(string)) ? DbString.DefaultLength : size ?? 0; if (parameters.TryGetValue(dynamicParamName, out ParamInfo parameter)) { parameter.ParameterDirection = parameter.AttachedParam.Direction = ParameterDirection.InputOutput; if (parameter.AttachedParam.Size == 0) { parameter.Size = parameter.AttachedParam.Size = sizeToSet; } } else { dbType = (!dbType.HasValue) #pragma warning disable 618 ? SqlMapper.LookupDbType(targetMemberType, targetMemberType?.Name, true, out SqlMapper.ITypeHandler handler) #pragma warning restore 618 : dbType; // CameFromTemplate property would not apply here because this new param // Still needs to be added to the command Add(dynamicParamName, expression.Compile().Invoke(target), null, ParameterDirection.InputOutput, sizeToSet); } parameter = parameters[dynamicParamName]; parameter.OutputCallback = setter; parameter.OutputTarget = target; }); return this; } private List<Action> outputCallbacks; void SqlMapper.IParameterCallbacks.OnCompleted() { foreach (var param in from p in parameters select p.Value) { param.OutputCallback?.Invoke(param.OutputTarget, this); } } } }
using System; using System.Collections.Generic; using NUnit.Framework; using System.Threading; using System.Linq; using Moq; using RestSharp; namespace Twilio.Api.Tests.Integration { [TestFixture] public class CallTests { private const string CALL_SID = "CA123"; private const string FROM = "+15005550006"; private const string TO = "+13144586142"; private const string URL = "http://www.example.com/phone/"; ManualResetEvent manualResetEvent = null; private Mock<TwilioRestClient> mockClient; [SetUp] public void Setup() { mockClient = new Mock<TwilioRestClient>(Credentials.AccountSid, Credentials.AuthToken); mockClient.CallBase = true; } [Test] public void ShouldInitiateOutboundCall() { IRestRequest savedRequest = null; mockClient.Setup(trc => trc.Execute<Call>(It.IsAny<IRestRequest>())) .Callback<IRestRequest>((request) => savedRequest = request) .Returns(new Call()); var client = mockClient.Object; client.InitiateOutboundCall(FROM, TO, URL); mockClient.Verify(trc => trc.Execute<Call>(It.IsAny<IRestRequest>()), Times.Once); Assert.IsNotNull(savedRequest); Assert.AreEqual("Accounts/{AccountSid}/Calls.json", savedRequest.Resource); Assert.AreEqual(Method.POST, savedRequest.Method); Assert.AreEqual(3, savedRequest.Parameters.Count); var fromParam = savedRequest.Parameters.Find(x => x.Name == "From"); Assert.IsNotNull(fromParam); Assert.AreEqual(FROM, fromParam.Value); var toParam = savedRequest.Parameters.Find(x => x.Name == "To"); Assert.IsNotNull(toParam); Assert.AreEqual(TO, toParam.Value); var urlParam = savedRequest.Parameters.Find(x => x.Name == "Url"); Assert.IsNotNull(urlParam); Assert.AreEqual(URL, urlParam.Value); } [Test] public void ShouldInitiateOutboundCallWithCallbackEvents() { IRestRequest savedRequest = null; mockClient.Setup(trc => trc.Execute<Call>(It.IsAny<IRestRequest>())) .Callback<IRestRequest>((request) => savedRequest = request) .Returns(new Call()); var client = mockClient.Object; var options = new CallOptions(); options.To = TO; options.From = FROM; options.Url = URL; options.StatusCallback = "http://example.com"; string[] events = { "initiated", "ringing", "completed" }; options.StatusCallbackEvents = events; client.InitiateOutboundCall(options); mockClient.Verify(trc => trc.Execute<Call>(It.IsAny<IRestRequest>()), Times.Once); Assert.IsNotNull(savedRequest); Assert.AreEqual("Accounts/{AccountSid}/Calls.json", savedRequest.Resource); Assert.AreEqual(Method.POST, savedRequest.Method); Assert.AreEqual(7, savedRequest.Parameters.Count); var fromParam = savedRequest.Parameters.Find(x => x.Name == "From"); Assert.IsNotNull(fromParam); Assert.AreEqual(FROM, fromParam.Value); var toParam = savedRequest.Parameters.Find(x => x.Name == "To"); Assert.IsNotNull(toParam); Assert.AreEqual(TO, toParam.Value); var urlParam = savedRequest.Parameters.Find(x => x.Name == "Url"); Assert.IsNotNull(urlParam); Assert.AreEqual(URL, urlParam.Value); var callbackParam = savedRequest.Parameters.Find(x => x.Name == "StatusCallback"); Assert.IsNotNull(callbackParam); Assert.AreEqual("http://example.com", callbackParam.Value); var eventParams = savedRequest.Parameters.FindAll(x => x.Name == "StatusCallbackEvent"); Assert.IsNotNull(eventParams); Assert.AreEqual(3, eventParams.Count); var values = new System.Collections.Generic.List<string>(); eventParams.ForEach((p => values.Add(p.Value.ToString()))); values.Sort(); Assert.AreEqual(new List<string>() { "completed", "initiated", "ringing" }, values); } [Test] public void ShouldInitiateOutboundCallAsynchronously() { IRestRequest savedRequest = null; mockClient.Setup(trc => trc.ExecuteAsync<Call>(It.IsAny<IRestRequest>(), It.IsAny<Action<Call>>())) .Callback<IRestRequest, Action<Call>>((request, action) => savedRequest = request); var client = mockClient.Object; manualResetEvent = new ManualResetEvent(false); client.InitiateOutboundCall(FROM, TO, URL, call => { manualResetEvent.Set(); }); manualResetEvent.WaitOne(1); mockClient.Verify(trc => trc.ExecuteAsync<Call>(It.IsAny<IRestRequest>(), It.IsAny<Action<Call>>()), Times.Once); Assert.IsNotNull(savedRequest); Assert.AreEqual("Accounts/{AccountSid}/Calls.json", savedRequest.Resource); Assert.AreEqual(Method.POST, savedRequest.Method); Assert.AreEqual(3, savedRequest.Parameters.Count); var fromParam = savedRequest.Parameters.Find(x => x.Name == "From"); Assert.IsNotNull(fromParam); Assert.AreEqual(FROM, fromParam.Value); var toParam = savedRequest.Parameters.Find(x => x.Name == "To"); Assert.IsNotNull(toParam); Assert.AreEqual(TO, toParam.Value); var urlParam = savedRequest.Parameters.Find(x => x.Name == "Url"); Assert.IsNotNull(urlParam); Assert.AreEqual(URL, urlParam.Value); } [Test] public void ShouldGetCall() { IRestRequest savedRequest = null; mockClient.Setup(trc => trc.Execute<Call>(It.IsAny<IRestRequest>())) .Callback<IRestRequest>((request) => savedRequest = request) .Returns(new Call()); var client = mockClient.Object; client.GetCall(CALL_SID); mockClient.Verify(trc => trc.Execute<Call>(It.IsAny<IRestRequest>()), Times.Once); Assert.IsNotNull(savedRequest); Assert.AreEqual("Accounts/{AccountSid}/Calls/{CallSid}.json", savedRequest.Resource); Assert.AreEqual(Method.GET, savedRequest.Method); Assert.AreEqual(1, savedRequest.Parameters.Count); var callSidParam = savedRequest.Parameters.Find(x => x.Name == "CallSid"); Assert.IsNotNull(callSidParam); Assert.AreEqual(CALL_SID, callSidParam.Value); } [Test] public void ShouldListCalls() { IRestRequest savedRequest = null; mockClient.Setup(trc => trc.Execute<CallResult>(It.IsAny<IRestRequest>())) .Callback<IRestRequest>((request) => savedRequest = request) .Returns(new CallResult()); var client = mockClient.Object; client.ListCalls(); mockClient.Verify(trc => trc.Execute<CallResult>(It.IsAny<IRestRequest>()), Times.Once); Assert.IsNotNull(savedRequest); Assert.AreEqual("Accounts/{AccountSid}/Calls.json", savedRequest.Resource); Assert.AreEqual(Method.GET, savedRequest.Method); Assert.AreEqual(0, savedRequest.Parameters.Count); } [Test] public void ShouldListCallsByNumber() { IRestRequest savedRequest = null; mockClient.Setup(trc => trc.Execute<CallResult>(It.IsAny<IRestRequest>())) .Callback<IRestRequest>((request) => savedRequest = request) .Returns(new CallResult()); var client = mockClient.Object; client.ListCalls(FROM); mockClient.Verify(trc => trc.Execute<CallResult>(It.IsAny<IRestRequest>()), Times.Once); Assert.IsNotNull(savedRequest); Assert.AreEqual("Accounts/{AccountSid}/Calls.json", savedRequest.Resource); Assert.AreEqual(Method.GET, savedRequest.Method); Assert.AreEqual(1, savedRequest.Parameters.Count); } [Test] public void ShouldListCallsAsynchronously() { IRestRequest savedRequest = null; mockClient.Setup(trc => trc.ExecuteAsync<CallResult>(It.IsAny<IRestRequest>(), It.IsAny<Action<CallResult>>())) .Callback<IRestRequest, Action<CallResult>>((request, action) => savedRequest = request); var client = mockClient.Object; manualResetEvent = new ManualResetEvent(false); client.ListCalls(calls => { manualResetEvent.Set(); }); manualResetEvent.WaitOne(1); mockClient.Verify(trc => trc.ExecuteAsync<CallResult>(It.IsAny<IRestRequest>(), It.IsAny<Action<CallResult>>()), Times.Once); Assert.IsNotNull(savedRequest); Assert.AreEqual("Accounts/{AccountSid}/Calls.json", savedRequest.Resource); Assert.AreEqual(Method.GET, savedRequest.Method); Assert.AreEqual(0, savedRequest.Parameters.Count); } [Test] public void ShouldListCallsWithFilters() { IRestRequest savedRequest = null; mockClient.Setup(trc => trc.Execute<CallResult>(It.IsAny<IRestRequest>())) .Callback<IRestRequest>((request) => savedRequest = request) .Returns(new CallResult()); var client = mockClient.Object; CallListRequest options = new CallListRequest(); options.From = FROM; options.StartTime = new DateTime(); client.ListCalls(options); mockClient.Verify(trc => trc.Execute<CallResult>(It.IsAny<IRestRequest>()), Times.Once); Assert.IsNotNull(savedRequest); Assert.AreEqual("Accounts/{AccountSid}/Calls.json", savedRequest.Resource); Assert.AreEqual(Method.GET, savedRequest.Method); Assert.AreEqual(2, savedRequest.Parameters.Count); var fromParam = savedRequest.Parameters.Find(x => x.Name == "From"); Assert.IsNotNull(fromParam); Assert.AreEqual(FROM, fromParam.Value); var startTimeParam = savedRequest.Parameters.Find(x => x.Name == "StartTime"); Assert.IsNotNull(startTimeParam); Assert.AreEqual(options.StartTime.Value.ToString("yyyy-MM-dd"), startTimeParam.Value); } [Test] public void ShouldRedirectCall() { IRestRequest savedRequest = null; mockClient.Setup(trc => trc.Execute<Call>(It.IsAny<IRestRequest>())) .Callback<IRestRequest>((request) => savedRequest = request) .Returns(new Call()); var client = mockClient.Object; var redirectedFriendlyName = Utilities.MakeRandomFriendlyName(); var redirectUrl = "http://devin.webscript.io/twilioconf?conf=" + redirectedFriendlyName; client.RedirectCall(CALL_SID, redirectUrl, "GET"); mockClient.Verify(trc => trc.Execute<Call>(It.IsAny<IRestRequest>()), Times.Once); Assert.IsNotNull(savedRequest); Assert.AreEqual("Accounts/{AccountSid}/Calls/{CallSid}.json", savedRequest.Resource); Assert.AreEqual(Method.POST, savedRequest.Method); Assert.AreEqual(3, savedRequest.Parameters.Count); var callSidParam = savedRequest.Parameters.Find(x => x.Name == "CallSid"); Assert.IsNotNull(callSidParam); Assert.AreEqual(CALL_SID, callSidParam.Value); var urlParam = savedRequest.Parameters.Find(x => x.Name == "Url"); Assert.IsNotNull(urlParam); Assert.AreEqual(redirectUrl, urlParam.Value); var methodParam = savedRequest.Parameters.Find(x => x.Name == "Method"); Assert.IsNotNull(methodParam); Assert.AreEqual("GET", methodParam.Value); } [Test] public void ShouldHangupCall() { IRestRequest savedRequest = null; mockClient.Setup(trc => trc.Execute<Call>(It.IsAny<IRestRequest>())) .Callback<IRestRequest>((request) => savedRequest = request) .Returns(new Call()); var client = mockClient.Object; client.HangupCall(CALL_SID, HangupStyle.Completed); mockClient.Verify(trc => trc.Execute<Call>(It.IsAny<IRestRequest>()), Times.Once); Assert.IsNotNull(savedRequest); Assert.AreEqual("Accounts/{AccountSid}/Calls/{CallSid}.json", savedRequest.Resource); Assert.AreEqual(Method.POST, savedRequest.Method); Assert.AreEqual(2, savedRequest.Parameters.Count); var callSidParam = savedRequest.Parameters.Find(x => x.Name == "CallSid"); Assert.IsNotNull(callSidParam); Assert.AreEqual(CALL_SID, callSidParam.Value); var statusParam = savedRequest.Parameters.Find(x => x.Name == "Status"); Assert.IsNotNull(statusParam); Assert.AreEqual(HangupStyle.Completed.ToString().ToLower(), statusParam.Value); } } }
using System; //System.Int32.System.IConvertibleToByte public class Int32IConvertibleToByte { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Convert a random int32 to byte "); try { Int32 i1 = (Int32)TestLibrary.Generator.GetByte(-55); IConvertible Icon1 = (IConvertible)i1; if (Icon1.ToByte(null) != i1) { TestLibrary.TestFramework.LogError("001", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Convert ByteMaxValue to byte "); try { Int32 i1 = (Int32)Byte.MaxValue; IConvertible Icon1 = (IConvertible)i1; if (Icon1.ToByte(null) != i1) { TestLibrary.TestFramework.LogError("003", "The result is not the value as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3:Convert zero to byte "); try { Int32 i1 = 0; IConvertible Icon1 = (IConvertible)i1; if (Icon1.ToByte(null) != 0) { TestLibrary.TestFramework.LogError("005", "The result is not zero as expected"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #region Nagetive Test Cases public bool NegTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest1: Convert a negative byte int32 to Byte "); try { Int32 i1 = 0; while (i1 == 0) { i1 = (Int32)TestLibrary.Generator.GetByte(-55); } IConvertible Icon1 = (IConvertible)(-i1); Byte b1 = Icon1.ToByte(null); TestLibrary.TestFramework.LogError("101", "An overflowException was not thrown as expected"); retVal = false; } catch (System.OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("102", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest2: Convert int32 to Byte "); try { Int32 i1 = 0; while (i1 <= 255) { i1 = (Int32)TestLibrary.Generator.GetInt32(-55); } IConvertible Icon1 = (IConvertible)(i1); Byte b1 = Icon1.ToByte(null); TestLibrary.TestFramework.LogError("103", "An overflowException was not thrown as expected"); retVal = false; } catch (System.OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("104", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("NegTest3: Check the border value "); try { Int32 i1 = 256; IConvertible Icon1 = (IConvertible)(i1); Byte b1 = Icon1.ToByte(null); TestLibrary.TestFramework.LogError("105", "An overflowException was not thrown as expected"); retVal = false; } catch (System.OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("106", "Unexpected exception: " + e); retVal = false; } return retVal; } #endregion #endregion public static int Main() { Int32IConvertibleToByte test = new Int32IConvertibleToByte(); TestLibrary.TestFramework.BeginTestCase("Int32IConvertibleToByte"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2015 FUJIWARA, Yusuke // // 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 -- License Terms -- #if UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT #define UNITY #endif using System; using System.Globalization; using System.IO; using System.Runtime.Serialization; namespace MsgPack.Serialization.DefaultSerializers { #if !UNITY internal sealed class MultidimensionalArraySerializer<TArray, TItem> : MessagePackSerializer<TArray> #else internal sealed class UnityMultidimensionalArraySerializer : NonGenericMessagePackSerializer #endif // !UNITY { #if !UNITY private readonly MessagePackSerializer<TItem> _itemSerializer; private readonly MessagePackSerializer<int[]> _int32ArraySerializer; #else private readonly IMessagePackSingleObjectSerializer _itemSerializer; private readonly IMessagePackSingleObjectSerializer _int32ArraySerializer; private readonly Type _itemType; #endif // !UNITY #if !UNITY public MultidimensionalArraySerializer( SerializationContext ownerContext, PolymorphismSchema itemsSchema ) : base( ownerContext ) { this._itemSerializer = ownerContext.GetSerializer<TItem>( itemsSchema ); this._int32ArraySerializer = ownerContext.GetSerializer<int[]>( itemsSchema ); } #else public UnityMultidimensionalArraySerializer( SerializationContext ownerContext, Type itemType, PolymorphismSchema itemsSchema ) : base( ownerContext, itemType.MakeArrayType() ) { this._itemSerializer = ownerContext.GetSerializer( itemType, itemsSchema ); this._int32ArraySerializer = ownerContext.GetSerializer( typeof( int[] ), itemsSchema ); this._itemType = itemType; } #endif // !UNITY [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "By design" )] [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "By design" )] #if !UNITY protected internal override void PackToCore( Packer packer, TArray objectTree ) { this.PackArrayCore( packer, ( Array )( object )objectTree ); } #else protected internal override void PackToCore( Packer packer, object objectTree ) { this.PackArrayCore( packer, ( Array )objectTree ); } #endif // !UNITY private void PackArrayCore( Packer packer, Array array ) { #if !SILVERLIGHT && !NETFX_CORE var longLength = array.LongLength; if ( longLength > Int32.MaxValue ) { throw new NotSupportedException( "Array length over 32bit is not supported." ); } var totalLength = unchecked( ( int )longLength ); #else var totalLength = array.Length; #endif // !SILVERLIGHT && !NETFX_CORE int[] lowerBounds, lengths; GetArrayMetadata( array, out lengths, out lowerBounds ); packer.PackArrayHeader( 2 ); using ( var buffer = new MemoryStream() ) using ( var bodyPacker = Packer.Create( buffer ) ) { bodyPacker.PackArrayHeader( 2 ); this._int32ArraySerializer.PackTo( bodyPacker, lengths ); this._int32ArraySerializer.PackTo( bodyPacker, lowerBounds ); packer.PackExtendedTypeValue( this.OwnerContext.ExtTypeCodeMapping[ KnownExtTypeName.MultidimensionalArray ], buffer.ToArray() ); } packer.PackArrayHeader( totalLength ); ForEach( array, totalLength, lowerBounds, lengths, #if !UNITY // ReSharper disable once AccessToDisposedClosure indices => this._itemSerializer.PackTo( packer, ( TItem )array.GetValue( indices ) ) #else // ReSharper disable once AccessToDisposedClosure indices => this._itemSerializer.PackTo( packer, array.GetValue( indices ) ) #endif // !UNITY ); } private static void GetArrayMetadata( Array array, out int[] lengths, out int[] lowerBounds ) { lowerBounds = new int[ array.Rank ]; lengths = new int[ array.Rank ]; for ( var dimension = 0; dimension < array.Rank; dimension++ ) { lowerBounds[ dimension ] = array.GetLowerBound( dimension ); lengths[ dimension ] = array.GetLength( dimension ); } } [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "By design" )] #if !UNITY protected internal override TArray UnpackFromCore( Unpacker unpacker ) #else protected internal override object UnpackFromCore( Unpacker unpacker ) #endif // !UNITY { if ( !unpacker.IsArrayHeader ) { throw SerializationExceptions.NewIsNotArrayHeader(); } if ( UnpackHelpers.GetItemsCount( unpacker ) != 2 ) { throw new SerializationException( "Multidimensional array must be encoded as 2 element array." ); } using ( var wholeUnpacker = unpacker.ReadSubtree() ) { if ( !wholeUnpacker.Read() ) { throw SerializationExceptions.NewUnexpectedEndOfStream(); } MessagePackExtendedTypeObject metadata; try { metadata = wholeUnpacker.LastReadData.AsMessagePackExtendedTypeObject(); } catch ( InvalidOperationException ex ) { throw new SerializationException( "Multidimensional array must be encoded as ext type.", ex ); } if ( metadata.TypeCode != this.OwnerContext.ExtTypeCodeMapping[ KnownExtTypeName.MultidimensionalArray ] ) { throw new SerializationException( String.Format( CultureInfo.CurrentCulture, "Multidimensional array must be encoded as ext type 0x{0:X2}.", this.OwnerContext.ExtTypeCodeMapping[ KnownExtTypeName.MultidimensionalArray ] ) ); } int[] lengths, lowerBounds; using ( var arrayMetadata = new MemoryStream( metadata.Body ) ) using ( var metadataUnpacker = Unpacker.Create( arrayMetadata ) ) { if ( !metadataUnpacker.Read() ) { throw SerializationExceptions.NewUnexpectedEndOfStream(); } if ( !metadataUnpacker.IsArrayHeader ) { throw SerializationExceptions.NewIsNotArrayHeader(); } if ( UnpackHelpers.GetItemsCount( metadataUnpacker ) != 2 ) { throw new SerializationException( "Multidimensional metadata array must be encoded as 2 element array." ); } this.ReadArrayMetadata( metadataUnpacker, out lengths, out lowerBounds ); } #if SILVERLIGHT // Simulate lowerbounds because Array.Initialize() in Silverlight does not support lowerbounds. var inflatedLengths = new int[ lengths.Length ]; for ( var i = 0; i < lowerBounds.Length; i++ ) { inflatedLengths[ i ] = lengths[ i ] + lowerBounds[ i ]; } #endif // SILVERLIGHT if ( !wholeUnpacker.Read() ) { throw SerializationExceptions.NewUnexpectedEndOfStream(); } if ( !wholeUnpacker.IsArrayHeader ) { throw SerializationExceptions.NewIsNotArrayHeader(); } using ( var arrayUnpacker = wholeUnpacker.ReadSubtree() ) { var result = Array.CreateInstance( #if !UNITY typeof( TItem ), #else this._itemType, #endif // !UNITY #if !SILVERLIGHT lengths, lowerBounds #else inflatedLengths #endif // !SILVERLIGHT ); var totalLength = UnpackHelpers.GetItemsCount( arrayUnpacker ); if ( totalLength > 0 ) { ForEach( result, totalLength, lowerBounds, lengths, indices => { // ReSharper disable AccessToDisposedClosure if ( !arrayUnpacker.Read() ) { throw SerializationExceptions.NewUnexpectedEndOfStream(); } result.SetValue( this._itemSerializer.UnpackFrom( arrayUnpacker ), indices ); // ReSharper restore AccessToDisposedClosure } ); } #if !UNITY return ( TArray ) ( object ) result; #else return result; #endif // !UNITY } } } private void ReadArrayMetadata( Unpacker metadataUnpacker, out int[] lengths, out int[] lowerBounds ) { if ( !metadataUnpacker.Read() ) { throw SerializationExceptions.NewUnexpectedEndOfStream(); } if ( !metadataUnpacker.IsArrayHeader ) { throw SerializationExceptions.NewIsNotArrayHeader(); } using ( var lengthsUnpacker = metadataUnpacker.ReadSubtree() ) { #if !UNITY lengths = this._int32ArraySerializer.UnpackFrom( lengthsUnpacker ); #else lengths = this._int32ArraySerializer.UnpackFrom( lengthsUnpacker ) as int[]; #endif // !UNITY } if ( !metadataUnpacker.Read() ) { throw SerializationExceptions.NewUnexpectedEndOfStream(); } if ( !metadataUnpacker.IsArrayHeader ) { throw SerializationExceptions.NewIsNotArrayHeader(); } using ( var lowerBoundsUnpacker = metadataUnpacker.ReadSubtree() ) { #if !UNITY lowerBounds = this._int32ArraySerializer.UnpackFrom( lowerBoundsUnpacker ); #else lowerBounds = this._int32ArraySerializer.UnpackFrom( lowerBoundsUnpacker ) as int[]; #endif // !UNITY } } private static void ForEach( Array array, int totalLength, int[] lowerBounds, int[] lengths, Action<int[]> action ) { var indices = new int[ array.Rank ]; for ( var dimension = 0; dimension < array.Rank; dimension++ ) { indices[ dimension ] = lowerBounds[ dimension ]; } for ( var i = 0; i < totalLength; i++ ) { action( indices ); // Canculate indices with carrying up. var dimension = indices.Length - 1; for ( ; dimension >= 0; dimension-- ) { if ( ( indices[ dimension ] + 1 ) < lengths[ dimension ] + lowerBounds[ dimension ] ) { indices[ dimension ]++; break; } // Let's carry up, so set 0 to current dimension. indices[ dimension ] = lowerBounds[ dimension ]; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.Runtime { public enum RhFailFastReason { Unknown = 0, InternalError = 1, // "Runtime internal error" UnhandledException_ExceptionDispatchNotAllowed = 2, // "Unhandled exception: no handler found before escaping a finally clause or other fail-fast scope." UnhandledException_CallerDidNotHandle = 3, // "Unhandled exception: no handler found in calling method." ClassLibDidNotTranslateExceptionID = 4, // "Unable to translate failure into a classlib-specific exception object." IllegalNativeCallableEntry = 5, // "Invalid Program: attempted to call a NativeCallable method from runtime-typesafe code." PN_UnhandledException = 6, // ProjectN: "unhandled exception" PN_UnhandledExceptionFromPInvoke = 7, // ProjectN: "Unhandled exception: an unmanaged exception was thrown out of a managed-to-native transition." Max } // Keep this synchronized with the duplicate definition in DebugEventSource.cpp [Flags] internal enum ExceptionEventKind { Thrown = 1, CatchHandlerFound = 2, Unhandled = 4, FirstPassFrameEntered = 8 } internal unsafe static class DebuggerNotify { // We cache the events a debugger is interested on the C# side to avoid p/invokes when the // debugger isn't attached. // // Ideally we would like the managed debugger to start toggling this directly so that // it stays perfectly up-to-date. However as a reasonable approximation we fetch // the value from native code at the beginning of each exception dispatch. If the debugger // attempts to enroll in more events mid-exception handling we aren't going to see it. private static ExceptionEventKind s_cachedEventMask; internal static void BeginFirstPass(Exception e, byte* faultingIP, UIntPtr faultingFrameSP) { s_cachedEventMask = InternalCalls.RhpGetRequestedExceptionEvents(); if ((s_cachedEventMask & ExceptionEventKind.Thrown) == 0) return; InternalCalls.RhpSendExceptionEventToDebugger(ExceptionEventKind.Thrown, faultingIP, faultingFrameSP); } internal static void FirstPassFrameEntered(Exception e, byte* enteredFrameIP, UIntPtr enteredFrameSP) { s_cachedEventMask = InternalCalls.RhpGetRequestedExceptionEvents(); if ((s_cachedEventMask & ExceptionEventKind.FirstPassFrameEntered) == 0) return; InternalCalls.RhpSendExceptionEventToDebugger(ExceptionEventKind.FirstPassFrameEntered, enteredFrameIP, enteredFrameSP); } internal static void EndFirstPass(Exception e, byte* handlerIP, UIntPtr handlingFrameSP) { if (handlerIP == null) { if ((s_cachedEventMask & ExceptionEventKind.Unhandled) == 0) return; InternalCalls.RhpSendExceptionEventToDebugger(ExceptionEventKind.Unhandled, null, UIntPtr.Zero); } else { if ((s_cachedEventMask & ExceptionEventKind.CatchHandlerFound) == 0) return; InternalCalls.RhpSendExceptionEventToDebugger(ExceptionEventKind.CatchHandlerFound, handlerIP, handlingFrameSP); } } internal static void BeginSecondPass() { //desktop debugging has an unwind begin event, however it appears that is unneeded for now, and possibly // will never be needed? } } internal unsafe static class EH { internal static UIntPtr MaxSP { get { return new UIntPtr(unchecked((void*)(ulong)-1L)); } } private enum RhEHClauseKind { RH_EH_CLAUSE_TYPED = 0, RH_EH_CLAUSE_FAULT = 1, RH_EH_CLAUSE_FILTER = 2, RH_EH_CLAUSE_UNUSED = 3, } private struct RhEHClause { internal RhEHClauseKind _clauseKind; internal uint _tryStartOffset; internal uint _tryEndOffset; internal uint _filterOffset; internal uint _handlerOffset; internal void* _pTargetType; ///<summary> /// We expect the stackwalker to adjust return addresses to point at 'return address - 1' so that we /// can use an interval here that is closed at the start and open at the end. When a hardware fault /// occurs, the IP is pointing at the start of the instruction and will not be adjusted by the /// stackwalker. Therefore, it will naturally work with an interval that has a closed start and open /// end. ///</summary> public bool ContainsCodeOffset(uint codeOffset) { return ((codeOffset >= _tryStartOffset) && (codeOffset < _tryEndOffset)); } } [StructLayout(LayoutKind.Explicit, Size = AsmOffsets.SIZEOF__EHEnum)] private struct EHEnum { [FieldOffset(0)] private IntPtr _dummy; // For alignment } // This is a fail-fast function used by the runtime as a last resort that will terminate the process with // as little effort as possible. No guarantee is made about the semantics of this fail-fast. internal static void FallbackFailFast(RhFailFastReason reason, Exception unhandledException) { InternalCalls.RhpFallbackFailFast(); } // Constants used with RhpGetClasslibFunction, to indicate which classlib function // we are interested in. // Note: make sure you change the def in EHHelpers.cpp if you change this! internal enum ClassLibFunctionId { GetRuntimeException = 0, FailFast = 1, // UnhandledExceptionHandler = 2, // unused AppendExceptionStackFrame = 3, } // Given an address pointing somewhere into a managed module, get the classlib-defined fail-fast // function and invoke it. Any failure to find and invoke the function, or if it returns, results in // Rtm-define fail-fast behavior. internal unsafe static void FailFastViaClasslib(RhFailFastReason reason, Exception unhandledException, IntPtr classlibAddress) { // Find the classlib function that will fail fast. This is a RuntimeExport function from the // classlib module, and is therefore managed-callable. IntPtr pFailFastFunction = (IntPtr)InternalCalls.RhpGetClasslibFunction(classlibAddress, ClassLibFunctionId.FailFast); if (pFailFastFunction == IntPtr.Zero) { // The classlib didn't provide a function, so we fail our way... FallbackFailFast(reason, unhandledException); } try { // Invoke the classlib fail fast function. CalliIntrinsics.CallVoid(pFailFastFunction, reason, unhandledException, IntPtr.Zero); } catch { // disallow all exceptions leaking out of callbacks } // The classlib's function should never return and should not throw. If it does, then we fail our way... FallbackFailFast(reason, unhandledException); } #if AMD64 [StructLayout(LayoutKind.Explicit, Size = 0x4d0)] #elif ARM [StructLayout(LayoutKind.Explicit, Size=0x1a0)] #elif X86 [StructLayout(LayoutKind.Explicit, Size=0x2cc)] #else [StructLayout(LayoutKind.Explicit, Size = 0x10)] // this is small enough that it should trip an assert in RhpCopyContextFromExInfo #endif private struct OSCONTEXT { } #if ARM private const int c_IPAdjustForHardwareFault = 2; #else private const int c_IPAdjustForHardwareFault = 1; #endif internal unsafe static void* PointerAlign(void* ptr, int alignmentInBytes) { int alignMask = alignmentInBytes - 1; #if BIT64 return (void*)((((long)ptr) + alignMask) & ~alignMask); #else return (void*)((((int)ptr) + alignMask) & ~alignMask); #endif } [MethodImpl(MethodImplOptions.NoInlining)] internal unsafe static void UnhandledExceptionFailFastViaClasslib( RhFailFastReason reason, Exception unhandledException, ref ExInfo exInfo) { IntPtr pFailFastFunction = (IntPtr)InternalCalls.RhpGetClasslibFunction(exInfo._pExContext->IP, ClassLibFunctionId.FailFast); if (pFailFastFunction == IntPtr.Zero) { FailFastViaClasslib( reason, unhandledException, exInfo._pExContext->IP); } // 16-byte align the context. This is overkill on x86 and ARM, but simplifies things slightly. const int contextAlignment = 16; byte* pbBuffer = stackalloc byte[sizeof(OSCONTEXT) + contextAlignment]; void* pContext = PointerAlign(pbBuffer, contextAlignment); // We 'normalized' the faulting IP of hardware faults to behave like return addresses. Undo this // normalization here so that we report the correct thing in the exception context record. if ((exInfo._kind & ExKind.KindMask) == ExKind.HardwareFault) { exInfo._pExContext->IP = (IntPtr)(((byte*)exInfo._pExContext->IP) - c_IPAdjustForHardwareFault); } InternalCalls.RhpCopyContextFromExInfo(pContext, sizeof(OSCONTEXT), exInfo._pExContext); try { CalliIntrinsics.CallVoid(pFailFastFunction, reason, unhandledException, (IntPtr)pContext); } catch { // disallow all exceptions leaking out of callbacks } // The classlib's funciton should never return and should not throw. If it does, then we fail our way... FallbackFailFast(reason, unhandledException); } private enum RhEHFrameType { RH_EH_FIRST_FRAME = 1, RH_EH_FIRST_RETHROW_FRAME = 2, } internal unsafe static void AppendExceptionStackFrameViaClasslib( Exception exception, IntPtr IP, bool isFirstRethrowFrame, IntPtr classlibAddress, bool isFirstFrame) { IntPtr pAppendStackFrame = (IntPtr)InternalCalls.RhpGetClasslibFunction(classlibAddress, ClassLibFunctionId.AppendExceptionStackFrame); int flags = (isFirstFrame ? (int)RhEHFrameType.RH_EH_FIRST_FRAME : 0) | (isFirstRethrowFrame ? (int)RhEHFrameType.RH_EH_FIRST_RETHROW_FRAME : 0); if (pAppendStackFrame != IntPtr.Zero) { try { CalliIntrinsics.CallVoid(pAppendStackFrame, exception, IP, flags); } catch { // disallow all exceptions leaking out of callbacks } } } // Given an ExceptionID and an address pointing somewhere into a managed module, get // an exception object of a type that the module contianing the given address will understand. // This finds the classlib-defined GetRuntimeException function and asks it for the exception object. internal static Exception GetClasslibException(ExceptionIDs id, IntPtr address) { unsafe { // Find the classlib function that will give us the exception object we want to throw. This // is a RuntimeExport function from the classlib module, and is therefore managed-callable. void* pGetRuntimeExceptionFunction = InternalCalls.RhpGetClasslibFunction(address, ClassLibFunctionId.GetRuntimeException); // Return the exception object we get from the classlib. Exception e = null; try { e = CalliIntrinsics.Call<Exception>((IntPtr)pGetRuntimeExceptionFunction, id); } catch { // disallow all exceptions leaking out of callbacks } // If the helper fails to yield an object, then we fail-fast. if (e == null) { FailFastViaClasslib( RhFailFastReason.ClassLibDidNotTranslateExceptionID, null, address); } return e; } } #if !CORERT #region ItWouldBeNiceToRemoveThese // These four functions are used to implement the special THROW_* MDIL instructions. [MethodImpl(MethodImplOptions.NoInlining)] [RuntimeExport("RhExceptionHandling_ThrowClasslibOverflowException")] public static void ThrowClasslibOverflowException() { // Throw the overflow exception defined by the classlib, using the return address from this helper // to find the correct classlib. ExceptionIDs exID = ExceptionIDs.Overflow; IntPtr returnAddr = BinderIntrinsics.GetReturnAddress(); Exception e = GetClasslibException(exID, returnAddr); BinderIntrinsics.TailCall_RhpThrowEx(e); throw e; } [MethodImpl(MethodImplOptions.NoInlining)] [RuntimeExport("RhExceptionHandling_ThrowClasslibDivideByZeroException")] public static void ThrowClasslibDivideByZeroException() { // Throw the divide by zero exception defined by the classlib, using the return address from this // helper to find the correct classlib. ExceptionIDs exID = ExceptionIDs.DivideByZero; IntPtr returnAddr = BinderIntrinsics.GetReturnAddress(); Exception e = GetClasslibException(exID, returnAddr); BinderIntrinsics.TailCall_RhpThrowEx(e); throw e; } [MethodImpl(MethodImplOptions.NoInlining)] [RuntimeExport("RhExceptionHandling_ThrowClasslibArithmeticException")] public static void ThrowClasslibArithmeticException() { // Throw the arithmetic exception defined by the classlib, using the return address from this // helper to find the correct classlib. ExceptionIDs exID = ExceptionIDs.Arithmetic; IntPtr returnAddr = BinderIntrinsics.GetReturnAddress(); Exception e = GetClasslibException(exID, returnAddr); BinderIntrinsics.TailCall_RhpThrowEx(e); throw e; } [MethodImpl(MethodImplOptions.NoInlining)] [RuntimeExport("RhExceptionHandling_ThrowClasslibIndexOutOfRangeException")] public static void ThrowClasslibIndexOutOfRangeException() { // Throw the index out of range exception defined by the classlib, using the return address from // this helper to find the correct classlib. ExceptionIDs exID = ExceptionIDs.IndexOutOfRange; IntPtr returnAddr = BinderIntrinsics.GetReturnAddress(); Exception e = GetClasslibException(exID, returnAddr); BinderIntrinsics.TailCall_RhpThrowEx(e); throw e; } #endregion // ItWouldBeNiceToRemoveThese #endif // This function is used to throw exceptions out of our fast allocation helpers, implemented in asm. We tail-call // from the allocation helpers to this function, which performs the throw. The tail-call is important: it ensures // that the stack is crawlable from within this function. Throwing from a sub-function is important, since this // is how we enforce our locality requirements and ensure that the method that invokes "new" is the method that // catches the exception. [MethodImpl(MethodImplOptions.NoInlining)] [RuntimeExport("RhExceptionHandling_FailedAllocation")] public static void FailedAllocation(EETypePtr pEEType, bool fIsOverflow) { // Throw the out of memory or overflow exception defined by the classlib, using the return address from this helper // to find the correct classlib. ExceptionIDs exID = fIsOverflow ? ExceptionIDs.Overflow : ExceptionIDs.OutOfMemory; // Throw the out of memory exception defined by the classlib, using the input EEType* // to find the correct classlib. IntPtr addr = pEEType.ToPointer()->GetAssociatedModuleAddress(); Exception e = GetClasslibException(exID, addr); BinderIntrinsics.TailCall_RhpThrowEx(e); } #if !CORERT private static OutOfMemoryException s_theOOMException = new OutOfMemoryException(); // Rtm exports GetRuntimeException for the few cases where we have a helper that throws an exception // and may be called by either slr100 or other classlibs and that helper needs to throw an exception. // There are only a few cases where this happens now (the fast allocation helpers), so we limit the // exception types that Rtm will return. [RuntimeExport("GetRuntimeException")] public static Exception GetRuntimeException(ExceptionIDs id) { switch (id) { case ExceptionIDs.OutOfMemory: // Throw a preallocated exception to avoid infinite recursion. return s_theOOMException; case ExceptionIDs.Overflow: return new OverflowException(); default: Debug.Assert(false, "unexpected ExceptionID"); FallbackFailFast(RhFailFastReason.InternalError, null); return null; } } #endif private enum HwExceptionCode : uint { STATUS_REDHAWK_NULL_REFERENCE = 0x00000000u, STATUS_DATATYPE_MISALIGNMENT = 0x80000002u, STATUS_ACCESS_VIOLATION = 0xC0000005u, STATUS_INTEGER_DIVIDE_BY_ZERO = 0xC0000094u, } [StructLayout(LayoutKind.Explicit, Size = AsmOffsets.SIZEOF__PAL_LIMITED_CONTEXT)] public struct PAL_LIMITED_CONTEXT { [FieldOffset(AsmOffsets.OFFSETOF__PAL_LIMITED_CONTEXT__IP)] internal IntPtr IP; // the rest of the struct is left unspecified. } internal struct StackRange { } // N.B. -- These values are burned into the throw helper assembly code and are also known the the // StackFrameIterator code. [Flags] internal enum ExKind : byte { None = 0, Throw = 1, HardwareFault = 2, // unused: 3 KindMask = 3, RethrowFlag = 4, Rethrow = 5, // RethrowFlag | Throw RethrowFault = 6, // RethrowFlag | HardwareFault } [StackOnly] [StructLayout(LayoutKind.Explicit)] public struct ExInfo { internal void Init(Exception exceptionObj) { // _pPrevExInfo -- set by asm helper // _pExContext -- set by asm helper // _passNumber -- set by asm helper // _kind -- set by asm helper // _idxCurClause -- set by asm helper // _frameIter -- initialized explicitly during dispatch _exception = exceptionObj; _notifyDebuggerSP = UIntPtr.Zero; } internal void Init(Exception exceptionObj, ref ExInfo rethrownExInfo) { // _pPrevExInfo -- set by asm helper // _pExContext -- set by asm helper // _passNumber -- set by asm helper // _idxCurClause -- set by asm helper // _frameIter -- initialized explicitly during dispatch _exception = exceptionObj; _kind = rethrownExInfo._kind | ExKind.RethrowFlag; _notifyDebuggerSP = UIntPtr.Zero; } internal Exception ThrownException { get { return _exception; } } [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_pPrevExInfo)] internal void* _pPrevExInfo; [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_pExContext)] internal PAL_LIMITED_CONTEXT* _pExContext; [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_exception)] private Exception _exception; // actual object reference, specially reported by GcScanRootsWorker [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_kind)] internal ExKind _kind; [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_passNumber)] internal byte _passNumber; // BEWARE: This field is used by the stackwalker to know if the dispatch code has reached the // point at which a handler is called. In other words, it serves as an "is a handler // active" state where '_idxCurClause == MaxTryRegionIdx' means 'no'. [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_idxCurClause)] internal uint _idxCurClause; [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_frameIter)] internal StackFrameIterator _frameIter; [FieldOffset(AsmOffsets.OFFSETOF__ExInfo__m_notifyDebuggerSP)] volatile internal UIntPtr _notifyDebuggerSP; } // // Called by RhpThrowHwEx // [RuntimeExport("RhThrowHwEx")] public static void RhThrowHwEx(uint exceptionCode, ref ExInfo exInfo) { // trigger a GC (only if gcstress) to ensure we can stackwalk at this point GCStress.TriggerGC(); InternalCalls.RhpValidateExInfoStack(); IntPtr faultingCodeAddress = exInfo._pExContext->IP; ExceptionIDs exceptionId; switch (exceptionCode) { case (uint)HwExceptionCode.STATUS_REDHAWK_NULL_REFERENCE: exceptionId = ExceptionIDs.NullReference; break; case (uint)HwExceptionCode.STATUS_DATATYPE_MISALIGNMENT: exceptionId = ExceptionIDs.DataMisaligned; break; // N.B. -- AVs that have a read/write address lower than 64k are already transformed to // HwExceptionCode.REDHAWK_NULL_REFERENCE prior to calling this routine. case (uint)HwExceptionCode.STATUS_ACCESS_VIOLATION: exceptionId = ExceptionIDs.AccessViolation; break; case (uint)HwExceptionCode.STATUS_INTEGER_DIVIDE_BY_ZERO: exceptionId = ExceptionIDs.DivideByZero; break; default: // We don't wrap SEH exceptions from foreign code like CLR does, so we believe that we // know the complete set of HW faults generated by managed code and do not need to handle // this case. FailFastViaClasslib(RhFailFastReason.InternalError, null, faultingCodeAddress); exceptionId = ExceptionIDs.NullReference; break; } Exception exceptionToThrow = GetClasslibException(exceptionId, faultingCodeAddress); exInfo.Init(exceptionToThrow); DispatchEx(ref exInfo._frameIter, ref exInfo, MaxTryRegionIdx); BinderIntrinsics.DebugBreak(); } private const uint MaxTryRegionIdx = 0xFFFFFFFFu; [RuntimeExport("RhThrowEx")] public static void RhThrowEx(Exception exceptionObj, ref ExInfo exInfo) { // trigger a GC (only if gcstress) to ensure we can stackwalk at this point GCStress.TriggerGC(); InternalCalls.RhpValidateExInfoStack(); // Transform attempted throws of null to a throw of NullReferenceException. if (exceptionObj == null) { IntPtr faultingCodeAddress = exInfo._pExContext->IP; exceptionObj = GetClasslibException(ExceptionIDs.NullReference, faultingCodeAddress); } exInfo.Init(exceptionObj); DispatchEx(ref exInfo._frameIter, ref exInfo, MaxTryRegionIdx); BinderIntrinsics.DebugBreak(); } [RuntimeExport("RhRethrow")] public static void RhRethrow(ref ExInfo activeExInfo, ref ExInfo exInfo) { // trigger a GC (only if gcstress) to ensure we can stackwalk at this point GCStress.TriggerGC(); InternalCalls.RhpValidateExInfoStack(); // We need to copy the Exception object to this stack location because collided unwinds will cause // the original stack location to go dead. Exception rethrownException = activeExInfo.ThrownException; exInfo.Init(rethrownException, ref activeExInfo); DispatchEx(ref exInfo._frameIter, ref exInfo, activeExInfo._idxCurClause); BinderIntrinsics.DebugBreak(); } private static void DispatchEx(ref StackFrameIterator frameIter, ref ExInfo exInfo, uint startIdx) { Debug.Assert(exInfo._passNumber == 1, "expected asm throw routine to set the pass"); Exception exceptionObj = exInfo.ThrownException; // ------------------------------------------------ // // First pass // // ------------------------------------------------ UIntPtr handlingFrameSP = MaxSP; byte* pCatchHandler = null; uint catchingTryRegionIdx = MaxTryRegionIdx; bool isFirstRethrowFrame = (startIdx != MaxTryRegionIdx); bool isFirstFrame = true; UIntPtr prevFramePtr = UIntPtr.Zero; bool unwoundReversePInvoke = false; bool isValid = frameIter.Init(exInfo._pExContext); Debug.Assert(isValid, "RhThrowEx called with an unexpected context"); DebuggerNotify.BeginFirstPass(exceptionObj, frameIter.ControlPC, frameIter.SP); for (; isValid; isValid = frameIter.Next(out startIdx, out unwoundReversePInvoke)) { // For GC stackwalking, we'll happily walk across native code blocks, but for EH dispatch, we // disallow dispatching exceptions across native code. if (unwoundReversePInvoke) break; DebugScanCallFrame(exInfo._passNumber, frameIter.ControlPC, frameIter.SP); // A debugger can subscribe to get callbacks at a specific frame of exception dispatch // exInfo._notifyDebuggerSP can be populated by the debugger from out of process // at any time. if (exInfo._notifyDebuggerSP == frameIter.SP) DebuggerNotify.FirstPassFrameEntered(exceptionObj, frameIter.ControlPC, frameIter.SP); UpdateStackTrace(exceptionObj, ref exInfo, ref isFirstRethrowFrame, ref prevFramePtr, ref isFirstFrame); byte* pHandler; if (FindFirstPassHandler(exceptionObj, startIdx, ref frameIter, out catchingTryRegionIdx, out pHandler)) { handlingFrameSP = frameIter.SP; pCatchHandler = pHandler; DebugVerifyHandlingFrame(handlingFrameSP); break; } } DebuggerNotify.EndFirstPass(exceptionObj, pCatchHandler, handlingFrameSP); if (pCatchHandler == null) { UnhandledExceptionFailFastViaClasslib( RhFailFastReason.PN_UnhandledException, exceptionObj, ref exInfo); } // We FailFast above if the exception goes unhandled. Therefore, we cannot run the second pass // without a catch handler. Debug.Assert(pCatchHandler != null, "We should have a handler if we're starting the second pass"); DebuggerNotify.BeginSecondPass(); // ------------------------------------------------ // // Second pass // // ------------------------------------------------ // Due to the stackwalker logic, we cannot tolerate triggering a GC from the dispatch code once we // are in the 2nd pass. This is because the stackwalker applies a particular unwind semantic to // 'collapse' funclets which gets confused when we walk out of the dispatch code and encounter the // 'main body' without first encountering the funclet. The thunks used to invoke 2nd-pass // funclets will always toggle this mode off before invoking them. InternalCalls.RhpSetThreadDoNotTriggerGC(); exInfo._passNumber = 2; startIdx = MaxTryRegionIdx; isValid = frameIter.Init(exInfo._pExContext); for (; isValid && ((byte*)frameIter.SP <= (byte*)handlingFrameSP); isValid = frameIter.Next(out startIdx)) { Debug.Assert(isValid, "second-pass EH unwind failed unexpectedly"); DebugScanCallFrame(exInfo._passNumber, frameIter.ControlPC, frameIter.SP); if (frameIter.SP == handlingFrameSP) { // invoke only a partial second-pass here... InvokeSecondPass(ref exInfo, startIdx, catchingTryRegionIdx); break; } InvokeSecondPass(ref exInfo, startIdx); } // ------------------------------------------------ // // Call the handler and resume execution // // ------------------------------------------------ exInfo._idxCurClause = catchingTryRegionIdx; InternalCalls.RhpCallCatchFunclet( exceptionObj, pCatchHandler, frameIter.RegisterSet, ref exInfo); // currently, RhpCallCatchFunclet will resume after the catch Debug.Assert(false, "unreachable"); BinderIntrinsics.DebugBreak(); } [System.Diagnostics.Conditional("DEBUG")] private static void DebugScanCallFrame(int passNumber, byte* ip, UIntPtr sp) { if (ip == null) { Debug.Assert(false, "false"); } } [System.Diagnostics.Conditional("DEBUG")] private static void DebugVerifyHandlingFrame(UIntPtr handlingFrameSP) { Debug.Assert(handlingFrameSP != MaxSP, "Handling frame must have an SP value"); Debug.Assert(((UIntPtr*)handlingFrameSP) > &handlingFrameSP, "Handling frame must have a valid stack frame pointer"); } private static void UpdateStackTrace(Exception exceptionObj, ref ExInfo exInfo, ref bool isFirstRethrowFrame, ref UIntPtr prevFramePtr, ref bool isFirstFrame) { // We use the fact that all funclet stack frames belonging to the same logical method activation // will have the same FramePointer value. Additionally, the stackwalker will return a sequence of // callbacks for all the funclet stack frames, one right after the other. The classlib doesn't // want to know about funclets, so we strip them out by only reporting the first frame of a // sequence of funclets. This is correct because the leafmost funclet is first in the sequence // and corresponds to the current 'IP state' of the method. UIntPtr curFramePtr = exInfo._frameIter.FramePointer; if ((prevFramePtr == UIntPtr.Zero) || (curFramePtr != prevFramePtr)) { AppendExceptionStackFrameViaClasslib(exceptionObj, (IntPtr)exInfo._frameIter.ControlPC, isFirstRethrowFrame, exInfo._pExContext->IP, isFirstFrame); } prevFramePtr = curFramePtr; isFirstRethrowFrame = false; isFirstFrame = false; } private static bool FindFirstPassHandler(Exception exception, uint idxStart, ref StackFrameIterator frameIter, out uint tryRegionIdx, out byte* pHandler) { pHandler = null; tryRegionIdx = MaxTryRegionIdx; EHEnum ehEnum; byte* pbMethodStartAddress; if (!InternalCalls.RhpEHEnumInitFromStackFrameIterator(ref frameIter, &pbMethodStartAddress, &ehEnum)) return false; byte* pbControlPC = frameIter.ControlPC; uint codeOffset = (uint)(pbControlPC - pbMethodStartAddress); uint lastTryStart = 0, lastTryEnd = 0; // Search the clauses for one that contains the current offset. RhEHClause ehClause; for (uint curIdx = 0; InternalCalls.RhpEHEnumNext(&ehEnum, &ehClause); curIdx++) { // // Skip to the starting try region. This is used by collided unwinds and rethrows to pickup where // the previous dispatch left off. // if (idxStart != MaxTryRegionIdx) { if (curIdx <= idxStart) { lastTryStart = ehClause._tryStartOffset; lastTryEnd = ehClause._tryEndOffset; continue; } // Now, we continue skipping while the try region is identical to the one that invoked the // previous dispatch. if ((ehClause._tryStartOffset == lastTryStart) && (ehClause._tryEndOffset == lastTryEnd)) continue; } RhEHClauseKind clauseKind = ehClause._clauseKind; if (((clauseKind != RhEHClauseKind.RH_EH_CLAUSE_TYPED) && (clauseKind != RhEHClauseKind.RH_EH_CLAUSE_FILTER)) || !ehClause.ContainsCodeOffset(codeOffset)) { continue; } // Found a containing clause. Because of the order of the clauses, we know this is the // most containing. if (clauseKind == RhEHClauseKind.RH_EH_CLAUSE_TYPED) { if (ShouldTypedClauseCatchThisException(exception, (EEType*)ehClause._pTargetType)) { pHandler = (pbMethodStartAddress + ehClause._handlerOffset); tryRegionIdx = curIdx; return true; } } else { byte* pFilterFunclet = (pbMethodStartAddress + ehClause._filterOffset); bool shouldInvokeHandler = InternalCalls.RhpCallFilterFunclet(exception, pFilterFunclet, frameIter.RegisterSet); if (shouldInvokeHandler) { pHandler = (pbMethodStartAddress + ehClause._handlerOffset); tryRegionIdx = curIdx; return true; } } } return false; } static EEType* s_pLowLevelObjectType; private static bool ShouldTypedClauseCatchThisException(Exception exception, EEType* pClauseType) { if (TypeCast.IsInstanceOfClass(exception, pClauseType) != null) return true; if (s_pLowLevelObjectType == null) { s_pLowLevelObjectType = new System.Object().EEType; } // This allows the typical try { } catch { }--which expands to a typed catch of System.Object--to work on // all objects when the clause is in the low level runtime code. This special case is needed because // objects from foreign type systems are sometimes throw back up at runtime code and this is the only way // to catch them outside of having a filter with no type check in it, which isn't currently possible to // write in C#. See https://github.com/dotnet/roslyn/issues/4388 if (pClauseType->IsEquivalentTo(s_pLowLevelObjectType)) return true; return false; } private static void InvokeSecondPass(ref ExInfo exInfo, uint idxStart) { InvokeSecondPass(ref exInfo, idxStart, MaxTryRegionIdx); } private static void InvokeSecondPass(ref ExInfo exInfo, uint idxStart, uint idxLimit) { EHEnum ehEnum; byte* pbMethodStartAddress; if (!InternalCalls.RhpEHEnumInitFromStackFrameIterator(ref exInfo._frameIter, &pbMethodStartAddress, &ehEnum)) return; byte* pbControlPC = exInfo._frameIter.ControlPC; uint codeOffset = (uint)(pbControlPC - pbMethodStartAddress); uint lastTryStart = 0, lastTryEnd = 0; // Search the clauses for one that contains the current offset. RhEHClause ehClause; for (uint curIdx = 0; InternalCalls.RhpEHEnumNext(&ehEnum, &ehClause) && curIdx < idxLimit; curIdx++) { // // Skip to the starting try region. This is used by collided unwinds and rethrows to pickup where // the previous dispatch left off. // if (idxStart != MaxTryRegionIdx) { if (curIdx <= idxStart) { lastTryStart = ehClause._tryStartOffset; lastTryEnd = ehClause._tryEndOffset; continue; } // Now, we continue skipping while the try region is identical to the one that invoked the // previous dispatch. if ((ehClause._tryStartOffset == lastTryStart) && (ehClause._tryEndOffset == lastTryEnd)) continue; } RhEHClauseKind clauseKind = ehClause._clauseKind; if ((clauseKind != RhEHClauseKind.RH_EH_CLAUSE_FAULT) || !ehClause.ContainsCodeOffset(codeOffset)) { continue; } // Found a containing clause. Because of the order of the clauses, we know this is the // most containing. // N.B. -- We need to suppress GC "in-between" calls to finallys in this loop because we do // not have the correct next-execution point live on the stack and, therefore, may cause a GC // hole if we allow a GC between invocation of finally funclets (i.e. after one has returned // here to the dispatcher, but before the next one is invoked). Once they are running, it's // fine for them to trigger a GC, obviously. // // As a result, RhpCallFinallyFunclet will set this state in the runtime upon return from the // funclet, and we need to reset it if/when we fall out of the loop and we know that the // method will no longer get any more GC callbacks. byte* pFinallyHandler = (pbMethodStartAddress + ehClause._handlerOffset); exInfo._idxCurClause = curIdx; InternalCalls.RhpCallFinallyFunclet(pFinallyHandler, exInfo._frameIter.RegisterSet); exInfo._idxCurClause = MaxTryRegionIdx; } } [NativeCallable(EntryPoint = "RhpFailFastForPInvokeExceptionPreemp", CallingConvention = CallingConvention.Cdecl)] static public void RhpFailFastForPInvokeExceptionPreemp(IntPtr PInvokeCallsiteReturnAddr, void* pExceptionRecord, void* pContextRecord) { FailFastViaClasslib(RhFailFastReason.PN_UnhandledExceptionFromPInvoke, null, PInvokeCallsiteReturnAddr); } [RuntimeExport("RhpFailFastForPInvokeExceptionCoop")] static public void RhpFailFastForPInvokeExceptionCoop(IntPtr classlibBreadcrumb, void* pExceptionRecord, void* pContextRecord) { FailFastViaClasslib(RhFailFastReason.PN_UnhandledExceptionFromPInvoke, null, classlibBreadcrumb); } } // static class EH }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Biggy.Core; using Biggy.Data.Json; using NUnit.Framework; namespace Tests { [TestFixture()] [Category("Biggy List with JSON Store")] public class BiggyListWithJsonStore { private JsonStore<Property> _propertyStore; [SetUp] public void init() { _propertyStore = new JsonStore<Property>(); string path = _propertyStore.DbPath; File.Delete(path); } [Test()] public void BiggyList_Initializes_From_Empty_Table() { var propertyList = new BiggyList<Property>(_propertyStore); Assert.True(propertyList.Store != null && propertyList.Count == 0); } [Test()] public void Biggylist_Adds_Single_Item_To_Json_Store() { var propertyList = new BiggyList<Property>(_propertyStore); int initialCount = propertyList.Count; var newProperty = new Property { Id = 1, Name = "Watergate Apartments", Address = "2639 I St NW, Washington, D.C. 20037" }; propertyList.Add(newProperty); // Reload from the store: propertyList = new BiggyList<Property>(_propertyStore); var addedItems = propertyList.FirstOrDefault(p => p.Name.Contains("Watergate")); Assert.IsTrue(initialCount == 0 && propertyList.Count == 1); } [Test()] public void Biggylist_Adds_Range_Of_Items_To_Json_Store() { var propertyList = new BiggyList<Property>(_propertyStore); int initialCount = propertyList.Count; var myBatch = new List<Property>(); int qtyToAdd = 10; // This test uses an initial index value of 1 so taht there is a non-zero ID for the first item: for (int i = 1; i <= qtyToAdd; i++) { var newProperty = new Property { Id = i, Name = "New Apartment " + i, Address = "Some Street in a Lonely Town" }; myBatch.Add(newProperty); } propertyList.Add(myBatch); // Reload from the store: propertyList = new BiggyList<Property>(_propertyStore); var addedItems = propertyList.FirstOrDefault(p => p.Name.Contains("New Apartment")); Assert.IsTrue(initialCount == 0 && propertyList.Count == qtyToAdd); } [Test()] public void Biggylist_Updates_Single_Item_In_Json_Store() { var propertyList = new BiggyList<Property>(_propertyStore); int initialCount = propertyList.Count; var newProperty = new Property { Id = 1, Name = "John's Luxury Apartments", Address = "2639 I St NW, Washington, D.C. 20037" }; propertyList.Add(newProperty); int addedItemId = newProperty.Id; // Just to be sure, reload from backing store and check what was added: propertyList = new BiggyList<Property>(_propertyStore); var addedProperty = propertyList.FirstOrDefault(p => p.Id == addedItemId); bool isAddedProperly = addedProperty.Name.Contains("John's Luxury"); // Now Update: string newName = "John's Low-Rent Apartments"; addedProperty.Name = newName; propertyList.Update(addedProperty); // Go fetch again: propertyList = new BiggyList<Property>(_propertyStore); addedProperty = propertyList.FirstOrDefault(p => p.Id == addedItemId); bool isUpdatedProperly = addedProperty.Name == newName; Assert.IsTrue(isAddedProperly && isUpdatedProperly); } [Test()] public void Biggylist_Updates_Range_Of_Items_In_Json_Store() { var propertyList = new BiggyList<Property>(_propertyStore); int initialCount = propertyList.Count; var myBatch = new List<Property>(); int qtyToAdd = 10; // This test uses an initial index value of 1 so taht there is a non-zero ID for the first item: for (int i = 1; i <= qtyToAdd; i++) { myBatch.Add(new Property { Id = i, Name = "John's Luxury Townhomes" + i, Address = i + " Property Parkway, Portland, OR 97204" }); } propertyList.Add(myBatch); // Just to be sure, reload from backing store and check what was added: propertyList = new BiggyList<Property>(_propertyStore); int addedCount = propertyList.Count; // Update each item: for (int i = 0; i < qtyToAdd; i++) { propertyList.ElementAt(i).Name = "John's Low-Rent Brick Homes " + i; } propertyList.Update(propertyList.ToList()); // Reload, and check updated names: propertyList = new BiggyList<Property>(_propertyStore); var updatedItems = propertyList.Where(p => p.Name.Contains("Low-Rent Brick")); Assert.IsTrue(updatedItems.Count() == qtyToAdd); } [Test()] public void Biggylist_Removes_Single_Item_From_Json_Store() { var propertyList = new BiggyList<Property>(_propertyStore); int initialCount = propertyList.Count; var newProperty = new Property { Id = 1, Name = "John's High-End Apartments", Address = "16 Property Parkway, Portland, OR 97204" }; propertyList.Add(newProperty); int addedItemId = newProperty.Id; // Just to be sure, reload from backing store and check what was added: propertyList = new BiggyList<Property>(_propertyStore); var addedProperty = propertyList.FirstOrDefault(p => p.Id == addedItemId); bool isAddedProperly = addedProperty.Name.Contains("High-End"); int qtyAdded = propertyList.Count; // Delete: var foundProperty = propertyList.FirstOrDefault(); propertyList.Remove(foundProperty); propertyList = new BiggyList<Property>(_propertyStore); int remaining = propertyList.Count; Assert.IsTrue(isAddedProperly && qtyAdded == 1 && remaining == 0); } [Test()] public void Biggylist_Removes_Range_Of_Items_From_Json_Store() { var propertyList = new BiggyList<Property>(_propertyStore); int initialCount = propertyList.Count; var myBatch = new List<Property>(); int qtyToAdd = 10; // This test uses an initial index value of 1 so taht there is a non-zero ID for the first item: for (int i = 1; i <= qtyToAdd; i++) { myBatch.Add(new Property { Id = i, Name = "Boardwalk " + i, Address = i + " Property Parkway, Portland, OR 97204" }); } propertyList.Add(myBatch); // Re-load from back-end: propertyList = new BiggyList<Property>(_propertyStore); int qtyAdded = propertyList.Count; // Select 5 for deletion: int qtyToDelete = 5; var deleteThese = propertyList.Where(c => c.Id <= qtyToDelete); propertyList.Remove(deleteThese); // Delete: propertyList = new BiggyList<Property>(_propertyStore); int remaining = propertyList.Count; Assert.IsTrue(qtyAdded == qtyToAdd && remaining == qtyAdded - qtyToDelete); } [Test()] public void Biggylist_Removes_All_Items_From_Json_Store() { var propertyList = new BiggyList<Property>(_propertyStore); int initialCount = propertyList.Count; var myBatch = new List<Property>(); int qtyToAdd = 10; for (int i = 0; i < qtyToAdd; i++) { myBatch.Add(new Property { Id = i, Name = "Marvin Gardens " + i, Address = i + " Property Parkway, Portland, OR 97204" }); } propertyList.Add(myBatch); // Re-load from back-end: propertyList = new BiggyList<Property>(_propertyStore); int qtyAdded = propertyList.Count; propertyList.Clear(); // Delete: propertyList = new BiggyList<Property>(_propertyStore); int remaining = propertyList.Count; Assert.IsTrue(qtyAdded == qtyToAdd && remaining == 0); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Text; using System.Globalization; using System.IO; using System.Collections; namespace System.Diagnostics { public class DelimitedListTraceListener : TextWriterTraceListener { private string _delimiter = ";"; private string _secondaryDelim = ","; public DelimitedListTraceListener(Stream stream) : base(stream) { } public DelimitedListTraceListener(Stream stream, string name) : base(stream, name) { } public DelimitedListTraceListener(TextWriter writer) : base(writer) { } public DelimitedListTraceListener(TextWriter writer, string name) : base(writer, name) { } public string Delimiter { get { return _delimiter; } set { if (value == null) throw new ArgumentNullException("Delimiter"); if (value.Length == 0) throw new ArgumentException(SR.Format(SR.Generic_ArgCantBeEmptyString, "Delimiter")); lock (this) { _delimiter = value; } if (_delimiter == ",") _secondaryDelim = ";"; else _secondaryDelim = ","; } } public override void TraceEvent(TraceEventCache eventCache, String source, TraceEventType eventType, int id, string format, params object[] args) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, format, args, null, null)) return; WriteHeader(source, eventType, id); if (args != null) WriteEscaped(String.Format(CultureInfo.InvariantCulture, format, args)); else WriteEscaped(format); Write(Delimiter); // Use get_Delimiter // one more delimiter for the data object Write(Delimiter); // Use get_Delimiter WriteFooter(eventCache); } public override void TraceEvent(TraceEventCache eventCache, String source, TraceEventType eventType, int id, string message) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, message, null, null, null)) return; WriteHeader(source, eventType, id); WriteEscaped(message); Write(Delimiter); // Use get_Delimiter // one more delimiter for the data object Write(Delimiter); // Use get_Delimiter WriteFooter(eventCache); } public override void TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, int id, object data) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, data, null)) return; WriteHeader(source, eventType, id); // first a delimiter for the message Write(Delimiter); // Use get_Delimiter WriteEscaped(data.ToString()); Write(Delimiter); // Use get_Delimiter WriteFooter(eventCache); } public override void TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, int id, params object[] data) { if (Filter != null && !Filter.ShouldTrace(eventCache, source, eventType, id, null, null, null, data)) return; WriteHeader(source, eventType, id); // first a delimiter for the message Write(Delimiter); // Use get_Delimiter if (data != null) { for (int i = 0; i < data.Length; i++) { if (i != 0) Write(_secondaryDelim); WriteEscaped(data[i].ToString()); } } Write(Delimiter); // Use get_Delimiter WriteFooter(eventCache); } private void WriteHeader(String source, TraceEventType eventType, int id) { WriteEscaped(source); Write(Delimiter); // Use get_Delimiter Write(eventType.ToString()); Write(Delimiter); // Use get_Delimiter Write(id.ToString(CultureInfo.InvariantCulture)); Write(Delimiter); // Use get_Delimiter } private void WriteFooter(TraceEventCache eventCache) { if (eventCache != null) { if (IsEnabled(TraceOptions.ProcessId)) Write(eventCache.ProcessId.ToString(CultureInfo.InvariantCulture)); Write(Delimiter); // Use get_Delimiter if (IsEnabled(TraceOptions.ThreadId)) WriteEscaped(eventCache.ThreadId); Write(Delimiter); // Use get_Delimiter if (IsEnabled(TraceOptions.DateTime)) WriteEscaped(eventCache.DateTime.ToString("o", CultureInfo.InvariantCulture)); Write(Delimiter); // Use get_Delimiter if (IsEnabled(TraceOptions.Timestamp)) Write(eventCache.Timestamp.ToString(CultureInfo.InvariantCulture)); Write(Delimiter); // Use get_Delimiter } else { for (int i = 0; i < 5; i++) Write(Delimiter); // Use get_Delimiter } WriteLine(""); } private void WriteEscaped(string message) { if (!String.IsNullOrEmpty(message)) { StringBuilder sb = new StringBuilder("\""); int index; int lastindex = 0; while ((index = message.IndexOf('"', lastindex)) != -1) { sb.Append(message, lastindex, index - lastindex); sb.Append("\"\""); lastindex = index + 1; } sb.Append(message, lastindex, message.Length - lastindex); sb.Append("\""); Write(sb.ToString()); } } private bool IsEnabled(TraceOptions opts) { return (opts & TraceOutputOptions) != 0; } } }
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel // // 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.Collections.Generic; using System.Linq; using System.Text; namespace SharpDoc.Model { /// <summary> /// An abstract member of a <see cref="NType"/>. /// </summary> public abstract class NMember : NModelBase, INMemberReference { /// <summary> /// Initializes a new instance of the <see cref="NMember"/> class. /// </summary> protected NMember() { Members = new List<NMember>(); Attributes = new List<string>(); GenericParameters = new List<NGenericParameter>(); GenericArguments = new List<NTypeReference>(); } /// <summary> /// Gets or sets a value indicating whether this instance is an array. /// </summary> /// <value> /// <c>true</c> if this instance is an array; otherwise, <c>false</c>. /// </value> public bool IsArray {get;set;} /// <summary> /// Gets or sets a value indicating whether this instance is pointer. /// </summary> /// <value> /// <c>true</c> if this instance is pointer; otherwise, <c>false</c>. /// </value> public bool IsPointer { get; set; } /// <summary> /// Gets or sets a value indicating whether this instance is sentinel. /// </summary> /// <value> /// <c>true</c> if this instance is sentinel; otherwise, <c>false</c>. /// </value> public bool IsSentinel { get; set; } /// <summary> /// Gets or sets a value indicating whether this instance is generic instance. /// </summary> /// <value> /// <c>true</c> if this instance is generic instance; otherwise, <c>false</c>. /// </value> public bool IsGenericInstance { get; set; } /// <summary> /// Gets or sets a value indicating whether this instance is generic parameter. /// </summary> /// <value> /// <c>true</c> if this instance is generic parameter; otherwise, <c>false</c>. /// </value> public bool IsGenericParameter { get; set; } /// <summary> /// Gets or sets the type of the element. /// </summary> /// <value>The type of the element.</value> public NTypeReference ElementType { get; set; } /// <summary> /// Gets or sets the generic parameters. /// </summary> /// <value>The generic parameters.</value> public List<NGenericParameter> GenericParameters { get; set; } /// <summary> /// Gets or sets the generic arguments. /// </summary> /// <value>The generic arguments.</value> public List<NTypeReference> GenericArguments {get;set;} /// <summary> /// Gets or sets the type that is declaring this member. /// </summary> /// <value>The type of the declaring.</value> public NTypeReference DeclaringType { get; set; } /// <summary> /// Gets or sets a value indicating whether this instance is static. /// </summary> /// <value><c>true</c> if this instance is static; otherwise, <c>false</c>.</value> public bool IsStatic { get; set; } /// <summary> /// Gets or sets a value indicating whether this instance is final. /// </summary> /// <value><c>true</c> if this instance is final; otherwise, <c>false</c>.</value> public bool IsFinal { get; set; } /// <summary> /// Gets or sets a value indicating whether this instance is abstract. /// </summary> /// <value> /// <c>true</c> if this instance is abstract; otherwise, <c>false</c>. /// </value> public bool IsAbstract { get; set; } /// <summary> /// Gets or sets the visibility. /// </summary> /// <value>The visibility.</value> public NVisibility Visibility { get; set; } /// <summary> /// Gets the name of the visibility. /// </summary> /// <value>The name of the visibility.</value> public string VisibilityName { get { switch (Visibility) { case NVisibility.Public: return "public"; case NVisibility.Protected: return "protected"; case NVisibility.Private: return "private"; case NVisibility.ProtectedInternal: return "protected internal"; case NVisibility.Internal: return "internal"; } return ""; } } /// <summary> /// Gets the name of the visibility. /// </summary> /// <value> /// The name of the visibility. /// </value> public string VisibilityFullName { get { var text = new StringBuilder(VisibilityName); if (IsStatic) text.Append(" static"); if (IsAbstract) text.Append(" abstract"); if (IsFinal) text.Append(" sealed"); return text.ToString(); } } /// <summary> /// Gets or sets the namespace this member is attached. /// </summary> /// <value>The namespace.</value> public NNamespace Namespace { get; set; } /// <summary> /// Gets or sets the type of the member. /// </summary> /// <value>The type of the member.</value> public NMemberType MemberType { get; set; } /// <summary> /// Gets or sets the parent. This is null for root type. /// </summary> /// <value>The parent.</value> public NMember Parent { get; set; } /// <summary> /// Gets or sets all the members. /// </summary> /// <value>The members.</value> public List<NMember> Members { get; private set; } /// <summary> /// Gets or sets the attributes declaration (as string). /// </summary> /// <value>The attributes.</value> public List<string> Attributes { get; private set; } /// <summary> /// Gets the type member. /// </summary> /// <value>The type member.</value> public virtual string TypeMember { get { return GetType().Name.Substring(1); } } /// <summary> /// Helper method to return a particular collection of members. /// </summary> /// <typeparam name="T">A member</typeparam> /// <returns>A collection of <paramref name="T"/></returns> protected IEnumerable<T> MembersAs<T>() where T : NMember { return Members.OfType<T>(); } /// <summary> /// Adds a member. /// </summary> /// <param name="member">The member.</param> public void AddMember(NMember member) { member.Parent = this; Members.Add(member); } public override string ToString() { return string.Format("{0}", FullName); } } }
using UnityEngine; using UnityEditor; using System.Collections.Generic; using System.Reflection; using SimpleSpritePacker; namespace SimpleSpritePackerEditor { public class SPTools { public static string Settings_UseSpriteThumbsKey = "SPSettings_UseSpriteThumbs"; public static string Settings_ThumbsHeightKey = "SPSettings_SpriteThumbsHeight"; public static string Settings_UseScrollViewKey = "SPSettings_SpriteScrollView"; public static string Settings_ScrollViewHeightKey = "SPSettings_SpriteScrollViewHeight"; public static string Settings_DisableReadWriteEnabled = "SPSettings_DisableReadWriteEnabled"; public static string Settings_AllowMuliSpritesOneSource = "SPSettings_AllowMuliSpritesOneSource"; public static string Settings_ShowSpritesKey = "SP_ShowSprites"; public static string Settings_SavedInstanceIDKey = "SP_SavedInstanceID"; /// <summary> /// Prepares the default editor preference values. /// </summary> public static void PrepareDefaultEditorPrefs() { if (!EditorPrefs.HasKey(SPTools.Settings_UseScrollViewKey)) { EditorPrefs.SetBool(SPTools.Settings_UseScrollViewKey, true); } if (!EditorPrefs.HasKey(SPTools.Settings_ScrollViewHeightKey)) { EditorPrefs.SetFloat(SPTools.Settings_ScrollViewHeightKey, 216f); } if (!EditorPrefs.HasKey(SPTools.Settings_ShowSpritesKey)) { EditorPrefs.SetBool(SPTools.Settings_ShowSpritesKey, true); } if (!EditorPrefs.HasKey(SPTools.Settings_UseSpriteThumbsKey)) { EditorPrefs.SetBool(SPTools.Settings_UseSpriteThumbsKey, true); } if (!EditorPrefs.HasKey(SPTools.Settings_ThumbsHeightKey)) { EditorPrefs.SetFloat(SPTools.Settings_ThumbsHeightKey, 50f); } if (!EditorPrefs.HasKey(SPTools.Settings_AllowMuliSpritesOneSource)) { EditorPrefs.SetBool(SPTools.Settings_AllowMuliSpritesOneSource, true); } } /// <summary> /// Gets the editor preference bool value with the specified key. /// </summary> /// <returns><c>true</c>, if editor preference bool was gotten, <c>false</c> otherwise.</returns> /// <param name="key">Key.</param> public static bool GetEditorPrefBool(string key) { return EditorPrefs.GetBool(key); } /// <summary> /// Gets the asset path of a texture. /// </summary> /// <returns>The asset path.</returns> /// <param name="texture">Texture.</param> public static string GetAssetPath(Texture2D texture) { if (texture == null) return string.Empty; return AssetDatabase.GetAssetPath(texture.GetInstanceID()); } /// <summary> /// Gets the asset path of a object. /// </summary> /// <returns>The asset path.</returns> /// <param name="obj">Object.</param> public static string GetAssetPath(Object obj) { if (obj == null) return string.Empty; return AssetDatabase.GetAssetPath(obj); } /// <summary> /// Does asset reimport. /// </summary> /// <param name="path">Path.</param> /// <param name="options">Options.</param> public static void DoAssetReimport(string path, ImportAssetOptions options) { try { AssetDatabase.StartAssetEditing(); AssetDatabase.ImportAsset(path, options); } finally { AssetDatabase.StopAssetEditing(); } } /// <summary> /// Removes the read only flag from the asset. /// </summary> /// <returns><c>true</c>, if read only flag was removed, <c>false</c> otherwise.</returns> /// <param name="path">Path.</param> public static bool RemoveReadOnlyFlag(string path) { if (string.IsNullOrEmpty(path)) return false; // Clear the read-only flag in texture file attributes if (System.IO.File.Exists(path)) { #if !UNITY_4_1 && !UNITY_4_0 && !UNITY_3_5 if (!AssetDatabase.IsOpenForEdit(path)) { Debug.LogError(path + " is not editable. Did you forget to do a check out?"); return false; } #endif System.IO.FileAttributes texPathAttrs = System.IO.File.GetAttributes(path); texPathAttrs &= ~System.IO.FileAttributes.ReadOnly; System.IO.File.SetAttributes(path, texPathAttrs); return true; } // Default return false; } /// <summary> /// Creates a blank atlas texture. /// </summary> /// <returns><c>true</c>, if blank texture was created, <c>false</c> otherwise.</returns> /// <param name="path">Asset Path.</param> /// <param name="alphaTransparency">If set to <c>true</c> alpha transparency.</param> public static bool CreateBlankTexture(string path, bool alphaTransparency) { if (string.IsNullOrEmpty(path)) return false; // Prepare blank texture Texture2D texture = new Texture2D(1, 1, TextureFormat.ARGB32, false); // Create the texture asset AssetDatabase.CreateAsset(texture, AssetDatabase.GenerateUniqueAssetPath(path)); // Clear the read-only flag in texture file attributes if (!SPTools.RemoveReadOnlyFlag(path)) return false; // Write the texture data byte[] bytes = texture.EncodeToPNG(); System.IO.File.WriteAllBytes(path, bytes); bytes = null; // Get the asset texture importer TextureImporter textureImporter = AssetImporter.GetAtPath(path) as TextureImporter; if (textureImporter == null) return false; TextureImporterSettings settings = new TextureImporterSettings(); textureImporter.ReadTextureSettings(settings); settings.spriteMode = 2; settings.readable = false; settings.maxTextureSize = 4096; settings.wrapMode = TextureWrapMode.Clamp; settings.npotScale = TextureImporterNPOTScale.ToNearest; settings.textureFormat = TextureImporterFormat.ARGB32; settings.filterMode = FilterMode.Point; settings.aniso = 4; settings.alphaIsTransparency = alphaTransparency; textureImporter.SetTextureSettings(settings); textureImporter.textureType = TextureImporterType.Sprite; AssetDatabase.SaveAssets(); SPTools.DoAssetReimport(path, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport); return true; } /// <summary> /// Imports a texture as asset. /// </summary> /// <returns><c>true</c>, if texture was imported, <c>false</c> otherwise.</returns> /// <param name="path">Path.</param> /// <param name="texture">Texture.</param> public static bool ImportTexture(string path, Texture2D texture) { if (string.IsNullOrEmpty(path)) return false; // Clear the read-only flag in texture file attributes if (!SPTools.RemoveReadOnlyFlag(path)) return false; byte[] bytes = texture.EncodeToPNG(); System.IO.File.WriteAllBytes(path, bytes); bytes = null; AssetDatabase.SaveAssets(); SPTools.DoAssetReimport(path, ImportAssetOptions.ForceSynchronousImport); return true; } /// <summary> /// Sets the texture asset Read/Write enabled state. /// </summary> /// <returns><c>true</c>, if set read write enabled was textured, <c>false</c> otherwise.</returns> /// <param name="texture">Texture.</param> /// <param name="enabled">If set to <c>true</c> enabled.</param> /// <param name="force">If set to <c>true</c> force.</param> public static bool TextureSetReadWriteEnabled(Texture2D texture, bool enabled, bool force) { return SPTools.AssetSetReadWriteEnabled(SPTools.GetAssetPath(texture), enabled, force); } /// <summary> /// Sets the asset Read/Write enabled state. /// </summary> /// <returns><c>true</c>, if set read write enabled was asseted, <c>false</c> otherwise.</returns> /// <param name="path">Path.</param> /// <param name="enabled">If set to <c>true</c> enabled.</param> /// <param name="force">If set to <c>true</c> force.</param> public static bool AssetSetReadWriteEnabled(string path, bool enabled, bool force) { if (string.IsNullOrEmpty(path)) return false; TextureImporter ti = AssetImporter.GetAtPath(path) as TextureImporter; if (ti == null) return false; TextureImporterSettings settings = new TextureImporterSettings(); ti.ReadTextureSettings(settings); if (force || settings.readable != enabled) { settings.readable = enabled; ti.SetTextureSettings(settings); SPTools.DoAssetReimport(path, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport); } return true; } /// <summary> /// Imports and configures atlas texture. /// </summary> /// <returns><c>true</c>, if import and configure atlas texture was successful, <c>false</c> otherwise.</returns> /// <param name="targetTexture">Target texture.</param> /// <param name="sourceTexture">Source texture.</param> /// <param name="uvs">Uvs.</param> /// <param name="names">Names.</param> /// <param name="defaultPivot">Default pivot.</param> /// <param name="defaultCustomPivot">Default custom pivot.</param> public static bool ImportAndConfigureAtlasTexture(Texture2D targetTexture, Texture2D sourceTexture, Rect[] uvs, SPSpriteImportData[] spritesImportData) { // Get the asset path string assetPath = SPTools.GetAssetPath(targetTexture); if (string.IsNullOrEmpty(assetPath)) { Debug.LogError("Sprite Packer failed to Import and Configure the atlas texture, reason: Could not resolve asset path."); return false; } // Clear the read-only flag in texture file attributes if (!SPTools.RemoveReadOnlyFlag(assetPath)) { Debug.LogError("Sprite Packer failed to Import and Configure the atlas texture, reason: Could not remove the readonly flag from the asset."); return false; } // Write the source texture data to the asset byte[] bytes = sourceTexture.EncodeToPNG(); System.IO.File.WriteAllBytes(assetPath, bytes); bytes = null; // Get the asset texture importer TextureImporter texImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter; if (texImporter == null) { Debug.LogError("Sprite Packer failed to Import and Configure the atlas texture, reason: Could not get the texture importer for the asset."); return false; } // Get the asset texture importer settings TextureImporterSettings texImporterSettings = new TextureImporterSettings(); // Apply sprite type texImporter.textureType = TextureImporterType.Sprite; texImporter.spriteImportMode = SpriteImportMode.Multiple; // Configure the spritesheet meta data SpriteMetaData[] spritesheetMeta = new SpriteMetaData[uvs.Length]; for (int i = 0; i < uvs.Length; i++) { if (SPTools.HasSpritesheetMeta(texImporter.spritesheet, spritesImportData[i].name)) { SpriteMetaData currentMeta = SPTools.GetSpritesheetMeta(texImporter.spritesheet, spritesImportData[i].name); Rect currentRect = uvs[i]; currentRect.x *= sourceTexture.width; currentRect.width *= sourceTexture.width; currentRect.y *= sourceTexture.height; currentRect.height *= sourceTexture.height; currentMeta.rect = currentRect; spritesheetMeta[i] = currentMeta; } else { SpriteMetaData currentMeta = new SpriteMetaData(); Rect currentRect = uvs[i]; currentRect.x *= sourceTexture.width; currentRect.width *= sourceTexture.width; currentRect.y *= sourceTexture.height; currentRect.height *= sourceTexture.height; currentMeta.rect = currentRect; currentMeta.name = spritesImportData[i].name; currentMeta.alignment = (int)spritesImportData[i].alignment; currentMeta.pivot = spritesImportData[i].pivot; currentMeta.border = spritesImportData[i].border; spritesheetMeta[i] = currentMeta; } } texImporter.spritesheet = spritesheetMeta; // Read the texture importer settings texImporter.ReadTextureSettings(texImporterSettings); // Disable Read/Write texImporterSettings.readable = false; // Re-set the texture importer settings texImporter.SetTextureSettings(texImporterSettings); // Save and Reimport the asset AssetDatabase.SaveAssets(); SPTools.DoAssetReimport(assetPath, ImportAssetOptions.ForceUpdate | ImportAssetOptions.ForceSynchronousImport); // Return success return true; } /// <summary> /// Determines if the specified name has spritesheet meta data. /// </summary> /// <returns><c>true</c> if has spritesheet meta the specified collection name; otherwise, <c>false</c>.</returns> /// <param name="collection">Collection.</param> /// <param name="name">Name.</param> private static bool HasSpritesheetMeta(SpriteMetaData[] collection, string name) { for (int i = 0; i < collection.Length; i++) { if (collection[i].name == name) return true; } return false; } /// <summary> /// Gets the spritesheet meta data for the specified name. /// </summary> /// <returns>The spritesheet meta.</returns> /// <param name="collection">Collection.</param> /// <param name="name">Name.</param> private static SpriteMetaData GetSpritesheetMeta(SpriteMetaData[] collection, string name) { for (int i = 0; i < collection.Length; i++) { if (collection[i].name == name) return collection[i]; } return new SpriteMetaData(); } /// <summary> /// Loads a sprite from a texture. /// </summary> /// <returns>The sprite.</returns> /// <param name="mainTexture">Main texture.</param> /// <param name="name">Name.</param> public static Sprite LoadSprite(Texture2D mainTexture, string name) { string texturePath = SPTools.GetAssetPath(mainTexture); Object[] atlasAssets = AssetDatabase.LoadAllAssetsAtPath(texturePath); foreach (Object asset in atlasAssets) { if (AssetDatabase.IsSubAsset(asset) && asset.name == name) { return asset as Sprite; } } return null; } /// <summary> /// Determines if the specified object is main asset. /// </summary> /// <returns><c>true</c> if is main asset the specified obj; otherwise, <c>false</c>.</returns> /// <param name="obj">Object.</param> public static bool IsMainAsset(Object obj) { return AssetDatabase.IsMainAsset(obj); } /// <summary> /// Determines if the specified object has sub assets. /// </summary> /// <returns><c>true</c> if has sub assets the specified obj; otherwise, <c>false</c>.</returns> /// <param name="obj">Object.</param> public static bool HasSubAssets(Object obj) { return (AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(obj)).Length > 1); } /// <summary> /// Gets the sub assets of an object. /// </summary> /// <returns>The sub assets.</returns> /// <param name="obj">Object.</param> public static Object[] GetSubAssets(Object obj) { Object[] assets = AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(obj)); List<Object> subAssets = new List<Object>(); foreach (Object asset in assets) { if (AssetDatabase.IsSubAsset(asset)) subAssets.Add(asset); } return subAssets.ToArray(); } /// <summary> /// Determines if the specified path is directory. /// </summary> /// <returns><c>true</c> if is directory the specified path; otherwise, <c>false</c>.</returns> /// <param name="path">Path.</param> public static bool IsDirectory(string path) { if (string.IsNullOrEmpty(path)) return false; return System.IO.Directory.Exists(path); } /// <summary> /// Gets the assets in the specified directory. /// </summary> /// <returns>The directory assets.</returns> /// <param name="path">Path.</param> public static Object[] GetDirectoryAssets(string path) { List<Object> assets = new List<Object>(); // Get the file paths of all the files in the specified directory string[] assetPaths = System.IO.Directory.GetFiles(path); // Enumerate through the list of files loading the assets they represent foreach (string assetPath in assetPaths) { // Check if it's a meta file if (assetPath.Contains(".meta")) continue; Object objAsset = AssetDatabase.LoadAssetAtPath(assetPath, typeof(Object)); if (objAsset != null) assets.Add(objAsset); } // Return the array of objects return assets.ToArray(); } /// <summary> /// Filters the resources for atlas import. /// </summary> /// <returns>The resources for atlas import.</returns> /// <param name="resources">Resources.</param> public static Object[] FilterResourcesForAtlasImport(Object[] resources) { List<Object> tempList = new List<Object>(); foreach (Object resource in resources) { string resourcePath = SPTools.GetAssetPath(resource); // Check if this is a main asset and queue all it's sub assets if (SPTools.IsMainAsset(resource) && SPTools.HasSubAssets(resource)) { Object[] subAssets = SPTools.FilterResourcesForAtlasImport(SPTools.GetSubAssets(resource)); foreach (Object a in subAssets) tempList.Add(a); } else if (resource is Texture2D || resource is Sprite) { tempList.Add(resource); } else if (SPTools.IsDirectory(resourcePath)) { Object[] subAssets = SPTools.FilterResourcesForAtlasImport(SPTools.GetDirectoryAssets(resourcePath)); foreach (Object a in subAssets) tempList.Add(a); } } return tempList.ToArray(); } /// <summary> /// Replaces all the references in the scene (does not work with internal properties). /// </summary> /// <param name="spriteInfoList">Sprite info list.</param> /// <param name="spriteRenderersOnly">If set to <c>true</c> sprite renderers only.</param> /// <returns>The replaced references count.</returns> public static int ReplaceReferencesInScene(List<SPSpriteInfo> spriteInfoList, bool spriteRenderersOnly) { Component[] comps = Resources.FindObjectsOfTypeAll<Component>(); int count = 0; foreach (SPSpriteInfo spriteInfo in spriteInfoList) { if (spriteInfo.source != null && spriteInfo.source is Sprite && spriteInfo.targetSprite != null) { count += SPTools.ReplaceReferences(comps, (spriteInfo.source as Sprite), spriteInfo.targetSprite, spriteRenderersOnly); } } return count; } /// <summary> /// Replaces all the references in the project (does not work with internal properties). /// </summary> /// <param name="spriteInfoList">Sprite info list.</param> /// <param name="spriteRenderersOnly">If set to <c>true</c> sprite renderers only.</param> /// <returns>The replaced references count.</returns> public static int ReplaceReferencesInProject(List<SPSpriteInfo> spriteInfoList, bool spriteRenderersOnly) { Component[] comps = SPTools.GetProjectPrefabComponents(); int count = 0; foreach (SPSpriteInfo spriteInfo in spriteInfoList) { if (spriteInfo.source != null && spriteInfo.source is Sprite && spriteInfo.targetSprite != null) { count += SPTools.ReplaceReferences(comps, (spriteInfo.source as Sprite), spriteInfo.targetSprite, spriteRenderersOnly); } } return count; } /// <summary> /// Replaces all the references in all scenes. /// </summary> /// <param name="spriteInfoList">Sprite info list.</param> /// <param name="spriteRenderersOnly">If set to <c>true</c> sprite renderers only.</param> /// <param name="skipCurrent">If set to <c>true</c> skip current scene.</param> /// <returns>The replaced references count.</returns> public static int ReplaceReferencesInAllScenes(List<SPSpriteInfo> spriteInfoList, bool spriteRenderersOnly, bool skipCurrent) { int count = 0; // Grab the current scene name string startingScene = EditorApplication.currentScene; // Get all scene names string[] sceneNames = SPTools.GetAllScenesNames(); if (sceneNames.Length == 0) return count; foreach (string sceneName in sceneNames) { // Check if we should skip the scene if (skipCurrent && sceneName.Equals(startingScene)) continue; // Try opening the scene if (EditorApplication.OpenScene(sceneName)) { Component[] comps = Object.FindObjectsOfType<Component>(); foreach (SPSpriteInfo spriteInfo in spriteInfoList) { if (spriteInfo.source != null && spriteInfo.source is Sprite && spriteInfo.targetSprite != null) { count += SPTools.ReplaceReferences(comps, (spriteInfo.source as Sprite), spriteInfo.targetSprite, spriteRenderersOnly); } } EditorApplication.SaveScene(); } } // Load back the original scene EditorApplication.OpenScene(startingScene); // Return the replaced references count return count; } /// <summary> /// Replaces all the references in the supplied array (does not work with internal properties). /// </summary> /// <param name="find">Find.</param> /// <param name="replaceWith">Replace with.</param> /// <param name="spriteRenderersOnly">If set to <c>true</c> sprite renderers only.</param> /// <returns>The replaced references count.</returns> public static int ReplaceReferences(Component[] components, Sprite find, Sprite replaceWith, bool spriteRenderersOnly) { if (components == null || components.Length == 0) return 0; int count = 0; foreach (Object comp in components) { // Handle sprite renderers differently if (comp is SpriteRenderer) { if ((comp as SpriteRenderer).sprite == find) { (comp as SpriteRenderer).sprite = replaceWith; count++; } } else { // If this component is not a sprite renderer if (spriteRenderersOnly) continue; // Get the fileds info FieldInfo[] fields = comp.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); foreach (FieldInfo fieldInfo in fields) { if (fieldInfo == null) continue; object fieldValue = fieldInfo.GetValue(comp); // Handle arrays if (fieldInfo.FieldType.IsArray) { var fieldValueArray = fieldValue as System.Array; if (fieldValueArray == null || fieldValueArray.GetType() != typeof(Sprite[])) continue; bool changed = false; System.Array newArray = new System.Array[fieldValueArray.Length]; fieldValueArray.CopyTo(newArray, 0); for (int i = 0; i < newArray.Length; i++) { object element = newArray.GetValue(i); if (element != null && element.GetType() == typeof(Sprite)) { Sprite o = element as Sprite; // Check if the value is what we are looking for if (o == find) { newArray.SetValue((replaceWith as object), i); changed = true; count++; } } } // Repalce the array if (changed) { fieldInfo.SetValue(comp, newArray); } } // Handle structs else if (fieldInfo.FieldType.IsValueType && !fieldInfo.FieldType.IsEnum && !fieldInfo.IsLiteral) { FieldInfo[] structFields = fieldInfo.FieldType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo structFieldInfo in structFields) { if (structFieldInfo == null) continue; if (structFieldInfo.FieldType == typeof(Sprite)) { Sprite structFieldValue = structFieldInfo.GetValue(fieldValue) as Sprite; // Check if the value is what we are looking for if (structFieldValue == find) { // Replace structFieldInfo.SetValue(fieldValue, (replaceWith as object)); count++; } } } fieldInfo.SetValue(comp, fieldValue); } // Handle direct sprites else if (fieldInfo.FieldType == typeof(Sprite)) { // Check if the value is what we are looking for if ((fieldValue as Sprite) == find) { // Replace fieldInfo.SetValue(comp, (replaceWith as object)); count++; } } } } if (PrefabUtility.GetPrefabType((comp as Component).gameObject) != PrefabType.None) EditorUtility.SetDirty((comp as Component)); } return count; } /// <summary> /// Gets all scenes names. /// </summary> /// <returns>The all scenes names.</returns> public static string[] GetAllScenesNames() { List<string> list = new List<string>(); foreach (EditorBuildSettingsScene scene in EditorBuildSettings.scenes) { if (!scene.enabled) continue; list.Add(scene.path); } return list.ToArray(); } public static Component[] GetProjectPrefabComponents() { List<Component> result = new List<Component>(); string[] assets = AssetDatabase.GetAllAssetPaths(); foreach (string assetPath in assets) { UnityEngine.Object assetObj = AssetDatabase.LoadAssetAtPath(assetPath, typeof(UnityEngine.Object)); if (PrefabUtility.GetPrefabType(assetObj) != PrefabType.None) { GameObject gameObject = assetObj as GameObject; if (gameObject != null) { Component[] comps = gameObject.transform.GetComponentsInChildren<Component>(true); foreach (Component comp in comps) result.Add(comp); } } } return result.ToArray(); } } }
#region WatiN Copyright (C) 2006-2009 Jeroen van Menen //Copyright 2006-2009 Jeroen van Menen // // 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 Copyright using System; using System.Text.RegularExpressions; using WatiN.Core.Comparers; using WatiN.Core.Constraints; namespace WatiN.Core { /// <summary> /// This class provides factory methods for de most commonly used attributes /// to find an element on a web page. /// </summary> public class Find { internal const string altAttribute = "alt"; internal const string idAttribute = "id"; internal const string forAttribute = "htmlFor"; internal const string nameAttribute = "name"; internal const string srcAttribute = "src"; internal const string styleBaseAttribute = "style."; internal const string innerTextAttribute = "innertext"; internal const string titleAttribute = "title"; internal const string tagNameAttribute = "tagName"; internal const string valueAttribute = "value"; internal const string hrefAttribute = "href"; internal const string classNameAttribute = "className"; /// <summary> /// Finds anything. /// </summary> public static AnyConstraint Any { get { return AnyConstraint.Instance; } } /// <summary> /// Finds nothing. /// </summary> public static NoneConstraint None { get { return NoneConstraint.Instance; } } /// <summary> /// Finds an element by its alt text. /// </summary> /// <param name="alt">The alt text to find.</param> /// <returns>The AttributeConstraint</returns> /// <example> /// <code>ie.Image(Find.ByAlt("alt text")).Name</code> /// </example> public static AttributeConstraint ByAlt(string alt) { return new AttributeConstraint(altAttribute, alt); } /// <summary> /// Finds an element by its alt text. /// </summary> /// <param name="regex">The regular expression for the alt text to find.</param> /// <returns>The AttributeConstraint</returns> /// <example> /// <code>ie.Image(Find.ByAlt(new Regex("pattern goes here")))).Name</code> /// </example> public static AttributeConstraint ByAlt(Regex regex) { return new AttributeConstraint(altAttribute, regex); } /// <summary> /// Finds an element by its alt text. /// </summary> /// <param name="compare">The compare.</param> /// <returns>The AttributeConstraint</returns> /// <example> /// <code>Image img = ie.Image(Find.ByAlt(new StringContainsAndCaseInsensitiveComparer("alt text")));</code> /// </example> public static AttributeConstraint ByAlt(Comparer<string> compare) { return new AttributeConstraint(altAttribute, compare); } /// <summary> /// Finds an element by its alt text. /// </summary> /// <param name="predicate">The predicate method to call to make the comparison.</param> /// <returns>The AttributeConstraint</returns> /// <example> /// <code>Image img = ie.Image(Find.ByAlt(MyOwnCompareMethod));</code> /// </example> public static AttributeConstraint ByAlt(Predicate<string> predicate) { return new AttributeConstraint(altAttribute, new PredicateComparer<string, string>(predicate)); } /// <summary> /// Finds an element by its (CSS) class name text. /// </summary> /// <param name="classname">The class name to find.</param> /// <returns>The AttributeConstraint</returns> /// <example> /// <code>ie.Div(Find.ByClass("HighlightedHeader")).Name</code> /// </example> public static AttributeConstraint ByClass(string classname) { return new AttributeConstraint(classNameAttribute, classname); } /// <summary> /// Finds an element by its (CSS) class name text. /// </summary> /// <param name="regex">The regular expression for the class name to find.</param> /// <returns>The AttributeConstraint</returns> /// <example> /// <code>ie.Div(Find.ByClass(new Regex("HighlightedHeader")))).Name</code> /// </example> public static AttributeConstraint ByClass(Regex regex) { return new AttributeConstraint(classNameAttribute, regex); } /// <summary> /// Finds an element by its (CSS) class name text. /// </summary> /// <param name="compare">The comparer.</param> /// <returns>The AttributeConstraint</returns> /// <example> /// <code>Div div = ie.Div(Find.ByClass(new StringContainsAndCaseInsensitiveComparer("Highlighted")));</code> /// </example> public static AttributeConstraint ByClass(Comparer<string> compare) { return new AttributeConstraint(classNameAttribute, compare); } /// <summary> /// Finds an element by its (CSS) class name text. /// </summary> /// <param name="predicate">The predicate method to call to make the comparison.</param> /// <returns>The AttributeConstraint</returns> /// <example> /// <code>Div div = ie.Div(Find.ByClass(MyOwnCompareMethod));</code> /// </example> public static AttributeConstraint ByClass(Predicate<string> predicate) { return new AttributeConstraint(classNameAttribute, new PredicateComparer<string, string>(predicate)); } /// <summary> /// Finds a Label element by the id of the element it's linked with. /// </summary> /// <param name="forId">Id of the element the label is linked with.</param> /// <returns><see cref="AttributeConstraint" /></returns> /// <example> /// <code>ie.Label(Find.ByFor("optionbuttonid")).Text</code> /// </example> public static AttributeConstraint ByFor(string forId) { return new AttributeConstraint(forAttribute, forId); } /// <summary> /// Finds a Label element by the id of the element it's linked with. /// </summary> /// <param name="regex">Regular expression to find the matching Id of the element /// the label is linked with.</param> /// <returns><see cref="AttributeConstraint" /></returns> /// <example> /// <code>ie.Label(Find.ByFor(new Regex("pattern goes here")).Text</code> /// </example> public static AttributeConstraint ByFor(Regex regex) { return new AttributeConstraint(forAttribute, regex); } /// <summary> /// Finds a Label element by the id of the element it's linked with. /// </summary> /// <param name="element">The element to which the Label element is attached. This element must an Id value.</param> /// <returns><see cref="AttributeConstraint" /></returns> /// <example> /// <code> /// CheckBox checkbox = ie.CheckBox("checkboxid"); /// ie.Label(Find.ByFor(checkbox).Text</code> /// </example> public static AttributeConstraint ByFor(Element element) { return new AttributeConstraint(forAttribute, element.Id); } /// <summary> /// Finds a Label element by the id of the element it's linked with. /// </summary> /// <param name="comparer">The comparer.</param> /// <returns><see cref="AttributeConstraint"/></returns> /// <example> /// <code> /// Label label = ie.Label(Find.ByFor(new StringContainsAndCaseInsensitiveComparer("optionbuttonid")));</code> /// </example> public static AttributeConstraint ByFor(Comparer<string> comparer) { return new AttributeConstraint(forAttribute, comparer); } /// <summary> /// Finds a Label element by the id of the element it's linked with. /// </summary> /// <param name="predicate">The predicate method to call to make the comparison.</param> /// <returns>The AttributeConstraint</returns> /// <example> /// <code> /// Label label = ie.Label(Find.ByFor(MyOwnCompareMethod)); /// </code> /// </example> public static AttributeConstraint ByFor(Predicate<string> predicate) { return new AttributeConstraint(forAttribute, new PredicateComparer<string, string>(predicate)); } /// <summary> /// Finds an element by its id. /// </summary> /// <param name="id">Element id to find.</param> /// <returns><see cref="AttributeConstraint" /></returns> /// <example> /// <code>ie.Link(Find.ById("testlinkid")).Url</code> /// </example> public static AttributeConstraint ById(string id) { return new AttributeConstraint(idAttribute, id); } /// <summary> /// Finds an element by its id. /// </summary> /// <param name="regex">Regular expression to find a matching Id.</param> /// <returns><see cref="AttributeConstraint" /></returns> /// <example> /// <code>ie.Link(Find.ById(new Regex("pattern goes here"))).Url</code> /// </example> public static AttributeConstraint ById(Regex regex) { return new AttributeConstraint(idAttribute, regex); } /// <summary> /// Finds an element by its id. /// </summary> /// <param name="compare">The compare.</param> /// <returns><see cref="AttributeConstraint"/></returns> /// <example> /// <code>Link link = ie.Link(Find.ById(new StringContainsAndCaseInsensitiveComparer("linkId1")));</code> /// </example> public static AttributeConstraint ById(Comparer<string> compare) { return new AttributeConstraint(idAttribute, compare); } /// <summary> /// Finds an element by its id. /// </summary> /// <param name="predicate">The predicate method to call to make the comparison.</param> /// <returns>The AttributeConstraint</returns> /// <example> /// <code> /// Link link = ie.Link(Find.ById(MyOwnCompareMethod)); /// </code> /// </example> public static AttributeConstraint ById(Predicate<string> predicate) { return new AttributeConstraint(idAttribute, new PredicateComparer<string, string>(predicate)); } /// <summary> /// Finds an element by its index. /// </summary> /// <param name="index">The zero-based index.</param> /// <returns></returns> /// <example> /// <code> /// // Returns the 3rd link with class "link". /// Link link = ie.Link(Find.ByClass("link") &amp; Find.ByIndex(2)); /// </code> /// </example> public static IndexConstraint ByIndex(int index) { return new IndexConstraint(index); } /// <summary> /// Finds an element by its name. /// </summary> /// <param name="name">Name to find.</param> /// <returns><see cref="AttributeConstraint" /></returns> /// <example> /// <code>ie.Link(Find.ByName("testlinkname")).Url</code> /// </example> public static AttributeConstraint ByName(string name) { return new AttributeConstraint(nameAttribute, name); } /// <summary> /// Finds an element by its name. /// </summary> /// <param regex="regex">Regular expression to find a matching Name.</param> /// <returns><see cref="AttributeConstraint" /></returns> /// <example> /// <code>ie.Link(Find.ByName(new Regex("pattern goes here")))).Url</code> /// </example> public static AttributeConstraint ByName(Regex regex) { return new AttributeConstraint(nameAttribute, regex); } /// <summary> /// Finds an element by its name. /// </summary> /// <param name="comparer">The comparer.</param> /// <returns><see cref="AttributeConstraint"/></returns> /// <example> /// <code>ie.Link(Find.ByName(new StringContainsAndCaseInsensitiveComparer("linkname")))).Url</code> /// </example> public static AttributeConstraint ByName(Comparer<string> comparer) { return new AttributeConstraint(nameAttribute, comparer); } /// <summary> /// Finds an element by its name. /// </summary> /// <param name="predicate">The predicate method to call to make the comparison.</param> /// <returns>The AttributeConstraint</returns> /// <example> /// <code> /// Link link = ie.Link(Find.ByName(MyOwnCompareMethod)); /// </code> /// </example> public static AttributeConstraint ByName(Predicate<string> predicate) { return new AttributeConstraint(nameAttribute, new PredicateComparer<string, string>(predicate)); } /// <summary> /// Finds an element by its (inner) text. /// </summary> /// <param name="text">Element text</param> /// <returns><see cref="AttributeConstraint" /></returns> /// <example> /// <code>ie.Link(Find.ByText("my link")).Url</code> /// </example> public static AttributeConstraint ByText(string text) { var escapedText = text == null ? null : text.Replace("\\", "\\\\"); return new AttributeConstraint(innerTextAttribute, new Regex("^ *" + escapedText + " *$")); } /// <summary> /// Finds an element by its (inner) text. /// </summary> /// <param name="regex">Regular expression to find a matching Text.</param> /// <returns><see cref="AttributeConstraint" /></returns> /// <example> /// <code>ie.Link(Find.ByText(new Regex("pattern goes here"))).Url</code> /// </example> public static AttributeConstraint ByText(Regex regex) { return new AttributeConstraint(innerTextAttribute, regex); } /// <summary> /// Finds an element by its (inner) text. /// </summary> /// <param name="comparer">The comparer.</param> /// <returns><see cref="AttributeConstraint"/></returns> /// <example> /// <code>Link link = ie.Link(Find.ByText(new StringContainsAndCaseInsensitiveComparer("my li"))).Url</code> /// </example> public static AttributeConstraint ByText(Comparer<string> comparer) { return new AttributeConstraint(innerTextAttribute, comparer); } /// <summary> /// Finds an element by its (inner) text. /// </summary> /// <param name="predicate">The predicate method to call to make the comparison.</param> /// <returns>The AttributeConstraint</returns> /// <example> /// <code> /// Link link = ie.Link(Find.ByText(MyOwnCompareMethod)); /// </code> /// </example> public static AttributeConstraint ByText(Predicate<string> predicate) { return new AttributeConstraint(innerTextAttribute, new PredicateComparer<string, string>(predicate)); } /// <summary> /// Finds an element, frame, IE instance or HTMLDialog by its Url. /// </summary> /// <param name="url">The well-formed url to find.</param> /// <returns><see cref="AttributeConstraint" /></returns> /// <example> /// <code>ie.Link(Find.ByUrl("http://watin.sourceforge.net")).Url</code> /// </example> public static AttributeConstraint ByUrl(string url) { return ByUrl(new Uri(url)); } /// <summary> /// Finds an element, frame, IE instance or HTMLDialog by its Url. /// </summary> /// <param name="url">The well-formed url to find.</param> /// <param name="ignoreQuery">Set to true to ignore querystring when matching.</param> /// <returns><see cref="AttributeConstraint" /></returns> /// <example> /// <code>ie.Link(Find.ByUrl("http://watin.sourceforge.net", true)).Url</code> /// </example> public static AttributeConstraint ByUrl(string url, bool ignoreQuery) { return ByUrl(new Uri(url), ignoreQuery); } /// <summary> /// Finds an element, frame, IE instance or HTMLDialog by its Url. /// </summary> /// <param name="uri">The uri to find.</param> /// <returns><see cref="AttributeConstraint" /></returns> /// <example> /// <code>ie.Link(Find.ByUrl(new Uri("watin.sourceforge.net"))).Url</code> /// </example> public static AttributeConstraint ByUrl(Uri uri) { return ByUrl(uri, false); } /// <summary> /// Finds an element, frame, IE instance or HTMLDialog by its Url. /// </summary> /// <param name="uri">The uri to find.</param> /// <param name="ignoreQuery">Set to true to ignore querystring when matching.</param> /// <returns><see cref="AttributeConstraint" /></returns> /// <example> /// <code>ie.Link(Find.ByUrl(new Uri("watin.sourceforge.net", true))).Url</code> /// </example> public static AttributeConstraint ByUrl(Uri uri, bool ignoreQuery) { return new AttributeConstraint(hrefAttribute, new UriComparer(uri, ignoreQuery)); } /// <summary> /// Finds an element, frame, IE instance or HTMLDialog by its Url. /// </summary> /// <param name="regex">Regular expression to find a matching Url.</param> /// <returns><see cref="AttributeConstraint" /></returns> /// <example> /// <code>ie.Link(Find.ByUrl(new Regex("pattern goes here"))).Url</code> /// </example> public static Constraint ByUrl(Regex regex) { return new AttributeConstraint(hrefAttribute, regex); } /// <summary> /// Finds an element, frame, IE instance or HTMLDialog by its Url. /// </summary> /// <param name="comparer">The comparer.</param> /// <returns><see cref="AttributeConstraint"/></returns> /// <example> /// <code>ie.Link(Find.ByUrl(new UriComparer(uri, ignoreQuery))).Url</code> /// </example> public static AttributeConstraint ByUrl(Comparer<string> comparer) { return new AttributeConstraint(hrefAttribute, comparer); } /// <summary> /// Finds an element, frame, IE instance or HTMLDialog by its Url. /// </summary> /// <param name="predicate">The predicate method to call to make the comparison.</param> /// <returns>The AttributeConstraint</returns> /// <example> /// <code> /// Link link = ie.Link(Find.ByUrl(MyOwnCompareMethod)); /// </code> /// </example> public static AttributeConstraint ByUrl(Predicate<string> predicate) { return new AttributeConstraint(hrefAttribute, new PredicateComparer<string, string>(predicate)); } /// <summary> /// Finds an element, frame, IE instance or HTMLDialog by its Title. /// </summary> /// <param name="title">The title to match partially.</param> /// <returns><see cref="AttributeConstraint"/></returns> /// <example> /// <code>IE ie = IE.AttachToIE(Find.ByTitle("WatiN Home Page"))</code> /// </example> public static AttributeConstraint ByTitle(string title) { return new AttributeConstraint(titleAttribute, new StringContainsAndCaseInsensitiveComparer(title)); } /// <summary> /// Finds an element, frame, IE instance or HTMLDialog by its Title. /// </summary> /// <param name="regex">Regular expression to find a matching Title.</param> /// <returns><see cref="AttributeConstraint"/></returns> /// <example> /// <code>IE ie = IE.AttachToIE(Find.ByTitle(new Regex("pattern goes here")))</code> /// </example> public static AttributeConstraint ByTitle(Regex regex) { return new AttributeConstraint(titleAttribute, regex); } /// <summary> /// Finds an element, frame, IE instance or HTMLDialog by its Title. /// </summary> /// <param name="comparer">The comparer.</param> /// <returns><see cref="AttributeConstraint"/></returns> /// <example> /// <code>IE ie = IE.AttachToIE(Find.ByTitle(new StringContainsAndCaseInsensitiveComparer("part of the title")));</code> /// </example> public static AttributeConstraint ByTitle(Comparer<string> comparer) { return new AttributeConstraint(titleAttribute, comparer); } /// <summary> /// Finds an element, frame, IE instance or HTMLDialog by its Title. /// </summary> /// <param name="predicate">The predicate method to call to make the comparison.</param> /// <returns>The AttributeConstraint</returns> /// <example> /// <code> /// IE ie = IE.AttachToIE(Find.ByTitle(MyOwnCompareMethod)); /// </code> /// </example> public static AttributeConstraint ByTitle(Predicate<string> predicate) { return new AttributeConstraint(titleAttribute, new PredicateComparer<string, string>(predicate)); } /// <summary> /// Finds an element by its value attribute. /// </summary> /// <param name="value">The value to find.</param> /// <returns><see cref="AttributeConstraint"/></returns> /// <example> /// <code> /// Button button = ie.Button(Find.ByValue("My Button")) /// </code> /// </example> public static AttributeConstraint ByValue(string value) { return new AttributeConstraint(valueAttribute, value); } /// <summary> /// Finds an element by its value attribute. /// </summary> /// <param name="regex">Regular expression to find a matching Value.</param> /// <returns><see cref="AttributeConstraint"/></returns> /// <example> /// <code> /// Button button = ie.Button(Find.ByValue(new Regex("pattern goes here"))) /// </code> /// </example> public static AttributeConstraint ByValue(Regex regex) { return new AttributeConstraint(valueAttribute, regex); } /// <summary> /// Finds an element by its value attribute. /// </summary> /// <param name="comparer">The comparer.</param> /// <returns><see cref="AttributeConstraint"/></returns> /// <example> /// <code> /// Button button = ie.Button(Find.ByValue(new StringContainsAndCaseInsensitiveComparer("pattern goes here"))); /// </code> /// </example> public static AttributeConstraint ByValue(Comparer<string> comparer) { return new AttributeConstraint(valueAttribute, comparer); } /// <summary> /// Finds an element by its value attribute. /// </summary> /// <param name="predicate">The predicate method to call to make the comparison.</param> /// <returns>The AttributeConstraint</returns> /// <example> /// <code> /// Button button = ie.Button(Find.ByValue(MyOwnCompareMethod)); /// </code> /// </example> public static AttributeConstraint ByValue(Predicate<string> predicate) { return new AttributeConstraint(valueAttribute, new PredicateComparer<string, string>(predicate)); } /// <summary> /// Finds an <see cref="Image"/> by its source (src) attribute. /// </summary> /// <param name="src">Src to find.</param> /// <returns><see cref="AttributeConstraint" /></returns> /// <example> /// <code>ie.Image(Find.BySrc("image.gif"))</code> /// </example> public static AttributeConstraint BySrc(string src) { return new AttributeConstraint(srcAttribute, src); } /// <summary> /// Finds an <see cref="Image"/> by its source (src) attribute. /// </summary> /// <param regex="regex">Regular expression to find a matching Src.</param> /// <returns><see cref="AttributeConstraint" /></returns> /// <example> /// <code>ie.Image(Find.BySrc(new Regex("pattern goes here"))))</code> /// </example> public static AttributeConstraint BySrc(Regex regex) { return new AttributeConstraint(srcAttribute, regex); } /// <summary> /// Finds an <see cref="Image"/> by its source (src) attribute. /// </summary> /// <param name="comparer">The comparer.</param> /// <returns><see cref="AttributeConstraint"/></returns> /// <example> /// <code>Image image = ie.Image(Find.BySrc(new StringContainsAndCaseInsensitiveComparer("watin/sourceforge")));</code> /// </example> public static AttributeConstraint BySrc(Comparer<string> comparer) { return new AttributeConstraint(srcAttribute, comparer); } /// <summary> /// Finds an <see cref="Image"/> by its source (src) attribute. /// </summary> /// <param name="predicate">The predicate method to call to make the comparison.</param> /// <returns>The AttributeConstraint</returns> /// <example> /// <code> /// Image image = ie.Image(Find.BySrc(MyOwnCompareMethod)); /// </code> /// </example> public static AttributeConstraint BySrc(Predicate<string> predicate) { return new AttributeConstraint(srcAttribute, new PredicateComparer<string, string>(predicate)); } /// <summary> /// Finds an element by an attribute. /// </summary> /// <param name="attributeName">The attribute name to compare the value with.</param> /// <param name="value">The exact matching value of the attribute.</param> /// <returns><see cref="AttributeConstraint" /></returns> /// <example> /// <code>ie.Link(Find.By("id", "testlinkid")).Url</code> /// </example> public static AttributeConstraint By(string attributeName, string value) { return new AttributeConstraint(attributeName, value); } /// <summary> /// Finds an element by an attribute. /// </summary> /// <param name="attributeName">The attribute name to compare the value with.</param> /// <param name="regex">Regular expression to find a matching value of the given attribute.</param> /// <returns><see cref="AttributeConstraint" /></returns> /// <example> /// <code>ie.Link(Find.By("id", new Regex("pattern goes here"))).Url</code> /// </example> public static AttributeConstraint By(string attributeName, Regex regex) { return new AttributeConstraint(attributeName, regex); } /// <summary> /// Finds an element by an attribute. /// </summary> /// <param name="attributeName">The attribute to compare the value with.</param> /// <param name="comparer">The comparer to be used.</param> /// <returns><see cref="AttributeConstraint"/></returns> /// <example> /// <code>Link link = ie.Link(Find.By("innertext", new StringContainsAndCaseInsensitiveComparer("pattern goes here")));</code> /// </example> public static AttributeConstraint By(string attributeName, Comparer<string> comparer) { return new AttributeConstraint(attributeName, comparer); } /// <summary> /// Finds an element by an attribute. /// </summary> /// <param name="attributeName">The attribute to compare the value with.</param> /// <param name="predicate">The predicate method to call to make the comparison.</param> /// <returns>The AttributeConstraint</returns> /// <example> /// <code> /// Link link = ie.Link(Find.By("innertext", MyOwnCompareMethod)); /// </code> /// </example> public static AttributeConstraint By(string attributeName, Predicate<string> predicate) { return new AttributeConstraint(attributeName, new PredicateComparer<string, string>(predicate)); } /// <summary> /// Finds an element by a style attribute. /// </summary> /// <param name="styleAttributeName">Name of the style attribute.</param> /// <param name="value">The exact matching value of the attribute.</param> /// <returns><see cref="AttributeConstraint"/></returns> /// <example> /// <code>ie.Span(Find.ByStyle("background-color", "red"))</code> /// </example> public static AttributeConstraint ByStyle(string styleAttributeName, string value) { return new AttributeConstraint(styleBaseAttribute + styleAttributeName, value); } /// <summary> /// Finds an element by a style attribute. /// </summary> /// <param name="styleAttributeName">Name of the style attribute.</param> /// <param name="value">Regular expression to find a matching value of the given style attribute.</param> /// <returns><see cref="AttributeConstraint"/></returns> /// <example> /// <code>ie.Link(Find.ByStyle("font-family", new Regex("pattern goes here")))</code> /// </example> public static AttributeConstraint ByStyle(string styleAttributeName, Regex value) { return new AttributeConstraint(styleBaseAttribute + styleAttributeName, value); } /// <summary> /// Finds an element by a style attribute. /// </summary> /// <param name="styleAttributeName">Name of the style attribute.</param> /// <param name="comparer">The comparer.</param> /// <returns><see cref="AttributeConstraint"/></returns> /// <example> /// <code>Link link = ie.Link(Find.ByStyle("font-family", new StringContainsAndCaseInsensitiveComparer("aria")));</code> /// </example> public static AttributeConstraint ByStyle(string styleAttributeName, Comparer<string> comparer) { return new AttributeConstraint(styleBaseAttribute + styleAttributeName, comparer); } /// <summary> /// Finds an element by a style attribute. /// </summary> /// <param name="styleAttributeName">Name of the style attribute.</param> /// <param name="predicate">The predicate method to call to make the comparison.</param> /// <returns>The AttributeConstraint</returns> /// <example> /// <code> /// Link link = ie.Link(Find.ByStyle("font-family", MyOwnCompareMethod)); /// </code> /// </example> public static AttributeConstraint ByStyle(string styleAttributeName, Predicate<string> predicate) { return new AttributeConstraint(styleBaseAttribute + styleAttributeName, new PredicateComparer<string, string>(predicate)); } /// <summary> /// Finds an Element by using a specialized Element comparer. /// </summary> /// <param name="comparer">The comparer</param> /// <returns>An ElementConstraint instance</returns> public static ElementConstraint ByElement(Comparer<Element> comparer) { return new ElementConstraint(comparer); } /// <summary> /// Finds an Element by calling the predicate for each element that /// needs to be evaluated. /// </summary> /// <param name="predicate">The predicate</param> /// <returns>An ElementConstraint instance</returns> public static ElementConstraint ByElement(Predicate<Element> predicate) { return ByElement<Element>(predicate); } /// <summary> /// Finds an Element by calling the predicate for each element that /// needs to be evaluated. /// </summary> /// <param name="predicate">The predicate</param> /// <returns>An ElementConstraint instance</returns> public static ElementConstraint ByElement<TElement>(Predicate<TElement> predicate) where TElement:Element { return new ElementConstraint(new PredicateComparer<TElement, Element>(predicate)); } /// <summary> /// Finds an Element by determining whether there exists some other element /// in a position relative to it, such as an ancestor or descendant. /// </summary> /// <param name="selector">The relative selector</param> /// <returns>An ElementConstraint instance</returns> /// <example> /// <code> /// // Finds a row by the fact that it contains a table cell with particular text content. /// ie.TableRow(Find.ByExistenceOfRelatedElement&lt;TableRow&gt;(row => row.TableCell(Find.ByText("foo"))) /// </code> /// </example> public static ElementConstraint ByExistenceOfRelatedElement<T>(ElementSelector<T> selector) where T : Element { return ByElement<T>(element => IsNotNullAndExists(selector(element))); } private static bool IsNotNullAndExists(Element element) { return element != null && element.Exists; } /// <summary> /// Finds the first element of the expected type. /// </summary> /// <returns></returns> public static IndexConstraint First() { return ByIndex(0); } /// <summary> /// Finds a form element by looking for specific text on the page near the field. /// </summary> /// <param name="labelText">The text near the field</param> /// <returns><see cref="ProximityTextConstraint"/></returns> /// <example> /// <code>TextField = ie.TextField(Find.Near("User Name"));</code> /// </example> // public static ProximityTextConstraint Near(string labelText) // { // return new ProximityTextConstraint(labelText); // } /// <summary> /// Finds a form element by looking for the &lt;label&gt; associated with it by searching the label text. /// </summary> /// <param name="labelText">The text of the label element</param> /// <returns><see cref="LabelTextConstraint"/></returns> /// <example> /// This will look for a tet field that has a label element with the innerText "User Name:" /// <code>TextField = ie.TextField(Find.ByLabelText("User Name:"));</code> /// </example> public static LabelTextConstraint ByLabelText(string labelText) { return new LabelTextConstraint(labelText); } /// <summary> /// Finds an element by its default characteristics as defined by <see cref="Settings.FindByDefaultFactory" />. /// </summary> /// <param name="value">The string to match against</param> /// <returns>A constraint</returns> public static Constraint ByDefault(string value) { return Settings.FindByDefaultFactory.ByDefault(value); } /// <summary> /// Finds an element by its default characteristics as defined by <see cref="Settings.FindByDefaultFactory" />. /// </summary> /// <param name="value">The regular expression to match against</param> /// <returns>A constraint</returns> public static Constraint ByDefault(Regex value) { return Settings.FindByDefaultFactory.ByDefault(value); } /// <summary> /// Finds a <see cref="TableRow" /> element by the (inner) text of one of its cells. /// </summary> /// <param name="text">Element text</param> /// <param name="columnIndex">The zero-based column index</param> /// <returns><see cref="AttributeConstraint" /></returns> /// <example> /// <code>ie.TableRow(Find.ByTextInColumn("my link")).Url</code> /// </example> public static ElementConstraint ByTextInColumn(string text, int columnIndex) { return ByExistenceOfRelatedElement<TableRow>(row => row.OwnTableCell(ByIndex(columnIndex) && ByText(new StringEqualsAndCaseInsensitiveComparer(text)))); } /// <summary> /// Finds a <see cref="TableRow" /> element by the (inner) text of one of its cells. /// </summary> /// <param name="regex">Regular expression to find a matching Text.</param> /// <param name="columnIndex">The zero-based column index</param> /// <returns><see cref="AttributeConstraint" /></returns> /// <example> /// <code>ie.TableRow(Find.ByTextInColumn(new Regex("my link"))).Url</code> /// </example> public static ElementConstraint ByTextInColumn(Regex regex, int columnIndex) { return ByExistenceOfRelatedElement<TableRow>(row => row.OwnTableCell(ByIndex(columnIndex) && ByText(regex))); } /// <summary> /// Finds a <see cref="TableRow" /> element by the (inner) text of one of its cells. /// </summary> /// <param name="comparer">The comparer.</param> /// <param name="columnIndex">The zero-based column index</param> /// <returns><see cref="AttributeConstraint" /></returns> /// <example> /// <code>ie.TableRow(Find.ByTextInColumn(new StringContainsAndCaseInsensitiveComparer("my li"))).Url</code> /// </example> public static ElementConstraint ByTextInColumn(Comparer<string> comparer, int columnIndex) { return ByExistenceOfRelatedElement<TableRow>(row => row.OwnTableCell(ByIndex(columnIndex) && ByText(comparer))); } /// <summary> /// Finds a <see cref="TableRow" /> element by the (inner) text of one of its cells. /// </summary> /// <param name="predicate">The predicate method to call to make the comparison.</param> /// <param name="columnIndex">The zero-based column index</param> /// <returns><see cref="AttributeConstraint" /></returns> /// <example> /// <code>ie.TableRow(Find.ByTextInColumn(MyOwnCompareMethod)).Url</code> /// </example> public static ElementConstraint ByTextInColumn(Predicate<string> predicate, int columnIndex) { return ByExistenceOfRelatedElement<TableRow>(row => row.OwnTableCell(ByIndex(columnIndex) && ByText(predicate))); } } }
#region Copyright // <copyright file="BbCodeBaseConverter.cs"> // Copyright (c) 2013-2015, Justin Kadrovach, All rights reserved. // // This source is subject to the Simplified BSD License. // Please see the License.txt file for more information. // All other rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // </copyright> #endregion namespace slimCat.Utilities { #region Usings using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Media; using System.Windows.Shapes; using Libraries; using Models; using Services; #endregion /// <summary> /// The common logic for parsing bbcode. /// </summary> public abstract class BbCodeBaseConverter { private readonly ICharacterManager characters; internal readonly IThemeLocator Locator; #region Properties internal IChatModel ChatModel { get; set; } #endregion #region Static Fields private static readonly string[] ValidStartTerms = {"http://", "https://", "ftp://"}; public static readonly IDictionary<string, BbCodeType> Types = new Dictionary<string, BbCodeType> { {"big", BbCodeType.Big}, {"b", BbCodeType.Bold}, {"i", BbCodeType.Italic}, {"user", BbCodeType.User}, {"url", BbCodeType.Url}, {"u", BbCodeType.Underline}, {"icon", BbCodeType.Icon}, {"eicon", BbCodeType.EIcon}, {"sup", BbCodeType.Superscript}, {"sub", BbCodeType.Subscript}, {"small", BbCodeType.Small}, {"session", BbCodeType.Session}, {"s", BbCodeType.Strikethrough}, {"channel", BbCodeType.Channel}, {"color", BbCodeType.Color}, {"noparse", BbCodeType.NoParse}, {"collapse", BbCodeType.Collapse}, {"quote", BbCodeType.Quote}, {"hr", BbCodeType.HorizontalRule}, {"indent", BbCodeType.Indent}, {"justify", BbCodeType.Justify}, {"heading", BbCodeType.Heading}, {"left", BbCodeType.Left}, {"right", BbCodeType.Right}, {"center", BbCodeType.Center} }; #endregion #region Constructors protected BbCodeBaseConverter(IChatState chatState, IThemeLocator locator) { characters = chatState.CharacterManager; Locator = locator; ChatModel = chatState.ChatModel; } protected BbCodeBaseConverter() { } #endregion #region Methods internal Inline MakeUsernameLink(ICharacter target) { return MakeInlineContainer(target, "UsernameTemplate"); } internal Inline MakeIcon(ICharacter target) { return MakeInlineContainer(target, "UserIconTemplate"); } internal Inline MakeEIcon(string target) { return MakeInlineContainer(target, "EIconTemplate"); } internal Inline MakeChannelLink(ChannelModel channel) { return MakeInlineContainer(channel, "ChannelTemplate"); } private Inline MakeInlineContainer(object model, string template) { return new InlineUIContainer { Child = new ContentControl { ContentTemplate = Locator.Find<DataTemplate>(template), Content = model, Margin = new Thickness(2, 0, 2, 0) }, BaselineAlignment = BaselineAlignment.TextBottom }; } /// <summary> /// Converts a string to richly-formatted inline elements. /// </summary> internal Inline Parse(string text) { return AsInline(PreProcessBbCode(text)); } /// <summary> /// Gets a simplified display Url from a string. /// </summary> /// <example> /// <code> /// GetUrlDisplay("https://www.google.com"); // returns google.com /// </code> /// </example> private static string GetUrlDisplay(string args) { if (args == null) return null; var match = ValidStartTerms.FirstOrDefault(args.StartsWith); if (match == null) return args; var stripped = args.Substring(match.Length); if (stripped.Contains('/')) { // remove anything after the slash stripped = stripped.Substring(0, stripped.IndexOf('/')); } if (stripped.StartsWith("www.")) { // remove the www. stripped = stripped.Substring("www.".Length); } return stripped; } /// <summary> /// Marks up URL with the corresponding url bbcode and with a simplified link to display. /// </summary> private static string MarkUpUrlWithBbCode(string args) { var toShow = GetUrlDisplay(args); return "[url=" + args + "]" + toShow + "[/url]"; } /// <summary> /// If a given string starts with text valid for a link. /// </summary> private static bool StartsWithValidTerm(string text) { return ValidStartTerms.Any(text.StartsWith); } /// <summary> /// Auto-marks up links; a user expectation. /// </summary> private static string PreProcessBbCode(string text) { var exploded = text.Split(new[] {' ', '\n', '\r'}, StringSplitOptions.RemoveEmptyEntries); var valid = new List<string>(); for (var i = 0; i < exploded.Length; i++) { var current = exploded[i]; if (i != 0) { var last = exploded[i - 1]; if (last.EndsWith("[url=", StringComparison.Ordinal)) continue; if (last.EndsWith("url:")) continue; } if (StartsWithValidTerm(current)) valid.Add(current); } var matches = valid.Select(x => new Tuple<string, string>(x, MarkUpUrlWithBbCode(x))).Distinct(); return matches.Aggregate(text, (current, toReplace) => current.Replace(toReplace.Item1, toReplace.Item2)); } private Inline ToInline(ParsedChunk chunk) { var converters = new Dictionary<BbCodeType, Func<ParsedChunk, Inline>> { {BbCodeType.Bold, MakeBold}, {BbCodeType.Italic, MakeItalic}, {BbCodeType.Underline, MakeUnderline}, {BbCodeType.Url, MakeUrl}, {BbCodeType.None, MakeNormalText}, {BbCodeType.Color, MakeColor}, {BbCodeType.Strikethrough, MakeStrikeThrough}, {BbCodeType.Session, MakeSession}, {BbCodeType.Channel, MakeChannel}, {BbCodeType.Big, MakeBig}, {BbCodeType.Small, MakeSmall}, {BbCodeType.Subscript, MakeSubscript}, {BbCodeType.Superscript, MakeSuperscript}, {BbCodeType.User, MakeUser}, {BbCodeType.NoParse, MakeNormalText}, {BbCodeType.Icon, MakeIcon}, {BbCodeType.EIcon, MakeEIcon}, {BbCodeType.Collapse, MakeCollapse}, {BbCodeType.Quote, MakeQuote}, {BbCodeType.HorizontalRule, MakeHorizontalRule}, {BbCodeType.Indent, MakeIndentText}, {BbCodeType.Heading, MakeHeading}, {BbCodeType.Justify, MakeNormalText}, {BbCodeType.Right, MakeRightText}, {BbCodeType.Center, MakeCenterText}, {BbCodeType.Left, MakeBlockText} }; var converter = converters[chunk.Type]; Inline toReturn; try { toReturn = converter(chunk); } catch { toReturn = MakeNormalText(chunk); } var span = toReturn as Span; if (chunk.Children?.Any() ?? false) span?.Inlines.AddRange(chunk.Children.Select(ToInline)); return toReturn; } public static IList<ParsedChunk> ParseChunk(string input) { #region init // init var toReturn = new List<ParsedChunk>(); var openTags = new Stack<BbTag>(); var tags = new Queue<BbTag>(); var processedQueue = new Queue<BbTag>(); var finder = new BbFinder(input); // find all tags while (!finder.HasReachedEnd) { var next = finder.Next(); if (next != null) tags.Enqueue(next); } // return original input if we've no valid bbcode tags if (tags.All(x => x.Type == BbCodeType.None)) return new[] {AsChunk(input)}; #endregion while (tags.Count > 0) { // get the next tag to process var tag = tags.Dequeue(); var addToQueue = true; #region add as child of last tag // check if we're in the context of another open tag if (openTags.Count > 0) { var lastOpen = openTags.Peek(); var lastMatching = openTags.FirstOrDefault(x => tag.IsClosing && x.Type == tag.Type); // check if we're closing any previous tags if (lastMatching != null) { lastMatching.ClosingTag = tag; // keep going through our opened tag stack until we find the one // we're closing do { lastOpen = openTags.Pop(); // if we end up with a tag that isn't the one we're closing, // it must not have been closed correctly, e.g // [i] [b] [/i] // we'll treat that '[b]' as text if (lastOpen != lastMatching) lastOpen.Type = BbCodeType.None; } while (lastOpen != lastMatching); #region handle noparse if (lastMatching.Type == BbCodeType.NoParse) { lastMatching.Children = lastMatching.Children ?? new List<BbTag>(); lastMatching.Children.Add(new BbTag { Type = BbCodeType.None, End = tag.Start, Start = lastMatching.End }); } #endregion } else { if (openTags.All(x => x.Type != BbCodeType.NoParse)) { // if not, we have to be a child of it lastOpen.Children = lastOpen.Children ?? new List<BbTag>(); lastOpen.Children.Add(tag); } // any matching closing tags would be caught in the if part of this // branch, this is an invalid tag, treat as text if (tag.IsClosing) tag.Type = BbCodeType.None; addToQueue = false; } } #endregion // we don't need to continue processing closing tags if (tag.IsClosing) continue; // tell the system we're in the context of this tag now // though ignore children of 'text' and 'hr' if (tag.Type != BbCodeType.None && tag.Type != BbCodeType.HorizontalRule) openTags.Push(tag); // if we're added as a child to another tag, don't process independently of parent if (addToQueue) processedQueue.Enqueue(tag); } // these tags haven't been closed, so treat them as invalid foreach (var openTag in openTags) openTag.Type = BbCodeType.None; // if we have no bbcode present, just return the text as-is if (processedQueue.All(x => x.Type == BbCodeType.None && x.Children == null)) return new[] {AsChunk(input)}; toReturn.AddRange(processedQueue.Select(x => FromTag(x, input))); return toReturn; } internal static ParsedChunk AsChunk(string input) { return new ParsedChunk { Type = BbCodeType.None, Start = 0, End = input.Length, InnerText = input }; } public Inline AsInline(string bbcode) { var inlines = ParseChunk(bbcode).Select(ToInline).ToList(); if (inlines.Count == 1) return inlines.First(); var toReturn = new Span(); toReturn.Inlines.AddRange(inlines); return toReturn; } internal static ParsedChunk FromTag(BbTag tag, string context) { var last = tag.ClosingTag?.End ?? tag.End; var toReturn = new ParsedChunk { Start = tag.Start, End = last, Type = tag.Type, Arguments = tag.Arguments }; if (tag.Children != null && tag.Children.Any()) toReturn.Children = tag.Children.Select(x => FromTag(x, context)).ToList(); if (tag.Type == BbCodeType.None) toReturn.InnerText = context.Substring(tag.Start, tag.End - tag.Start); return toReturn; } #region BBCode implementations private Inline MakeUser(ParsedChunk arg) { if (arg.Children != null && arg.Children.Any()) { var user = MakeUsernameLink(characters.Find(arg.Children.First().InnerText)); arg.Children.Clear(); return user; } return !string.IsNullOrEmpty(arg.Arguments) ? MakeUsernameLink(characters.Find(arg.Arguments)) : MakeNormalText(arg); } private Inline MakeIcon(ParsedChunk arg) { if (!ApplicationSettings.AllowIcons) return MakeUser(arg); if (arg.Children != null && arg.Children.Any()) { var characterName = arg.Children.First().InnerText; var character = characters.Find(characterName); var icon = MakeIcon(character); arg.Children.Clear(); return icon; } return !string.IsNullOrEmpty(arg.Arguments) ? MakeIcon(characters.Find(arg.Arguments)) : MakeNormalText(arg); } private Inline MakeEIcon(ParsedChunk arg) { if (!ApplicationSettings.AllowIcons) return new Span(); if (arg.Children != null && arg.Children.Any()) { var target = arg.Children.First().InnerText; var icon = MakeEIcon(target); arg.Children.Clear(); return icon; } return !string.IsNullOrEmpty(arg.Arguments) ? MakeIcon(characters.Find(arg.Arguments)) : MakeNormalText(arg); } private Inline MakeSuperscript(ParsedChunk arg) { var small = MakeSmall(arg); small.BaselineAlignment = BaselineAlignment.TextTop; return small; } private Inline MakeSubscript(ParsedChunk arg) { var small = MakeSmall(arg); small.BaselineAlignment = BaselineAlignment.Subscript; return small; } private Inline MakeSmall(ParsedChunk arg) { var toReturn = new Span(WrapInRun(arg.InnerText)); toReturn.FontSize = ApplicationSettings.FontSize * 0.75; return toReturn; } private Inline MakeBig(ParsedChunk arg) { var toReturn = new Span(WrapInRun(arg.InnerText)); toReturn.FontSize = ApplicationSettings.FontSize * 1.5; return toReturn; } private Inline MakeChannel(ParsedChunk arg) { if (arg.Children != null && arg.Children.Any()) { var channel = MakeChannelLink(ChatModel.FindChannel(arg.Children.First().InnerText)); arg.Children.Clear(); return channel; } return !string.IsNullOrEmpty(arg.Arguments) ? MakeChannelLink(ChatModel.FindChannel(arg.Arguments)) : MakeNormalText(arg); } private Span MakeStrikeThrough(ParsedChunk arg) { return new Span(WrapInRun(arg.InnerText)) {TextDecorations = TextDecorations.Strikethrough}; } private static Span MakeNormalText(ParsedChunk arg) { return new Span(WrapInRun(arg.InnerText)); } private static Run WrapInRun(string text) { return new Run(text); } private Span MakeUrl(ParsedChunk arg) { if (arg.Arguments == null && arg.Children == null) return MakeNormalText(arg); var url = arg.Arguments; var display = arg.Children != null ? arg.Children.First().InnerText : GetUrlDisplay(arg.Arguments); if (url == null) { url = arg.InnerText; display = arg.Children != null ? GetUrlDisplay(arg.Children.First().InnerText) : string.Empty; } if (url == null && arg.Children != null) { url = arg.Children.First().InnerText; } arg.Children?.Clear(); var contextMenu = new ContextMenu(); var menuItemCopyLink = new MenuItem { CommandParameter = url, Style = Locator.FindStyle("MenuItemCopy") }; contextMenu.Items.Add(menuItemCopyLink); return new Hyperlink(WrapInRun(display)) { CommandParameter = url, ToolTip = url, ContextMenu = contextMenu, Style = Locator.FindStyle("Hyperlink") }; } private Inline MakeSession(ParsedChunk arg) { if (arg.Children == null || !arg.Children.Any() || string.IsNullOrEmpty(arg.Arguments)) return MakeNormalText(arg); var channel = MakeChannelLink(ChatModel.FindChannel(arg.Children.First().InnerText, arg.Arguments)); arg.Children.Clear(); return channel; } private static Span MakeUnderline(ParsedChunk arg) { return new Underline(WrapInRun(arg.InnerText)); } private static Span MakeBold(ParsedChunk arg) { return new Bold(WrapInRun(arg.InnerText)); } private static Span MakeItalic(ParsedChunk arg) { return new Italic(WrapInRun(arg.InnerText)); } private Span MakeColor(ParsedChunk arg) { var colorString = arg.Arguments; if (!ApplicationSettings.AllowColors || colorString == null) return MakeNormalText(arg); try { var brush = new BrushConverter().ConvertFromString(colorString) as SolidColorBrush; return brush == null ? new Span() : new Span {Foreground = brush}; } catch (FormatException) { } return new Span(); } private Inline MakeCollapse(ParsedChunk arg) { var title = arg.Arguments; var container = new InlineUIContainer(); var panel = new StackPanel(); var expander = new Expander { Header = title, Margin = new Thickness(0), Padding = new Thickness(0) }; var text = new TextBlock { Foreground = Locator.Find<SolidColorBrush>("ForegroundBrush"), TextWrapping = TextWrapping.Wrap, Margin = new Thickness(25, 0, 0, 0) }; TextBlockHelper.SetInlineList(text, arg.Children.Select(ToInline).ToList()); expander.Content = text; panel.Children.Add(expander); panel.Children.Add(new Line { Stretch = Stretch.Fill, X2 = 1, Stroke = new SolidColorBrush(Colors.Transparent) }); container.Child = panel; arg.Children.Clear(); return container; } private Inline MakeQuote(ParsedChunk arg) { var container = new InlineUIContainer(); var text = new TextBlock { Foreground = Locator.Find<SolidColorBrush>("ForegroundBrush"), Opacity = 0.8, Margin = new Thickness(50, 5, 0, 5), TextWrapping = TextWrapping.Wrap }; TextBlockHelper.SetInlineList(text, arg.Children.Select(ToInline).ToList()); container.Child = text; arg.Children.Clear(); return container; } private Inline MakeHorizontalRule(ParsedChunk arg) { return new InlineUIContainer(new Line { Stretch = Stretch.Fill, X2 = 1, Margin = new Thickness(0, 5, 0, 5), Stroke = Locator.Find<SolidColorBrush>("HighlightBrush") }); } private Span MakeHeading(ParsedChunk arg) { var toReturn = new Span { Foreground = Locator.Find<SolidColorBrush>("ContrastBrush") }; toReturn.FontSize *= 2; SpanHelper.SetInlineSource(toReturn, arg.Children.Select(ToInline).ToList()); toReturn.Inlines.Add(new Line { Stretch = Stretch.Fill, X2 = 1, Stroke = new SolidColorBrush(Colors.Transparent) }); arg.Children.Clear(); return toReturn; } private Inline MakeBlockText(ParsedChunk arg) { return MakeBlockWithAlignment(arg, TextAlignment.Left, new Thickness(0)); } private Inline MakeIndentText(ParsedChunk arg) { return MakeBlockWithAlignment(arg, TextAlignment.Left, new Thickness(ApplicationSettings.AllowIndent ? 15 : 0, 0, 0, 0)); } private Inline MakeBlockWithAlignment(ParsedChunk arg, TextAlignment alignment, Thickness thickness) { if (arg.Children == null || !arg.Children.Any()) return MakeNormalText(arg); var container = new InlineUIContainer(); var panel = new StackPanel(); var text = new TextBlock { Foreground = Locator.Find<SolidColorBrush>("ForegroundBrush"), Margin = thickness, TextWrapping = TextWrapping.Wrap, TextAlignment = alignment }; TextBlockHelper.SetInlineList(text, arg.Children.Select(ToInline).ToList()); panel.Children.Add(text); panel.Children.Add(new Line { Stretch = Stretch.Fill, X2 = 1, Stroke = new SolidColorBrush(Colors.Transparent) }); container.Child = panel; arg.Children.Clear(); return container; } private Inline MakeRightText(ParsedChunk arg) { return ApplicationSettings.AllowAlignment ? MakeBlockWithAlignment(arg, TextAlignment.Right, new Thickness(0)) : MakeNormalText(arg); } private Inline MakeCenterText(ParsedChunk arg) { var padding = ApplicationSettings.AllowIndent ? 15 : 0; return ApplicationSettings.AllowAlignment ? MakeBlockWithAlignment(arg, TextAlignment.Center, new Thickness(padding, 0, padding, 0)) : MakeNormalText(arg); } #endregion public class BbFinder { private const int NotFound = -1; private readonly string input; private string arguments; private int currentPosition; private int lastStart; public BbFinder(string input) { this.input = input; } public BbTag Last { get; private set; } public bool HasReachedEnd { get; private set; } private BbTag ReturnAsTextBetween(int start, int end) { if (end - start <= 1) end = start + 2; var toReturn = new BbTag { Type = BbCodeType.None, Start = start, End = end - 1 }; var rewindTo = Last?.End ?? 0; currentPosition = rewindTo; Last = toReturn; return toReturn; } public BbTag Next() { if (HasReachedEnd) return NoResult(); var openBrace = input.IndexOf('[', currentPosition); var closeBrace = input.IndexOf(']', currentPosition); currentPosition = closeBrace + 1; lastStart = openBrace + 1; if (openBrace == NotFound || closeBrace == NotFound) { HasReachedEnd = true; var start = Last?.End ?? 0; var end = input.Length; if (end - start > 0) { return new BbTag { Type = BbCodeType.None, Start = start, End = end }; } return null; } if (Last == null && openBrace > 0) return ReturnAsTextBetween(0, lastStart); if (Last != null && lastStart - Last.End > 1) return ReturnAsTextBetween(Last.End, lastStart); if (closeBrace < openBrace) return ReturnAsTextBetween(closeBrace, openBrace); arguments = null; var type = input.Substring(openBrace + 1, closeBrace - openBrace - 1); var equalsSign = type.IndexOf('='); if (equalsSign != NotFound) { var typeBeforeEquals = type.Substring(0, equalsSign); arguments = type.Substring(equalsSign + 1, type.Length - equalsSign - 1).Trim(); type = typeBeforeEquals.Trim(); } var isEndType = false; if (type.Length > 1) { isEndType = type[0].Equals('/'); type = isEndType ? type.Substring(1) : type; } var possibleMatch = Types.Keys.FirstOrDefault(x => x.Equals(type, StringComparison.Ordinal)); if (possibleMatch == null) return NoResult(); Last = new BbTag { Arguments = arguments, End = currentPosition, Start = openBrace, Type = Types[possibleMatch], IsClosing = isEndType }; return Last; } private BbTag NoResult() { var toReturn = new BbTag { Start = lastStart - 1, End = currentPosition, Type = BbCodeType.None }; Last = toReturn; return toReturn; } } public class BbTag { public BbCodeType Type { get; set; } public int Start { get; set; } public int End { get; set; } public string Arguments { get; set; } public bool IsClosing { get; set; } public BbTag ClosingTag { get; set; } public IList<BbTag> Children { get; set; } public BbTag Parent { get; set; } } public class ParsedChunk { public int Start { get; set; } public int End { get; set; } public string InnerText { get; set; } public string Arguments { get; set; } public BbCodeType Type { get; set; } public IList<ParsedChunk> Children { get; set; } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.CommandLine; using Microsoft.Extensions.Configuration.EnvironmentVariables; using Newtonsoft.Json.Linq; using OrchardCore.Environment.Shell.Configuration; using OrchardCore.Environment.Shell.Models; namespace OrchardCore.Environment.Shell { public class ShellSettingsManager : IShellSettingsManager { private readonly IConfiguration _applicationConfiguration; private readonly IShellsConfigurationSources _tenantsConfigSources; private readonly IShellConfigurationSources _tenantConfigSources; private readonly IShellsSettingsSources _settingsSources; private IConfiguration _configuration; private IEnumerable<string> _configuredTenants; private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1); private Func<string, Task<IConfigurationBuilder>> _tenantConfigBuilderFactory; private readonly SemaphoreSlim _tenantConfigSemaphore = new SemaphoreSlim(1); public ShellSettingsManager( IConfiguration applicationConfiguration, IShellsConfigurationSources tenantsConfigSources, IShellConfigurationSources tenantConfigSources, IShellsSettingsSources settingsSources) { _applicationConfiguration = applicationConfiguration; _tenantsConfigSources = tenantsConfigSources; _tenantConfigSources = tenantConfigSources; _settingsSources = settingsSources; } public ShellSettings CreateDefaultSettings() { return new ShellSettings ( new ShellConfiguration(_configuration), new ShellConfiguration(_configuration) ); } public async Task<IEnumerable<ShellSettings>> LoadSettingsAsync() { await _semaphore.WaitAsync(); try { await EnsureConfigurationAsync(); var tenantsSettings = (await new ConfigurationBuilder() .AddSourcesAsync(_settingsSources)) .Build(); var tenants = tenantsSettings.GetChildren().Select(section => section.Key); var allTenants = _configuredTenants.Concat(tenants).Distinct().ToArray(); var allSettings = new List<ShellSettings>(); foreach (var tenant in allTenants) { var tenantSettings = new ConfigurationBuilder() .AddConfiguration(_configuration) .AddConfiguration(_configuration.GetSection(tenant)) .AddConfiguration(tenantsSettings.GetSection(tenant)) .Build(); var settings = new ShellConfiguration(tenantSettings); var configuration = new ShellConfiguration(tenant, _tenantConfigBuilderFactory); var shellSettings = new ShellSettings(settings, configuration) { Name = tenant, }; allSettings.Add(shellSettings); }; return allSettings; } finally { _semaphore.Release(); } } public async Task<IEnumerable<string>> LoadSettingsNamesAsync() { await _semaphore.WaitAsync(); try { await EnsureConfigurationAsync(); var tenantsSettings = (await new ConfigurationBuilder() .AddSourcesAsync(_settingsSources)) .Build(); var tenants = tenantsSettings.GetChildren().Select(section => section.Key); return _configuredTenants.Concat(tenants).Distinct().ToArray(); } finally { _semaphore.Release(); } } public async Task<ShellSettings> LoadSettingsAsync(string tenant) { await _semaphore.WaitAsync(); try { await EnsureConfigurationAsync(); var tenantsSettings = (await new ConfigurationBuilder() .AddSourcesAsync(_settingsSources)) .Build(); var tenantSettings = new ConfigurationBuilder() .AddConfiguration(_configuration) .AddConfiguration(_configuration.GetSection(tenant)) .AddConfiguration(tenantsSettings.GetSection(tenant)) .Build(); var settings = new ShellConfiguration(tenantSettings); var configuration = new ShellConfiguration(tenant, _tenantConfigBuilderFactory); return new ShellSettings(settings, configuration) { Name = tenant, }; } finally { _semaphore.Release(); } } public async Task SaveSettingsAsync(ShellSettings settings) { await _semaphore.WaitAsync(); try { await EnsureConfigurationAsync(); if (settings == null) { throw new ArgumentNullException(nameof(settings)); } var configuration = new ConfigurationBuilder() .AddConfiguration(_configuration) .AddConfiguration(_configuration.GetSection(settings.Name)) .Build(); var shellSettings = new ShellSettings() { Name = settings.Name }; configuration.Bind(shellSettings); var configSettings = JObject.FromObject(shellSettings); var tenantSettings = JObject.FromObject(settings); foreach (var property in configSettings) { var tenantValue = tenantSettings.Value<string>(property.Key); var configValue = configSettings.Value<string>(property.Key); if (tenantValue != configValue) { tenantSettings[property.Key] = tenantValue; } else { tenantSettings[property.Key] = null; } } tenantSettings.Remove("Name"); await _settingsSources.SaveAsync(settings.Name, tenantSettings.ToObject<Dictionary<string, string>>()); var tenantConfig = new JObject(); var sections = settings.ShellConfiguration.GetChildren() .Where(s => !s.GetChildren().Any()) .ToArray(); foreach (var section in sections) { if (settings[section.Key] != configuration[section.Key]) { tenantConfig[section.Key] = settings[section.Key]; } else { tenantConfig[section.Key] = null; } } tenantConfig.Remove("Name"); await _tenantConfigSemaphore.WaitAsync(); try { await _tenantConfigSources.SaveAsync(settings.Name, tenantConfig.ToObject<Dictionary<string, string>>()); } finally { _tenantConfigSemaphore.Release(); } } finally { _semaphore.Release(); } } private async Task EnsureConfigurationAsync() { if (_configuration != null) { return; } var lastProviders = (_applicationConfiguration as IConfigurationRoot)?.Providers .Where(p => p is EnvironmentVariablesConfigurationProvider || p is CommandLineConfigurationProvider) .ToArray(); var configurationBuilder = await new ConfigurationBuilder() .AddConfiguration(_applicationConfiguration) .AddSourcesAsync(_tenantsConfigSources); if (lastProviders.Count() > 0) { configurationBuilder.AddConfiguration(new ConfigurationRoot(lastProviders)); } var configuration = configurationBuilder.Build().GetSection("OrchardCore"); _configuredTenants = configuration.GetChildren() .Where(section => Enum.TryParse<TenantState>(section["State"], ignoreCase: true, out _)) .Select(section => section.Key) .Distinct() .ToArray(); _tenantConfigBuilderFactory = async (tenant) => { await _tenantConfigSemaphore.WaitAsync(); try { var builder = new ConfigurationBuilder().AddConfiguration(_configuration); builder.AddConfiguration(configuration.GetSection(tenant)); return await builder.AddSourcesAsync(tenant, _tenantConfigSources); } finally { _tenantConfigSemaphore.Release(); } }; _configuration = configuration; } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Projection // Description: The basic module for MapWindow version 6.0 // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 8/14/2009 5:08:05 PM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // Name | Date | Comment // --------------------|------------|------------------------------------------------------------ // Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL // ******************************************************************************************************** #pragma warning disable 1591 namespace DotSpatial.Projections.ProjectedCategories { /// <summary> /// UtmNad1983 /// </summary> public class UtmNad1983 : CoordinateSystemCategory { #region Private Variables public readonly ProjectionInfo NAD1983UTMZone10N; public readonly ProjectionInfo NAD1983UTMZone10S; public readonly ProjectionInfo NAD1983UTMZone11N; public readonly ProjectionInfo NAD1983UTMZone11S; public readonly ProjectionInfo NAD1983UTMZone12N; public readonly ProjectionInfo NAD1983UTMZone12S; public readonly ProjectionInfo NAD1983UTMZone13N; public readonly ProjectionInfo NAD1983UTMZone13S; public readonly ProjectionInfo NAD1983UTMZone14N; public readonly ProjectionInfo NAD1983UTMZone14S; public readonly ProjectionInfo NAD1983UTMZone15N; public readonly ProjectionInfo NAD1983UTMZone15S; public readonly ProjectionInfo NAD1983UTMZone16N; public readonly ProjectionInfo NAD1983UTMZone16S; public readonly ProjectionInfo NAD1983UTMZone17N; public readonly ProjectionInfo NAD1983UTMZone17S; public readonly ProjectionInfo NAD1983UTMZone18N; public readonly ProjectionInfo NAD1983UTMZone18S; public readonly ProjectionInfo NAD1983UTMZone19N; public readonly ProjectionInfo NAD1983UTMZone19S; public readonly ProjectionInfo NAD1983UTMZone1N; public readonly ProjectionInfo NAD1983UTMZone1S; public readonly ProjectionInfo NAD1983UTMZone20N; public readonly ProjectionInfo NAD1983UTMZone20S; public readonly ProjectionInfo NAD1983UTMZone21N; public readonly ProjectionInfo NAD1983UTMZone21S; public readonly ProjectionInfo NAD1983UTMZone22N; public readonly ProjectionInfo NAD1983UTMZone22S; public readonly ProjectionInfo NAD1983UTMZone23N; public readonly ProjectionInfo NAD1983UTMZone23S; public readonly ProjectionInfo NAD1983UTMZone24N; public readonly ProjectionInfo NAD1983UTMZone24S; public readonly ProjectionInfo NAD1983UTMZone25N; public readonly ProjectionInfo NAD1983UTMZone25S; public readonly ProjectionInfo NAD1983UTMZone26N; public readonly ProjectionInfo NAD1983UTMZone26S; public readonly ProjectionInfo NAD1983UTMZone27N; public readonly ProjectionInfo NAD1983UTMZone27S; public readonly ProjectionInfo NAD1983UTMZone28N; public readonly ProjectionInfo NAD1983UTMZone28S; public readonly ProjectionInfo NAD1983UTMZone29N; public readonly ProjectionInfo NAD1983UTMZone29S; public readonly ProjectionInfo NAD1983UTMZone2N; public readonly ProjectionInfo NAD1983UTMZone2S; public readonly ProjectionInfo NAD1983UTMZone30N; public readonly ProjectionInfo NAD1983UTMZone30S; public readonly ProjectionInfo NAD1983UTMZone31N; public readonly ProjectionInfo NAD1983UTMZone31S; public readonly ProjectionInfo NAD1983UTMZone32N; public readonly ProjectionInfo NAD1983UTMZone32S; public readonly ProjectionInfo NAD1983UTMZone33N; public readonly ProjectionInfo NAD1983UTMZone33S; public readonly ProjectionInfo NAD1983UTMZone34N; public readonly ProjectionInfo NAD1983UTMZone34S; public readonly ProjectionInfo NAD1983UTMZone35N; public readonly ProjectionInfo NAD1983UTMZone35S; public readonly ProjectionInfo NAD1983UTMZone36N; public readonly ProjectionInfo NAD1983UTMZone36S; public readonly ProjectionInfo NAD1983UTMZone37N; public readonly ProjectionInfo NAD1983UTMZone37S; public readonly ProjectionInfo NAD1983UTMZone38N; public readonly ProjectionInfo NAD1983UTMZone38S; public readonly ProjectionInfo NAD1983UTMZone39N; public readonly ProjectionInfo NAD1983UTMZone39S; public readonly ProjectionInfo NAD1983UTMZone3N; public readonly ProjectionInfo NAD1983UTMZone3S; public readonly ProjectionInfo NAD1983UTMZone40N; public readonly ProjectionInfo NAD1983UTMZone40S; public readonly ProjectionInfo NAD1983UTMZone41N; public readonly ProjectionInfo NAD1983UTMZone41S; public readonly ProjectionInfo NAD1983UTMZone42N; public readonly ProjectionInfo NAD1983UTMZone42S; public readonly ProjectionInfo NAD1983UTMZone43N; public readonly ProjectionInfo NAD1983UTMZone43S; public readonly ProjectionInfo NAD1983UTMZone44N; public readonly ProjectionInfo NAD1983UTMZone44S; public readonly ProjectionInfo NAD1983UTMZone45N; public readonly ProjectionInfo NAD1983UTMZone45S; public readonly ProjectionInfo NAD1983UTMZone46N; public readonly ProjectionInfo NAD1983UTMZone46S; public readonly ProjectionInfo NAD1983UTMZone47N; public readonly ProjectionInfo NAD1983UTMZone47S; public readonly ProjectionInfo NAD1983UTMZone48N; public readonly ProjectionInfo NAD1983UTMZone48S; public readonly ProjectionInfo NAD1983UTMZone49N; public readonly ProjectionInfo NAD1983UTMZone49S; public readonly ProjectionInfo NAD1983UTMZone4N; public readonly ProjectionInfo NAD1983UTMZone4S; public readonly ProjectionInfo NAD1983UTMZone50N; public readonly ProjectionInfo NAD1983UTMZone50S; public readonly ProjectionInfo NAD1983UTMZone51N; public readonly ProjectionInfo NAD1983UTMZone51S; public readonly ProjectionInfo NAD1983UTMZone52N; public readonly ProjectionInfo NAD1983UTMZone52S; public readonly ProjectionInfo NAD1983UTMZone53N; public readonly ProjectionInfo NAD1983UTMZone53S; public readonly ProjectionInfo NAD1983UTMZone54N; public readonly ProjectionInfo NAD1983UTMZone54S; public readonly ProjectionInfo NAD1983UTMZone55N; public readonly ProjectionInfo NAD1983UTMZone55S; public readonly ProjectionInfo NAD1983UTMZone56N; public readonly ProjectionInfo NAD1983UTMZone56S; public readonly ProjectionInfo NAD1983UTMZone57N; public readonly ProjectionInfo NAD1983UTMZone57S; public readonly ProjectionInfo NAD1983UTMZone58N; public readonly ProjectionInfo NAD1983UTMZone58S; public readonly ProjectionInfo NAD1983UTMZone59N; public readonly ProjectionInfo NAD1983UTMZone59S; public readonly ProjectionInfo NAD1983UTMZone5N; public readonly ProjectionInfo NAD1983UTMZone5S; public readonly ProjectionInfo NAD1983UTMZone60N; public readonly ProjectionInfo NAD1983UTMZone60S; public readonly ProjectionInfo NAD1983UTMZone6N; public readonly ProjectionInfo NAD1983UTMZone6S; public readonly ProjectionInfo NAD1983UTMZone7N; public readonly ProjectionInfo NAD1983UTMZone7S; public readonly ProjectionInfo NAD1983UTMZone8N; public readonly ProjectionInfo NAD1983UTMZone8S; public readonly ProjectionInfo NAD1983UTMZone9N; public readonly ProjectionInfo NAD1983UTMZone9S; #endregion #region Constructors /// <summary> /// Creates a new instance of UtmNad1983 /// </summary> public UtmNad1983() { NAD1983UTMZone1N = ProjectionInfo.FromProj4String("+proj=utm +zone=1 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone2N = ProjectionInfo.FromProj4String("+proj=utm +zone=2 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone3N = ProjectionInfo.FromProj4String("+proj=utm +zone=3 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone4N = ProjectionInfo.FromProj4String("+proj=utm +zone=4 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone5N = ProjectionInfo.FromProj4String("+proj=utm +zone=5 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone6N = ProjectionInfo.FromProj4String("+proj=utm +zone=6 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone7N = ProjectionInfo.FromProj4String("+proj=utm +zone=7 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone8N = ProjectionInfo.FromProj4String("+proj=utm +zone=8 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone9N = ProjectionInfo.FromProj4String("+proj=utm +zone=9 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone10N = ProjectionInfo.FromProj4String("+proj=utm +zone=10 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone11N = ProjectionInfo.FromProj4String("+proj=utm +zone=11 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone12N = ProjectionInfo.FromProj4String("+proj=utm +zone=12 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone13N = ProjectionInfo.FromProj4String("+proj=utm +zone=13 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone14N = ProjectionInfo.FromProj4String("+proj=utm +zone=14 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone15N = ProjectionInfo.FromProj4String("+proj=utm +zone=15 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone16N = ProjectionInfo.FromProj4String("+proj=utm +zone=16 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone17N = ProjectionInfo.FromProj4String("+proj=utm +zone=17 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone18N = ProjectionInfo.FromProj4String("+proj=utm +zone=18 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone19N = ProjectionInfo.FromProj4String("+proj=utm +zone=19 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone20N = ProjectionInfo.FromProj4String("+proj=utm +zone=20 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone21N = ProjectionInfo.FromProj4String("+proj=utm +zone=21 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone22N = ProjectionInfo.FromProj4String("+proj=utm +zone=22 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone23N = ProjectionInfo.FromProj4String("+proj=utm +zone=23 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone24N = ProjectionInfo.FromProj4String("+proj=utm +zone=24 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone25N = ProjectionInfo.FromProj4String("+proj=utm +zone=25 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone26N = ProjectionInfo.FromProj4String("+proj=utm +zone=26 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone27N = ProjectionInfo.FromProj4String("+proj=utm +zone=27 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone28N = ProjectionInfo.FromProj4String("+proj=utm +zone=28 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone29N = ProjectionInfo.FromProj4String("+proj=utm +zone=29 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone30N = ProjectionInfo.FromProj4String("+proj=utm +zone=30 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone31N = ProjectionInfo.FromProj4String("+proj=utm +zone=31 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone32N = ProjectionInfo.FromProj4String("+proj=utm +zone=32 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone33N = ProjectionInfo.FromProj4String("+proj=utm +zone=33 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone34N = ProjectionInfo.FromProj4String("+proj=utm +zone=34 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone35N = ProjectionInfo.FromProj4String("+proj=utm +zone=35 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone36N = ProjectionInfo.FromProj4String("+proj=utm +zone=36 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone37N = ProjectionInfo.FromProj4String("+proj=utm +zone=37 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone38N = ProjectionInfo.FromProj4String("+proj=utm +zone=38 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone39N = ProjectionInfo.FromProj4String("+proj=utm +zone=39 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone40N = ProjectionInfo.FromProj4String("+proj=utm +zone=40 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone41N = ProjectionInfo.FromProj4String("+proj=utm +zone=41 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone42N = ProjectionInfo.FromProj4String("+proj=utm +zone=42 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone43N = ProjectionInfo.FromProj4String("+proj=utm +zone=43 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone44N = ProjectionInfo.FromProj4String("+proj=utm +zone=44 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone45N = ProjectionInfo.FromProj4String("+proj=utm +zone=45 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone46N = ProjectionInfo.FromProj4String("+proj=utm +zone=46 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone47N = ProjectionInfo.FromProj4String("+proj=utm +zone=47 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone48N = ProjectionInfo.FromProj4String("+proj=utm +zone=48 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone49N = ProjectionInfo.FromProj4String("+proj=utm +zone=49 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone50N = ProjectionInfo.FromProj4String("+proj=utm +zone=50 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone51N = ProjectionInfo.FromProj4String("+proj=utm +zone=51 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone52N = ProjectionInfo.FromProj4String("+proj=utm +zone=52 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone53N = ProjectionInfo.FromProj4String("+proj=utm +zone=53 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone54N = ProjectionInfo.FromProj4String("+proj=utm +zone=54 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone55N = ProjectionInfo.FromProj4String("+proj=utm +zone=55 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone56N = ProjectionInfo.FromProj4String("+proj=utm +zone=56 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone57N = ProjectionInfo.FromProj4String("+proj=utm +zone=57 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone58N = ProjectionInfo.FromProj4String("+proj=utm +zone=58 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone59N = ProjectionInfo.FromProj4String("+proj=utm +zone=59 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone60N = ProjectionInfo.FromProj4String("+proj=utm +zone=60 +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone1S = ProjectionInfo.FromProj4String("+proj=utm +zone=1 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone2S = ProjectionInfo.FromProj4String("+proj=utm +zone=2 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone3S = ProjectionInfo.FromProj4String("+proj=utm +zone=3 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone4S = ProjectionInfo.FromProj4String("+proj=utm +zone=4 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone5S = ProjectionInfo.FromProj4String("+proj=utm +zone=5 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone6S = ProjectionInfo.FromProj4String("+proj=utm +zone=6 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone7S = ProjectionInfo.FromProj4String("+proj=utm +zone=7 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone8S = ProjectionInfo.FromProj4String("+proj=utm +zone=8 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone9S = ProjectionInfo.FromProj4String("+proj=utm +zone=9 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone10S = ProjectionInfo.FromProj4String("+proj=utm +zone=10 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone11S = ProjectionInfo.FromProj4String("+proj=utm +zone=11 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone12S = ProjectionInfo.FromProj4String("+proj=utm +zone=12 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone13S = ProjectionInfo.FromProj4String("+proj=utm +zone=13 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone14S = ProjectionInfo.FromProj4String("+proj=utm +zone=14 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone15S = ProjectionInfo.FromProj4String("+proj=utm +zone=15 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone16S = ProjectionInfo.FromProj4String("+proj=utm +zone=16 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone17S = ProjectionInfo.FromProj4String("+proj=utm +zone=17 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone18S = ProjectionInfo.FromProj4String("+proj=utm +zone=18 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone19S = ProjectionInfo.FromProj4String("+proj=utm +zone=19 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone20S = ProjectionInfo.FromProj4String("+proj=utm +zone=20 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone21S = ProjectionInfo.FromProj4String("+proj=utm +zone=21 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone22S = ProjectionInfo.FromProj4String("+proj=utm +zone=22 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone23S = ProjectionInfo.FromProj4String("+proj=utm +zone=23 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone24S = ProjectionInfo.FromProj4String("+proj=utm +zone=24 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone25S = ProjectionInfo.FromProj4String("+proj=utm +zone=25 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone26S = ProjectionInfo.FromProj4String("+proj=utm +zone=26 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone27S = ProjectionInfo.FromProj4String("+proj=utm +zone=27 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone28S = ProjectionInfo.FromProj4String("+proj=utm +zone=28 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone29S = ProjectionInfo.FromProj4String("+proj=utm +zone=29 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone30S = ProjectionInfo.FromProj4String("+proj=utm +zone=30 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone31S = ProjectionInfo.FromProj4String("+proj=utm +zone=31 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone32S = ProjectionInfo.FromProj4String("+proj=utm +zone=32 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone33S = ProjectionInfo.FromProj4String("+proj=utm +zone=33 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone34S = ProjectionInfo.FromProj4String("+proj=utm +zone=34 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone35S = ProjectionInfo.FromProj4String("+proj=utm +zone=35 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone36S = ProjectionInfo.FromProj4String("+proj=utm +zone=36 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone37S = ProjectionInfo.FromProj4String("+proj=utm +zone=37 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone38S = ProjectionInfo.FromProj4String("+proj=utm +zone=38 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone39S = ProjectionInfo.FromProj4String("+proj=utm +zone=39 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone40S = ProjectionInfo.FromProj4String("+proj=utm +zone=40 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone41S = ProjectionInfo.FromProj4String("+proj=utm +zone=41 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone42S = ProjectionInfo.FromProj4String("+proj=utm +zone=42 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone43S = ProjectionInfo.FromProj4String("+proj=utm +zone=43 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone44S = ProjectionInfo.FromProj4String("+proj=utm +zone=44 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone45S = ProjectionInfo.FromProj4String("+proj=utm +zone=45 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone46S = ProjectionInfo.FromProj4String("+proj=utm +zone=46 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone47S = ProjectionInfo.FromProj4String("+proj=utm +zone=47 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone48S = ProjectionInfo.FromProj4String("+proj=utm +zone=48 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone49S = ProjectionInfo.FromProj4String("+proj=utm +zone=49 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone50S = ProjectionInfo.FromProj4String("+proj=utm +zone=50 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone51S = ProjectionInfo.FromProj4String("+proj=utm +zone=51 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone52S = ProjectionInfo.FromProj4String("+proj=utm +zone=52 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone53S = ProjectionInfo.FromProj4String("+proj=utm +zone=53 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone54S = ProjectionInfo.FromProj4String("+proj=utm +zone=54 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone55S = ProjectionInfo.FromProj4String("+proj=utm +zone=55 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone56S = ProjectionInfo.FromProj4String("+proj=utm +zone=56 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone57S = ProjectionInfo.FromProj4String("+proj=utm +zone=57 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone58S = ProjectionInfo.FromProj4String("+proj=utm +zone=58 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone59S = ProjectionInfo.FromProj4String("+proj=utm +zone=59 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone60S = ProjectionInfo.FromProj4String("+proj=utm +zone=60 +south +ellps=GRS80 +datum=NAD83 +units=m +no_defs "); NAD1983UTMZone1N.Name = "NAD_1983_UTM_Zone_1N"; NAD1983UTMZone2N.Name = "NAD_1983_UTM_Zone_2N"; NAD1983UTMZone3N.Name = "NAD_1983_UTM_Zone_3N"; NAD1983UTMZone4N.Name = "NAD_1983_UTM_Zone_4N"; NAD1983UTMZone5N.Name = "NAD_1983_UTM_Zone_5N"; NAD1983UTMZone6N.Name = "NAD_1983_UTM_Zone_6N"; NAD1983UTMZone7N.Name = "NAD_1983_UTM_Zone_7N"; NAD1983UTMZone8N.Name = "NAD_1983_UTM_Zone_8N"; NAD1983UTMZone9N.Name = "NAD_1983_UTM_Zone_9N"; NAD1983UTMZone10N.Name = "NAD_1983_UTM_Zone_10N"; NAD1983UTMZone11N.Name = "NAD_1983_UTM_Zone_11N"; NAD1983UTMZone12N.Name = "NAD_1983_UTM_Zone_12N"; NAD1983UTMZone13N.Name = "NAD_1983_UTM_Zone_13N"; NAD1983UTMZone14N.Name = "NAD_1983_UTM_Zone_14N"; NAD1983UTMZone15N.Name = "NAD_1983_UTM_Zone_15N"; NAD1983UTMZone16N.Name = "NAD_1983_UTM_Zone_16N"; NAD1983UTMZone17N.Name = "NAD_1983_UTM_Zone_17N"; NAD1983UTMZone18N.Name = "NAD_1983_UTM_Zone_18N"; NAD1983UTMZone19N.Name = "NAD_1983_UTM_Zone_19N"; NAD1983UTMZone20N.Name = "NAD_1983_UTM_Zone_20N"; NAD1983UTMZone21N.Name = "NAD_1983_UTM_Zone_21N"; NAD1983UTMZone22N.Name = "NAD_1983_UTM_Zone_22N"; NAD1983UTMZone23N.Name = "NAD_1983_UTM_Zone_23N"; NAD1983UTMZone24N.Name = "NAD_1983_UTM_Zone_24N"; NAD1983UTMZone25N.Name = "NAD_1983_UTM_Zone_25N"; NAD1983UTMZone26N.Name = "NAD_1983_UTM_Zone_26N"; NAD1983UTMZone27N.Name = "NAD_1983_UTM_Zone_27N"; NAD1983UTMZone28N.Name = "NAD_1983_UTM_Zone_28N"; NAD1983UTMZone29N.Name = "NAD_1983_UTM_Zone_29N"; NAD1983UTMZone30N.Name = "NAD_1983_UTM_Zone_30N"; NAD1983UTMZone31N.Name = "NAD_1983_UTM_Zone_31N"; NAD1983UTMZone32N.Name = "NAD_1983_UTM_Zone_32N"; NAD1983UTMZone33N.Name = "NAD_1983_UTM_Zone_33N"; NAD1983UTMZone34N.Name = "NAD_1983_UTM_Zone_34N"; NAD1983UTMZone35N.Name = "NAD_1983_UTM_Zone_35N"; NAD1983UTMZone36N.Name = "NAD_1983_UTM_Zone_36N"; NAD1983UTMZone37N.Name = "NAD_1983_UTM_Zone_37N"; NAD1983UTMZone38N.Name = "NAD_1983_UTM_Zone_38N"; NAD1983UTMZone39N.Name = "NAD_1983_UTM_Zone_39N"; NAD1983UTMZone40N.Name = "NAD_1983_UTM_Zone_40N"; NAD1983UTMZone41N.Name = "NAD_1983_UTM_Zone_41N"; NAD1983UTMZone42N.Name = "NAD_1983_UTM_Zone_42N"; NAD1983UTMZone43N.Name = "NAD_1983_UTM_Zone_43N"; NAD1983UTMZone44N.Name = "NAD_1983_UTM_Zone_44N"; NAD1983UTMZone45N.Name = "NAD_1983_UTM_Zone_45N"; NAD1983UTMZone46N.Name = "NAD_1983_UTM_Zone_46N"; NAD1983UTMZone47N.Name = "NAD_1983_UTM_Zone_47N"; NAD1983UTMZone48N.Name = "NAD_1983_UTM_Zone_48N"; NAD1983UTMZone49N.Name = "NAD_1983_UTM_Zone_49N"; NAD1983UTMZone50N.Name = "NAD_1983_UTM_Zone_50N"; NAD1983UTMZone51N.Name = "NAD_1983_UTM_Zone_51N"; NAD1983UTMZone52N.Name = "NAD_1983_UTM_Zone_52N"; NAD1983UTMZone53N.Name = "NAD_1983_UTM_Zone_53N"; NAD1983UTMZone54N.Name = "NAD_1983_UTM_Zone_54N"; NAD1983UTMZone55N.Name = "NAD_1983_UTM_Zone_55N"; NAD1983UTMZone56N.Name = "NAD_1983_UTM_Zone_56N"; NAD1983UTMZone57N.Name = "NAD_1983_UTM_Zone_57N"; NAD1983UTMZone58N.Name = "NAD_1983_UTM_Zone_58N"; NAD1983UTMZone59N.Name = "NAD_1983_UTM_Zone_59N"; NAD1983UTMZone60N.Name = "NAD_1983_UTM_Zone_60N"; NAD1983UTMZone1S.Name = "NAD_1983_UTM_Zone_1S"; NAD1983UTMZone2S.Name = "NAD_1983_UTM_Zone_2S"; NAD1983UTMZone3S.Name = "NAD_1983_UTM_Zone_3S"; NAD1983UTMZone4S.Name = "NAD_1983_UTM_Zone_4S"; NAD1983UTMZone5S.Name = "NAD_1983_UTM_Zone_5S"; NAD1983UTMZone6S.Name = "NAD_1983_UTM_Zone_6S"; NAD1983UTMZone7S.Name = "NAD_1983_UTM_Zone_7S"; NAD1983UTMZone8S.Name = "NAD_1983_UTM_Zone_8S"; NAD1983UTMZone9S.Name = "NAD_1983_UTM_Zone_9S"; NAD1983UTMZone10S.Name = "NAD_1983_UTM_Zone_10S"; NAD1983UTMZone11S.Name = "NAD_1983_UTM_Zone_11S"; NAD1983UTMZone12S.Name = "NAD_1983_UTM_Zone_12S"; NAD1983UTMZone13S.Name = "NAD_1983_UTM_Zone_13S"; NAD1983UTMZone14S.Name = "NAD_1983_UTM_Zone_14S"; NAD1983UTMZone15S.Name = "NAD_1983_UTM_Zone_15S"; NAD1983UTMZone16S.Name = "NAD_1983_UTM_Zone_16S"; NAD1983UTMZone17S.Name = "NAD_1983_UTM_Zone_17S"; NAD1983UTMZone18S.Name = "NAD_1983_UTM_Zone_18S"; NAD1983UTMZone19S.Name = "NAD_1983_UTM_Zone_19S"; NAD1983UTMZone20S.Name = "NAD_1983_UTM_Zone_20S"; NAD1983UTMZone21S.Name = "NAD_1983_UTM_Zone_21S"; NAD1983UTMZone22S.Name = "NAD_1983_UTM_Zone_22S"; NAD1983UTMZone23S.Name = "NAD_1983_UTM_Zone_23S"; NAD1983UTMZone24S.Name = "NAD_1983_UTM_Zone_24S"; NAD1983UTMZone25S.Name = "NAD_1983_UTM_Zone_25S"; NAD1983UTMZone26S.Name = "NAD_1983_UTM_Zone_26S"; NAD1983UTMZone27S.Name = "NAD_1983_UTM_Zone_27S"; NAD1983UTMZone28S.Name = "NAD_1983_UTM_Zone_28S"; NAD1983UTMZone29S.Name = "NAD_1983_UTM_Zone_29S"; NAD1983UTMZone30S.Name = "NAD_1983_UTM_Zone_30S"; NAD1983UTMZone31S.Name = "NAD_1983_UTM_Zone_31S"; NAD1983UTMZone32S.Name = "NAD_1983_UTM_Zone_32S"; NAD1983UTMZone33S.Name = "NAD_1983_UTM_Zone_33S"; NAD1983UTMZone34S.Name = "NAD_1983_UTM_Zone_34S"; NAD1983UTMZone35S.Name = "NAD_1983_UTM_Zone_35S"; NAD1983UTMZone36S.Name = "NAD_1983_UTM_Zone_36S"; NAD1983UTMZone37S.Name = "NAD_1983_UTM_Zone_37S"; NAD1983UTMZone38S.Name = "NAD_1983_UTM_Zone_38S"; NAD1983UTMZone39S.Name = "NAD_1983_UTM_Zone_39S"; NAD1983UTMZone40S.Name = "NAD_1983_UTM_Zone_40S"; NAD1983UTMZone41S.Name = "NAD_1983_UTM_Zone_41S"; NAD1983UTMZone42S.Name = "NAD_1983_UTM_Zone_42S"; NAD1983UTMZone43S.Name = "NAD_1983_UTM_Zone_43S"; NAD1983UTMZone44S.Name = "NAD_1983_UTM_Zone_44S"; NAD1983UTMZone45S.Name = "NAD_1983_UTM_Zone_45S"; NAD1983UTMZone46S.Name = "NAD_1983_UTM_Zone_46S"; NAD1983UTMZone47S.Name = "NAD_1983_UTM_Zone_47S"; NAD1983UTMZone48S.Name = "NAD_1983_UTM_Zone_48S"; NAD1983UTMZone49S.Name = "NAD_1983_UTM_Zone_49S"; NAD1983UTMZone50S.Name = "NAD_1983_UTM_Zone_50S"; NAD1983UTMZone51S.Name = "NAD_1983_UTM_Zone_51S"; NAD1983UTMZone52S.Name = "NAD_1983_UTM_Zone_52S"; NAD1983UTMZone53S.Name = "NAD_1983_UTM_Zone_53S"; NAD1983UTMZone54S.Name = "NAD_1983_UTM_Zone_54S"; NAD1983UTMZone55S.Name = "NAD_1983_UTM_Zone_55S"; NAD1983UTMZone56S.Name = "NAD_1983_UTM_Zone_56S"; NAD1983UTMZone57S.Name = "NAD_1983_UTM_Zone_57S"; NAD1983UTMZone58S.Name = "NAD_1983_UTM_Zone_58S"; NAD1983UTMZone59S.Name = "NAD_1983_UTM_Zone_59S"; NAD1983UTMZone60S.Name = "NAD_1983_UTM_Zone_60S"; NAD1983UTMZone1N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone2N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone3N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone4N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone5N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone6N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone7N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone8N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone9N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone10N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone11N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone12N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone13N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone14N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone15N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone16N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone17N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone18N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone19N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone20N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone21N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone22N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone23N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone24N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone25N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone26N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone27N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone28N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone29N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone30N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone31N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone32N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone33N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone34N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone35N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone36N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone37N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone38N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone39N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone40N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone41N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone42N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone43N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone44N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone45N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone46N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone47N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone48N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone49N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone50N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone51N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone52N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone53N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone54N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone55N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone56N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone57N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone58N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone59N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone60N.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone1S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone2S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone3S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone4S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone5S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone6S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone7S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone8S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone9S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone10S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone11S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone12S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone13S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone14S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone15S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone16S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone17S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone18S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone19S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone20S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone21S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone22S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone23S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone24S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone25S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone26S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone27S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone28S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone29S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone30S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone31S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone32S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone33S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone34S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone35S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone36S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone37S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone38S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone39S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone40S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone41S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone42S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone43S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone44S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone45S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone46S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone47S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone48S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone49S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone50S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone51S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone52S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone53S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone54S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone55S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone56S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone57S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone58S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone59S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone60S.GeographicInfo.Name = "GCS_North_American_1983"; NAD1983UTMZone1N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone2N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone3N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone4N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone5N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone6N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone7N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone8N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone9N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone10N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone11N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone12N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone13N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone14N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone15N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone16N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone17N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone18N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone19N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone20N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone21N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone22N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone23N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone24N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone25N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone26N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone27N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone28N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone29N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone30N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone31N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone32N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone33N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone34N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone35N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone36N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone37N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone38N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone39N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone40N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone41N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone42N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone43N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone44N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone45N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone46N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone47N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone48N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone49N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone50N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone51N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone52N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone53N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone54N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone55N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone56N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone57N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone58N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone59N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone60N.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone1S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone2S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone3S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone4S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone5S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone6S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone7S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone8S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone9S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone10S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone11S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone12S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone13S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone14S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone15S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone16S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone17S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone18S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone19S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone20S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone21S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone22S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone23S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone24S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone25S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone26S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone27S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone28S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone29S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone30S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone31S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone32S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone33S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone34S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone35S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone36S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone37S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone38S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone39S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone40S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone41S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone42S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone43S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone44S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone45S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone46S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone47S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone48S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone49S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone50S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone51S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone52S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone53S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone54S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone55S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone56S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone57S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone58S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone59S.GeographicInfo.Datum.Name = "D_North_American_1983"; NAD1983UTMZone60S.GeographicInfo.Datum.Name = "D_North_American_1983"; } #endregion } } #pragma warning restore 1591
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using BenderProxy; using BenderProxy.Writers; using NUnit.Framework; using OpenQA.Selenium.Environment; using OpenQA.Selenium.IE; namespace OpenQA.Selenium { [TestFixture] public class ProxySettingTest : DriverTestFixture { private IWebDriver localDriver; private ProxyServer proxyServer; [SetUp] public void RestartOriginalDriver() { driver = EnvironmentManager.Instance.GetCurrentDriver(); proxyServer = new ProxyServer(); EnvironmentManager.Instance.DriverStarting += EnvironmentManagerDriverStarting; } [TearDown] public void QuitAdditionalDriver() { if (localDriver != null) { localDriver.Quit(); localDriver = null; } if (proxyServer != null) { proxyServer.Quit(); proxyServer = null; } EnvironmentManager.Instance.DriverStarting -= EnvironmentManagerDriverStarting; } [Test] [IgnoreBrowser(Browser.Safari, "SafariDriver does not support setting proxy")] [IgnoreBrowser(Browser.EdgeLegacy, "EdgeDriver does not support setting proxy")] public void CanConfigureManualHttpProxy() { proxyServer.EnableLogResourcesOnResponse(); Proxy proxyToUse = proxyServer.AsProxy(); InitLocalDriver(proxyToUse); localDriver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("simpleTest.html"); Assert.That(proxyServer.HasBeenCalled("simpleTest.html"), Is.True); } [Test] [IgnoreBrowser(Browser.Safari, "SafariDriver does not support setting proxy")] [IgnoreBrowser(Browser.EdgeLegacy, "EdgeDriver does not support setting proxy")] public void CanConfigureNoProxy() { proxyServer.EnableLogResourcesOnResponse(); Proxy proxyToUse = proxyServer.AsProxy(); proxyToUse.AddBypassAddresses(EnvironmentManager.Instance.UrlBuilder.HostName); if (TestUtilities.IsInternetExplorer(driver)) { proxyToUse.AddBypassAddress("<-localhost>"); } InitLocalDriver(proxyToUse); localDriver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("simpleTest.html"); Assert.That(proxyServer.HasBeenCalled("simpleTest.html"), Is.False); localDriver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIsViaNonLoopbackAddress("simpleTest.html"); Assert.That(proxyServer.HasBeenCalled("simpleTest.html"), Is.True); } [Test] [IgnoreBrowser(Browser.Safari, "SafariDriver does not support setting proxy")] [IgnoreBrowser(Browser.EdgeLegacy, "EdgeDriver does not support setting proxy")] public void CanConfigureProxyThroughAutoConfigFile() { StringBuilder pacFileContentBuilder = new StringBuilder(); pacFileContentBuilder.AppendLine("function FindProxyForURL(url, host) {"); pacFileContentBuilder.AppendFormat(" return 'PROXY {0}';\n", proxyServer.BaseUrl); pacFileContentBuilder.AppendLine("}"); string pacFileContent = pacFileContentBuilder.ToString(); using (ProxyAutoConfigServer pacServer = new ProxyAutoConfigServer(pacFileContent)) { proxyServer.EnableContentOverwriteOnRequest(); Proxy proxyToUse = new Proxy(); proxyToUse.ProxyAutoConfigUrl = string.Format("http://{0}:{1}/proxy.pac", pacServer.HostName, pacServer.Port); InitLocalDriver(proxyToUse); localDriver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("simpleTest.html"); Assert.That(localDriver.FindElement(By.TagName("h3")).Text, Is.EqualTo("Hello, world!")); } } [Test] [IgnoreBrowser(Browser.Safari, "SafariDriver does not support setting proxy")] [IgnoreBrowser(Browser.EdgeLegacy, "EdgeDriver does not support setting proxy")] public void CanUseAutoConfigFileThatOnlyProxiesCertainHosts() { StringBuilder pacFileContentBuilder = new StringBuilder(); pacFileContentBuilder.AppendLine("function FindProxyForURL(url, host) {"); pacFileContentBuilder.AppendFormat(" if (url.indexOf('{0}') != -1) {{\n", EnvironmentManager.Instance.UrlBuilder.HostName); pacFileContentBuilder.AppendFormat(" return 'PROXY {0}';\n", proxyServer.BaseUrl); pacFileContentBuilder.AppendLine(" }"); pacFileContentBuilder.AppendLine(" return 'DIRECT';"); pacFileContentBuilder.AppendLine("}"); string pacFileContent = pacFileContentBuilder.ToString(); using (ProxyAutoConfigServer pacServer = new ProxyAutoConfigServer(pacFileContent)) { proxyServer.EnableContentOverwriteOnRequest(); Proxy proxyToUse = new Proxy(); proxyToUse.ProxyAutoConfigUrl = string.Format("http://{0}:{1}/proxy.pac", pacServer.HostName, pacServer.Port); InitLocalDriver(proxyToUse); localDriver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("simpleTest.html"); Assert.That(localDriver.FindElement(By.TagName("h3")).Text, Is.EqualTo("Hello, world!")); localDriver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIsViaNonLoopbackAddress("simpleTest.html"); Assert.That(localDriver.FindElement(By.TagName("h1")).Text, Is.EqualTo("Heading")); } } private void EnvironmentManagerDriverStarting(object sender, DriverStartingEventArgs e) { InternetExplorerOptions ieOptions = e.Options as InternetExplorerOptions; if (ieOptions != null) { ieOptions.EnsureCleanSession = true; } } private void InitLocalDriver(Proxy proxy) { EnvironmentManager.Instance.CloseCurrentDriver(); if (localDriver != null) { localDriver.Quit(); } ProxyOptions options = new ProxyOptions(); options.Proxy = proxy; localDriver = EnvironmentManager.Instance.CreateDriverInstance(options); } private class ProxyOptions : DriverOptions { [Obsolete] public override void AddAdditionalCapability(string capabilityName, object capabilityValue) { } public override ICapabilities ToCapabilities() { return null; } } private class ProxyAutoConfigServer : IDisposable { private int listenerPort; private string hostName; private string pacFileContent; private bool disposedValue = false; // To detect redundant calls private bool keepRunning = true; private HttpListener listener; private Thread listenerThread; public ProxyAutoConfigServer(string pacFileContent) : this(pacFileContent, "localhost") { } public ProxyAutoConfigServer(string pacFileContent, string hostName) { this.pacFileContent = pacFileContent; this.hostName = hostName; //get an empty port TcpListener l = new TcpListener(IPAddress.Loopback, 0); l.Start(); this.listenerPort = ((IPEndPoint)l.LocalEndpoint).Port; l.Stop(); this.listenerThread = new Thread(this.Listen); this.listenerThread.Start(); } public string HostName { get { return hostName; } } public int Port { get { return listenerPort; } } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { this.keepRunning = false; this.listenerThread.Join(TimeSpan.FromSeconds(5)); this.listener.Stop(); } disposedValue = true; } } private void ProcessContext(HttpListenerContext context) { if (context.Request.Url.AbsoluteUri.ToLowerInvariant().Contains("proxy.pac")) { byte[] pacFileBuffer = Encoding.ASCII.GetBytes(this.pacFileContent); context.Response.ContentType = "application/x-javascript-config"; context.Response.ContentLength64 = pacFileBuffer.LongLength; context.Response.ContentEncoding = Encoding.ASCII; context.Response.StatusCode = 200; context.Response.OutputStream.Write(pacFileBuffer, 0, pacFileBuffer.Length); context.Response.OutputStream.Flush(); } } private void Listen() { listener = new HttpListener(); listener.Prefixes.Add("http://" + this.HostName + ":" + this.listenerPort.ToString() + "/"); listener.Start(); while (this.keepRunning) { try { HttpListenerContext context = listener.GetContext(); this.ProcessContext(context); } catch (HttpListenerException) { } } } } private class ProxyServer { private HttpProxyServer server; private List<string> uris = new List<string>(); int port; string hostName = string.Empty; public ProxyServer() : this("127.0.0.1") { } public ProxyServer(string hostName) { this.hostName = hostName; this.server = new HttpProxyServer(this.hostName, new HttpProxy()); this.server.Start().WaitOne(); this.port = this.server.ProxyEndPoint.Port; // this.server.Log += OnServerLog; } public string BaseUrl { get { return string.Format("{0}:{1}", this.hostName, this.port); } } public HttpProxyServer Server { get { return this.server; } } public string HostName { get { return hostName; } } public int Port { get { return port; } } public void EnableLogResourcesOnResponse() { this.server.Proxy.OnResponseSent = this.LogRequestedResources; } public void DisableLogResourcesOnResponse() { this.server.Proxy.OnResponseSent = null; } public void EnableContentOverwriteOnRequest() { this.server.Proxy.OnRequestReceived = this.OverwriteRequestedContent; } public void DisableContentOverwriteOnRequest() { this.server.Proxy.OnRequestReceived = null; } public bool HasBeenCalled(string resourceName) { return this.uris.Contains(resourceName); } public void Quit() { this.server.Proxy.OnResponseSent = null; this.server.Stop(); } public Proxy AsProxy() { Proxy proxy = new Proxy(); proxy.HttpProxy = this.BaseUrl; return proxy; } private void OnServerLog(object sender, BenderProxy.Logging.LogEventArgs e) { Console.WriteLine(e.LogMessage); } private void LogRequestedResources(ProcessingContext context) { string[] parts = context.RequestHeader.RequestURI.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 0) { string finalPart = parts[parts.Length - 1]; uris.Add(finalPart); } } private void OverwriteRequestedContent(ProcessingContext context) { StringBuilder pageContentBuilder = new StringBuilder("<!DOCTYPE html>"); pageContentBuilder.AppendLine("<html>"); pageContentBuilder.AppendLine("<head>"); pageContentBuilder.AppendLine(" <title>Hello</title>"); pageContentBuilder.AppendLine("</head>"); pageContentBuilder.AppendLine("<body>"); pageContentBuilder.AppendLine(" <h3>Hello, world!</h3>"); pageContentBuilder.AppendLine("</body>"); pageContentBuilder.AppendLine("</html>"); string pageContent = pageContentBuilder.ToString(); context.StopProcessing(); MemoryStream responseStream = new MemoryStream(Encoding.UTF8.GetBytes(pageContent)); var responseHeader = new BenderProxy.Headers.HttpResponseHeader(200, "OK", "1.1"); responseHeader.EntityHeaders.ContentType = "text/html"; responseHeader.EntityHeaders.ContentEncoding = "utf-8"; responseHeader.EntityHeaders.ContentLength = responseStream.Length; new HttpResponseWriter(context.ClientStream).Write(responseHeader, responseStream, responseStream.Length); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Runtime.Serialization; namespace System.Data.SqlClient.ManualTesting.Tests { /// <summary> /// Random number generator that tracks information necessary to reproduce a sequence of random numbers. To save the current state, /// tests should query the CurrentState property before execution of the test case that uses random. /// In addition, the test needs to capture the current state of random instance before setup steps, if random is used during setup. /// /// This class also provides more helper methods, like create numbers with high probability for low numbers. /// /// Use the CurrentState property to save repro information, and, when crash is detected, dump the state to file or log /// with its ToString method. The performance of CurrentState has been optimized to ensure it does not affect the overall performance /// of the test app. But, the CurrentState.ToString is not optimum, so use it only when crash is detected. /// /// For easy Random scope and repro management, see also RandomizerScope class. /// /// Note: instances of this class are not thread-safe! /// <example> /// To remember the current state of Randomizer, use randomizerInstance.CurrentState method before its first use! /// To recreate the randomizer object from its log, use Randomizer.Create(state) method. /// </example> /// </summary> public class Randomizer { /// <summary> /// counter used to prevent same seed generation for multi-threaded operations /// </summary> private static int s_seedCounter; /// <summary> /// Generates a seed value based on current ticks count (Environment.TickCount) XORed with /// incrementing counter to prevent duplicates if called within the interval of the 500 milliseconds /// (time resolution of OS ticks). This method is thread-safe! /// </summary> public static int CreateSeed() { return Environment.TickCount ^ Interlocked.Increment(ref s_seedCounter); } /// <summary> /// encapsulate the randomizer state which is a byte array within the read-only structure /// </summary> /// <remarks>Keep it immutable - randomizer pool creates shallow copies of the state struct only!</remarks> public struct State { internal readonly Type _randomizerType; internal readonly byte[] _binState; internal State(Type randType, byte[] binState) { _binState = binState; _randomizerType = randType; } private const char Separator = ':'; /// <summary> /// Creates human-readable string representation of the state. /// Use it only when you need to dump the rand state to the file or log. /// </summary> public override string ToString() { if (_binState == null && _randomizerType == null) return string.Empty; return string.Format("{0}{1}{2}", _randomizerType.FullName, Separator, Convert.ToBase64String(_binState)); } /// <summary> /// recreates the state instance from string, generated by ToString() /// </summary> public static State Parse(string strState) { if (string.IsNullOrEmpty(strState)) return State.Empty; string[] items = strState.Split(new char[] { Separator }, 2); return new State( Type.GetType(items[0]), Convert.FromBase64String(items[1])); } /// <summary> /// represents an empty randomizer state, it cannot be used to create a randomizer! /// </summary> public static readonly State Empty = new State(null, null); } /// <summary> /// creates a new randomizer from seed /// Target Randomizer implementation must have an explicit c-tor that accepts seed only! /// </summary> public static RandomizerType Create<RandomizerType>(int seed) where RandomizerType : Randomizer, new() { if (typeof(RandomizerType) == typeof(Randomizer)) { // optimization for Randomizer itself to avoid reflection call return (RandomizerType)new Randomizer(seed); } else { return (RandomizerType)Activator.CreateInstance(typeof(RandomizerType), new object[] { seed }); } } /// <summary> /// Recreates randomizer from the state, state must not be empty! /// Target Randomizer implementation must have an explicit c-tor that accepts state only and calls into base c-tor(state)! /// </summary> public static RandomizerType Create<RandomizerType>(State state) where RandomizerType : Randomizer, new() { if (typeof(RandomizerType) == typeof(Randomizer)) { // optimization for Randomizer itself to avoid redundant construction return (RandomizerType)new Randomizer(state); } else { return (RandomizerType)Activator.CreateInstance(typeof(RandomizerType), new object[] { state }); } } /// <summary> /// Used to create an instance of randomizer from its state. Use Create static method to create the instance. /// </summary> /// <remarks>when overriding Randomizer, explicitly define a new protected constructor that accepts state only</remarks> protected Randomizer(State state) { Deserialize(state); } /// <summary> /// gets the current state of the Randomizer /// To trace it, you can use state.ToString() method. /// </summary> public State GetCurrentState() { byte[] binState = new byte[BinaryStateSize]; int offset; Serialize(binState, out offset); return new State(GetType(), binState); } /// <summary> /// returns size needed to serialize the randomizer state, override this method to reserve space for custom fields. /// </summary> protected virtual int BinaryStateSize { get { return BinaryStateSizeRandom; } } /// <summary> /// this method is used to serialize the state, binState size must be BinaryStateSize /// </summary> /// <remarks> /// call base.Serialize first when overriding this method and use the nextOffset to write custom data /// </remarks> /// <remarks> /// For fast performance, avoid using MemoryStream/BinaryReader or reflection/serialization. I measured the difference between several implementations and found that: /// * Difference in time performance between using plain byte array versus MemoryStream with BinaryReader is ~ 1/10! /// * Difference between this implementation and serialization via .Net Serialization is ~1/100! /// </remarks> protected virtual void Serialize(byte[] binState, out int nextOffset) { nextOffset = 0; SerializeInt(_inext, binState, ref nextOffset); SerializeInt(_inextp, binState, ref nextOffset); Buffer.BlockCopy(_seedArray, 0, binState, nextOffset, 4 * _seedArray.Length); nextOffset += 4 * _seedArray.Length; } private void Deserialize(State state) { if (state._randomizerType != GetType()) throw new ArgumentException("Type mismatch!"); int offset; Deserialize(state._binState, out offset); } /// <summary> /// this method is used to deserialize the randomizer from its binary state, binState size is BinaryStateSize /// </summary> /// <remarks> /// call base.Deserialize first when overriding this method and use the nextOffset to read custom data /// </remarks> protected internal virtual void Deserialize(byte[] binState, out int nextOffset) { if (binState == null) throw new ArgumentNullException("empty state should not be used to create an instance of randomizer!"); if (binState.Length != BinaryStateSize) throw new ArgumentNullException("wrong size of the state binary data"); nextOffset = 0; _inext = DeserializeInt(binState, ref nextOffset); _inextp = DeserializeInt(binState, ref nextOffset); Buffer.BlockCopy(binState, nextOffset, _seedArray, 0, 4 * _seedArray.Length); nextOffset += 4 * _seedArray.Length; } /// <summary> /// helper method to serialize int field /// </summary> protected static void SerializeInt(int val, byte[] buf, ref int offset) { uint uval = unchecked((uint)val); buf[offset++] = (byte)((uval & 0x000000FF)); buf[offset++] = (byte)((uval & 0x0000FF00) >> 8); buf[offset++] = (byte)((uval & 0x00FF0000) >> 16); buf[offset++] = (byte)((uval & 0xFF000000) >> 24); } /// <summary> /// helper method to deserialize int field /// </summary> protected static int DeserializeInt(byte[] buf, ref int offset) { uint uval = 0; uval |= (uint)(0X000000FF & buf[offset++]); uval |= (uint)(0X0000FF00 & (buf[offset++] << 8)); uval |= (uint)(0X00FF0000 & (buf[offset++] << 16)); uval |= (uint)(0XFF000000 & (buf[offset++] << 24)); return unchecked((int)uval); } /// <summary> /// deserialization constructor /// </summary> public Randomizer(StreamingContext context) { string base64State = GetCurrentState().ToString(); int offset; Deserialize(Convert.FromBase64String(base64State), out offset); } /// <summary> /// use this method to create seeds for nested randomizers out of current one /// </summary> public int NextSeed() { return Next(); } #region DO NOT CHANGE BEYOND THIS POINT // The code below was copied from https://github.com/dotnet/coreclr/blob/master/src/mscorlib/src/System/Random.cs // I copy-pasted the source instead of inheritance to get super-fast performance on state management (see State Management section above) // which is 100 times faster than using Reflection. See remarks on Serialize method for more details. // // Private Constants // private const int MBIG = int.MaxValue; private const int MSEED = 161803398; private const int MZ = 0; // // Member Variables - make sure to update state size and update serialization code when adding more members // private const int BinaryStateSizeRandom = 4 + 4 + 56 * 4; private int _inext; private int _inextp; private int[] _seedArray = new int[56]; // // Public Constants // // // Native Declarations // // // Constructors // public Randomizer() : this(CreateSeed()) { } public Randomizer(int Seed) { int ii; int mj, mk; //Initialize our Seed array. //This algorithm comes from Numerical Recipes in C (2nd Ed.) int subtraction = (Seed == int.MinValue) ? int.MaxValue : Math.Abs(Seed); mj = MSEED - subtraction; _seedArray[55] = mj; mk = 1; for (int i = 1; i < 55; i++) { //Apparently the range [1..55] is special (Knuth) and so we're wasting the 0'th position. ii = (21 * i) % 55; _seedArray[ii] = mk; mk = mj - mk; if (mk < 0) mk += MBIG; mj = _seedArray[ii]; } for (int k = 1; k < 5; k++) { for (int i = 1; i < 56; i++) { _seedArray[i] -= _seedArray[1 + (i + 30) % 55]; if (_seedArray[i] < 0) _seedArray[i] += MBIG; } } _inext = 0; _inextp = 21; Seed = 1; } // // Package Private Methods // /*====================================Sample==================================== **Action: Return a new random number [0..1) and reSeed the Seed array. **Returns: A double [0..1) **Arguments: None **Exceptions: None ==============================================================================*/ protected virtual double Sample() { //Including this division at the end gives us significantly improved //random number distribution. return (InternalSample() * (1.0 / MBIG)); } private int InternalSample() { int retVal; int locINext = _inext; int locINextp = _inextp; if (++locINext >= 56) locINext = 1; if (++locINextp >= 56) locINextp = 1; retVal = _seedArray[locINext] - _seedArray[locINextp]; if (retVal == MBIG) retVal--; if (retVal < 0) retVal += MBIG; _seedArray[locINext] = retVal; _inext = locINext; _inextp = locINextp; return retVal; } // // Public Instance Methods // /*=====================================Next===================================== **Returns: An int [0..int.MaxValue) **Arguments: None **Exceptions: None. ==============================================================================*/ public virtual int Next() { return InternalSample(); } private double GetSampleForLargeRange() { // The distribution of double value returned by Sample // is not distributed well enough for a large range. // If we use Sample for a range [int.MinValue..int.MaxValue) // We will end up getting even numbers only. int result = InternalSample(); // Note we can't use addition here. The distribution will be bad if we do that. bool negative = (InternalSample() % 2 == 0) ? true : false; // decide the sign based on second sample if (negative) { result = -result; } double d = result; d += (int.MaxValue - 1); // get a number in range [0 .. 2 * Int32MaxValue - 1) d /= 2 * (uint)int.MaxValue - 1; return d; } /*=====================================Next===================================== **Returns: An int [minvalue..maxvalue) **Arguments: minValue -- the least legal value for the Random number. ** maxValue -- One greater than the greatest legal return value. **Exceptions: None. ==============================================================================*/ public virtual int Next(int minValue, int maxValue) { if (minValue > maxValue) { throw new ArgumentOutOfRangeException("minValue > maxValue"); } long range = (long)maxValue - minValue; if (range <= (long)int.MaxValue) { return ((int)(Sample() * range) + minValue); } else { return (int)((long)(GetSampleForLargeRange() * range) + minValue); } } /*=====================================Next===================================== **Returns: An int [0..maxValue) **Arguments: maxValue -- One more than the greatest legal return value. **Exceptions: None. ==============================================================================*/ public virtual int Next(int maxValue) { if (maxValue < 0) { throw new ArgumentOutOfRangeException("maxValue < 0"); } return (int)(Sample() * maxValue); } /*=====================================Next===================================== **Returns: A double [0..1) **Arguments: None **Exceptions: None ==============================================================================*/ public virtual double NextDouble() { return Sample(); } /*==================================NextBytes=================================== **Action: Fills the byte array with random bytes [0..0x7f]. The entire array is filled. **Returns:Void **Arguments: buffer -- the array to be filled. **Exceptions: None ==============================================================================*/ public virtual void NextBytes(byte[] buffer) { if (buffer == null) throw new ArgumentNullException(nameof(buffer)); for (int i = 0; i < buffer.Length; i++) { buffer[i] = (byte)(InternalSample() % (byte.MaxValue + 1)); } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** ** ** Purpose: Centralized error methods for the IO package. ** Mostly useful for translating Win32 HRESULTs into meaningful ** error strings & exceptions. ** ** ===========================================================*/ using System; using System.Runtime.InteropServices; using Win32Native = Microsoft.Win32.Win32Native; using System.Text; using System.Globalization; using System.Security; using System.Diagnostics.Contracts; namespace System.IO { [Pure] internal static class __Error { internal static void EndOfFile() { throw new EndOfStreamException(Environment.GetResourceString("IO.EOF_ReadBeyondEOF")); } internal static void FileNotOpen() { throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_FileClosed")); } internal static void StreamIsClosed() { throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_StreamClosed")); } internal static void MemoryStreamNotExpandable() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_MemStreamNotExpandable")); } internal static void ReaderClosed() { throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ReaderClosed")); } internal static void ReadNotSupported() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream")); } internal static void WrongAsyncResult() { throw new ArgumentException(Environment.GetResourceString("Arg_WrongAsyncResult")); } internal static void EndReadCalledTwice() { // Should ideally be InvalidOperationExc but we can't maitain parity with Stream and FileStream without some work throw new ArgumentException(Environment.GetResourceString("InvalidOperation_EndReadCalledMultiple")); } internal static void EndWriteCalledTwice() { // Should ideally be InvalidOperationExc but we can't maintain parity with Stream and FileStream without some work throw new ArgumentException(Environment.GetResourceString("InvalidOperation_EndWriteCalledMultiple")); } // Given a possible fully qualified path, ensure that we have path // discovery permission to that path. If we do not, return just the // file name. If we know it is a directory, then don't return the // directory name. internal static String GetDisplayablePath(String path, bool isInvalidPath) { if (String.IsNullOrEmpty(path)) return String.Empty; // Is it a fully qualified path? bool isFullyQualified = false; if (path.Length < 2) return path; if (PathInternal.IsDirectorySeparator(path[0]) && PathInternal.IsDirectorySeparator(path[1])) isFullyQualified = true; else if (path[1] == Path.VolumeSeparatorChar) { isFullyQualified = true; } if (!isFullyQualified && !isInvalidPath) return path; bool safeToReturn = false; try { if (!isInvalidPath) { safeToReturn = true; } } catch (SecurityException) { } catch (ArgumentException) { // ? and * characters cause ArgumentException to be thrown from HasIllegalCharacters // inside FileIOPermission.AddPathList } catch (NotSupportedException) { // paths like "!Bogus\\dir:with/junk_.in it" can cause NotSupportedException to be thrown // from Security.Util.StringExpressionSet.CanonicalizePath when ':' is found in the path // beyond string index position 1. } if (!safeToReturn) { if (PathInternal.IsDirectorySeparator(path[path.Length - 1])) path = Environment.GetResourceString("IO.IO_NoPermissionToDirectoryName"); else path = Path.GetFileName(path); } return path; } internal static void WinIOError() { int errorCode = Marshal.GetLastWin32Error(); WinIOError(errorCode, String.Empty); } // After calling GetLastWin32Error(), it clears the last error field, // so you must save the HResult and pass it to this method. This method // will determine the appropriate exception to throw dependent on your // error, and depending on the error, insert a string into the message // gotten from the ResourceManager. internal static void WinIOError(int errorCode, String maybeFullPath) { // This doesn't have to be perfect, but is a perf optimization. bool isInvalidPath = errorCode == Win32Native.ERROR_INVALID_NAME || errorCode == Win32Native.ERROR_BAD_PATHNAME; String str = GetDisplayablePath(maybeFullPath, isInvalidPath); switch (errorCode) { case Win32Native.ERROR_FILE_NOT_FOUND: if (str.Length == 0) throw new FileNotFoundException(Environment.GetResourceString("IO.FileNotFound")); else throw new FileNotFoundException(Environment.GetResourceString("IO.FileNotFound_FileName", str), str); case Win32Native.ERROR_PATH_NOT_FOUND: if (str.Length == 0) throw new DirectoryNotFoundException(Environment.GetResourceString("IO.PathNotFound_NoPathName")); else throw new DirectoryNotFoundException(Environment.GetResourceString("IO.PathNotFound_Path", str)); case Win32Native.ERROR_ACCESS_DENIED: if (str.Length == 0) throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_IODenied_NoPathName")); else throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_IODenied_Path", str)); case Win32Native.ERROR_ALREADY_EXISTS: if (str.Length == 0) goto default; throw new IOException(Environment.GetResourceString("IO.IO_AlreadyExists_Name", str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath); case Win32Native.ERROR_FILENAME_EXCED_RANGE: throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong")); case Win32Native.ERROR_INVALID_DRIVE: throw new DriveNotFoundException(Environment.GetResourceString("IO.DriveNotFound_Drive", str)); case Win32Native.ERROR_INVALID_PARAMETER: throw new IOException(Win32Native.GetMessage(errorCode), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath); case Win32Native.ERROR_SHARING_VIOLATION: if (str.Length == 0) throw new IOException(Environment.GetResourceString("IO.IO_SharingViolation_NoFileName"), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath); else throw new IOException(Environment.GetResourceString("IO.IO_SharingViolation_File", str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath); case Win32Native.ERROR_FILE_EXISTS: if (str.Length == 0) goto default; throw new IOException(Environment.GetResourceString("IO.IO_FileExists_Name", str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath); case Win32Native.ERROR_OPERATION_ABORTED: throw new OperationCanceledException(); default: throw new IOException(Win32Native.GetMessage(errorCode), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath); } } internal static void WriteNotSupported() { throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnwritableStream")); } // From WinError.h internal const int ERROR_FILE_NOT_FOUND = Win32Native.ERROR_FILE_NOT_FOUND; internal const int ERROR_PATH_NOT_FOUND = Win32Native.ERROR_PATH_NOT_FOUND; internal const int ERROR_ACCESS_DENIED = Win32Native.ERROR_ACCESS_DENIED; internal const int ERROR_INVALID_PARAMETER = Win32Native.ERROR_INVALID_PARAMETER; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Diagnostics.CodeAnalysis; namespace Apache.Ignite.Service { using System; using System.Collections.Generic; using System.Configuration.Install; using System.IO; using System.Linq; using System.Reflection; using System.ServiceProcess; using System.Text; using Apache.Ignite.Core; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Lifecycle; /// <summary> /// Ignite windows service. /// </summary> internal class IgniteService : ServiceBase, ILifecycleHandler { /** Service name. */ public const string SvcName = "Apache Ignite.NET"; /** Service display name. */ public static readonly string SvcDisplayName = SvcName + " " + Assembly.GetExecutingAssembly().GetName().Version.ToString(4); /** Service description. */ public const string SvcDesc = "Apache Ignite.NET Service"; /** Current executable name. */ private static readonly string ExeName = new FileInfo(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath).FullName; /** Ignite configuration to start with. */ private readonly IgniteConfiguration _cfg; /** Stopping recurse check flag. */ private bool _isStopping; /// <summary> /// Constructor. /// </summary> public IgniteService(IgniteConfiguration cfg) { AutoLog = true; CanStop = true; ServiceName = SvcName; _cfg = cfg; // Subscribe to lifecycle events var beans = _cfg.LifecycleHandlers ?? new List<ILifecycleHandler>(); beans.Add(this); _cfg.LifecycleHandlers = beans; } /** <inheritDoc /> */ protected override void OnStart(string[] args) { Ignition.Start(_cfg); } /** <inheritDoc /> */ protected override void OnStop() { if (!_isStopping) Ignition.StopAll(true); } /// <summary> /// Install service programmatically. /// </summary> /// <param name="args">The arguments.</param> internal static void DoInstall(Tuple<string, string>[] args) { // 1. Check if already defined. if (ServiceController.GetServices().Any(svc => SvcName.Equals(svc.ServiceName, StringComparison.Ordinal))) { throw new IgniteException("Ignite service is already installed (uninstall it using \"" + ExeName + " " + IgniteRunner.SvcUninstall + "\" first)"); } // 2. Create startup arguments. if (args.Length > 0) { Console.WriteLine("Installing \"" + SvcName + "\" service with the following startup " + "arguments:"); foreach (var arg in args) Console.WriteLine("\t" + arg); } else Console.WriteLine("Installing \"" + SvcName + "\" service ..."); // 3. Actual installation. Install0(args); Console.WriteLine("\"" + SvcName + "\" service installed successfully."); } /// <summary> /// Uninstall service programmatically. /// </summary> internal static void Uninstall() { var svc = ServiceController.GetServices().FirstOrDefault(x => SvcName == x.ServiceName); if (svc == null) { Console.WriteLine("\"" + SvcName + "\" service is not installed."); } else if (svc.Status != ServiceControllerStatus.Stopped) { throw new IgniteException("Ignite service is running, please stop it first."); } else { Console.WriteLine("Uninstalling \"" + SvcName + "\" service ..."); Uninstall0(); Console.WriteLine("\"" + SvcName + "\" service uninstalled successfully."); } } /// <summary> /// Runs the service. /// </summary> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Service lifetime is the same as process lifetime.")] internal static void Run(IgniteConfiguration cfg) { ServiceBase.Run(new IgniteService(cfg)); } /// <summary> /// Native service installation. /// </summary> /// <param name="args">Arguments.</param> private static void Install0(Tuple<string, string>[] args) { // 1. Prepare arguments. var argString = new StringBuilder(IgniteRunner.Svc); foreach (var arg in args) { var val = arg.Item2; if (val.Contains(' ')) { val = '"' + val + '"'; } argString.Append(" ").AppendFormat("-{0}={1}", arg.Item1, val); } IgniteServiceInstaller.Args = argString.ToString(); // 2. Install service. ManagedInstallerClass.InstallHelper(new[] { ExeName }); } /// <summary> /// Native service uninstallation. /// </summary> private static void Uninstall0() { ManagedInstallerClass.InstallHelper(new[] { ExeName, "/u" }); } /** <inheritdoc /> */ public void OnLifecycleEvent(LifecycleEventType evt) { if (evt == LifecycleEventType.AfterNodeStop) { _isStopping = true; Stop(); } } } }
/* * ****************************************************************************** * Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file 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. * **************************************************************************** */ // This code is auto-generated, do not modify using Ds3.Models; using System; using System.Net; namespace Ds3.Calls { public class GetDegradedS3DataReplicationRulesSpectraS3Request : Ds3Request { private string _dataPolicyId; public string DataPolicyId { get { return _dataPolicyId; } set { WithDataPolicyId(value); } } private bool? _lastPage; public bool? LastPage { get { return _lastPage; } set { WithLastPage(value); } } private int? _pageLength; public int? PageLength { get { return _pageLength; } set { WithPageLength(value); } } private int? _pageOffset; public int? PageOffset { get { return _pageOffset; } set { WithPageOffset(value); } } private string _pageStartMarker; public string PageStartMarker { get { return _pageStartMarker; } set { WithPageStartMarker(value); } } private DataPlacementRuleState? _state; public DataPlacementRuleState? State { get { return _state; } set { WithState(value); } } private string _targetId; public string TargetId { get { return _targetId; } set { WithTargetId(value); } } private DataReplicationRuleType? _type; public DataReplicationRuleType? Type { get { return _type; } set { WithType(value); } } public GetDegradedS3DataReplicationRulesSpectraS3Request WithDataPolicyId(Guid? dataPolicyId) { this._dataPolicyId = dataPolicyId.ToString(); if (dataPolicyId != null) { this.QueryParams.Add("data_policy_id", dataPolicyId.ToString()); } else { this.QueryParams.Remove("data_policy_id"); } return this; } public GetDegradedS3DataReplicationRulesSpectraS3Request WithDataPolicyId(string dataPolicyId) { this._dataPolicyId = dataPolicyId; if (dataPolicyId != null) { this.QueryParams.Add("data_policy_id", dataPolicyId); } else { this.QueryParams.Remove("data_policy_id"); } return this; } public GetDegradedS3DataReplicationRulesSpectraS3Request WithLastPage(bool? lastPage) { this._lastPage = lastPage; if (lastPage != null) { this.QueryParams.Add("last_page", lastPage.ToString()); } else { this.QueryParams.Remove("last_page"); } return this; } public GetDegradedS3DataReplicationRulesSpectraS3Request WithPageLength(int? pageLength) { this._pageLength = pageLength; if (pageLength != null) { this.QueryParams.Add("page_length", pageLength.ToString()); } else { this.QueryParams.Remove("page_length"); } return this; } public GetDegradedS3DataReplicationRulesSpectraS3Request WithPageOffset(int? pageOffset) { this._pageOffset = pageOffset; if (pageOffset != null) { this.QueryParams.Add("page_offset", pageOffset.ToString()); } else { this.QueryParams.Remove("page_offset"); } return this; } public GetDegradedS3DataReplicationRulesSpectraS3Request WithPageStartMarker(Guid? pageStartMarker) { this._pageStartMarker = pageStartMarker.ToString(); if (pageStartMarker != null) { this.QueryParams.Add("page_start_marker", pageStartMarker.ToString()); } else { this.QueryParams.Remove("page_start_marker"); } return this; } public GetDegradedS3DataReplicationRulesSpectraS3Request WithPageStartMarker(string pageStartMarker) { this._pageStartMarker = pageStartMarker; if (pageStartMarker != null) { this.QueryParams.Add("page_start_marker", pageStartMarker); } else { this.QueryParams.Remove("page_start_marker"); } return this; } public GetDegradedS3DataReplicationRulesSpectraS3Request WithState(DataPlacementRuleState? state) { this._state = state; if (state != null) { this.QueryParams.Add("state", state.ToString()); } else { this.QueryParams.Remove("state"); } return this; } public GetDegradedS3DataReplicationRulesSpectraS3Request WithTargetId(Guid? targetId) { this._targetId = targetId.ToString(); if (targetId != null) { this.QueryParams.Add("target_id", targetId.ToString()); } else { this.QueryParams.Remove("target_id"); } return this; } public GetDegradedS3DataReplicationRulesSpectraS3Request WithTargetId(string targetId) { this._targetId = targetId; if (targetId != null) { this.QueryParams.Add("target_id", targetId); } else { this.QueryParams.Remove("target_id"); } return this; } public GetDegradedS3DataReplicationRulesSpectraS3Request WithType(DataReplicationRuleType? type) { this._type = type; if (type != null) { this.QueryParams.Add("type", type.ToString()); } else { this.QueryParams.Remove("type"); } return this; } public GetDegradedS3DataReplicationRulesSpectraS3Request() { } internal override HttpVerb Verb { get { return HttpVerb.GET; } } internal override string Path { get { return "/_rest_/degraded_s3_data_replication_rule"; } } } }
/* JSONObject.cs -- Simple C# JSON parser version 1.4 - March 17, 2014 Copyright (C) 2012 Boomlagoon Ltd. This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Boomlagoon Ltd. contact@boomlagoon.com */ #define PARSE_ESCAPED_UNICODE #if UNITY_EDITOR || UNITY_ANDROID || UNITY_IOS || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH #define USE_UNITY_DEBUGGING #endif using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Text; #if PARSE_ESCAPED_UNICODE using System.Text.RegularExpressions; #endif #if USE_UNITY_DEBUGGING using UnityEngine; #else using System.Diagnostics; #endif namespace Boomlagoon.JSON { public static class Extensions { public static T Pop<T>(this List<T> list) { var result = list[list.Count - 1]; list.RemoveAt(list.Count - 1); return result; } } static class JSONLogger { #if USE_UNITY_DEBUGGING public static void Log(string str) { Debug.Log(str); } public static void Error(string str) { Debug.LogError(str); } #else public static void Log(string str) { Debug.WriteLine(str); } public static void Error(string str) { Debug.WriteLine(str); } #endif } public enum JSONValueType { String, Number, Object, Array, Boolean, Null } public class JSONValue { public JSONValue(JSONValueType type) { Type = type; } public JSONValue(string str) { Type = JSONValueType.String; Str = str; } public JSONValue(double number) { Type = JSONValueType.Number; Number = number; } public JSONValue(JSONObject obj) { if (obj == null) { Type = JSONValueType.Null; } else { Type = JSONValueType.Object; Obj = obj; } } public JSONValue(JSONArray array) { Type = JSONValueType.Array; Array = array; } public JSONValue(bool boolean) { Type = JSONValueType.Boolean; Boolean = boolean; } /// <summary> /// Construct a copy of the JSONValue given as a parameter /// </summary> /// <param name="value"></param> public JSONValue(JSONValue value) { Type = value.Type; switch (Type) { case JSONValueType.String: Str = value.Str; break; case JSONValueType.Boolean: Boolean = value.Boolean; break; case JSONValueType.Number: Number = value.Number; break; case JSONValueType.Object: if (value.Obj != null) { Obj = new JSONObject(value.Obj); } break; case JSONValueType.Array: Array = new JSONArray(value.Array); break; } } public JSONValueType Type { get; private set; } public string Str { get; set; } public double Number { get; set; } public JSONObject Obj { get; set; } public JSONArray Array { get; set; } public bool Boolean { get; set; } public JSONValue Parent { get; set; } public static implicit operator JSONValue(string str) { return new JSONValue(str); } public static implicit operator JSONValue(double number) { return new JSONValue(number); } public static implicit operator JSONValue(JSONObject obj) { return new JSONValue(obj); } public static implicit operator JSONValue(JSONArray array) { return new JSONValue(array); } public static implicit operator JSONValue(bool boolean) { return new JSONValue(boolean); } /// <returns>String representation of this JSONValue</returns> public override string ToString() { switch (Type) { case JSONValueType.Object: return Obj.ToString(); case JSONValueType.Array: return Array.ToString(); case JSONValueType.Boolean: return Boolean ? "true" : "false"; case JSONValueType.Number: return Number.ToString(); case JSONValueType.String: return "\"" + Str + "\""; case JSONValueType.Null: return "null"; } return "null"; } } public class JSONArray : IEnumerable<JSONValue> { private readonly List<JSONValue> values = new List<JSONValue>(); public JSONArray() { } /// <summary> /// Construct a new array and copy each value from the given array into the new one /// </summary> /// <param name="array"></param> public JSONArray(JSONArray array) { values = new List<JSONValue>(); foreach (var v in array.values) { values.Add(new JSONValue(v)); } } /// <summary> /// Add a JSONValue to this array /// </summary> /// <param name="value"></param> public void Add(JSONValue value) { values.Add(value); } public JSONValue this[int index] { get { return values[index]; } set { values[index] = value; } } /// <returns> /// Return the length of the array /// </returns> public int Length { get { return values.Count; } } /// <returns>String representation of this JSONArray</returns> public override string ToString() { var stringBuilder = new StringBuilder(); stringBuilder.Append('['); foreach (var value in values) { stringBuilder.Append(value.ToString()); stringBuilder.Append(','); } if (values.Count > 0) { stringBuilder.Remove(stringBuilder.Length - 1, 1); } stringBuilder.Append(']'); return stringBuilder.ToString(); } public IEnumerator<JSONValue> GetEnumerator() { return values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return values.GetEnumerator(); } /// <summary> /// Attempt to parse a string as a JSON array. /// </summary> /// <param name="jsonString"></param> /// <returns>A new JSONArray object if successful, null otherwise.</returns> public static JSONArray Parse(string jsonString) { var tempObject = JSONObject.Parse("{ \"array\" :" + jsonString + '}'); return tempObject == null ? null : tempObject.GetValue("array").Array; } /// <summary> /// Empty the array of all values. /// </summary> public void Clear() { values.Clear(); } /// <summary> /// Remove the value at the given index, if it exists. /// </summary> /// <param name="index"></param> public void Remove(int index) { if (index >= 0 && index < values.Count) { values.RemoveAt(index); } else { JSONLogger.Error("index out of range: " + index + " (Expected 0 <= index < " + values.Count + ")"); } } /// <summary> /// Concatenate two JSONArrays /// </summary> /// <param name="lhs"></param> /// <param name="rhs"></param> /// <returns>A new JSONArray that is the result of adding all of the right-hand side array's values to the left-hand side array.</returns> public static JSONArray operator +(JSONArray lhs, JSONArray rhs) { var result = new JSONArray(lhs); foreach (var value in rhs.values) { result.Add(value); } return result; } } public class JSONObject : IEnumerable<KeyValuePair<string, JSONValue>> { private enum JSONParsingState { Object, Array, EndObject, EndArray, Key, Value, KeyValueSeparator, ValueSeparator, String, Number, Boolean, Null } private readonly IDictionary<string, JSONValue> values = new Dictionary<string, JSONValue>(); #if PARSE_ESCAPED_UNICODE private static readonly Regex unicodeRegex = new Regex(@"\\u([0-9a-fA-F]{4})"); private static readonly byte[] unicodeBytes = new byte[2]; #endif public JSONObject() { } /// <summary> /// Construct a copy of the given JSONObject. /// </summary> /// <param name="other"></param> public JSONObject(JSONObject other) { values = new Dictionary<string, JSONValue>(); if (other != null) { foreach (var keyValuePair in other.values) { values[keyValuePair.Key] = new JSONValue(keyValuePair.Value); } } } /// <param name="key"></param> /// <returns>Does 'key' exist in this object.</returns> public bool ContainsKey(string key) { return values.ContainsKey(key); } public JSONValue GetValue(string key) { JSONValue value; values.TryGetValue(key, out value); return value; } public string GetString(string key) { var value = GetValue(key); if (value == null) { JSONLogger.Error(key + "(string) == null"); return string.Empty; } return value.Str; } public double GetNumber(string key) { var value = GetValue(key); if (value == null) { JSONLogger.Error(key + " == null"); return double.NaN; } return value.Number; } public JSONObject GetObject(string key) { var value = GetValue(key); if (value == null) { JSONLogger.Error(key + " == null"); return null; } return value.Obj; } public bool GetBoolean(string key) { var value = GetValue(key); if (value == null) { JSONLogger.Error(key + " == null"); return false; } return value.Boolean; } public JSONArray GetArray(string key) { var value = GetValue(key); if (value == null) { JSONLogger.Error(key + " == null"); return null; } return value.Array; } public JSONValue this[string key] { get { return GetValue(key); } set { values[key] = value; } } public void Add(string key, JSONValue value) { values[key] = value; } public void Add(KeyValuePair<string, JSONValue> pair) { values[pair.Key] = pair.Value; } /// <summary> /// Attempt to parse a string into a JSONObject. /// </summary> /// <param name="jsonString"></param> /// <returns>A new JSONObject or null if parsing fails.</returns> public static JSONObject Parse(string jsonString) { if (string.IsNullOrEmpty(jsonString)) { return null; } JSONValue currentValue = null; var keyList = new List<string>(); var state = JSONParsingState.Object; for (var startPosition = 0; startPosition < jsonString.Length; ++startPosition) { startPosition = SkipWhitespace(jsonString, startPosition); switch (state) { case JSONParsingState.Object: if (jsonString[startPosition] != '{') { return Fail('{', startPosition); } JSONValue newObj = new JSONObject(); if (currentValue != null) { newObj.Parent = currentValue; } currentValue = newObj; state = JSONParsingState.Key; break; case JSONParsingState.EndObject: if (jsonString[startPosition] != '}') { return Fail('}', startPosition); } if (currentValue.Parent == null) { return currentValue.Obj; } switch (currentValue.Parent.Type) { case JSONValueType.Object: currentValue.Parent.Obj.values[keyList.Pop()] = new JSONValue(currentValue.Obj); break; case JSONValueType.Array: currentValue.Parent.Array.Add(new JSONValue(currentValue.Obj)); break; default: return Fail("valid object", startPosition); } currentValue = currentValue.Parent; state = JSONParsingState.ValueSeparator; break; case JSONParsingState.Key: if (jsonString[startPosition] == '}') { --startPosition; state = JSONParsingState.EndObject; break; } var key = ParseString(jsonString, ref startPosition); if (key == null) { return Fail("key string", startPosition); } keyList.Add(key); state = JSONParsingState.KeyValueSeparator; break; case JSONParsingState.KeyValueSeparator: if (jsonString[startPosition] != ':') { return Fail(':', startPosition); } state = JSONParsingState.Value; break; case JSONParsingState.ValueSeparator: switch (jsonString[startPosition]) { case ',': state = currentValue.Type == JSONValueType.Object ? JSONParsingState.Key : JSONParsingState.Value; break; case '}': state = JSONParsingState.EndObject; --startPosition; break; case ']': state = JSONParsingState.EndArray; --startPosition; break; default: return Fail(", } ]", startPosition); } break; case JSONParsingState.Value: { var c = jsonString[startPosition]; if (c == '"') { state = JSONParsingState.String; } else if (char.IsDigit(c) || c == '-') { state = JSONParsingState.Number; } else switch (c) { case '{': state = JSONParsingState.Object; break; case '[': state = JSONParsingState.Array; break; case ']': if (currentValue.Type == JSONValueType.Array) { state = JSONParsingState.EndArray; } else { return Fail("valid array", startPosition); } break; case 'f': case 't': state = JSONParsingState.Boolean; break; case 'n': state = JSONParsingState.Null; break; default: return Fail("beginning of value", startPosition); } --startPosition; //To re-evaluate this char in the newly selected state break; } case JSONParsingState.String: var str = ParseString(jsonString, ref startPosition); if (str == null) { return Fail("string value", startPosition); } switch (currentValue.Type) { case JSONValueType.Object: currentValue.Obj.values[keyList.Pop()] = new JSONValue(str); break; case JSONValueType.Array: currentValue.Array.Add(str); break; default: JSONLogger.Error("Fatal error, current JSON value not valid"); return null; } state = JSONParsingState.ValueSeparator; break; case JSONParsingState.Number: var number = ParseNumber(jsonString, ref startPosition); if (double.IsNaN(number)) { return Fail("valid number", startPosition); } switch (currentValue.Type) { case JSONValueType.Object: currentValue.Obj.values[keyList.Pop()] = new JSONValue(number); break; case JSONValueType.Array: currentValue.Array.Add(number); break; default: JSONLogger.Error("Fatal error, current JSON value not valid"); return null; } state = JSONParsingState.ValueSeparator; break; case JSONParsingState.Boolean: if (jsonString[startPosition] == 't') { if (jsonString.Length < startPosition + 4 || jsonString[startPosition + 1] != 'r' || jsonString[startPosition + 2] != 'u' || jsonString[startPosition + 3] != 'e') { return Fail("true", startPosition); } switch (currentValue.Type) { case JSONValueType.Object: currentValue.Obj.values[keyList.Pop()] = new JSONValue(true); break; case JSONValueType.Array: currentValue.Array.Add(new JSONValue(true)); break; default: JSONLogger.Error("Fatal error, current JSON value not valid"); return null; } startPosition += 3; } else { if (jsonString.Length < startPosition + 5 || jsonString[startPosition + 1] != 'a' || jsonString[startPosition + 2] != 'l' || jsonString[startPosition + 3] != 's' || jsonString[startPosition + 4] != 'e') { return Fail("false", startPosition); } switch (currentValue.Type) { case JSONValueType.Object: currentValue.Obj.values[keyList.Pop()] = new JSONValue(false); break; case JSONValueType.Array: currentValue.Array.Add(new JSONValue(false)); break; default: JSONLogger.Error("Fatal error, current JSON value not valid"); return null; } startPosition += 4; } state = JSONParsingState.ValueSeparator; break; case JSONParsingState.Array: if (jsonString[startPosition] != '[') { return Fail('[', startPosition); } JSONValue newArray = new JSONArray(); if (currentValue != null) { newArray.Parent = currentValue; } currentValue = newArray; state = JSONParsingState.Value; break; case JSONParsingState.EndArray: if (jsonString[startPosition] != ']') { return Fail(']', startPosition); } if (currentValue.Parent == null) { return currentValue.Obj; } switch (currentValue.Parent.Type) { case JSONValueType.Object: currentValue.Parent.Obj.values[keyList.Pop()] = new JSONValue(currentValue.Array); break; case JSONValueType.Array: currentValue.Parent.Array.Add(new JSONValue(currentValue.Array)); break; default: return Fail("valid object", startPosition); } currentValue = currentValue.Parent; state = JSONParsingState.ValueSeparator; break; case JSONParsingState.Null: if (jsonString[startPosition] == 'n') { if (jsonString.Length < startPosition + 4 || jsonString[startPosition + 1] != 'u' || jsonString[startPosition + 2] != 'l' || jsonString[startPosition + 3] != 'l') { return Fail("null", startPosition); } switch (currentValue.Type) { case JSONValueType.Object: currentValue.Obj.values[keyList.Pop()] = new JSONValue(JSONValueType.Null); break; case JSONValueType.Array: currentValue.Array.Add(new JSONValue(JSONValueType.Null)); break; default: JSONLogger.Error("Fatal error, current JSON value not valid"); return null; } startPosition += 3; } state = JSONParsingState.ValueSeparator; break; } } JSONLogger.Error("Unexpected end of string"); return null; } private static int SkipWhitespace(string str, int pos) { for (; pos < str.Length && char.IsWhiteSpace(str[pos]); ++pos) ; return pos; } private static string ParseString(string str, ref int startPosition) { if (str[startPosition] != '"' || startPosition + 1 >= str.Length) { Fail('"', startPosition); return null; } var endPosition = str.IndexOf('"', startPosition + 1); if (endPosition <= startPosition) { Fail('"', startPosition + 1); return null; } while (str[endPosition - 1] == '\\') { endPosition = str.IndexOf('"', endPosition + 1); if (endPosition <= startPosition) { Fail('"', startPosition + 1); return null; } } var result = string.Empty; if (endPosition > startPosition + 1) { result = str.Substring(startPosition + 1, endPosition - startPosition - 1); } startPosition = endPosition; #if PARSE_ESCAPED_UNICODE // Parse Unicode characters that are escaped as \uXXXX do { Match m = unicodeRegex.Match(result); if (!m.Success) { break; } string s = m.Groups[1].Captures[0].Value; unicodeBytes[1] = byte.Parse(s.Substring(0, 2), NumberStyles.HexNumber); unicodeBytes[0] = byte.Parse(s.Substring(2, 2), NumberStyles.HexNumber); s = Encoding.Unicode.GetString(unicodeBytes); result = result.Replace(m.Value, s); } while (true); #endif return result; } private static double ParseNumber(string str, ref int startPosition) { if (startPosition >= str.Length || (!char.IsDigit(str[startPosition]) && str[startPosition] != '-')) { return double.NaN; } var endPosition = startPosition + 1; for (; endPosition < str.Length && str[endPosition] != ',' && str[endPosition] != ']' && str[endPosition] != '}'; ++endPosition) ; double result; if ( !double.TryParse(str.Substring(startPosition, endPosition - startPosition), System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out result)) { return double.NaN; } startPosition = endPosition - 1; return result; } private static JSONObject Fail(char expected, int position) { return Fail(new string(expected, 1), position); } private static JSONObject Fail(string expected, int position) { JSONLogger.Error("Invalid json string, expecting " + expected + " at " + position); return null; } /// <returns>String representation of this JSONObject</returns> public override string ToString() { var stringBuilder = new StringBuilder(); stringBuilder.Append('{'); foreach (var pair in values) { stringBuilder.Append("\"" + pair.Key + "\""); stringBuilder.Append(':'); stringBuilder.Append(pair.Value.ToString()); stringBuilder.Append(','); } if (values.Count > 0) { stringBuilder.Remove(stringBuilder.Length - 1, 1); } stringBuilder.Append('}'); return stringBuilder.ToString(); } public IEnumerator<KeyValuePair<string, JSONValue>> GetEnumerator() { return values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return values.GetEnumerator(); } /// <summary> /// Empty this JSONObject of all values. /// </summary> public void Clear() { values.Clear(); } /// <summary> /// Remove the JSONValue attached to the given key. /// </summary> /// <param name="key"></param> public void Remove(string key) { if (values.ContainsKey(key)) { values.Remove(key); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using JetBrains.Annotations; using JsonApiDotNetCore.Configuration; using JsonApiDotNetCore.Diagnostics; using JsonApiDotNetCore.Errors; using JsonApiDotNetCore.Middleware; using JsonApiDotNetCore.Queries; using JsonApiDotNetCore.Queries.Expressions; using JsonApiDotNetCore.Repositories; using JsonApiDotNetCore.Resources; using JsonApiDotNetCore.Resources.Annotations; using Microsoft.Extensions.Logging; namespace JsonApiDotNetCore.Services { /// <inheritdoc /> [PublicAPI] public class JsonApiResourceService<TResource, TId> : IResourceService<TResource, TId> where TResource : class, IIdentifiable<TId> { private readonly CollectionConverter _collectionConverter = new(); private readonly IResourceRepositoryAccessor _repositoryAccessor; private readonly IQueryLayerComposer _queryLayerComposer; private readonly IPaginationContext _paginationContext; private readonly IJsonApiOptions _options; private readonly TraceLogWriter<JsonApiResourceService<TResource, TId>> _traceWriter; private readonly IJsonApiRequest _request; private readonly IResourceChangeTracker<TResource> _resourceChangeTracker; private readonly IResourceDefinitionAccessor _resourceDefinitionAccessor; public JsonApiResourceService(IResourceRepositoryAccessor repositoryAccessor, IQueryLayerComposer queryLayerComposer, IPaginationContext paginationContext, IJsonApiOptions options, ILoggerFactory loggerFactory, IJsonApiRequest request, IResourceChangeTracker<TResource> resourceChangeTracker, IResourceDefinitionAccessor resourceDefinitionAccessor) { ArgumentGuard.NotNull(repositoryAccessor, nameof(repositoryAccessor)); ArgumentGuard.NotNull(queryLayerComposer, nameof(queryLayerComposer)); ArgumentGuard.NotNull(paginationContext, nameof(paginationContext)); ArgumentGuard.NotNull(options, nameof(options)); ArgumentGuard.NotNull(loggerFactory, nameof(loggerFactory)); ArgumentGuard.NotNull(request, nameof(request)); ArgumentGuard.NotNull(resourceChangeTracker, nameof(resourceChangeTracker)); ArgumentGuard.NotNull(resourceDefinitionAccessor, nameof(resourceDefinitionAccessor)); _repositoryAccessor = repositoryAccessor; _queryLayerComposer = queryLayerComposer; _paginationContext = paginationContext; _options = options; _request = request; _resourceChangeTracker = resourceChangeTracker; _resourceDefinitionAccessor = resourceDefinitionAccessor; _traceWriter = new TraceLogWriter<JsonApiResourceService<TResource, TId>>(loggerFactory); } /// <inheritdoc /> public virtual async Task<IReadOnlyCollection<TResource>> GetAsync(CancellationToken cancellationToken) { _traceWriter.LogMethodStart(); using IDisposable _ = CodeTimingSessionManager.Current.Measure("Service - Get resources"); if (_options.IncludeTotalResourceCount) { FilterExpression topFilter = _queryLayerComposer.GetTopFilterFromConstraints(_request.PrimaryResource); _paginationContext.TotalResourceCount = await _repositoryAccessor.CountAsync<TResource>(topFilter, cancellationToken); if (_paginationContext.TotalResourceCount == 0) { return Array.Empty<TResource>(); } } QueryLayer queryLayer = _queryLayerComposer.ComposeFromConstraints(_request.PrimaryResource); IReadOnlyCollection<TResource> resources = await _repositoryAccessor.GetAsync<TResource>(queryLayer, cancellationToken); if (queryLayer.Pagination?.PageSize != null && queryLayer.Pagination.PageSize.Value == resources.Count) { _paginationContext.IsPageFull = true; } return resources; } /// <inheritdoc /> public virtual async Task<TResource> GetAsync(TId id, CancellationToken cancellationToken) { _traceWriter.LogMethodStart(new { id }); using IDisposable _ = CodeTimingSessionManager.Current.Measure("Service - Get single resource"); return await GetPrimaryResourceByIdAsync(id, TopFieldSelection.PreserveExisting, cancellationToken); } /// <inheritdoc /> public virtual async Task<object> GetSecondaryAsync(TId id, string relationshipName, CancellationToken cancellationToken) { _traceWriter.LogMethodStart(new { id, relationshipName }); using IDisposable _ = CodeTimingSessionManager.Current.Measure("Service - Get secondary resource(s)"); AssertHasRelationship(_request.Relationship, relationshipName); QueryLayer secondaryLayer = _queryLayerComposer.ComposeFromConstraints(_request.SecondaryResource); QueryLayer primaryLayer = _queryLayerComposer.WrapLayerForSecondaryEndpoint(secondaryLayer, _request.PrimaryResource, id, _request.Relationship); IReadOnlyCollection<TResource> primaryResources = await _repositoryAccessor.GetAsync<TResource>(primaryLayer, cancellationToken); TResource primaryResource = primaryResources.SingleOrDefault(); AssertPrimaryResourceExists(primaryResource); object rightValue = _request.Relationship.GetValue(primaryResource); if (rightValue is ICollection rightResources && secondaryLayer.Pagination?.PageSize?.Value == rightResources.Count) { _paginationContext.IsPageFull = true; } return rightValue; } /// <inheritdoc /> public virtual async Task<object> GetRelationshipAsync(TId id, string relationshipName, CancellationToken cancellationToken) { _traceWriter.LogMethodStart(new { id, relationshipName }); ArgumentGuard.NotNullNorEmpty(relationshipName, nameof(relationshipName)); using IDisposable _ = CodeTimingSessionManager.Current.Measure("Service - Get relationship"); AssertHasRelationship(_request.Relationship, relationshipName); QueryLayer secondaryLayer = _queryLayerComposer.ComposeSecondaryLayerForRelationship(_request.SecondaryResource); QueryLayer primaryLayer = _queryLayerComposer.WrapLayerForSecondaryEndpoint(secondaryLayer, _request.PrimaryResource, id, _request.Relationship); IReadOnlyCollection<TResource> primaryResources = await _repositoryAccessor.GetAsync<TResource>(primaryLayer, cancellationToken); TResource primaryResource = primaryResources.SingleOrDefault(); AssertPrimaryResourceExists(primaryResource); return _request.Relationship.GetValue(primaryResource); } /// <inheritdoc /> public virtual async Task<TResource> CreateAsync(TResource resource, CancellationToken cancellationToken) { _traceWriter.LogMethodStart(new { resource }); ArgumentGuard.NotNull(resource, nameof(resource)); using IDisposable _ = CodeTimingSessionManager.Current.Measure("Service - Create resource"); TResource resourceFromRequest = resource; _resourceChangeTracker.SetRequestAttributeValues(resourceFromRequest); TResource resourceForDatabase = await _repositoryAccessor.GetForCreateAsync<TResource, TId>(resource.Id, cancellationToken); _resourceChangeTracker.SetInitiallyStoredAttributeValues(resourceForDatabase); await InitializeResourceAsync(resourceForDatabase, cancellationToken); try { await _repositoryAccessor.CreateAsync(resourceFromRequest, resourceForDatabase, cancellationToken); } catch (DataStoreUpdateException) { if (!Equals(resourceFromRequest.Id, default(TId))) { TResource existingResource = await TryGetPrimaryResourceByIdAsync(resourceFromRequest.Id, TopFieldSelection.OnlyIdAttribute, cancellationToken); if (existingResource != null) { throw new ResourceAlreadyExistsException(resourceFromRequest.StringId, _request.PrimaryResource.PublicName); } } await AssertResourcesToAssignInRelationshipsExistAsync(resourceFromRequest, cancellationToken); throw; } TResource resourceFromDatabase = await GetPrimaryResourceByIdAsync(resourceForDatabase.Id, TopFieldSelection.WithAllAttributes, cancellationToken); _resourceChangeTracker.SetFinallyStoredAttributeValues(resourceFromDatabase); bool hasImplicitChanges = _resourceChangeTracker.HasImplicitChanges(); return hasImplicitChanges ? resourceFromDatabase : null; } protected virtual async Task InitializeResourceAsync(TResource resourceForDatabase, CancellationToken cancellationToken) { await _resourceDefinitionAccessor.OnPrepareWriteAsync(resourceForDatabase, WriteOperationKind.CreateResource, cancellationToken); } protected async Task AssertResourcesToAssignInRelationshipsExistAsync(TResource primaryResource, CancellationToken cancellationToken) { var missingResources = new List<MissingResourceInRelationship>(); foreach ((QueryLayer queryLayer, RelationshipAttribute relationship) in _queryLayerComposer.ComposeForGetTargetedSecondaryResourceIds( primaryResource)) { object rightValue = relationship.GetValue(primaryResource); ICollection<IIdentifiable> rightResourceIds = _collectionConverter.ExtractResources(rightValue); IAsyncEnumerable<MissingResourceInRelationship> missingResourcesInRelationship = GetMissingRightResourcesAsync(queryLayer, relationship, rightResourceIds, cancellationToken); await missingResources.AddRangeAsync(missingResourcesInRelationship, cancellationToken); } if (missingResources.Any()) { throw new ResourcesInRelationshipsNotFoundException(missingResources); } } private async IAsyncEnumerable<MissingResourceInRelationship> GetMissingRightResourcesAsync(QueryLayer existingRightResourceIdsQueryLayer, RelationshipAttribute relationship, ICollection<IIdentifiable> rightResourceIds, [EnumeratorCancellation] CancellationToken cancellationToken) { IReadOnlyCollection<IIdentifiable> existingResources = await _repositoryAccessor.GetAsync( existingRightResourceIdsQueryLayer.ResourceContext.ResourceType, existingRightResourceIdsQueryLayer, cancellationToken); string[] existingResourceIds = existingResources.Select(resource => resource.StringId).ToArray(); foreach (IIdentifiable rightResourceId in rightResourceIds) { if (!existingResourceIds.Contains(rightResourceId.StringId)) { yield return new MissingResourceInRelationship(relationship.PublicName, existingRightResourceIdsQueryLayer.ResourceContext.PublicName, rightResourceId.StringId); } } } /// <inheritdoc /> public virtual async Task AddToToManyRelationshipAsync(TId leftId, string relationshipName, ISet<IIdentifiable> rightResourceIds, CancellationToken cancellationToken) { _traceWriter.LogMethodStart(new { leftId, rightResourceIds }); ArgumentGuard.NotNullNorEmpty(relationshipName, nameof(relationshipName)); ArgumentGuard.NotNull(rightResourceIds, nameof(rightResourceIds)); using IDisposable _ = CodeTimingSessionManager.Current.Measure("Service - Add to to-many relationship"); AssertHasRelationship(_request.Relationship, relationshipName); if (rightResourceIds.Any() && _request.Relationship is HasManyAttribute { IsManyToMany: true } manyToManyRelationship) { // In the case of a many-to-many relationship, creating a duplicate entry in the join table results in a // unique constraint violation. We avoid that by excluding already-existing entries from the set in advance. await RemoveExistingIdsFromRelationshipRightSideAsync(manyToManyRelationship, leftId, rightResourceIds, cancellationToken); } try { await _repositoryAccessor.AddToToManyRelationshipAsync<TResource, TId>(leftId, rightResourceIds, cancellationToken); } catch (DataStoreUpdateException) { await GetPrimaryResourceByIdAsync(leftId, TopFieldSelection.OnlyIdAttribute, cancellationToken); await AssertRightResourcesExistAsync(rightResourceIds, cancellationToken); throw; } } private async Task RemoveExistingIdsFromRelationshipRightSideAsync(HasManyAttribute hasManyRelationship, TId leftId, ISet<IIdentifiable> rightResourceIds, CancellationToken cancellationToken) { TResource leftResource = await GetForHasManyUpdateAsync(hasManyRelationship, leftId, rightResourceIds, cancellationToken); object rightValue = _request.Relationship.GetValue(leftResource); ICollection<IIdentifiable> existingRightResourceIds = _collectionConverter.ExtractResources(rightValue); rightResourceIds.ExceptWith(existingRightResourceIds); } private async Task<TResource> GetForHasManyUpdateAsync(HasManyAttribute hasManyRelationship, TId leftId, ISet<IIdentifiable> rightResourceIds, CancellationToken cancellationToken) { QueryLayer queryLayer = _queryLayerComposer.ComposeForHasMany(hasManyRelationship, leftId, rightResourceIds); IReadOnlyCollection<TResource> leftResources = await _repositoryAccessor.GetAsync<TResource>(queryLayer, cancellationToken); TResource leftResource = leftResources.FirstOrDefault(); AssertPrimaryResourceExists(leftResource); return leftResource; } protected async Task AssertRightResourcesExistAsync(object rightValue, CancellationToken cancellationToken) { ICollection<IIdentifiable> rightResourceIds = _collectionConverter.ExtractResources(rightValue); if (rightResourceIds.Any()) { QueryLayer queryLayer = _queryLayerComposer.ComposeForGetRelationshipRightIds(_request.Relationship, rightResourceIds); List<MissingResourceInRelationship> missingResources = await GetMissingRightResourcesAsync(queryLayer, _request.Relationship, rightResourceIds, cancellationToken).ToListAsync(cancellationToken); if (missingResources.Any()) { throw new ResourcesInRelationshipsNotFoundException(missingResources); } } } /// <inheritdoc /> public virtual async Task<TResource> UpdateAsync(TId id, TResource resource, CancellationToken cancellationToken) { _traceWriter.LogMethodStart(new { id, resource }); ArgumentGuard.NotNull(resource, nameof(resource)); using IDisposable _ = CodeTimingSessionManager.Current.Measure("Service - Update resource"); TResource resourceFromRequest = resource; _resourceChangeTracker.SetRequestAttributeValues(resourceFromRequest); TResource resourceFromDatabase = await GetPrimaryResourceForUpdateAsync(id, cancellationToken); _resourceChangeTracker.SetInitiallyStoredAttributeValues(resourceFromDatabase); await _resourceDefinitionAccessor.OnPrepareWriteAsync(resourceFromDatabase, WriteOperationKind.UpdateResource, cancellationToken); try { await _repositoryAccessor.UpdateAsync(resourceFromRequest, resourceFromDatabase, cancellationToken); } catch (DataStoreUpdateException) { await AssertResourcesToAssignInRelationshipsExistAsync(resourceFromRequest, cancellationToken); throw; } TResource afterResourceFromDatabase = await GetPrimaryResourceByIdAsync(id, TopFieldSelection.WithAllAttributes, cancellationToken); _resourceChangeTracker.SetFinallyStoredAttributeValues(afterResourceFromDatabase); bool hasImplicitChanges = _resourceChangeTracker.HasImplicitChanges(); return hasImplicitChanges ? afterResourceFromDatabase : null; } /// <inheritdoc /> public virtual async Task SetRelationshipAsync(TId leftId, string relationshipName, object rightValue, CancellationToken cancellationToken) { _traceWriter.LogMethodStart(new { leftId, relationshipName, rightValue }); ArgumentGuard.NotNullNorEmpty(relationshipName, nameof(relationshipName)); using IDisposable _ = CodeTimingSessionManager.Current.Measure("Service - Set relationship"); AssertHasRelationship(_request.Relationship, relationshipName); TResource resourceFromDatabase = await GetPrimaryResourceForUpdateAsync(leftId, cancellationToken); await _resourceDefinitionAccessor.OnPrepareWriteAsync(resourceFromDatabase, WriteOperationKind.SetRelationship, cancellationToken); try { await _repositoryAccessor.SetRelationshipAsync(resourceFromDatabase, rightValue, cancellationToken); } catch (DataStoreUpdateException) { await AssertRightResourcesExistAsync(rightValue, cancellationToken); throw; } } /// <inheritdoc /> public virtual async Task DeleteAsync(TId id, CancellationToken cancellationToken) { _traceWriter.LogMethodStart(new { id }); using IDisposable _ = CodeTimingSessionManager.Current.Measure("Repository - Delete resource"); try { await _repositoryAccessor.DeleteAsync<TResource, TId>(id, cancellationToken); } catch (DataStoreUpdateException) { await GetPrimaryResourceByIdAsync(id, TopFieldSelection.OnlyIdAttribute, cancellationToken); throw; } } /// <inheritdoc /> public virtual async Task RemoveFromToManyRelationshipAsync(TId leftId, string relationshipName, ISet<IIdentifiable> rightResourceIds, CancellationToken cancellationToken) { _traceWriter.LogMethodStart(new { leftId, relationshipName, rightResourceIds }); ArgumentGuard.NotNullNorEmpty(relationshipName, nameof(relationshipName)); ArgumentGuard.NotNull(rightResourceIds, nameof(rightResourceIds)); using IDisposable _ = CodeTimingSessionManager.Current.Measure("Repository - Remove from to-many relationship"); AssertHasRelationship(_request.Relationship, relationshipName); var hasManyRelationship = (HasManyAttribute)_request.Relationship; TResource resourceFromDatabase = await GetForHasManyUpdateAsync(hasManyRelationship, leftId, rightResourceIds, cancellationToken); await AssertRightResourcesExistAsync(rightResourceIds, cancellationToken); await _repositoryAccessor.RemoveFromToManyRelationshipAsync(resourceFromDatabase, rightResourceIds, cancellationToken); } protected async Task<TResource> GetPrimaryResourceByIdAsync(TId id, TopFieldSelection fieldSelection, CancellationToken cancellationToken) { TResource primaryResource = await TryGetPrimaryResourceByIdAsync(id, fieldSelection, cancellationToken); AssertPrimaryResourceExists(primaryResource); return primaryResource; } private async Task<TResource> TryGetPrimaryResourceByIdAsync(TId id, TopFieldSelection fieldSelection, CancellationToken cancellationToken) { QueryLayer primaryLayer = _queryLayerComposer.ComposeForGetById(id, _request.PrimaryResource, fieldSelection); IReadOnlyCollection<TResource> primaryResources = await _repositoryAccessor.GetAsync<TResource>(primaryLayer, cancellationToken); return primaryResources.SingleOrDefault(); } protected async Task<TResource> GetPrimaryResourceForUpdateAsync(TId id, CancellationToken cancellationToken) { QueryLayer queryLayer = _queryLayerComposer.ComposeForUpdate(id, _request.PrimaryResource); var resource = await _repositoryAccessor.GetForUpdateAsync<TResource>(queryLayer, cancellationToken); AssertPrimaryResourceExists(resource); return resource; } [AssertionMethod] private void AssertPrimaryResourceExists(TResource resource) { if (resource == null) { throw new ResourceNotFoundException(_request.PrimaryId, _request.PrimaryResource.PublicName); } } [AssertionMethod] private void AssertHasRelationship(RelationshipAttribute relationship, string name) { if (relationship == null) { throw new RelationshipNotFoundException(name, _request.PrimaryResource.PublicName); } } } /// <summary> /// Represents the foundational Resource Service layer in the JsonApiDotNetCore architecture that uses a Resource Repository for data access. /// </summary> /// <typeparam name="TResource"> /// The resource type. /// </typeparam> [PublicAPI] public class JsonApiResourceService<TResource> : JsonApiResourceService<TResource, int>, IResourceService<TResource> where TResource : class, IIdentifiable<int> { public JsonApiResourceService(IResourceRepositoryAccessor repositoryAccessor, IQueryLayerComposer queryLayerComposer, IPaginationContext paginationContext, IJsonApiOptions options, ILoggerFactory loggerFactory, IJsonApiRequest request, IResourceChangeTracker<TResource> resourceChangeTracker, IResourceDefinitionAccessor resourceDefinitionAccessor) : base(repositoryAccessor, queryLayerComposer, paginationContext, options, loggerFactory, request, resourceChangeTracker, resourceDefinitionAccessor) { } } }
using System; using System.Text; using Jsonics.FromJson; namespace Jsonics.FromJson { public struct LazyString { readonly string _buffer; readonly int _start; readonly int _length; public LazyString(string buffer) { _buffer = buffer; _start = 0; _length = buffer.Length; } public string Buffer => _buffer; public int Start => _start; public int Length => _length; public LazyString(string buffer, int start, int length) { _buffer = buffer; _start = start; _length = length; } public LazyString SubString(int start, int length) { return new LazyString(_buffer, _start + start, length); } public override string ToString() { return _buffer.Substring(_start, _length); } public int ReadTo(int start, char value) { int end = _start + _length; for(int index = _start + start; index < end; index++) { if(_buffer[index] == value) { return index - _start; } } return -1; } public (int, char) ReadToAny(int start, char value1, char value2) { int end = _start + _length; for(int index = _start + start; index < end; index++) { if(_buffer[index] == value1) { return (index - _start, value1); } else if(_buffer[index] == value2) { return (index - _start, value2); } } return (-1, ' '); } public int SkipWhitespace(int start) { int end = _start + _length; for(int index = _start + start; index < end; index++) { var character = _buffer[index]; switch(character) { case ' ': case '\r': case '\n': case '\t': continue; default: return index - _start; } } return -1; } public int ReadToPropertyValueEnd(int start) { int unclosedBrakets = 0; int end = _start + _length; for(int index = _start + start; index < end; index++) { int value = _buffer[index]; if(value == '{') { unclosedBrakets++; } else if(value == '}') { if(unclosedBrakets == 0) { //end of object return index; } unclosedBrakets--; } else if(value == '\\') { index++; //skip because next character is escaped continue; } if(value == ',' && unclosedBrakets == 0) { return index; } } throw new InvalidJsonException($"Property starting at {start + _start} didn't end."); } public char At(int index) { return _buffer[index + _start]; } public bool EqualsString(string other) { if(_length != other.Length) { return false; } for(int index = 0; index < other.Length; index++) { if(other[index] != _buffer[index + _start]) { return false; } } return true; } bool IsNumber(char character) { return character >= '0' && character <= '9'; } [ThreadStatic] static StringBuilder _builder = new StringBuilder(); public (string, int) ToString(int start) { int index = start + _start; while(true) { var value = _buffer[index]; if(value == 'n') { //null return (null, index + 4 - _start); } else if(value == '\"') { break; } index++; } _builder.Clear(); index++; while(true) { char value = _buffer[index]; if(value == '\\') { //escape character index++; value = _buffer[index]; switch(value) { case '\"': case '\\': case '/': _builder.Append(value); break; case 'b': _builder.Append('\b'); break; case 'f': _builder.Append('\f'); break; case 'n': _builder.Append('\n'); break; case 'r': _builder.Append('\r'); break; case 't': _builder.Append('\t'); break; case 'u': index++; _builder.Append(FromHex(index)); index += 3; break; } index++; continue; } else if(value == '\"') { //end of string value return (_builder.ToString(), index + 1 - _start); } _builder.Append(value); index++; } //we got to the end of the lazy string without finding the end of string character throw new InvalidJsonException("Missing end of string value"); } public (char, int) ToChar(int start) { int index = start + _start; char value; while(true) { value = _buffer[index]; if(value == '\"') { break; } index++; } index++; value = _buffer[index]; if(value == '\\') { //escape character index++; value = _buffer[index]; switch(value) { case '\"': case '\\': case '/': return (value, index + 2 - _start); case 'b': return ('\b', index + 2 - _start); case 'f': return ('\f', index + 2 - _start); case 'n': return ('\n', index + 2 - _start); case 'r': return ('\r', index + 2 - _start); case 't': return ('\t', index + 2 - _start); case 'u': index++; return (FromHex(index), index + 5 - _start); default: throw new InvalidJsonException("Invalid char escape sequence"); } } index++; return (value, index + 1 - _start); } public (char?, int) ToNullableChar(int start) { int index = start + _start; char value; while(true) { value = _buffer[index]; if(value == 'n') { //null return (null, index + 4 - _start); } else if(value == '\"') { break; } index++; } index++; value = _buffer[index]; if(value == '\\') { //escape character index++; value = _buffer[index]; switch(value) { case '\"': case '\\': case '/': return (value, index + 2 - _start); case 'b': return ('\b', index + 2 - _start); case 'f': return ('\f', index + 2 - _start); case 'n': return ('\n', index + 2 - _start); case 'r': return ('\r', index + 2 - _start); case 't': return ('\t', index + 2 - _start); case 'u': index++; return (FromHex(index), index + 5 - _start); default: throw new InvalidJsonException("Invalid char escape sequence"); } } index++; return (value, index + 1 - _start); } byte FromHexChar(char character) { switch(character) { case '0': return 0; case '1': return 1; case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; case 'a': return 10; case 'A': return 10; case 'b': return 11; case 'B': return 11; case 'c': return 12; case 'C': return 12; case 'd': return 13; case 'D': return 13; case 'e': return 14; case 'E': return 14; case 'f': return 15; case 'F': return 15; default: throw new InvalidJsonException("character must be a hex value"); } } char FromHex(int internalStart) { int value = (FromHexChar(_buffer[internalStart]) << 12) + (FromHexChar(_buffer[internalStart + 1]) << 8) + (FromHexChar(_buffer[internalStart + 2]) << 4) + (FromHexChar(_buffer[internalStart + 3])); return (char)value; } public (bool, int) ToBool(int start) { int index = start + _start; while(true) { var value = _buffer[index]; if(value == 't') { return (true, index + 4 - _start); } else if(value == 'f') { return (false, index + 5 - _start); } index++; } } public (bool?, int) ToNullableBool(int start) { int index = start + _start; while(true) { var character = _buffer[index]; if(character == 'n') { return (null, index + 4 - _start); } else if(character == 't') { return (true, index + 4 - _start); } else if(character == 'f') { return (false, index + 5 - _start); } index++; } } public (sbyte, int) ToSByte(int start) { (int result, int index) = ToInt(start); return ((sbyte)result, index); } public (byte,int) ToByte(int start) { int index = start + _start; //skip any whitespace at start char character = ' '; while(true) { character = _buffer[index]; if(IsNumber(character)) { break; } index++; } int end = _start + _length; //read byte int soFar = 0; if(!IsNumber(character)) goto Return; soFar += character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; Return: return ((byte)soFar, index - _start) ; } public (byte?,int) ToNullableByte(int start) { int index = start + _start; //skip any whitespace at start char character = ' '; while(true) { character = _buffer[index]; if(character == 'n') { return (null, index + 4 - _start); } else if(IsNumber(character)) { break; } index++; } int end = _start + _length; //read byte int soFar = 0; if(!IsNumber(character)) goto Return; soFar += character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; Return: return ((byte)soFar, index - _start) ; } public (short, int) ToShort(int start) { (int result, int index) = ToInt(start); return ((short)result, index); } public (short?, int) ToNullableShort(int start) { (int? result, int index) = ToNullableInt(start); return ((short?)result, index); } public (ushort, int) ToUShort(int start) { (uint result, int index) = ToUInt(start); return ((ushort)result, index); } public (ushort?, int) ToNullableUShort(int start) { (uint? result, int index) = ToNullableUInt(start); return ((ushort?)result, index); } public (sbyte?, int) ToNullableSByte(int start) { (int? result, int index) = ToNullableInt(start); return ((sbyte?)result, index); } public (int,int) ToInt(int start) { int index = start + _start; int sign = 1; //skip any whitespace at start char character = ' '; while(true) { character = _buffer[index]; if(IsNumber(character)) { break; } else if(character == '-') { index++; sign = -1; break; } index++; } int end = _start + _length; int soFar = 0; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar += character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; Return: return (soFar * sign, index - _start) ; } public (int?,int) ToNullableInt(int start) { int index = start + _start; int sign = 1; //skip any whitespace at start char character = ' '; while(true) { character = _buffer[index]; if(character == 'n') { return (null, index + 4 - _start); } else if(IsNumber(character)) { break; } else if(character == '-') { index++; sign = -1; break; } index++; } int end = _start + _length; int soFar = 0; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar += character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; Return: return (soFar * sign, index - _start) ; } public (uint,int) ToUInt(int start) { int index = start + _start; //skip any whitespace at start char character = ' '; while(true) { character = _buffer[index]; if(IsNumber(character)) { break; } index++; } int end = _start + _length; uint soFar = 0; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar += (uint)character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; Return: return (soFar, index - _start) ; } public (uint?,int) ToNullableUInt(int start) { int index = start + _start; //skip any whitespace at start char character = ' '; while(true) { character = _buffer[index]; if(character == 'n') { return (null, index + 4 - _start); } else if (IsNumber(character)) { break; } index++; } int end = _start + _length; uint soFar = 0; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar += (uint)character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; if(index >= end) goto Return; character = _buffer[index]; if(!IsNumber(character)) goto Return; soFar = (soFar*10) + character - '0'; index++; Return: return (soFar, index - _start) ; } public (decimal, int) ToDecimal(int start) { int index = start + _start; int sign = 1; //skip any whitespace at start char character = ' '; while(true) { character = _buffer[index]; if(IsNumber(character)) { break; } else if(character == '-') { index++; sign = -1; break; } index++; } int end = _start + _length; decimal wholePart = 0; for(index = index+0; index < end; index++) { character = _buffer[index]; if(!IsNumber(character)) break; wholePart = (wholePart*10M) + (character - '0'); } decimal fractionalPart = 0; if(character == '.') { long fractionalValue = 0; int factionalLength = 0; for(index = index+1; index < end; index++) { character = _buffer[index]; if(!IsNumber(character)) break; fractionalValue = (fractionalValue*10) + character - '0'; factionalLength++; } decimal divisor = (decimal)Math.Pow(10, factionalLength); fractionalPart = fractionalValue/divisor; } return (sign*(wholePart + fractionalPart), index - _start); } public (decimal?, int) ToNullableDecimal(int start) { int index = start + _start; int sign = 1; //skip any whitespace at start char character = ' '; while(true) { character = _buffer[index]; if(character == 'n') { return (null, index + 4 - _start); } else if(IsNumber(character)) { break; } else if(character == '-') { index++; sign = -1; break; } index++; } int end = _start + _length; decimal wholePart = 0; for(index = index+0; index < end; index++) { character = _buffer[index]; if(!IsNumber(character)) break; wholePart = (wholePart*10M) + (character - '0'); } decimal fractionalPart = 0; if(character == '.') { long fractionalValue = 0; int factionalLength = 0; for(index = index+1; index < end; index++) { character = _buffer[index]; if(!IsNumber(character)) break; fractionalValue = (fractionalValue*10) + character - '0'; factionalLength++; } decimal divisor = (decimal)Math.Pow(10, factionalLength); fractionalPart = fractionalValue/divisor; } return (sign*(wholePart + fractionalPart), index - _start); } public (long, int) ToLong(int start) { int index = start + _start; int sign = 1; //skip any whitespace at start char character = ' '; while(true) { character = _buffer[index]; if(IsNumber(character)) { break; } else if(character == '-') { index++; sign = -1; break; } index++; } int end = _start + _length; long soFar = 0; for(index = index+0; index < end; index++) { character = _buffer[index]; if(!IsNumber(character)) break; soFar = (soFar*10) + character - '0'; } return (soFar * sign, index - _start) ; } public (long?, int) ToNullableLong(int start) { int index = start + _start; int sign = 1; //skip any whitespace at start char character = ' '; while(true) { character = _buffer[index]; if(character == 'n') { return (null, index + 4 - _start); } else if(IsNumber(character)) { break; } else if(character == '-') { index++; sign = -1; break; } index++; } int end = _start + _length; long soFar = 0; for(index = index+0; index < end; index++) { character = _buffer[index]; if(!IsNumber(character)) break; soFar = (soFar*10) + character - '0'; } return (soFar * sign, index - _start) ; } public (ulong, int) ToULong(int start) { int index = start + _start; //skip any whitespace at start char character = ' '; while(true) { character = _buffer[index]; if(IsNumber(character)) { break; } index++; } int end = _start + _length; ulong soFar = 0; for(index = index+0; index < end; index++) { character = _buffer[index]; if(!IsNumber(character)) break; soFar = (soFar*10) + character - '0'; } return (soFar, index - _start) ; } public (ulong?, int) ToNullableULong(int start) { int index = start + _start; //skip any whitespace at start char character = ' '; while(true) { character = _buffer[index]; if(character == 'n') { return (null, index + 4 - _start); } else if(IsNumber(character)) { break; } index++; } int end = _start + _length; ulong soFar = 0; for(index = index+0; index < end; index++) { character = _buffer[index]; if(!IsNumber(character)) break; soFar = (soFar*10) + character - '0'; } return (soFar, index - _start) ; } public (double?, int) ToNullableDouble(int start) { int index = start + _start; int sign = 1; //skip any whitespace at start char character = ' '; while(true) { character = _buffer[index]; if(character == 'n') { return (null, index + 4 - _start); } else if(IsNumber(character)) { break; } else if(character == '-') { index++; sign = -1; break; } index++; } int end = _start + _length; double wholePart = 0; for(index = index+0; index < end; index++) { character = _buffer[index]; if(!IsNumber(character)) break; wholePart = (wholePart*10) + character - '0'; } double fractionalPart = 0; if(character == '.') { long fractionalValue = 0; int factionalLength = 0; for(index = index+1; index < end; index++) { character = _buffer[index]; if(!IsNumber(character)) break; fractionalValue = (fractionalValue*10) + character - '0'; factionalLength++; } double divisor = Math.Pow(10, factionalLength); fractionalPart = fractionalValue/divisor; } int exponentPart = 0; if(character == 'E' || character == 'e') { index++; character = _buffer[index]; int exponentSign = 1; if(character == '-') { index++; exponentSign = -1; } else if(character == '+') { index++; } for(index = index+0; index < end; index++) { character = _buffer[index]; if(!IsNumber(character)) break; exponentPart = (exponentPart*10) + character - '0'; } exponentPart *= exponentSign; } else { return (sign*(wholePart + fractionalPart), index - _start); } double value = sign*(wholePart + fractionalPart) * Math.Pow(10, exponentPart); return (value, index - _start); } public (double, int) ToDouble(int start) { int index = start + _start; int sign = 1; //skip any whitespace at start char character = ' '; while(true) { character = _buffer[index]; if(IsNumber(character)) { break; } else if(character == '-') { index++; sign = -1; break; } index++; } int end = _start + _length; double wholePart = 0; for(index = index+0; index < end; index++) { character = _buffer[index]; if(!IsNumber(character)) break; wholePart = (wholePart*10) + character - '0'; } double fractionalPart = 0; if(character == '.') { long fractionalValue = 0; int factionalLength = 0; for(index = index+1; index < end; index++) { character = _buffer[index]; if(!IsNumber(character)) break; fractionalValue = (fractionalValue*10) + character - '0'; factionalLength++; } double divisor = Math.Pow(10, factionalLength); fractionalPart = fractionalValue/divisor; } int exponentPart = 0; if(character == 'E' || character == 'e') { index++; character = _buffer[index]; int exponentSign = 1; if(character == '-') { index++; exponentSign = -1; } else if(character == '+') { index++; } for(index = index+0; index < end; index++) { character = _buffer[index]; if(!IsNumber(character)) break; exponentPart = (exponentPart*10) + character - '0'; } exponentPart *= exponentSign; } else { return (sign*(wholePart + fractionalPart), index - _start); } double value = sign*(wholePart + fractionalPart) * Math.Pow(10, exponentPart); return (value, index - _start); } public (float, int) ToFloat(int start) { (double value, int index) = ToDouble(start); return ((float)value, index); } public (float?, int) ToNullableFloat(int start) { (double? value, int index) = ToNullableDouble(start); return ((float?)value, index); } public (Guid, int) ToGuid(int start) { start += _start; //skip any whitespace at start char character = ' '; while(true) { character = _buffer[start]; start++; if(character == '\"') { break; } } uint a = ((uint)FromHexChar(_buffer[start]) << 28) + ((uint)FromHexChar(_buffer[start + 1]) << 24) + (uint)(FromHexChar(_buffer[start + 2]) << 20) + (uint)(FromHexChar(_buffer[start + 3]) << 16) + (uint)(FromHexChar(_buffer[start + 4]) << 12) + (uint)(FromHexChar(_buffer[start + 5]) << 8) + (uint)(FromHexChar(_buffer[start + 6]) << 4) + (uint)FromHexChar(_buffer[start + 7]); ushort b = (ushort) ((FromHexChar(_buffer[start + 9]) << 12) + (FromHexChar(_buffer[start + 10]) << 8) + (FromHexChar(_buffer[start + 11]) << 4) + FromHexChar(_buffer[start + 12])); ushort c = (ushort) ((FromHexChar(_buffer[start + 14]) << 12) + (FromHexChar(_buffer[start + 15]) << 8) + (FromHexChar(_buffer[start + 16]) << 4) + FromHexChar(_buffer[start + 17])); byte d = (byte)((FromHexChar(_buffer[start + 19]) << 4) + FromHexChar(_buffer[start + 20])); byte e = (byte)((FromHexChar(_buffer[start + 21]) << 4) + FromHexChar(_buffer[start + 22])); byte f = (byte)((FromHexChar(_buffer[start + 24]) << 4) + FromHexChar(_buffer[start + 25])); byte g = (byte)((FromHexChar(_buffer[start + 26]) << 4) + FromHexChar(_buffer[start + 27])); byte h = (byte)((FromHexChar(_buffer[start + 28]) << 4) + FromHexChar(_buffer[start + 29])); byte i = (byte)((FromHexChar(_buffer[start + 30]) << 4) + FromHexChar(_buffer[start + 31])); byte j = (byte)((FromHexChar(_buffer[start + 32]) << 4) + FromHexChar(_buffer[start + 33])); byte k = (byte)((FromHexChar(_buffer[start + 34]) << 4) + FromHexChar(_buffer[start + 35])); var guid = new Guid(a, b, c, d, e, f, g, h, i, j, k); return (guid, start + 37 - _start); } public (Guid?, int) ToNullableGuid(int start) { start += _start; //skip any whitespace at start char character = ' '; while(true) { character = _buffer[start]; start++; if(character == 'n') { if(character == 'n') { return (null, start + 3 - _start); } } else if (character == '\"') { break; } } uint a = ((uint)FromHexChar(_buffer[start]) << 28) + ((uint)FromHexChar(_buffer[start + 1]) << 24) + (uint)(FromHexChar(_buffer[start + 2]) << 20) + (uint)(FromHexChar(_buffer[start + 3]) << 16) + (uint)(FromHexChar(_buffer[start + 4]) << 12) + (uint)(FromHexChar(_buffer[start + 5]) << 8) + (uint)(FromHexChar(_buffer[start + 6]) << 4) + (uint)FromHexChar(_buffer[start + 7]); ushort b = (ushort) ((FromHexChar(_buffer[start + 9]) << 12) + (FromHexChar(_buffer[start + 10]) << 8) + (FromHexChar(_buffer[start + 11]) << 4) + FromHexChar(_buffer[start + 12])); ushort c = (ushort) ((FromHexChar(_buffer[start + 14]) << 12) + (FromHexChar(_buffer[start + 15]) << 8) + (FromHexChar(_buffer[start + 16]) << 4) + FromHexChar(_buffer[start + 17])); byte d = (byte)((FromHexChar(_buffer[start + 19]) << 4) + FromHexChar(_buffer[start + 20])); byte e = (byte)((FromHexChar(_buffer[start + 21]) << 4) + FromHexChar(_buffer[start + 22])); byte f = (byte)((FromHexChar(_buffer[start + 24]) << 4) + FromHexChar(_buffer[start + 25])); byte g = (byte)((FromHexChar(_buffer[start + 26]) << 4) + FromHexChar(_buffer[start + 27])); byte h = (byte)((FromHexChar(_buffer[start + 28]) << 4) + FromHexChar(_buffer[start + 29])); byte i = (byte)((FromHexChar(_buffer[start + 30]) << 4) + FromHexChar(_buffer[start + 31])); byte j = (byte)((FromHexChar(_buffer[start + 32]) << 4) + FromHexChar(_buffer[start + 33])); byte k = (byte)((FromHexChar(_buffer[start + 34]) << 4) + FromHexChar(_buffer[start + 35])); var guid = new Guid(a, b, c, d, e, f, g, h, i, j, k); return (guid, start + 37 - _start); } } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; namespace BinxEd { /// <summary> /// Summary description for FormCase. /// </summary> public class FormCase : System.Windows.Forms.Form { private string varName_; private string[] userTypes; //reference to external instance of user-defined type strings private System.Windows.Forms.Button buttonOK; private System.Windows.Forms.TextBox textBoxValue; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button buttonCancel; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.ComboBox comboBox1; private System.Windows.Forms.TextBox textBoxVarName; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public FormCase() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.buttonOK = new System.Windows.Forms.Button(); this.textBoxValue = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.buttonCancel = new System.Windows.Forms.Button(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.label4 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.textBoxVarName = new System.Windows.Forms.TextBox(); this.comboBox1 = new System.Windows.Forms.ComboBox(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // buttonOK // this.buttonOK.DialogResult = System.Windows.Forms.DialogResult.OK; this.buttonOK.Location = new System.Drawing.Point(120, 144); this.buttonOK.Name = "buttonOK"; this.buttonOK.Size = new System.Drawing.Size(72, 24); this.buttonOK.TabIndex = 14; this.buttonOK.Text = "OK"; // // textBoxValue // this.textBoxValue.Location = new System.Drawing.Point(136, 8); this.textBoxValue.Name = "textBoxValue"; this.textBoxValue.Size = new System.Drawing.Size(136, 20); this.textBoxValue.TabIndex = 9; this.textBoxValue.Text = "1"; this.textBoxValue.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; // // label1 // this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.label1.Location = new System.Drawing.Point(14, 8); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(114, 16); this.label1.TabIndex = 7; this.label1.Text = "Discriminant Value"; // // buttonCancel // this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonCancel.Location = new System.Drawing.Point(200, 144); this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.Size = new System.Drawing.Size(72, 24); this.buttonCancel.TabIndex = 13; this.buttonCancel.Text = "Cancel"; // // groupBox1 // this.groupBox1.Controls.Add(this.label4); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.textBoxVarName); this.groupBox1.Controls.Add(this.comboBox1); this.groupBox1.Location = new System.Drawing.Point(16, 40); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(256, 96); this.groupBox1.TabIndex = 15; this.groupBox1.TabStop = false; this.groupBox1.Text = "Body Data"; // // label4 // this.label4.Location = new System.Drawing.Point(16, 56); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(48, 16); this.label4.TabIndex = 15; this.label4.Text = "Name:"; // // label3 // this.label3.Location = new System.Drawing.Point(16, 24); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(40, 24); this.label3.TabIndex = 14; this.label3.Text = "Type:"; // // textBoxVarName // this.textBoxVarName.Location = new System.Drawing.Point(64, 56); this.textBoxVarName.Name = "textBoxVarName"; this.textBoxVarName.Size = new System.Drawing.Size(176, 20); this.textBoxVarName.TabIndex = 13; this.textBoxVarName.Text = ""; // // comboBox1 // this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.comboBox1.Items.AddRange(new object[] { "byte-8", "unsignedByte-8", "short-16", "unsignedShort-16", "integer-32", "unsignedInteger-32", "long-64", "unsignedLong-64", "character-8"}); this.comboBox1.Location = new System.Drawing.Point(64, 24); this.comboBox1.Name = "comboBox1"; this.comboBox1.Size = new System.Drawing.Size(176, 21); this.comboBox1.TabIndex = 11; // // FormCase // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(292, 181); this.Controls.Add(this.groupBox1); this.Controls.Add(this.buttonOK); this.Controls.Add(this.textBoxValue); this.Controls.Add(this.label1); this.Controls.Add(this.buttonCancel); this.Name = "FormCase"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Union Case"; this.Closing += new System.ComponentModel.CancelEventHandler(this.FormCase_Closing); this.Load += new System.EventHandler(this.FormCase_Load); this.groupBox1.ResumeLayout(false); this.ResumeLayout(false); } #endregion private void FormCase_Load(object sender, System.EventArgs e) { if (varName_ != null) { textBoxVarName.Text = varName_; } if (userTypes != null && userTypes.Length > 0) { comboBox1.Items.Clear(); comboBox1.Items.AddRange(userTypes); } if (comboBox1.Items.Count > 0) { comboBox1.SelectedIndex = 0; } } /// <summary> /// Validate case value before closing input window. /// </summary> /// <remarks> /// Can't validate case body here as it is unknown which case it is. /// </remarks> /// <param name="sender"></param> /// <param name="e"></param> private void FormCase_Closing(object sender, System.ComponentModel.CancelEventArgs e) { if (this.DialogResult==DialogResult.Yes && textBoxValue.Text.Trim().Equals("")) { MessageBox.Show(this, "Case value must not be empty"); e.Cancel = true; } } /// <summary> /// Set data types array reference /// </summary> public string[] DataTypeSource { set { userTypes = value; } } public string DiscriminantValue { get { return textBoxValue.Text; } } public string SelectedType { get { return comboBox1.Text; } } public string VarName { get { return textBoxVarName.Text; } set { varName_ = value; } } } }
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using ZXing.Common; using ZXing.QrCode.Internal; namespace ZXing.QrCode { /// <summary> /// This implementation can detect and decode QR Codes in an image. /// <author>Sean Owen</author> /// </summary> internal class QRCodeReader : Reader { private static readonly ResultPoint[] NO_POINTS = new ResultPoint[0]; private readonly Decoder decoder = new Decoder(); /// <summary> /// Gets the decoder. /// </summary> /// <returns></returns> protected Decoder getDecoder() { return decoder; } /// <summary> /// Locates and decodes a QR code in an image. /// /// <returns>a String representing the content encoded by the QR code</returns> /// </summary> public Result decode(BinaryBitmap image) { return decode(image, null); } /// <summary> /// Locates and decodes a barcode in some format within an image. This method also accepts /// hints, each possibly associated to some data, which may help the implementation decode. /// </summary> /// <param name="image">image of barcode to decode</param> /// <param name="hints">passed as a <see cref="IDictionary{TKey, TValue}"/> from <see cref="DecodeHintType"/> /// to arbitrary data. The /// meaning of the data depends upon the hint type. The implementation may or may not do /// anything with these hints.</param> /// <returns> /// String which the barcode encodes /// </returns> public Result decode(BinaryBitmap image, IDictionary<DecodeHintType, object> hints) { DecoderResult decoderResult; ResultPoint[] points; if (image == null || image.BlackMatrix == null) { // something is wrong with the image return null; } if (hints != null && hints.ContainsKey(DecodeHintType.PURE_BARCODE)) { var bits = extractPureBits(image.BlackMatrix); if (bits == null) return null; decoderResult = decoder.decode(bits, hints); points = NO_POINTS; } else { var detectorResult = new Detector(image.BlackMatrix).detect(hints); if (detectorResult == null) return null; decoderResult = decoder.decode(detectorResult.Bits, hints); points = detectorResult.Points; } if (decoderResult == null) return null; // If the code was mirrored: swap the bottom-left and the top-right points. var data = decoderResult.Other as QRCodeDecoderMetaData; if (data != null) { data.applyMirroredCorrection(points); } var result = new Result(decoderResult.Text, decoderResult.RawBytes, points, BarcodeFormat.QR_CODE); var byteSegments = decoderResult.ByteSegments; if (byteSegments != null) { result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments); } var ecLevel = decoderResult.ECLevel; if (ecLevel != null) { result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel); } if (decoderResult.StructuredAppend) { result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_SEQUENCE, decoderResult.StructuredAppendSequenceNumber); result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_PARITY, decoderResult.StructuredAppendParity); } return result; } /// <summary> /// Resets any internal state the implementation has after a decode, to prepare it /// for reuse. /// </summary> public void reset() { // do nothing } /// <summary> /// This method detects a code in a "pure" image -- that is, pure monochrome image /// which contains only an unrotated, unskewed, image of a code, with some white border /// around it. This is a specialized method that works exceptionally fast in this special /// case. /// /// <seealso cref="ZXing.Datamatrix.DataMatrixReader.extractPureBits(BitMatrix)" /> /// </summary> private static BitMatrix extractPureBits(BitMatrix image) { int[] leftTopBlack = image.getTopLeftOnBit(); int[] rightBottomBlack = image.getBottomRightOnBit(); if (leftTopBlack == null || rightBottomBlack == null) { return null; } float moduleSize; if (!QRCodeReader.moduleSize(leftTopBlack, image, out moduleSize)) return null; int top = leftTopBlack[1]; int bottom = rightBottomBlack[1]; int left = leftTopBlack[0]; int right = rightBottomBlack[0]; // Sanity check! if (left >= right || top >= bottom) { return null; } if (bottom - top != right - left) { // Special case, where bottom-right module wasn't black so we found something else in the last row // Assume it's a square, so use height as the width right = left + (bottom - top); } int matrixWidth = (int)Math.Round((right - left + 1) / moduleSize); int matrixHeight = (int)Math.Round((bottom - top + 1) / moduleSize); if (matrixWidth <= 0 || matrixHeight <= 0) { return null; } if (matrixHeight != matrixWidth) { // Only possibly decode square regions return null; } // Push in the "border" by half the module width so that we start // sampling in the middle of the module. Just in case the image is a // little off, this will help recover. int nudge = (int)(moduleSize / 2.0f); top += nudge; left += nudge; // But careful that this does not sample off the edge int nudgedTooFarRight = left + (int)((matrixWidth - 1) * moduleSize) - (right - 1); if (nudgedTooFarRight > 0) { if (nudgedTooFarRight > nudge) { // Neither way fits; abort return null; } left -= nudgedTooFarRight; } int nudgedTooFarDown = top + (int)((matrixHeight - 1) * moduleSize) - (bottom - 1); if (nudgedTooFarDown > 0) { if (nudgedTooFarDown > nudge) { // Neither way fits; abort return null; } top -= nudgedTooFarDown; } // Now just read off the bits BitMatrix bits = new BitMatrix(matrixWidth, matrixHeight); for (int y = 0; y < matrixHeight; y++) { int iOffset = top + (int)(y * moduleSize); for (int x = 0; x < matrixWidth; x++) { if (image[left + (int)(x * moduleSize), iOffset]) { bits[x, y] = true; } } } return bits; } private static bool moduleSize(int[] leftTopBlack, BitMatrix image, out float msize) { int height = image.Height; int width = image.Width; int x = leftTopBlack[0]; int y = leftTopBlack[1]; bool inBlack = true; int transitions = 0; while (x < width && y < height) { if (inBlack != image[x, y]) { if (++transitions == 5) { break; } inBlack = !inBlack; } x++; y++; } if (x == width || y == height) { msize = 0.0f; return false; } msize = (x - leftTopBlack[0]) / 7.0f; return true; } } }
namespace Microsoft.Protocols.TestSuites.Common { using System; using System.Runtime.InteropServices; /// <summary> /// RopOpenEmbeddedMessage request buffer structure. /// </summary> [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct RopOpenEmbeddedMessageRequest : ISerializable { /// <summary> /// This value specifies the type of remote operation. For this operation, this field is set to 0x46. /// </summary> public byte RopId; /// <summary> /// This value specifies the logon associated with this operation. /// </summary> public byte LogonId; /// <summary> /// This index specifies the location in the Server Object Handle Table where the handle for the input Server Object is stored. /// </summary> public byte InputHandleIndex; /// <summary> /// This index specifies the location in the Server Object Handle Table where the handle for the output Server Object will be stored. /// </summary> public byte OutputHandleIndex; /// <summary> /// This value specifies which code page is used for string values associated with the message. /// </summary> public ushort CodePageId; /// <summary> /// The possible values are specified in [MS-OXCMSG]. These flags control the access to the message. /// </summary> public byte OpenModeFlags; /// <summary> /// Serialize the ROP request buffer. /// </summary> /// <returns>The ROP request buffer serialized.</returns> public byte[] Serialize() { byte[] serializedBuffer = new byte[Marshal.SizeOf(this)]; IntPtr requestBuffer = new IntPtr(); requestBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(this)); try { Marshal.StructureToPtr(this, requestBuffer, true); Marshal.Copy(requestBuffer, serializedBuffer, 0, Marshal.SizeOf(this)); return serializedBuffer; } finally { Marshal.FreeHGlobal(requestBuffer); } } /// <summary> /// Return the size of RopOpenEmbeddedMessage request buffer structure. /// </summary> /// <returns>The size of RopOpenEmbeddedMessage request buffer structure.</returns> public int Size() { return Marshal.SizeOf(this); } } /// <summary> /// RopOpenEmbeddedMessage response buffer structure. /// </summary> [StructLayout(LayoutKind.Sequential, Pack = 1)] public struct RopOpenEmbeddedMessageResponse : IDeserializable { /// <summary> /// This value specifies the type of remote operation. For this operation, this field is set to 0x46. /// </summary> public byte RopId; /// <summary> /// This index MUST be set to the OutputHandleIndex specified in the request. /// </summary> public byte OutputHandleIndex; /// <summary> /// This value specifies the status of the remote operation. For successful response, this field is set to 0x00000000. /// For failure response, this field is set to 0x00000000. /// </summary> public uint ReturnValue; /// <summary> /// This field MUST be set to 0x00. /// </summary> public byte Reserved; /// <summary> /// This value specifies the ID of the embedded message. /// </summary> public ulong MessageId; /// <summary> /// 8-bit Boolean. This value specifies whether the message has named properties. /// </summary> public byte HasNamedProperties; /// <summary> /// TypedString structure. The format of the TypedString structure is specified in [MS-OXCDATA]. /// This structure specifies the subject prefix of the message. /// </summary> public TypedString SubjectPrefix; /// <summary> /// TypedString structure. The format of the TypedString structure is specified in [MS-OXCDATA]. /// This structure specifies the normalized subject of the message. /// </summary> public TypedString NormalizedSubject; /// <summary> /// This value specifies the number of recipients on the message. /// </summary> public ushort RecipientCount; /// <summary> /// This value specifies the number of structures in the RecipientColumns field. /// </summary> public ushort ColumnCount; /// <summary> /// Array of Property Tag structures. The number of structures contained in this field is specified by the ColumnCount field. /// The format of the Property Tag structure is specified in [MS-OXCDATA]. /// This field specifies the property values that can be included for each recipient row. /// </summary> public PropertyTag[] RecipientColumns; /// <summary> /// This value specifies the number of rows in the RecipientRows field. /// </summary> public byte RowCount; /// <summary> /// List of OpenRecipientRow structures. The number of structures contained in this field is specified by the RowCount field. /// </summary> public OpenRecipientRow[] RecipientRows; /// <summary> /// Deserialize the ROP response buffer. /// </summary> /// <param name="ropBytes">ROPs bytes in response.</param> /// <param name="startIndex">The start index of this ROP.</param> /// <returns>The size of response buffer structure.</returns> public int Deserialize(byte[] ropBytes, int startIndex) { int index = startIndex; this.RopId = ropBytes[index++]; this.OutputHandleIndex = ropBytes[index++]; this.ReturnValue = (uint)BitConverter.ToInt32(ropBytes, index); index += 4; // Only success response has below fields if (this.ReturnValue == 0) { this.Reserved = ropBytes[index++]; this.MessageId = (ulong)BitConverter.ToInt64(ropBytes, index); index += 8; this.HasNamedProperties = ropBytes[index++]; index += this.SubjectPrefix.Deserialize(ropBytes, index); index += this.NormalizedSubject.Deserialize(ropBytes, index); this.RecipientCount = (ushort)BitConverter.ToInt16(ropBytes, index); index += 2; this.ColumnCount = (ushort)BitConverter.ToInt16(ropBytes, index); index += 2; // RecipientColumns if (this.ColumnCount >= 0) { this.RecipientColumns = new PropertyTag[this.ColumnCount]; Context.Instance.Init(); for (int i = 0; i < this.ColumnCount; i++) { index += this.RecipientColumns[i].Deserialize(ropBytes, index); Context.Instance.Properties.Add(new Property((PropertyType)this.RecipientColumns[i].PropertyType)); } this.RowCount = ropBytes[index++]; if (this.RowCount >= 0) { this.RecipientRows = new OpenRecipientRow[this.RowCount]; for (int i = 0; i < this.RowCount; i++) { index += this.RecipientRows[i].Deserialize(ropBytes, index); } } } } return index - startIndex; } } }
// Copyright 2007-2012 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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 MassTransit.RequestResponse { using System; using System.Collections.Generic; using System.Threading; using Exceptions; using Logging; using Magnum.Extensions; public class RequestImpl<TRequest> : IAsyncRequest<TRequest>, IRequestComplete where TRequest : class { static readonly ILog _log = Logger.Get(typeof(RequestImpl<TRequest>)); readonly IList<AsyncCallback> _completionCallbacks; readonly object _lock = new object(); readonly TRequest _message; readonly string _requestId; ManualResetEvent _complete; bool _completed; Exception _exception; object _state; TimeSpan _timeout = TimeSpan.MaxValue; TimeoutHandler<TRequest> _timeoutHandler; RegisteredWaitHandle _waitHandle; public RequestImpl(string requestId, TRequest message) { _requestId = requestId; _message = message; _completionCallbacks = new List<AsyncCallback>(); } ManualResetEvent CompleteEvent { get { lock (_lock) { if (_complete == null) _complete = new ManualResetEvent(false); } return _complete; } } public bool IsCompleted { get { return _completed; } } public WaitHandle AsyncWaitHandle { get { return CompleteEvent; } } public object AsyncState { get { return _state; } } public bool CompletedSynchronously { get { return false; } } public bool Wait(TimeSpan timeout) { _timeout = timeout; return Wait(); } public string RequestId { get { return _requestId; } } public void Cancel() { Fail(new RequestCancelledException(_requestId)); } public bool Wait() { bool alreadyCompleted; lock (_lock) alreadyCompleted = _completed; bool result = alreadyCompleted || CompleteEvent.WaitOne(_timeout == TimeSpan.MaxValue ? -1 : (int)_timeout.TotalMilliseconds, true); if (!result) { lock (_completionCallbacks) { if (_timeoutHandler != null) _completionCallbacks.Add(asyncResult => _timeoutHandler.HandleTimeout(_message)); else _exception = new RequestTimeoutException(_requestId); } NotifyComplete(); } Close(); if (_exception != null) throw _exception; return result; } public IAsyncResult BeginAsync(AsyncCallback callback, object state) { if (_waitHandle != null) { throw new InvalidOperationException("The asynchronous request was already started."); } _state = state; lock (_completionCallbacks) _completionCallbacks.Add(callback); WaitOrTimerCallback timerCallback = (s, timeoutExpired) => { if (timeoutExpired) { lock (_completionCallbacks) { if (_timeoutHandler != null) _completionCallbacks.Add(asyncResult => _timeoutHandler.HandleTimeout(_message)); else _exception = new RequestTimeoutException(_requestId); } NotifyComplete(); } }; _waitHandle = ThreadPool.RegisterWaitForSingleObject(CompleteEvent, timerCallback, state, _timeout, true); return this; } public TRequest Message { get { return _message; } } public void Complete<TResponse>(TResponse response) where TResponse : class { NotifyComplete(); } public void Fail(Exception exception) { _exception = exception; NotifyComplete(); } public void SetTimeout(TimeSpan timeout) { _timeout = timeout; } public void SetTimeoutHandler(TimeoutHandler<TRequest> timeoutHandler ) { _timeoutHandler = timeoutHandler; } public void SetUnsubscribeAction(UnsubscribeAction unsubscribeAction) { _completionCallbacks.Add(x => unsubscribeAction()); } void Close() { if (_waitHandle != null) { _waitHandle.Unregister(_complete); _waitHandle = null; } lock (_lock) { if (_complete != null) { using (_complete) _complete.Close(); _complete = null; } } } void NotifyComplete() { if (_completed) return; lock (_lock) { _completed = true; CompleteEvent.Set(); } lock (_completionCallbacks) { _completionCallbacks.Each(callback => { try { if(callback != null) callback(this); } catch (Exception ex) { _log.Error("The request callback threw an exception", ex); } }); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the Roslyn project root for license information. // define TRACE_LEAKS to get additional diagnostics that can lead to the leak sources. note: it will // make everything about 2-3x slower // //#define TRACE_LEAKS // define DETECT_LEAKS to detect possible leaks //#if DEBUG // #define DETECT_LEAKS //for now always enable DETECT_LEAKS in debug. //#endif namespace Sparrow { using System; using System.Diagnostics; using System.Threading; #if DETECT_LEAKS using System.Runtime.CompilerServices; #endif /// <summary> /// Generic implementation of object pooling pattern with predefined pool size limit. The main /// purpose is that limited number of frequently used objects can be kept in the pool for /// further recycling. /// /// Notes: /// 1) it is not the goal to keep all returned objects. Pool is not meant for storage. If there /// is no space in the pool, extra returned objects will be dropped. /// /// 2) it is implied that if object was obtained from a pool, the caller will return it back in /// a relatively short time. Keeping checked out objects for long durations is ok, but /// reduces usefulness of pooling. Just new up your own. /// /// Not returning objects to the pool in not detrimental to the pool's work, but is a bad practice. /// Rationale: /// If there is no intent for reusing the object, do not use pool - just use "new". /// </summary> public class ObjectPool<T> where T : class { private struct Element { internal T Value; } /// <remarks> /// Not using System.Func{T} because this file is linked into the (debugger) Formatter, /// which does not have that type (since it compiles against .NET 2.0). /// </remarks> public delegate T Factory(); // Storage for the pool objects. The first item is stored in a dedicated field because we // expect to be able to satisfy most requests from it. private T _firstItem; private readonly Element[] _items; // factory is stored for the lifetime of the pool. We will call this only when pool needs to // expand. compared to "new T()", Func gives more flexibility to implementers and faster // than "new T()". private readonly Factory _factory; #if DETECT_LEAKS private static readonly ConditionalWeakTable<T, LeakTracker> leakTrackers = new ConditionalWeakTable<T, LeakTracker>(); private class LeakTracker : IDisposable { private volatile bool disposed; #if TRACE_LEAKS internal volatile object Trace = null; #endif public void Dispose() { disposed = true; GC.SuppressFinalize(this); } private string GetTrace() { #if TRACE_LEAKS return Trace == null ? "" : Trace.ToString(); #else return "Leak tracing information is disabled. Define TRACE_LEAKS on ObjectPool`1.cs to get more info \n"; #endif } ~LeakTracker() { if (!this.disposed && !Environment.HasShutdownStarted) { var trace = GetTrace(); // If you are seeing this message it means that object has been allocated from the pool // and has not been returned back. This is not critical, but turns pool into rather // inefficient kind of "new". Debug.WriteLine(string.Format("TRACEOBJECTPOOLLEAKS_BEGIN\nPool detected potential leaking of {0}. \n Location of the leak: \n {1} TRACEOBJECTPOOLLEAKS_END", typeof(T), GetTrace())); } } } #endif public ObjectPool(Factory factory) : this(factory, Environment.ProcessorCount * 2) { } public ObjectPool(Factory factory, int size) { Debug.Assert(size >= 1); _factory = factory; _items = new Element[size - 1]; } private T CreateInstance() { var inst = _factory(); return inst; } /// <summary> /// Produces an instance. /// </summary> /// <remarks> /// Search strategy is a simple linear probing which is chosen for it cache-friendliness. /// Note that Free will try to store recycled objects close to the start thus statistically /// reducing how far we will typically search. /// </remarks> public T Allocate() { // PERF: Examine the first element. If that fails, AllocateSlow will look at the remaining elements. // Note that the initial read is optimistically not synchronized. That is intentional. // We will interlock only when we have a candidate. in a worst case we may miss some // recently returned objects. Not a big deal. T inst = _firstItem; if (inst == null || inst != Interlocked.CompareExchange(ref _firstItem, null, inst)) { inst = AllocateSlow(); } #if DETECT_LEAKS var tracker = new LeakTracker(); leakTrackers.Add(inst, tracker); #if TRACE_LEAKS var frame = CaptureStackTrace(); tracker.Trace = frame; #endif #endif return inst; } private T AllocateSlow() { var items = _items; for (int i = 0; i < items.Length; i++) { // Note that the initial read is optimistically not synchronized. That is intentional. // We will interlock only when we have a candidate. in a worst case we may miss some // recently returned objects. Not a big deal. T inst = items[i].Value; if (inst != null) { if (inst == Interlocked.CompareExchange(ref items[i].Value, null, inst)) { return inst; } } } return CreateInstance(); } /// <summary> /// Returns objects to the pool. /// </summary> /// <remarks> /// Search strategy is a simple linear probing which is chosen for it cache-friendliness. /// Note that Free will try to store recycled objects close to the start thus statistically /// reducing how far we will typically search in Allocate. /// </remarks> public void Free(T obj) { Validate(obj); ForgetTrackedObject(obj); if (_firstItem == null) { // Intentionally not using interlocked here. // In a worst case scenario two objects may be stored into same slot. // It is very unlikely to happen and will only mean that one of the objects will get collected. _firstItem = obj; } else { FreeSlow(obj); } } private void FreeSlow(T obj) { var items = _items; for (int i = 0; i < items.Length; i++) { if (items[i].Value == null) { // Intentionally not using interlocked here. // In a worst case scenario two objects may be stored into same slot. // It is very unlikely to happen and will only mean that one of the objects will get collected. items[i].Value = obj; break; } } } /// <summary> /// Removes an object from leak tracking. /// /// This is called when an object is returned to the pool. It may also be explicitly /// called if an object allocated from the pool is intentionally not being returned /// to the pool. This can be of use with pooled arrays if the consumer wants to /// return a larger array to the pool than was originally allocated. /// </summary> [Conditional("DEBUG")] public void ForgetTrackedObject(T old, T replacement = null) { #if DETECT_LEAKS LeakTracker tracker; if (leakTrackers.TryGetValue(old, out tracker)) { tracker.Dispose(); leakTrackers.Remove(old); } else { var trace = CaptureStackTrace(); Debug.WriteLine(string.Format("TRACEOBJECTPOOLLEAKS_BEGIN\nObject of type {0} was freed, but was not from pool. \n Callstack: \n {1} TRACEOBJECTPOOLLEAKS_END", typeof(T), trace)); } if (replacement != null) { tracker = new LeakTracker(); leakTrackers.Add(replacement, tracker); } #endif } #if DETECT_LEAKS private static Lazy<Type> _stackTraceType = new Lazy<Type>(() => Type.GetType("System.Diagnostics.StackTrace")); private static object CaptureStackTrace() { return Activator.CreateInstance(_stackTraceType.Value); } #endif [Conditional("DEBUG")] private void Validate(object obj) { Debug.Assert(obj != null, "freeing null?"); var items = _items; for (int i = 0; i < items.Length; i++) { var value = items[i].Value; if (value == null) { return; } Debug.Assert(value != obj, "freeing twice?"); } } } }
using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Security.Cryptography; using System.Threading; using UnityEngine; using DarkMultiPlayerCommon; using MessageStream2; namespace DarkMultiPlayer { public class NetworkWorker { //Read from ConnectionWindow public ClientState state { private set; get; } private static NetworkWorker singleton = new NetworkWorker(); private TcpClient clientConnection = null; private float lastSendTime = 0f; private AutoResetEvent sendEvent = new AutoResetEvent(false); private Queue<ClientMessage> sendMessageQueueHigh = new Queue<ClientMessage>(); private Queue<ClientMessage> sendMessageQueueSplit = new Queue<ClientMessage>(); private Queue<ClientMessage> sendMessageQueueLow = new Queue<ClientMessage>(); private ClientMessageType lastSplitMessageType = ClientMessageType.HEARTBEAT; //Receive buffer private float lastReceiveTime = 0f; private bool isReceivingMessage = false; private int receiveMessageBytesLeft = 0; private ServerMessage receiveMessage = null; //Receive split buffer private bool isReceivingSplitMessage = false; private int receiveSplitMessageBytesLeft = 0; private ServerMessage receiveSplitMessage = null; //Used for the initial sync private int numberOfKerbals = 0; private int numberOfKerbalsReceived = 0; private int numberOfVessels = 0; private int numberOfVesselsReceived = 0; //Connection tracking private bool terminateOnNextMessageSend; private string connectionEndReason; private bool terminateThreadsOnNextUpdate; //Network traffic tracking private long bytesQueuedOut; private long bytesSent; private long bytesReceived; //Locking private int connectingThreads = 0; private object connectLock = new object(); private object disconnectLock = new object(); private object messageQueueLock = new object(); private Thread connectThread; private List<Thread> parallelConnectThreads = new List<Thread>(); private Thread receiveThread; private Thread sendThread; private string serverMotd; private bool displayMotd; public NetworkWorker() { lock (Client.eventLock) { Client.updateEvent.Add(this.Update); } } public static NetworkWorker fetch { get { return singleton; } } //Called from main private void Update() { if (terminateThreadsOnNextUpdate) { terminateThreadsOnNextUpdate = false; TerminateThreads(); } if (state == ClientState.CONNECTED) { Client.fetch.status = "Connected"; } if (state == ClientState.HANDSHAKING) { Client.fetch.status = "Handshaking"; } if (state == ClientState.AUTHENTICATED) { NetworkWorker.fetch.SendPlayerStatus(PlayerStatusWorker.fetch.myPlayerStatus); DarkLog.Debug("Sending time sync!"); state = ClientState.TIME_SYNCING; Client.fetch.status = "Syncing server clock"; SendTimeSync(); } if (TimeSyncer.fetch.synced && state == ClientState.TIME_SYNCING) { DarkLog.Debug("Time Synced!"); state = ClientState.TIME_SYNCED; } if (state == ClientState.TIME_SYNCED) { DarkLog.Debug("Requesting kerbals!"); Client.fetch.status = "Syncing kerbals"; state = ClientState.SYNCING_KERBALS; SendKerbalsRequest(); } if (state == ClientState.VESSELS_SYNCED) { DarkLog.Debug("Vessels Synced!"); Client.fetch.status = "Syncing universe time"; state = ClientState.TIME_LOCKING; //The subspaces are held in the wrap control messages, but the warp worker will create a new subspace if we aren't locked. //Process the messages so we get the subspaces, but don't enable the worker until the game is started. WarpWorker.fetch.ProcessWarpMessages(); TimeSyncer.fetch.workerEnabled = true; ChatWorker.fetch.workerEnabled = true; PlayerColorWorker.fetch.workerEnabled = true; FlagSyncer.fetch.workerEnabled = true; FlagSyncer.fetch.SendFlagList(); PlayerColorWorker.fetch.SendPlayerColorToServer(); } if (state == ClientState.TIME_LOCKING) { if (TimeSyncer.fetch.locked) { DarkLog.Debug("Time Locked!"); DarkLog.Debug("Starting Game!"); Client.fetch.status = "Starting game"; state = ClientState.STARTING; Client.fetch.startGame = true; } } if ((state == ClientState.STARTING) && (HighLogic.LoadedScene == GameScenes.SPACECENTER)) { state = ClientState.RUNNING; Client.fetch.status = "Running"; Client.fetch.gameRunning = true; AsteroidWorker.fetch.workerEnabled = true; VesselWorker.fetch.workerEnabled = true; PlayerStatusWorker.fetch.workerEnabled = true; ScenarioWorker.fetch.workerEnabled = true; DynamicTickWorker.fetch.workerEnabled = true; WarpWorker.fetch.workerEnabled = true; CraftLibraryWorker.fetch.workerEnabled = true; ScreenshotWorker.fetch.workerEnabled = true; SendMotdRequest(); ToolbarSupport.fetch.EnableToolbar(); } if (displayMotd && (HighLogic.LoadedScene != GameScenes.LOADING) && (Time.timeSinceLevelLoad > 2f)) { displayMotd = false; ScreenMessages.PostScreenMessage(serverMotd, 10f, ScreenMessageStyle.UPPER_CENTER); } } //This isn't tied to frame rate, During the loading screen Update doesn't fire. public void SendThreadMain() { try { while (true) { CheckDisconnection(); SendHeartBeat(); bool sentMessage = SendOutgoingMessages(); if (!sentMessage) { sendEvent.WaitOne(100); } } } catch (ThreadAbortException) { //Don't care } catch (Exception e) { DarkLog.Debug("Send thread error: " + e); } } #region Connecting to server //Called from main public void ConnectToServer(string address, int port) { DMPServerAddress connectAddress = new DMPServerAddress(); connectAddress.ip = address; connectAddress.port = port; connectThread = new Thread(new ParameterizedThreadStart(ConnectToServerMain)); connectThread.IsBackground = true; //ParameterizedThreadStart only takes one object. connectThread.Start(connectAddress); } private void ConnectToServerMain(object connectAddress) { DMPServerAddress connectAddressCast = (DMPServerAddress)connectAddress; string address = connectAddressCast.ip; int port = connectAddressCast.port; if (state == ClientState.DISCONNECTED) { DarkLog.Debug("Trying to connect to " + address + ", port " + port); Client.fetch.status = "Connecting to " + address + " port " + port; sendMessageQueueHigh = new Queue<ClientMessage>(); sendMessageQueueSplit = new Queue<ClientMessage>(); sendMessageQueueLow = new Queue<ClientMessage>(); numberOfKerbals = 0; numberOfKerbalsReceived = 0; numberOfVessels = 0; numberOfVesselsReceived = 0; bytesReceived = 0; bytesQueuedOut = 0; bytesSent = 0; receiveSplitMessage = null; receiveSplitMessageBytesLeft = 0; isReceivingSplitMessage = false; IPAddress destinationAddress; if (!IPAddress.TryParse(address, out destinationAddress)) { try { IPHostEntry dnsResult = Dns.GetHostEntry(address); if (dnsResult.AddressList.Length > 0) { List<IPEndPoint> addressToConnectTo = new List<IPEndPoint>(); foreach (IPAddress testAddress in dnsResult.AddressList) { if (testAddress.AddressFamily == AddressFamily.InterNetwork || testAddress.AddressFamily == AddressFamily.InterNetworkV6) { Interlocked.Increment(ref connectingThreads); Client.fetch.status = "Connecting"; lastSendTime = UnityEngine.Time.realtimeSinceStartup; lastReceiveTime = UnityEngine.Time.realtimeSinceStartup; state = ClientState.CONNECTING; addressToConnectTo.Add(new IPEndPoint(testAddress, port)); } } foreach (IPEndPoint endpoint in addressToConnectTo) { Thread parallelConnectThread = new Thread(new ParameterizedThreadStart(ConnectToServerAddress)); parallelConnectThreads.Add(parallelConnectThread); parallelConnectThread.Start(endpoint); } if (addressToConnectTo.Count == 0) { DarkLog.Debug("DNS does not contain a valid address entry"); Client.fetch.status = "DNS does not contain a valid address entry"; return; } } else { DarkLog.Debug("Address is not a IP or DNS name"); Client.fetch.status = "Address is not a IP or DNS name"; return; } } catch (Exception e) { DarkLog.Debug("DNS Error: " + e.ToString()); Client.fetch.status = "DNS Error: " + e.Message; return; } } else { Interlocked.Increment(ref connectingThreads); Client.fetch.status = "Connecting"; lastSendTime = UnityEngine.Time.realtimeSinceStartup; lastReceiveTime = UnityEngine.Time.realtimeSinceStartup; state = ClientState.CONNECTING; ConnectToServerAddress(new IPEndPoint(destinationAddress, port)); } } while (state == ClientState.CONNECTING) { Thread.Sleep(500); CheckInitialDisconnection(); } } private void ConnectToServerAddress(object destinationObject) { IPEndPoint destination = (IPEndPoint)destinationObject; TcpClient testConnection = new TcpClient(destination.AddressFamily); testConnection.NoDelay = true; try { DarkLog.Debug("Connecting to " + destination.Address + " port " + destination.Port + "..."); testConnection.Connect(destination.Address, destination.Port); lock (connectLock) { if (state == ClientState.CONNECTING) { if (testConnection.Connected) { clientConnection = testConnection; //Timeout didn't expire. DarkLog.Debug("Connected to " + destination.Address + " port " + destination.Port); Client.fetch.status = "Connected"; state = ClientState.CONNECTED; sendThread = new Thread(new ThreadStart(SendThreadMain)); sendThread.IsBackground = true; sendThread.Start(); receiveThread = new Thread(new ThreadStart(StartReceivingIncomingMessages)); receiveThread.IsBackground = true; receiveThread.Start(); } else { //The connection actually comes good, but after the timeout, so we can send the disconnect message. if ((connectingThreads == 1) && (state == ClientState.CONNECTING)) { DarkLog.Debug("Failed to connect within the timeout!"); Disconnect("Initial connection timeout"); } } } else { if (testConnection.Connected) { testConnection.GetStream().Close(); testConnection.GetStream().Dispose(); } } } } catch (Exception e) { if ((connectingThreads == 1) && (state == ClientState.CONNECTING)) { HandleDisconnectException(e); } } Interlocked.Decrement(ref connectingThreads); lock (parallelConnectThreads) { parallelConnectThreads.Remove(Thread.CurrentThread); } } #endregion #region Connection housekeeping private void CheckInitialDisconnection() { if (state == ClientState.CONNECTING) { if ((UnityEngine.Time.realtimeSinceStartup - lastReceiveTime) > (Common.INITIAL_CONNECTION_TIMEOUT / 1000)) { Disconnect("Failed to connect!"); Client.fetch.status = "Failed to connect - no reply"; if (connectThread != null) { try { lock (parallelConnectThreads) { foreach (Thread parallelConnectThread in parallelConnectThreads) { parallelConnectThread.Abort(); } parallelConnectThreads.Clear(); connectingThreads = 0; } } catch { } } } } } private void CheckDisconnection() { if (state >= ClientState.CONNECTED) { if ((UnityEngine.Time.realtimeSinceStartup - lastReceiveTime) > (Common.CONNECTION_TIMEOUT / 1000)) { Disconnect("Connection timeout"); } } } public void Disconnect(string reason) { lock (disconnectLock) { if (state != ClientState.DISCONNECTED) { DarkLog.Debug("Disconnected, reason: " + reason); if (!HighLogic.LoadedSceneIsEditor && !HighLogic.LoadedSceneIsFlight) { NetworkWorker.fetch.SendDisconnect("Force quit to main menu"); Client.fetch.forceQuit = true; } else { Client.fetch.displayDisconnectMessage = true; } Client.fetch.status = reason; state = ClientState.DISCONNECTED; try { if (clientConnection != null) { clientConnection.GetStream().Close(); clientConnection.Close(); clientConnection = null; } } catch (Exception e) { DarkLog.Debug("Error closing connection: " + e.Message); } terminateThreadsOnNextUpdate = true; } } } private void TerminateThreads() { foreach (Thread parallelConnectThread in parallelConnectThreads) { try { parallelConnectThread.Abort(); } catch { //Don't care } } parallelConnectThreads.Clear(); connectingThreads = 0; try { connectThread.Abort(); } catch { //Don't care } try { sendThread.Abort(); } catch { //Don't care } try { receiveThread.Abort(); } catch { //Don't care } } #endregion #region Network writers/readers private void StartReceivingIncomingMessages() { lastReceiveTime = UnityEngine.Time.realtimeSinceStartup; //Allocate byte for header isReceivingMessage = false; receiveMessage = new ServerMessage(); receiveMessage.data = new byte[8]; receiveMessageBytesLeft = receiveMessage.data.Length; try { while (true) { int bytesRead = clientConnection.GetStream().Read(receiveMessage.data, receiveMessage.data.Length - receiveMessageBytesLeft, receiveMessageBytesLeft); bytesReceived += bytesRead; receiveMessageBytesLeft -= bytesRead; if (bytesRead > 0) { lastReceiveTime = UnityEngine.Time.realtimeSinceStartup; } else { Thread.Sleep(10); } if (receiveMessageBytesLeft == 0) { //We either have the header or the message data, let's do something if (!isReceivingMessage) { //We have the header using (MessageReader mr = new MessageReader(receiveMessage.data)) { int messageType = mr.Read<int>(); int messageLength = mr.Read<int>(); //This is from the little endian -> big endian format change. //The handshake challange type is 1, and the payload length is always 1032 bytes. //Little endian (the previous format) DMPServer sends 01 00 00 00 | 08 04 00 00 as the first message, the handshake challange. if (messageType == 16777216 && messageLength == 134479872) { Disconnect("Disconnected from pre-v0.2 DMP server"); return; } if (messageType > (Enum.GetNames(typeof(ServerMessageType)).Length - 1)) { //Malformed message, most likely from a non DMP-server. Disconnect("Disconnected from non-DMP server"); //Returning from ReceiveCallback will break the receive loop and stop processing any further messages. return; } receiveMessage.type = (ServerMessageType)messageType; if (messageLength == 0) { //Null message, handle it. receiveMessage.data = null; HandleMessage(receiveMessage); receiveMessage.type = 0; receiveMessage.data = new byte[8]; receiveMessageBytesLeft = receiveMessage.data.Length; } else { if (messageLength < Common.MAX_MESSAGE_SIZE) { isReceivingMessage = true; receiveMessage.data = new byte[messageLength]; receiveMessageBytesLeft = receiveMessage.data.Length; } else { //Malformed message, most likely from a non DMP-server. Disconnect("Disconnected from non-DMP server"); //Returning from ReceiveCallback will break the receive loop and stop processing any further messages. return; } } } } else { //We have the message data to a non-null message, handle it isReceivingMessage = false; HandleMessage(receiveMessage); receiveMessage.type = 0; receiveMessage.data = new byte[8]; receiveMessageBytesLeft = receiveMessage.data.Length; } } if (state < ClientState.CONNECTED || state == ClientState.DISCONNECTING) { return; } } } catch (Exception e) { HandleDisconnectException(e); } } private void QueueOutgoingMessage(ClientMessage message, bool highPriority) { lock (messageQueueLock) { //All messages have an 8 byte header bytesQueuedOut += 8; if (message.data != null && message.data.Length > 0) { //Count the payload if we have one. bytesQueuedOut += message.data.Length; } if (highPriority) { sendMessageQueueHigh.Enqueue(message); } else { sendMessageQueueLow.Enqueue(message); } } sendEvent.Set(); } private bool SendOutgoingMessages() { ClientMessage sendMessage = null; lock (messageQueueLock) { if (state >= ClientState.CONNECTED) { if (sendMessageQueueHigh.Count > 0) { sendMessage = sendMessageQueueHigh.Dequeue(); } if ((sendMessage == null) && (sendMessageQueueSplit.Count > 0)) { sendMessage = sendMessageQueueSplit.Dequeue(); //We just sent the last piece of a split message if (sendMessageQueueSplit.Count == 0) { if (lastSplitMessageType == ClientMessageType.CRAFT_LIBRARY) { CraftLibraryWorker.fetch.finishedUploadingCraft = true; } if (lastSplitMessageType == ClientMessageType.SCREENSHOT_LIBRARY) { ScreenshotWorker.fetch.finishedUploadingScreenshot = true; } } } if ((sendMessage == null) && (sendMessageQueueLow.Count > 0)) { sendMessage = sendMessageQueueLow.Dequeue(); //Splits large messages to higher priority messages can get into the queue faster SplitAndRewriteMessage(ref sendMessage); } } } if (sendMessage != null) { SendNetworkMessage(sendMessage); return true; } return false; } private void SplitAndRewriteMessage(ref ClientMessage message) { if (message == null) { return; } if (message.data == null) { return; } if (message.data.Length > Common.SPLIT_MESSAGE_LENGTH) { lastSplitMessageType = message.type; ClientMessage newSplitMessage = new ClientMessage(); newSplitMessage.type = ClientMessageType.SPLIT_MESSAGE; int splitBytesLeft = message.data.Length; using (MessageWriter mw = new MessageWriter()) { mw.Write<int>((int)message.type); mw.Write<int>(message.data.Length); byte[] firstSplit = new byte[Common.SPLIT_MESSAGE_LENGTH]; Array.Copy(message.data, 0, firstSplit, 0, Common.SPLIT_MESSAGE_LENGTH); mw.Write<byte[]>(firstSplit); splitBytesLeft -= Common.SPLIT_MESSAGE_LENGTH; newSplitMessage.data = mw.GetMessageBytes(); //SPLIT_MESSAGE adds a 12 byte header. bytesQueuedOut += 12; sendMessageQueueSplit.Enqueue(newSplitMessage); } while (splitBytesLeft > 0) { ClientMessage currentSplitMessage = new ClientMessage(); currentSplitMessage.type = ClientMessageType.SPLIT_MESSAGE; currentSplitMessage.data = new byte[Math.Min(splitBytesLeft, Common.SPLIT_MESSAGE_LENGTH)]; Array.Copy(message.data, message.data.Length - splitBytesLeft, currentSplitMessage.data, 0, currentSplitMessage.data.Length); splitBytesLeft -= currentSplitMessage.data.Length; //Add the SPLIT_MESSAGE header to the out queue count. bytesQueuedOut += 8; sendMessageQueueSplit.Enqueue(currentSplitMessage); } message = sendMessageQueueSplit.Dequeue(); } } private void SendNetworkMessage(ClientMessage message) { byte[] messageBytes = Common.PrependNetworkFrame((int)message.type, message.data); lock (messageQueueLock) { bytesQueuedOut -= messageBytes.Length; bytesSent += messageBytes.Length; } //Disconnect after EndWrite completes if (message.type == ClientMessageType.CONNECTION_END) { using (MessageReader mr = new MessageReader(message.data)) { terminateOnNextMessageSend = true; connectionEndReason = mr.Read<string>(); } } lastSendTime = UnityEngine.Time.realtimeSinceStartup; try { clientConnection.GetStream().Write(messageBytes, 0, messageBytes.Length); if (terminateOnNextMessageSend) { Disconnect("Connection ended: " + connectionEndReason); connectionEndReason = null; terminateOnNextMessageSend = false; } } catch (Exception e) { HandleDisconnectException(e); } } private void HandleDisconnectException(Exception e) { if (e.InnerException != null) { DarkLog.Debug("Connection error: " + e.Message + ", " + e.InnerException); Disconnect("Connection error: " + e.Message + ", " + e.InnerException.Message); } else { DarkLog.Debug("Connection error: " + e); Disconnect("Connection error: " + e.Message); } } #endregion #region Message Handling private void HandleMessage(ServerMessage message) { try { switch (message.type) { case ServerMessageType.HEARTBEAT: break; case ServerMessageType.HANDSHAKE_CHALLANGE: HandleHandshakeChallange(message.data); break; case ServerMessageType.HANDSHAKE_REPLY: HandleHandshakeReply(message.data); break; case ServerMessageType.CHAT_MESSAGE: HandleChatMessage(message.data); break; case ServerMessageType.SERVER_SETTINGS: HandleServerSettings(message.data); break; case ServerMessageType.PLAYER_STATUS: HandlePlayerStatus(message.data); break; case ServerMessageType.PLAYER_COLOR: PlayerColorWorker.fetch.HandlePlayerColorMessage(message.data); break; case ServerMessageType.PLAYER_JOIN: HandlePlayerJoin(message.data); break; case ServerMessageType.PLAYER_DISCONNECT: HandlePlayerDisconnect(message.data); break; case ServerMessageType.SCENARIO_DATA: HandleScenarioModuleData(message.data); break; case ServerMessageType.KERBAL_REPLY: HandleKerbalReply(message.data); break; case ServerMessageType.KERBAL_COMPLETE: HandleKerbalComplete(); break; case ServerMessageType.VESSEL_LIST: HandleVesselList(message.data); break; case ServerMessageType.VESSEL_PROTO: HandleVesselProto(message.data); break; case ServerMessageType.VESSEL_UPDATE: HandleVesselUpdate(message.data); break; case ServerMessageType.VESSEL_COMPLETE: HandleVesselComplete(); break; case ServerMessageType.VESSEL_REMOVE: HandleVesselRemove(message.data); break; case ServerMessageType.CRAFT_LIBRARY: HandleCraftLibrary(message.data); break; case ServerMessageType.SCREENSHOT_LIBRARY: HandleScreenshotLibrary(message.data); break; case ServerMessageType.FLAG_SYNC: FlagSyncer.fetch.HandleMessage(message.data); break; case ServerMessageType.SET_SUBSPACE: HandleSetSubspace(message.data); break; case ServerMessageType.SYNC_TIME_REPLY: HandleSyncTimeReply(message.data); break; case ServerMessageType.PING_REPLY: HandlePingReply(message.data); break; case ServerMessageType.MOTD_REPLY: HandleMotdReply(message.data); break; case ServerMessageType.WARP_CONTROL: HandleWarpControl(message.data); break; case ServerMessageType.ADMIN_SYSTEM: AdminSystem.fetch.HandleAdminMessage(message.data); break; case ServerMessageType.LOCK_SYSTEM: LockSystem.fetch.HandleLockMessage(message.data); break; case ServerMessageType.MOD_DATA: DMPModInterface.fetch.HandleModData(message.data); break; case ServerMessageType.SPLIT_MESSAGE: HandleSplitMessage(message.data); break; case ServerMessageType.CONNECTION_END: HandleConnectionEnd(message.data); break; default: DarkLog.Debug("Unhandled message type " + message.type); break; } } catch (Exception e) { DarkLog.Debug("Error handling message type " + message.type + ", exception: " + e); SendDisconnect("Error handling " + message.type + " message"); } } private void HandleHandshakeChallange(byte[] messageData) { try { using (MessageReader mr = new MessageReader(messageData)) { byte[] challange = mr.Read<byte[]>(); using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(1024)) { rsa.PersistKeyInCsp = false; rsa.FromXmlString(Settings.fetch.playerPrivateKey); byte[] signature = rsa.SignData(challange, CryptoConfig.CreateFromName("SHA256")); SendHandshakeResponse(signature); state = ClientState.HANDSHAKING; } } } catch (Exception e) { DarkLog.Debug("Error handling HANDSHAKE_CHALLANGE message, exception: " + e); } } private void HandleHandshakeReply(byte[] messageData) { int reply = 0; string reason = ""; string modFileData = ""; int serverProtocolVersion = -1; string serverVersion = "Unknown"; try { using (MessageReader mr = new MessageReader(messageData)) { reply = mr.Read<int>(); reason = mr.Read<string>(); try { serverProtocolVersion = mr.Read<int>(); serverVersion = mr.Read<string>(); } catch { //We don't care about this throw on pre-protocol-9 servers. } //If we handshook successfully, the mod data will be available to read. if (reply == 0) { Compression.compressionEnabled = mr.Read<bool>() && Settings.fetch.compressionEnabled; ModWorker.fetch.modControl = (ModControlMode)mr.Read<int>(); if (ModWorker.fetch.modControl != ModControlMode.DISABLED) { modFileData = mr.Read<string>(); } } } } catch (Exception e) { DarkLog.Debug("Error handling HANDSHAKE_REPLY message, exception: " + e); reply = 99; reason = "Incompatible HANDSHAKE_REPLY message"; } switch (reply) { case 0: { if (ModWorker.fetch.ParseModFile(modFileData)) { DarkLog.Debug("Handshake successful"); state = ClientState.AUTHENTICATED; } else { DarkLog.Debug("Failed to pass mod validation"); SendDisconnect("Failed mod validation"); } } break; default: string disconnectReason = "Handshake failure: " + reason; //If it's a protocol mismatch, append the client/server version. if (reply == 1) { string clientTrimmedVersion = Common.PROGRAM_VERSION; //Trim git tags if (Common.PROGRAM_VERSION.Length == 40) { clientTrimmedVersion = Common.PROGRAM_VERSION.Substring(0, 7); } string serverTrimmedVersion = serverVersion; if (serverVersion.Length == 40) { serverTrimmedVersion = serverVersion.Substring(0, 7); } disconnectReason += "\nClient: " + clientTrimmedVersion + ", Server: " + serverTrimmedVersion; //If they both aren't a release version, display the actual protocol version. if (!serverVersion.Contains("v") || !Common.PROGRAM_VERSION.Contains("v")) { if (serverProtocolVersion != -1) { disconnectReason += "\nClient protocol: " + Common.PROTOCOL_VERSION + ", Server: " + serverProtocolVersion; } else { disconnectReason += "\nClient protocol: " + Common.PROTOCOL_VERSION + ", Server: 8-"; } } } DarkLog.Debug(disconnectReason); Disconnect(disconnectReason); break; } } private void HandleChatMessage(byte[] messageData) { using (MessageReader mr = new MessageReader(messageData)) { ChatMessageType chatMessageType = (ChatMessageType)mr.Read<int>(); switch (chatMessageType) { case ChatMessageType.LIST: { string[] playerList = mr.Read<string[]>(); foreach (string playerName in playerList) { string[] channelList = mr.Read<string[]>(); foreach (string channelName in channelList) { ChatWorker.fetch.QueueChatJoin(playerName, channelName); } } } break; case ChatMessageType.JOIN: { string playerName = mr.Read<string>(); string channelName = mr.Read<string>(); ChatWorker.fetch.QueueChatJoin(playerName, channelName); } break; case ChatMessageType.LEAVE: { string playerName = mr.Read<string>(); string channelName = mr.Read<string>(); ChatWorker.fetch.QueueChatLeave(playerName, channelName); } break; case ChatMessageType.CHANNEL_MESSAGE: { string playerName = mr.Read<string>(); string channelName = mr.Read<string>(); string channelMessage = mr.Read<string>(); ChatWorker.fetch.QueueChannelMessage(playerName, channelName, channelMessage); } break; case ChatMessageType.PRIVATE_MESSAGE: { string fromPlayer = mr.Read<string>(); string toPlayer = mr.Read<string>(); string privateMessage = mr.Read<string>(); if (toPlayer == Settings.fetch.playerName || fromPlayer == Settings.fetch.playerName) { ChatWorker.fetch.QueuePrivateMessage(fromPlayer, toPlayer, privateMessage); } } break; case ChatMessageType.CONSOLE_MESSAGE: { string message = mr.Read<string>(); ChatWorker.fetch.QueueSystemMessage(message); } break; } } } private void HandleServerSettings(byte[] messageData) { using (MessageReader mr = new MessageReader(messageData)) { WarpWorker.fetch.warpMode = (WarpMode)mr.Read<int>(); Client.fetch.gameMode = (GameMode)mr.Read<int>(); Client.fetch.serverAllowCheats = mr.Read<bool>(); numberOfKerbals = mr.Read<int>(); numberOfVessels = mr.Read<int>(); ScreenshotWorker.fetch.screenshotHeight = mr.Read<int>(); AsteroidWorker.fetch.maxNumberOfUntrackedAsteroids = mr.Read<int>(); ChatWorker.fetch.consoleIdentifier = mr.Read<string>(); Client.fetch.serverDifficulty = (GameDifficulty)mr.Read<int>(); if (Client.fetch.serverDifficulty != GameDifficulty.CUSTOM) { Client.fetch.serverParameters = GameParameters.GetDefaultParameters(Client.fetch.ConvertGameMode(Client.fetch.gameMode), (GameParameters.Preset)Client.fetch.serverDifficulty); } else { GameParameters newParameters = new GameParameters(); newParameters.Difficulty.AllowStockVessels = mr.Read<bool>(); newParameters.Difficulty.AutoHireCrews = mr.Read<bool>(); newParameters.Difficulty.BypassEntryPurchaseAfterResearch = mr.Read<bool>(); newParameters.Difficulty.IndestructibleFacilities = mr.Read<bool>(); newParameters.Difficulty.MissingCrewsRespawn = mr.Read<bool>(); newParameters.Career.FundsGainMultiplier = mr.Read<float>(); newParameters.Career.FundsLossMultiplier = mr.Read<float>(); newParameters.Career.RepGainMultiplier = mr.Read<float>(); newParameters.Career.RepLossMultiplier = mr.Read<float>(); newParameters.Career.ScienceGainMultiplier = mr.Read<float>(); newParameters.Career.StartingFunds = mr.Read<float>(); newParameters.Career.StartingReputation = mr.Read<float>(); newParameters.Career.StartingScience = mr.Read<float>(); Client.fetch.serverParameters = newParameters; } } } private void HandlePlayerStatus(byte[] messageData) { using (MessageReader mr = new MessageReader(messageData)) { string playerName = mr.Read<string>(); string vesselText = mr.Read<string>(); string statusText = mr.Read<string>(); PlayerStatus newStatus = new PlayerStatus(); newStatus.playerName = playerName; newStatus.vesselText = vesselText; newStatus.statusText = statusText; PlayerStatusWorker.fetch.AddPlayerStatus(newStatus); } } private void HandlePlayerJoin(byte[] messageData) { using (MessageReader mr = new MessageReader(messageData)) { string playerName = mr.Read<string>(); ChatWorker.fetch.QueueChannelMessage(ChatWorker.fetch.consoleIdentifier, "", playerName + " has joined the server"); } } private void HandlePlayerDisconnect(byte[] messageData) { using (MessageReader mr = new MessageReader(messageData)) { string playerName = mr.Read<string>(); WarpWorker.fetch.RemovePlayer(playerName); PlayerStatusWorker.fetch.RemovePlayerStatus(playerName); ChatWorker.fetch.QueueRemovePlayer(playerName); LockSystem.fetch.ReleasePlayerLocks(playerName); ChatWorker.fetch.QueueChannelMessage(ChatWorker.fetch.consoleIdentifier, "", playerName + " has left the server"); } } private void HandleSyncTimeReply(byte[] messageData) { using (MessageReader mr = new MessageReader(messageData)) { long clientSend = mr.Read<long>(); long serverReceive = mr.Read<long>(); long serverSend = mr.Read<long>(); TimeSyncer.fetch.HandleSyncTime(clientSend, serverReceive, serverSend); } } private void HandleScenarioModuleData(byte[] messageData) { using (MessageReader mr = new MessageReader(messageData)) { string[] scenarioName = mr.Read<string[]>(); for (int i = 0; i < scenarioName.Length; i++) { byte[] scenarioData = Compression.DecompressIfNeeded(mr.Read<byte[]>()); ConfigNode scenarioNode = ConfigNodeSerializer.fetch.Deserialize(scenarioData); if (scenarioNode != null) { ScenarioWorker.fetch.QueueScenarioData(scenarioName[i], scenarioNode); } else { DarkLog.Debug("Scenario data has been lost for " + scenarioName[i]); ScreenMessages.PostScreenMessage("Scenario data has been lost for " + scenarioName[i], 5f, ScreenMessageStyle.UPPER_CENTER); } } } } private void HandleKerbalReply(byte[] messageData) { numberOfKerbalsReceived++; using (MessageReader mr = new MessageReader(messageData)) { double planetTime = mr.Read<double>(); string kerbalName = mr.Read<string>(); byte[] kerbalData = mr.Read<byte[]>(); ConfigNode kerbalNode = ConfigNodeSerializer.fetch.Deserialize(kerbalData); if (kerbalNode != null) { VesselWorker.fetch.QueueKerbal(planetTime, kerbalName, kerbalNode); } else { DarkLog.Debug("Failed to load kerbal!"); } } if (state == ClientState.SYNCING_KERBALS) { if (numberOfKerbals != 0) { Client.fetch.status = "Syncing kerbals " + numberOfKerbalsReceived + "/" + numberOfKerbals + " (" + (int)((numberOfKerbalsReceived / (float)numberOfKerbals) * 100) + "%)"; } } } private void HandleKerbalComplete() { state = ClientState.KERBALS_SYNCED; DarkLog.Debug("Kerbals Synced!"); Client.fetch.status = "Kerbals synced"; } private void HandleVesselList(byte[] messageData) { state = ClientState.SYNCING_VESSELS; Client.fetch.status = "Syncing vessels"; using (MessageReader mr = new MessageReader(messageData)) { List<string> serverVessels = new List<string>(mr.Read<string[]>()); List<string> cacheObjects = new List<string>(UniverseSyncCache.fetch.GetCachedObjects()); List<string> requestedObjects = new List<string>(); foreach (string serverVessel in serverVessels) { if (!cacheObjects.Contains(serverVessel)) { requestedObjects.Add(serverVessel); } else { numberOfVesselsReceived++; byte[] vesselBytes = UniverseSyncCache.fetch.GetFromCache(serverVessel); if (vesselBytes.Length != 0) { ConfigNode vesselNode = ConfigNodeSerializer.fetch.Deserialize(vesselBytes); if (vesselNode != null) { string vesselID = Common.ConvertConfigStringToGUIDString(vesselNode.GetValue("pid")); if (vesselID != null) { VesselWorker.fetch.QueueVesselProto(vesselID, 0, vesselNode); } else { DarkLog.Debug("Cached object " + serverVessel + " is damaged - Failed to get vessel ID"); } } else { DarkLog.Debug("Cached object " + serverVessel + " is damaged - Failed to create a config node"); } } else { DarkLog.Debug("Cached object " + serverVessel + " is damaged - Object is a 0 length file!"); } } } if (numberOfVessels != 0) { Client.fetch.status = "Syncing vessels " + numberOfVesselsReceived + "/" + numberOfVessels + " (" + (int)((numberOfVesselsReceived / (float)numberOfVessels) * 100) + "%)"; } SendVesselsRequest(requestedObjects.ToArray()); } } private void HandleVesselProto(byte[] messageData) { numberOfVesselsReceived++; using (MessageReader mr = new MessageReader(messageData)) { double planetTime = mr.Read<double>(); string vesselID = mr.Read<string>(); //Docking - don't care. mr.Read<bool>(); //Flying - don't care. mr.Read<bool>(); byte[] vesselData = Compression.DecompressIfNeeded(mr.Read<byte[]>()); UniverseSyncCache.fetch.QueueToCache(vesselData); ConfigNode vesselNode = ConfigNodeSerializer.fetch.Deserialize(vesselData); if (vesselNode != null) { string vesselIDConfigNode = Common.ConvertConfigStringToGUIDString(vesselNode.GetValue("pid")); if ((vesselID != null) && (vesselID == vesselIDConfigNode)) { VesselWorker.fetch.QueueVesselProto(vesselID, planetTime, vesselNode); } else { DarkLog.Debug("Failed to load vessel " + vesselID + "!"); } } else { DarkLog.Debug("Failed to load vessel" + vesselID + "!"); } } if (state == ClientState.SYNCING_VESSELS) { if (numberOfVessels != 0) { if (numberOfVesselsReceived > numberOfVessels) { //Received 102 / 101 vessels! numberOfVessels = numberOfVesselsReceived; } Client.fetch.status = "Syncing vessels " + numberOfVesselsReceived + "/" + numberOfVessels + " (" + (int)((numberOfVesselsReceived / (float)numberOfVessels) * 100) + "%)"; } } } private void HandleVesselUpdate(byte[] messageData) { VesselUpdate update = new VesselUpdate(); using (MessageReader mr = new MessageReader(messageData)) { update.planetTime = mr.Read<double>(); update.vesselID = mr.Read<string>(); update.bodyName = mr.Read<string>(); update.rotation = mr.Read<float[]>(); update.angularVelocity = mr.Read<float[]>(); //FlightState variables update.flightState = new FlightCtrlState(); update.flightState.mainThrottle = mr.Read<float>(); update.flightState.wheelThrottleTrim = mr.Read<float>(); update.flightState.X = mr.Read<float>(); update.flightState.Y = mr.Read<float>(); update.flightState.Z = mr.Read<float>(); update.flightState.killRot = mr.Read<bool>(); update.flightState.gearUp = mr.Read<bool>(); update.flightState.gearDown = mr.Read<bool>(); update.flightState.headlight = mr.Read<bool>(); update.flightState.wheelThrottle = mr.Read<float>(); update.flightState.roll = mr.Read<float>(); update.flightState.yaw = mr.Read<float>(); update.flightState.pitch = mr.Read<float>(); update.flightState.rollTrim = mr.Read<float>(); update.flightState.yawTrim = mr.Read<float>(); update.flightState.pitchTrim = mr.Read<float>(); update.flightState.wheelSteer = mr.Read<float>(); update.flightState.wheelSteerTrim = mr.Read<float>(); //Action group controls update.actiongroupControls = mr.Read<bool[]>(); //Position/velocity update.isSurfaceUpdate = mr.Read<bool>(); if (update.isSurfaceUpdate) { update.position = mr.Read<double[]>(); update.velocity = mr.Read<double[]>(); update.acceleration = mr.Read<double[]>(); } else { update.orbit = mr.Read<double[]>(); } VesselWorker.fetch.QueueVesselUpdate(update); } } private void HandleSetActiveVessel(byte[] messageData) { using (MessageReader mr = new MessageReader(messageData)) { string player = mr.Read<string>(); string vesselID = mr.Read<string>(); VesselWorker.fetch.QueueActiveVessel(player, vesselID); } } private void HandleVesselComplete() { state = ClientState.VESSELS_SYNCED; } private void HandleVesselRemove(byte[] messageData) { using (MessageReader mr = new MessageReader(messageData)) { //We don't care about the subspace ID anymore. mr.Read<int>(); double planetTime = mr.Read<double>(); string vesselID = mr.Read<string>(); bool isDockingUpdate = mr.Read<bool>(); string dockingPlayer = null; if (isDockingUpdate) { DarkLog.Debug("Got a docking update!"); dockingPlayer = mr.Read<string>(); } else { DarkLog.Debug("Got removal command for vessel " + vesselID); } VesselWorker.fetch.QueueVesselRemove(vesselID, planetTime, isDockingUpdate, dockingPlayer); } } private void HandleCraftLibrary(byte[] messageData) { using (MessageReader mr = new MessageReader(messageData)) { CraftMessageType messageType = (CraftMessageType)mr.Read<int>(); switch (messageType) { case CraftMessageType.LIST: { string[] playerList = mr.Read<string[]>(); foreach (string player in playerList) { bool vabExists = mr.Read<bool>(); bool sphExists = mr.Read<bool>(); bool subassemblyExists = mr.Read<bool>(); DarkLog.Debug("Player: " + player + ", VAB: " + vabExists + ", SPH: " + sphExists + ", SUBASSEMBLY" + subassemblyExists); if (vabExists) { string[] vabCrafts = mr.Read<string[]>(); foreach (string vabCraft in vabCrafts) { CraftChangeEntry cce = new CraftChangeEntry(); cce.playerName = player; cce.craftType = CraftType.VAB; cce.craftName = vabCraft; CraftLibraryWorker.fetch.QueueCraftAdd(cce); } } if (sphExists) { string[] sphCrafts = mr.Read<string[]>(); foreach (string sphCraft in sphCrafts) { CraftChangeEntry cce = new CraftChangeEntry(); cce.playerName = player; cce.craftType = CraftType.SPH; cce.craftName = sphCraft; CraftLibraryWorker.fetch.QueueCraftAdd(cce); } } if (subassemblyExists) { string[] subassemblyCrafts = mr.Read<string[]>(); foreach (string subassemblyCraft in subassemblyCrafts) { CraftChangeEntry cce = new CraftChangeEntry(); cce.playerName = player; cce.craftType = CraftType.SUBASSEMBLY; cce.craftName = subassemblyCraft; CraftLibraryWorker.fetch.QueueCraftAdd(cce); } } } } break; case CraftMessageType.ADD_FILE: { CraftChangeEntry cce = new CraftChangeEntry(); cce.playerName = mr.Read<string>(); cce.craftType = (CraftType)mr.Read<int>(); cce.craftName = mr.Read<string>(); CraftLibraryWorker.fetch.QueueCraftAdd(cce); ChatWorker.fetch.QueueChannelMessage(ChatWorker.fetch.consoleIdentifier, "", cce.playerName + " shared " + cce.craftName + " (" + cce.craftType + ")"); } break; case CraftMessageType.DELETE_FILE: { CraftChangeEntry cce = new CraftChangeEntry(); cce.playerName = mr.Read<string>(); cce.craftType = (CraftType)mr.Read<int>(); cce.craftName = mr.Read<string>(); CraftLibraryWorker.fetch.QueueCraftDelete(cce); } break; case CraftMessageType.RESPOND_FILE: { CraftResponseEntry cre = new CraftResponseEntry(); cre.playerName = mr.Read<string>(); cre.craftType = (CraftType)mr.Read<int>(); cre.craftName = mr.Read<string>(); bool hasCraft = mr.Read<bool>(); if (hasCraft) { cre.craftData = mr.Read<byte[]>(); CraftLibraryWorker.fetch.QueueCraftResponse(cre); } else { ScreenMessages.PostScreenMessage("Craft " + cre.craftName + " from " + cre.playerName + " not available", 5f, ScreenMessageStyle.UPPER_CENTER); } } break; } } } private void HandleScreenshotLibrary(byte[] messageData) { using (MessageReader mr = new MessageReader(messageData)) { ScreenshotMessageType messageType = (ScreenshotMessageType)mr.Read<int>(); switch (messageType) { case ScreenshotMessageType.SEND_START_NOTIFY: { string fromPlayer = mr.Read<string>(); ScreenshotWorker.fetch.downloadingScreenshotFromPlayer = fromPlayer; } break; case ScreenshotMessageType.NOTIFY: { string fromPlayer = mr.Read<string>(); ScreenshotWorker.fetch.QueueNewNotify(fromPlayer); } break; case ScreenshotMessageType.SCREENSHOT: { string fromPlayer = mr.Read<string>(); byte[] screenshotData = mr.Read<byte[]>(); ScreenshotWorker.fetch.QueueNewScreenshot(fromPlayer, screenshotData); } break; case ScreenshotMessageType.WATCH: { string fromPlayer = mr.Read<string>(); string watchPlayer = mr.Read<string>(); ScreenshotWorker.fetch.QueueNewScreenshotWatch(fromPlayer, watchPlayer); } break; } } } private void HandleSetSubspace(byte[] messageData) { using (MessageReader mr = new MessageReader(messageData)) { int subspaceID = mr.Read<int>(); TimeSyncer.fetch.LockSubspace(subspaceID); } } private void HandlePingReply(byte[] messageData) { using (MessageReader mr = new MessageReader(messageData)) { int pingTime = (int)((DateTime.UtcNow.Ticks - mr.Read<long>()) / 10000f); ChatWorker.fetch.QueueChannelMessage(ChatWorker.fetch.consoleIdentifier, "", "Ping: " + pingTime + "ms."); } } private void HandleMotdReply(byte[] messageData) { using (MessageReader mr = new MessageReader(messageData)) { serverMotd = mr.Read<string>(); if (serverMotd != "") { displayMotd = true; ChatWorker.fetch.QueueChannelMessage(ChatWorker.fetch.consoleIdentifier, "", serverMotd); } } } private void HandleWarpControl(byte[] messageData) { WarpWorker.fetch.QueueWarpMessage(messageData); } private void HandleSplitMessage(byte[] messageData) { if (!isReceivingSplitMessage) { //New split message using (MessageReader mr = new MessageReader(messageData)) { receiveSplitMessage = new ServerMessage(); receiveSplitMessage.type = (ServerMessageType)mr.Read<int>(); receiveSplitMessage.data = new byte[mr.Read<int>()]; receiveSplitMessageBytesLeft = receiveSplitMessage.data.Length; byte[] firstSplitData = mr.Read<byte[]>(); firstSplitData.CopyTo(receiveSplitMessage.data, 0); receiveSplitMessageBytesLeft -= firstSplitData.Length; } isReceivingSplitMessage = true; } else { //Continued split message messageData.CopyTo(receiveSplitMessage.data, receiveSplitMessage.data.Length - receiveSplitMessageBytesLeft); receiveSplitMessageBytesLeft -= messageData.Length; } if (receiveSplitMessageBytesLeft == 0) { HandleMessage(receiveSplitMessage); receiveSplitMessage = null; isReceivingSplitMessage = false; } } private void HandleConnectionEnd(byte[] messageData) { string reason = ""; using (MessageReader mr = new MessageReader(messageData)) { reason = mr.Read<string>(); } Disconnect("Server closed connection: " + reason); } #endregion #region Message Sending private void SendHeartBeat() { if (state >= ClientState.CONNECTED && sendMessageQueueHigh.Count == 0) { if ((UnityEngine.Time.realtimeSinceStartup - lastSendTime) > (Common.HEART_BEAT_INTERVAL / 1000)) { lastSendTime = UnityEngine.Time.realtimeSinceStartup; ClientMessage newMessage = new ClientMessage(); newMessage.type = ClientMessageType.HEARTBEAT; QueueOutgoingMessage(newMessage, true); } } } private void SendHandshakeResponse(byte[] signature) { byte[] messageBytes; using (MessageWriter mw = new MessageWriter()) { mw.Write<int>(Common.PROTOCOL_VERSION); mw.Write<string>(Settings.fetch.playerName); mw.Write<string>(Settings.fetch.playerPublicKey); mw.Write<byte[]>(signature); mw.Write<string>(Common.PROGRAM_VERSION); mw.Write<bool>(Settings.fetch.compressionEnabled); messageBytes = mw.GetMessageBytes(); } ClientMessage newMessage = new ClientMessage(); newMessage.type = ClientMessageType.HANDSHAKE_RESPONSE; newMessage.data = messageBytes; QueueOutgoingMessage(newMessage, true); } //Called from ChatWindow public void SendChatMessage(byte[] messageData) { ClientMessage newMessage = new ClientMessage(); newMessage.type = ClientMessageType.CHAT_MESSAGE; newMessage.data = messageData; QueueOutgoingMessage(newMessage, true); } //Called from PlayerStatusWorker public void SendPlayerStatus(PlayerStatus playerStatus) { byte[] messageBytes; using (MessageWriter mw = new MessageWriter()) { mw.Write<string>(playerStatus.playerName); mw.Write<string>(playerStatus.vesselText); mw.Write<string>(playerStatus.statusText); messageBytes = mw.GetMessageBytes(); } ClientMessage newMessage = new ClientMessage(); newMessage.type = ClientMessageType.PLAYER_STATUS; newMessage.data = messageBytes; QueueOutgoingMessage(newMessage, true); } //Called from PlayerColorWorker public void SendPlayerColorMessage(byte[] messageData) { ClientMessage newMessage = new ClientMessage(); newMessage.type = ClientMessageType.PLAYER_COLOR; newMessage.data = messageData; QueueOutgoingMessage(newMessage, false); } //Called from timeSyncer public void SendTimeSync() { byte[] messageBytes; using (MessageWriter mw = new MessageWriter()) { mw.Write<long>(DateTime.UtcNow.Ticks); messageBytes = mw.GetMessageBytes(); } ClientMessage newMessage = new ClientMessage(); newMessage.type = ClientMessageType.SYNC_TIME_REQUEST; newMessage.data = messageBytes; QueueOutgoingMessage(newMessage, true); } private void SendKerbalsRequest() { ClientMessage newMessage = new ClientMessage(); newMessage.type = ClientMessageType.KERBALS_REQUEST; QueueOutgoingMessage(newMessage, true); } private void SendVesselsRequest(string[] requestList) { ClientMessage newMessage = new ClientMessage(); newMessage.type = ClientMessageType.VESSELS_REQUEST; using (MessageWriter mw = new MessageWriter()) { mw.Write<string[]>(requestList); newMessage.data = mw.GetMessageBytes(); } QueueOutgoingMessage(newMessage, true); } //Called from vesselWorker public void SendVesselProtoMessage(ProtoVessel vessel, bool isDockingUpdate, bool isFlyingUpdate) { ConfigNode vesselNode = new ConfigNode(); ClientMessage newMessage = new ClientMessage(); newMessage.type = ClientMessageType.VESSEL_PROTO; vessel.Save(vesselNode); byte[] vesselBytes = ConfigNodeSerializer.fetch.Serialize(vesselNode); if (vesselBytes != null && vesselBytes.Length > 0) { UniverseSyncCache.fetch.QueueToCache(vesselBytes); using (MessageWriter mw = new MessageWriter()) { mw.Write<double>(Planetarium.GetUniversalTime()); mw.Write<string>(vessel.vesselID.ToString()); mw.Write<bool>(isDockingUpdate); mw.Write<bool>(isFlyingUpdate); mw.Write<byte[]>(Compression.CompressIfNeeded(vesselBytes)); newMessage.data = mw.GetMessageBytes(); } DarkLog.Debug("Sending vessel " + vessel.vesselID + ", name " + vessel.vesselName + ", type: " + vessel.vesselType + ", size: " + newMessage.data.Length); QueueOutgoingMessage(newMessage, false); } else { DarkLog.Debug("Failed to create byte[] data for " + vessel.vesselID); } } //Called from vesselWorker public void SendVesselUpdate(VesselUpdate update) { ClientMessage newMessage = new ClientMessage(); newMessage.type = ClientMessageType.VESSEL_UPDATE; using (MessageWriter mw = new MessageWriter()) { mw.Write<double>(update.planetTime); mw.Write<string>(update.vesselID); mw.Write<string>(update.bodyName); mw.Write<float[]>(update.rotation); //mw.Write<float[]>(update.vesselForward); //mw.Write<float[]>(update.vesselUp); mw.Write<float[]>(update.angularVelocity); //FlightState variables mw.Write<float>(update.flightState.mainThrottle); mw.Write<float>(update.flightState.wheelThrottleTrim); mw.Write<float>(update.flightState.X); mw.Write<float>(update.flightState.Y); mw.Write<float>(update.flightState.Z); mw.Write<bool>(update.flightState.killRot); mw.Write<bool>(update.flightState.gearUp); mw.Write<bool>(update.flightState.gearDown); mw.Write<bool>(update.flightState.headlight); mw.Write<float>(update.flightState.wheelThrottle); mw.Write<float>(update.flightState.roll); mw.Write<float>(update.flightState.yaw); mw.Write<float>(update.flightState.pitch); mw.Write<float>(update.flightState.rollTrim); mw.Write<float>(update.flightState.yawTrim); mw.Write<float>(update.flightState.pitchTrim); mw.Write<float>(update.flightState.wheelSteer); mw.Write<float>(update.flightState.wheelSteerTrim); //Action group controls mw.Write<bool[]>(update.actiongroupControls); //Position/velocity mw.Write<bool>(update.isSurfaceUpdate); if (update.isSurfaceUpdate) { mw.Write<double[]>(update.position); mw.Write<double[]>(update.velocity); mw.Write<double[]>(update.acceleration); } else { mw.Write<double[]>(update.orbit); } newMessage.data = mw.GetMessageBytes(); } QueueOutgoingMessage(newMessage, false); } //Called from vesselWorker public void SendVesselRemove(string vesselID, bool isDockingUpdate) { DarkLog.Debug("Removing " + vesselID + " from the server"); ClientMessage newMessage = new ClientMessage(); newMessage.type = ClientMessageType.VESSEL_REMOVE; using (MessageWriter mw = new MessageWriter()) { mw.Write<int>(TimeSyncer.fetch.currentSubspace); mw.Write<double>(Planetarium.GetUniversalTime()); mw.Write<string>(vesselID); mw.Write<bool>(isDockingUpdate); if (isDockingUpdate) { mw.Write<string>(Settings.fetch.playerName); } newMessage.data = mw.GetMessageBytes(); } QueueOutgoingMessage(newMessage, false); } //Called fro craftLibraryWorker public void SendCraftLibraryMessage(byte[] messageData) { ClientMessage newMessage = new ClientMessage(); newMessage.type = ClientMessageType.CRAFT_LIBRARY; newMessage.data = messageData; QueueOutgoingMessage(newMessage, false); } //Called from ScreenshotWorker public void SendScreenshotMessage(byte[] messageData) { ClientMessage newMessage = new ClientMessage(); newMessage.type = ClientMessageType.SCREENSHOT_LIBRARY; newMessage.data = messageData; QueueOutgoingMessage(newMessage, false); } //Called from ScenarioWorker public void SendScenarioModuleData(string[] scenarioNames, byte[][] scenarioData) { ClientMessage newMessage = new ClientMessage(); newMessage.type = ClientMessageType.SCENARIO_DATA; using (MessageWriter mw = new MessageWriter()) { mw.Write<string[]>(scenarioNames); foreach (byte[] scenarioBytes in scenarioData) { mw.Write<byte[]>(Compression.CompressIfNeeded(scenarioBytes)); } newMessage.data = mw.GetMessageBytes(); } DarkLog.Debug("Sending " + scenarioNames.Length + " scenario modules"); QueueOutgoingMessage(newMessage, false); } //Called from vesselWorker public void SendKerbalProtoMessage(ProtoCrewMember kerbal) { ConfigNode kerbalNode = new ConfigNode(); kerbal.Save(kerbalNode); byte[] kerbalBytes = ConfigNodeSerializer.fetch.Serialize(kerbalNode); if (kerbalBytes != null && kerbalBytes.Length > 0) { ClientMessage newMessage = new ClientMessage(); newMessage.type = ClientMessageType.KERBAL_PROTO; using (MessageWriter mw = new MessageWriter()) { mw.Write<double>(Planetarium.GetUniversalTime()); mw.Write<string>(kerbal.name); mw.Write<byte[]>(kerbalBytes); newMessage.data = mw.GetMessageBytes(); } DarkLog.Debug("Sending kerbal " + kerbal.name + ", size: " + newMessage.data.Length); QueueOutgoingMessage(newMessage, false); } else { DarkLog.Debug("Failed to create byte[] data for kerbal " + kerbal.name); } } //Called from chatWorker public void SendPingRequest() { ClientMessage newMessage = new ClientMessage(); newMessage.type = ClientMessageType.PING_REQUEST; using (MessageWriter mw = new MessageWriter()) { mw.Write<long>(DateTime.UtcNow.Ticks); newMessage.data = mw.GetMessageBytes(); } QueueOutgoingMessage(newMessage, true); } //Called from networkWorker public void SendMotdRequest() { ClientMessage newMessage = new ClientMessage(); newMessage.type = ClientMessageType.MOTD_REQUEST; QueueOutgoingMessage(newMessage, true); } //Called from FlagSyncer public void SendFlagMessage(byte[] messageData) { ClientMessage newMessage = new ClientMessage(); newMessage.type = ClientMessageType.FLAG_SYNC; newMessage.data = messageData; QueueOutgoingMessage(newMessage, false); } //Called from warpWorker public void SendWarpMessage(byte[] messageData) { ClientMessage newMessage = new ClientMessage(); newMessage.type = ClientMessageType.WARP_CONTROL; newMessage.data = messageData; QueueOutgoingMessage(newMessage, true); } //Called from lockSystem public void SendLockSystemMessage(byte[] messageData) { ClientMessage newMessage = new ClientMessage(); newMessage.type = ClientMessageType.LOCK_SYSTEM; newMessage.data = messageData; QueueOutgoingMessage(newMessage, true); } /// <summary> /// If you are a mod, call DMPModInterface.fetch.SendModMessage. /// </summary> public void SendModMessage(byte[] messageData, bool highPriority) { ClientMessage newMessage = new ClientMessage(); newMessage.type = ClientMessageType.MOD_DATA; newMessage.data = messageData; QueueOutgoingMessage(newMessage, highPriority); } //Called from main public void SendDisconnect(string disconnectReason = "Unknown") { if (state != ClientState.DISCONNECTING && state >= ClientState.CONNECTED) { DarkLog.Debug("Sending disconnect message, reason: " + disconnectReason); Client.fetch.status = "Disconnected: " + disconnectReason; state = ClientState.DISCONNECTING; byte[] messageBytes; using (MessageWriter mw = new MessageWriter()) { mw.Write<string>(disconnectReason); messageBytes = mw.GetMessageBytes(); } ClientMessage newMessage = new ClientMessage(); newMessage.type = ClientMessageType.CONNECTION_END; newMessage.data = messageBytes; QueueOutgoingMessage(newMessage, true); } } public long GetStatistics(string statType) { switch (statType) { case "HighPriorityQueueLength": return sendMessageQueueHigh.Count; case "SplitPriorityQueueLength": return sendMessageQueueSplit.Count; case "LowPriorityQueueLength": return sendMessageQueueLow.Count; case "QueuedOutBytes": return bytesQueuedOut; case "SentBytes": return bytesSent; case "ReceivedBytes": return bytesReceived; case "LastReceiveTime": return (int)((UnityEngine.Time.realtimeSinceStartup - lastReceiveTime) * 1000); case "LastSendTime": return (int)((UnityEngine.Time.realtimeSinceStartup - lastSendTime) * 1000); } return 0; } #endregion } class DMPServerAddress { public string ip; public int port; } }
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. #nullable disable using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Scriban.Parsing; using Scriban.Runtime; namespace Scriban.Syntax { /// <summary> /// Used to rewrite a function call expression at evaluation time based /// on the arguments required by a function. Used by scientific mode scripting. /// </summary> internal partial class ScientificFunctionCallRewriter { /// <summary> /// The precedence of an implicit function call is between Add (+) and Multiply (*) operator /// </summary> private const int ImplicitFunctionCallPrecedence = Parser.PrecedenceOfAdd + 1; public static ScriptExpression Rewrite(TemplateContext context, ScriptBinaryExpression binaryExpression) { Debug.Assert(ImplicitFunctionCallPrecedence < Parser.PrecedenceOfMultiply); if (!HasImplicitBinaryExpression(binaryExpression)) { return binaryExpression; } // TODO: use a TLS cache var iterator = new BinaryExpressionIterator(); // a b c / d + e // stack will contain: // [0] a // [1] implicit * // [2] b // [3] implicit * // [4] c // [5] / // [6] d // [7] + // [8] e FlattenBinaryExpressions(context, binaryExpression, iterator); return ParseBinaryExpressionTree(iterator, 0, false); } private static bool HasImplicitBinaryExpression(ScriptExpression expression) { if (expression is ScriptBinaryExpression binaryExpression) { if (binaryExpression.OperatorToken == null && binaryExpression.Operator == ScriptBinaryOperator.Multiply) { return true; } return HasImplicitBinaryExpression(binaryExpression.Left) || HasImplicitBinaryExpression(binaryExpression.Right); } return false; } private static void FlattenBinaryExpressions(TemplateContext context, ScriptExpression expression, List<BinaryExpressionOrOperator> expressions) { while (true) { if (!(expression is ScriptBinaryExpression binaryExpression)) { expressions.Add(new BinaryExpressionOrOperator(expression, GetFunctionCallKind(context, expression))); return; } var left = (ScriptExpression)binaryExpression.Left.Clone(); var right = (ScriptExpression)binaryExpression.Right.Clone(); var token = (ScriptToken)binaryExpression.OperatorToken?.Clone(); FlattenBinaryExpressions(context, left, expressions); expressions.Add(new BinaryExpressionOrOperator(binaryExpression.Operator, token)); // Iterate on right (equivalent to tail recursive call) expression = right; } } private static ScriptExpression ParseBinaryExpressionTree(BinaryExpressionIterator it, int precedence, bool isExpectingExpression) { ScriptExpression leftOperand = null; while (it.HasCurrent) { var op = it.Current; var nextOperand = op.Expression; if (nextOperand == null) { var newPrecedence = Parser.GetDefaultBinaryOperatorPrecedence(op.Operator); // Probe if the next argument is a function call if (!isExpectingExpression && it.HasNext && it.PeekNext().CallKind != FunctionCallKind.None) { // If it is a function call, use its precedence newPrecedence = newPrecedence < ImplicitFunctionCallPrecedence ? newPrecedence : ImplicitFunctionCallPrecedence; } if (newPrecedence <= precedence) { break; } it.MoveNext(); // Skip operator var binary = new ScriptBinaryExpression { Left = leftOperand, Operator = op.Operator, OperatorToken = op.OperatorToken ?? ScriptToken.Star(), // Force an explicit token so that we don't enter an infinite loop when formatting an expression Span = { Start = leftOperand.Span.Start }, }; binary.Right = ParseBinaryExpressionTree(it, newPrecedence, isExpectingExpression); binary.Span.End = binary.Right.Span.End; leftOperand = binary; } else { if (!isExpectingExpression && op.CallKind != FunctionCallKind.None) { var functionCall = new ScriptFunctionCall { Target = nextOperand, ExplicitCall = true, Span = { Start = nextOperand.Span.Start } }; // Skip the function and move to the operator if (!it.MoveNext()) { throw new ScriptRuntimeException(nextOperand.Span, $"The function is expecting at least one argument"); } // We are expecting only an implicit multiply. Anything else is invalid. if (it.Current.Expression == null && (it.Current.Operator != ScriptBinaryOperator.Multiply || it.Current.OperatorToken != null)) { throw new ScriptRuntimeException(nextOperand.Span, $"The function expecting one argument cannot be followed by the operator {it.Current.OperatorToken?.ToString() ?? it.Current.Operator.ToText()}"); } // Skip the operator if (!it.MoveNext()) { throw new ScriptRuntimeException(nextOperand.Span, $"The function is expecting at least one argument"); } var argExpression = ParseBinaryExpressionTree(it, ImplicitFunctionCallPrecedence, op.CallKind == FunctionCallKind.Expression); functionCall.Arguments.Add(argExpression); functionCall.Span.End = argExpression.Span.End; leftOperand = functionCall; continue; } leftOperand = nextOperand; it.MoveNext(); } } return leftOperand; } private static FunctionCallKind GetFunctionCallKind(TemplateContext context, ScriptExpression expression) { var restoreStrictVariables = context.StrictVariables; // Don't fail on trying to lookup for a variable context.StrictVariables = false; object result = null; try { result = context.Evaluate(expression, true); } catch (ScriptRuntimeException) when (context.IgnoreExceptionsWhileRewritingScientific) { // ignore any exceptions during trial evaluating as we could try to evaluate // variable that aren't setup } finally { context.StrictVariables = restoreStrictVariables; } // If one argument is a function, the remaining arguments if (result is IScriptCustomFunction function) { var maxArg = function.RequiredParameterCount != 0 ? function.RequiredParameterCount : function.ParameterCount > 0 ? 1 : 0; // We match all functions with at least one argument. // If we are expecting more than one argument, let the error happen later with the function call. if (maxArg > 0) { var isExpectingExpression = function.IsParameterType<ScriptExpression>(0); return isExpectingExpression ? FunctionCallKind.Expression : FunctionCallKind.Regular; } } return FunctionCallKind.None; } /// <summary> /// Stores a list of binary expressions to rewrite. /// </summary> [DebuggerDisplay("Count = {Count}, Current = {Index} : {Current}")] private class BinaryExpressionIterator : List<BinaryExpressionOrOperator> { public int Index { get; set; } public BinaryExpressionOrOperator Current => Index < Count ? this[Index] : default; public bool HasCurrent => Index < Count; public bool HasNext => Index + 1 < Count; public bool MoveNext() { Index++; return HasCurrent; } public BinaryExpressionOrOperator PeekNext() { return this[Index + 1]; } } /// <summary> /// A binary expression part to rewrite. It is either: /// - An "terminal" expression /// - An operator (`*`, `+`...) /// </summary> [DebuggerDisplay("{" + nameof(ToDebuggerDisplay) + "(),nq}")] private readonly struct BinaryExpressionOrOperator { public BinaryExpressionOrOperator(ScriptExpression expression, FunctionCallKind kind) { Expression = expression; Operator = 0; OperatorToken = null; CallKind = kind; } public BinaryExpressionOrOperator(ScriptBinaryOperator @operator, ScriptToken operatorToken) { Expression = null; Operator = @operator; OperatorToken = operatorToken; CallKind = FunctionCallKind.None; } public readonly ScriptExpression Expression; public readonly ScriptBinaryOperator Operator; public readonly ScriptToken OperatorToken; public readonly FunctionCallKind CallKind; private string ToDebuggerDisplay() { return Expression != null ? Expression.ToString() : OperatorToken?.ToString() ?? $"`{Operator.ToText()}` - CallKind = {CallKind}"; } } private enum FunctionCallKind { None, Regular, Expression } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Threading.Tasks; using Xunit; using Xunit.Sdk; namespace Roslyn.Test.Utilities.Parallel { internal class ParallelTestClassCommand : ITestClassCommand { private readonly Dictionary<MethodInfo, object> _fixtures = new Dictionary<MethodInfo, object>(); private readonly IDictionary<IMethodInfo, Task<MethodResult>> _testMethodTasks = new Dictionary<IMethodInfo, Task<MethodResult>>(); private ITypeInfo _typeUnderTest; private bool _classStarted = false; private bool _invokingSingleMethod = true; private List<TraceListener> _oldListeners = null; public ParallelTestClassCommand() : this((ITypeInfo)null) { } public ParallelTestClassCommand(Type typeUnderTest) : this(Reflector.Wrap(typeUnderTest)) { } public ParallelTestClassCommand(ITypeInfo typeUnderTest) { _typeUnderTest = typeUnderTest; } public object ObjectUnderTest { get { return null; } } public ITypeInfo TypeUnderTest { get { return _typeUnderTest; } set { _typeUnderTest = value; } } public int ChooseNextTest(ICollection<IMethodInfo> testsLeftToRun) { return 0; } public Exception ClassFinish() { foreach (object fixtureData in _fixtures.Values) { try { if (fixtureData is IDisposable) { ((IDisposable)fixtureData).Dispose(); } Trace.Listeners.Clear(); Trace.Listeners.AddRange(_oldListeners.ToArray()); } catch (Exception ex) { return ex; } } return null; } public Exception ClassStart() { try { foreach (Type @interface in _typeUnderTest.Type.GetInterfaces()) { if (@interface.IsGenericType) { Type genericDefinition = @interface.GetGenericTypeDefinition(); if (genericDefinition == typeof(IUseFixture<>)) { Type dataType = @interface.GetGenericArguments()[0]; if (dataType == _typeUnderTest.Type) { throw new InvalidOperationException("Cannot use a test class as its own fixture data"); } object fixtureData = null; try { fixtureData = Activator.CreateInstance(dataType); } catch (TargetInvocationException ex) { return ex.InnerException; } MethodInfo method = @interface.GetMethod("SetFixture", new Type[] { dataType }); _fixtures[method] = fixtureData; } } } _oldListeners = new List<TraceListener>(); foreach (TraceListener oldListener in Trace.Listeners) { _oldListeners.Add(oldListener); } Trace.Listeners.Clear(); Trace.Listeners.Add(new AssertTraceListener()); if (!_invokingSingleMethod) { StartMethodsAsync(TestMethodTasks); } return null; } catch (Exception ex) { return ex; } finally { _classStarted = true; } } public IEnumerable<ITestCommand> EnumerateTestCommands(IMethodInfo testMethod) { string skipReason = MethodUtility.GetSkipReason(testMethod); if (skipReason != null) { yield return new SkipCommand(testMethod, MethodUtility.GetDisplayName(testMethod), skipReason); } else if (!_invokingSingleMethod) { yield return new FixtureCommand(new AsyncFactCommand(testMethod, TestMethodTasks), _fixtures); } else { yield return new FixtureCommand(new FactCommand(testMethod), _fixtures); } } public IEnumerable<IMethodInfo> EnumerateTestMethods() { if (!_classStarted && _testMethodTasks.Count == 0) { _invokingSingleMethod = false; } return TestMethodTasks.Keys; } public static IEnumerable<ITestCommand> Make(ITestClassCommand classCommand, IMethodInfo method) { foreach (var testCommand in classCommand.EnumerateTestCommands(method)) { ITestCommand wrappedCommand = testCommand; // Timeout (if they have one) -> Capture -> Timed -> Lifetime (if we need an instance) -> BeforeAfter wrappedCommand = new BeforeAfterCommand(wrappedCommand, method.MethodInfo); if (testCommand.ShouldCreateInstance) { wrappedCommand = new LifetimeCommand(wrappedCommand, method); } wrappedCommand = new TimedCommand(wrappedCommand); wrappedCommand = new ExceptionCaptureCommand(wrappedCommand, method); if (wrappedCommand.Timeout > 0) { wrappedCommand = new TimeoutCommand(wrappedCommand, wrappedCommand.Timeout, method); } yield return wrappedCommand; } } private IDictionary<IMethodInfo, Task<MethodResult>> TestMethodTasks { get { if (_testMethodTasks.Count == 0) { foreach (IMethodInfo testMethod in TypeUtility.GetTestMethods(_typeUnderTest)) { foreach (ITestCommand command in Make(new AsyncTestClassCommand(_fixtures), testMethod)) { // looks like sometimes compiler generated code will reuse "command". // and that can cause closure given to a task to be changed underneath. // make sure to use local copy of command so that closure doesn't get // changed. var localCopy = command; _testMethodTasks.Add(testMethod, new Task<MethodResult>(() => localCopy.Execute(null))); } } } return _testMethodTasks; } } public bool IsTestMethod(IMethodInfo testMethod) { return MethodUtility.IsTest(testMethod); } private static void StartMethodsAsync(IDictionary<IMethodInfo, Task<MethodResult>> testMethodInvokeInfo) { foreach (var testMethod in testMethodInvokeInfo) { testMethod.Value.Start(); } } private class AssertTraceListener : TraceListener { public override void Fail(string message, string detailMessage) { throw new TraceAssertException(message, detailMessage); } public override void Write(string message) { } public override void WriteLine(string message) { } } } }
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace System.Security.Policy { public static class __CodeGroup { public static IObservable<System.Reactive.Unit> FromXml( this IObservable<System.Security.Policy.CodeGroup> CodeGroupValue, IObservable<System.Security.SecurityElement> e, IObservable<System.Security.Policy.PolicyLevel> level) { return ObservableExt.ZipExecute(CodeGroupValue, e, level, (CodeGroupValueLambda, eLambda, levelLambda) => CodeGroupValueLambda.FromXml(eLambda, levelLambda)); } public static IObservable<System.Reactive.Unit> AddChild( this IObservable<System.Security.Policy.CodeGroup> CodeGroupValue, IObservable<System.Security.Policy.CodeGroup> group) { return ObservableExt.ZipExecute(CodeGroupValue, group, (CodeGroupValueLambda, groupLambda) => CodeGroupValueLambda.AddChild(groupLambda)); } public static IObservable<System.Reactive.Unit> RemoveChild( this IObservable<System.Security.Policy.CodeGroup> CodeGroupValue, IObservable<System.Security.Policy.CodeGroup> group) { return ObservableExt.ZipExecute(CodeGroupValue, group, (CodeGroupValueLambda, groupLambda) => CodeGroupValueLambda.RemoveChild(groupLambda)); } public static IObservable<System.Security.Policy.PolicyStatement> Resolve( this IObservable<System.Security.Policy.CodeGroup> CodeGroupValue, IObservable<System.Security.Policy.Evidence> evidence) { return Observable.Zip(CodeGroupValue, evidence, (CodeGroupValueLambda, evidenceLambda) => CodeGroupValueLambda.Resolve(evidenceLambda)); } public static IObservable<System.Security.Policy.CodeGroup> ResolveMatchingCodeGroups( this IObservable<System.Security.Policy.CodeGroup> CodeGroupValue, IObservable<System.Security.Policy.Evidence> evidence) { return Observable.Zip(CodeGroupValue, evidence, (CodeGroupValueLambda, evidenceLambda) => CodeGroupValueLambda.ResolveMatchingCodeGroups(evidenceLambda)); } public static IObservable<System.Security.Policy.CodeGroup> Copy( this IObservable<System.Security.Policy.CodeGroup> CodeGroupValue) { return Observable.Select(CodeGroupValue, (CodeGroupValueLambda) => CodeGroupValueLambda.Copy()); } public static IObservable<System.Security.SecurityElement> ToXml( this IObservable<System.Security.Policy.CodeGroup> CodeGroupValue) { return Observable.Select(CodeGroupValue, (CodeGroupValueLambda) => CodeGroupValueLambda.ToXml()); } public static IObservable<System.Reactive.Unit> FromXml( this IObservable<System.Security.Policy.CodeGroup> CodeGroupValue, IObservable<System.Security.SecurityElement> e) { return ObservableExt.ZipExecute(CodeGroupValue, e, (CodeGroupValueLambda, eLambda) => CodeGroupValueLambda.FromXml(eLambda)); } public static IObservable<System.Security.SecurityElement> ToXml( this IObservable<System.Security.Policy.CodeGroup> CodeGroupValue, IObservable<System.Security.Policy.PolicyLevel> level) { return Observable.Zip(CodeGroupValue, level, (CodeGroupValueLambda, levelLambda) => CodeGroupValueLambda.ToXml(levelLambda)); } public static IObservable<System.Boolean> Equals( this IObservable<System.Security.Policy.CodeGroup> CodeGroupValue, IObservable<System.Object> o) { return Observable.Zip(CodeGroupValue, o, (CodeGroupValueLambda, oLambda) => CodeGroupValueLambda.Equals(oLambda)); } public static IObservable<System.Boolean> Equals( this IObservable<System.Security.Policy.CodeGroup> CodeGroupValue, IObservable<System.Security.Policy.CodeGroup> cg, IObservable<System.Boolean> compareChildren) { return Observable.Zip(CodeGroupValue, cg, compareChildren, (CodeGroupValueLambda, cgLambda, compareChildrenLambda) => CodeGroupValueLambda.Equals(cgLambda, compareChildrenLambda)); } public static IObservable<System.Int32> GetHashCode( this IObservable<System.Security.Policy.CodeGroup> CodeGroupValue) { return Observable.Select(CodeGroupValue, (CodeGroupValueLambda) => CodeGroupValueLambda.GetHashCode()); } public static IObservable<System.Collections.IList> get_Children( this IObservable<System.Security.Policy.CodeGroup> CodeGroupValue) { return Observable.Select(CodeGroupValue, (CodeGroupValueLambda) => CodeGroupValueLambda.Children); } public static IObservable<System.Security.Policy.IMembershipCondition> get_MembershipCondition( this IObservable<System.Security.Policy.CodeGroup> CodeGroupValue) { return Observable.Select(CodeGroupValue, (CodeGroupValueLambda) => CodeGroupValueLambda.MembershipCondition); } public static IObservable<System.Security.Policy.PolicyStatement> get_PolicyStatement( this IObservable<System.Security.Policy.CodeGroup> CodeGroupValue) { return Observable.Select(CodeGroupValue, (CodeGroupValueLambda) => CodeGroupValueLambda.PolicyStatement); } public static IObservable<System.String> get_Name( this IObservable<System.Security.Policy.CodeGroup> CodeGroupValue) { return Observable.Select(CodeGroupValue, (CodeGroupValueLambda) => CodeGroupValueLambda.Name); } public static IObservable<System.String> get_Description( this IObservable<System.Security.Policy.CodeGroup> CodeGroupValue) { return Observable.Select(CodeGroupValue, (CodeGroupValueLambda) => CodeGroupValueLambda.Description); } public static IObservable<System.String> get_PermissionSetName( this IObservable<System.Security.Policy.CodeGroup> CodeGroupValue) { return Observable.Select(CodeGroupValue, (CodeGroupValueLambda) => CodeGroupValueLambda.PermissionSetName); } public static IObservable<System.String> get_AttributeString( this IObservable<System.Security.Policy.CodeGroup> CodeGroupValue) { return Observable.Select(CodeGroupValue, (CodeGroupValueLambda) => CodeGroupValueLambda.AttributeString); } public static IObservable<System.String> get_MergeLogic( this IObservable<System.Security.Policy.CodeGroup> CodeGroupValue) { return Observable.Select(CodeGroupValue, (CodeGroupValueLambda) => CodeGroupValueLambda.MergeLogic); } public static IObservable<System.Reactive.Unit> set_Children( this IObservable<System.Security.Policy.CodeGroup> CodeGroupValue, IObservable<System.Collections.IList> value) { return ObservableExt.ZipExecute(CodeGroupValue, value, (CodeGroupValueLambda, valueLambda) => CodeGroupValueLambda.Children = valueLambda); } public static IObservable<System.Reactive.Unit> set_MembershipCondition( this IObservable<System.Security.Policy.CodeGroup> CodeGroupValue, IObservable<System.Security.Policy.IMembershipCondition> value) { return ObservableExt.ZipExecute(CodeGroupValue, value, (CodeGroupValueLambda, valueLambda) => CodeGroupValueLambda.MembershipCondition = valueLambda); } public static IObservable<System.Reactive.Unit> set_PolicyStatement( this IObservable<System.Security.Policy.CodeGroup> CodeGroupValue, IObservable<System.Security.Policy.PolicyStatement> value) { return ObservableExt.ZipExecute(CodeGroupValue, value, (CodeGroupValueLambda, valueLambda) => CodeGroupValueLambda.PolicyStatement = valueLambda); } public static IObservable<System.Reactive.Unit> set_Name( this IObservable<System.Security.Policy.CodeGroup> CodeGroupValue, IObservable<System.String> value) { return ObservableExt.ZipExecute(CodeGroupValue, value, (CodeGroupValueLambda, valueLambda) => CodeGroupValueLambda.Name = valueLambda); } public static IObservable<System.Reactive.Unit> set_Description( this IObservable<System.Security.Policy.CodeGroup> CodeGroupValue, IObservable<System.String> value) { return ObservableExt.ZipExecute(CodeGroupValue, value, (CodeGroupValueLambda, valueLambda) => CodeGroupValueLambda.Description = valueLambda); } } }
using System; using System.Collections.Specialized; using System.Net; using Newtonsoft.Json; using SteamKit2; namespace SteamTrade.TradeWebAPI { /// <summary> /// This class provides the interface into the Web API for trading on the /// Steam network. /// </summary> public class TradeSession { private const string SteamTradeUrl = "http://steamcommunity.com/trade/{0}/"; private string sessionIdEsc; private string baseTradeURL; private readonly SteamWeb SteamWeb; private readonly SteamID OtherSID; /// <summary> /// Initializes a new instance of the <see cref="TradeSession"/> class. /// </summary> /// <param name="otherSid">The Steam id of the other trading partner.</param> /// <param name="steamWeb">The SteamWeb instance for this bot</param> public TradeSession(SteamID otherSid, SteamWeb steamWeb) { OtherSID = otherSid; SteamWeb = steamWeb; Init(); } #region Trade status properties /// <summary> /// Gets the LogPos number of the current trade. /// </summary> /// <remarks>This is not automatically updated by this class.</remarks> internal int LogPos { get; set; } /// <summary> /// Gets the version number of the current trade. This increments on /// every item added or removed from a trade. /// </summary> /// <remarks>This is not automatically updated by this class.</remarks> internal int Version { get; set; } #endregion Trade status properties #region Trade Web API command methods /// <summary> /// Gets the trade status. /// </summary> /// <returns>A deserialized JSON object into <see cref="TradeStatus"/></returns> /// <remarks> /// This is the main polling method for trading and must be done at a /// periodic rate (probably around 1 second). /// </remarks> internal TradeStatus GetStatus() { var data = new NameValueCollection (); data.Add ("sessionid", sessionIdEsc); data.Add ("logpos", "" + LogPos); data.Add ("version", "" + Version); string response = Fetch (baseTradeURL + "tradestatus", "POST", data); return JsonConvert.DeserializeObject<TradeStatus> (response); } /// <summary> /// Gets the foreign inventory. /// </summary> /// <param name="otherId">The other id.</param> /// <returns>A dynamic JSON object.</returns> internal dynamic GetForeignInventory(SteamID otherId) { return GetForeignInventory(otherId, 440, 2); } internal dynamic GetForeignInventory(SteamID otherId, long contextId, int appid) { var data = new NameValueCollection(); data.Add("sessionid", sessionIdEsc); data.Add("steamid", "" + otherId.ConvertToUInt64()); data.Add("appid", "" + appid); data.Add("contextid", "" + contextId); try { string response = Fetch(baseTradeURL + "foreigninventory", "GET", data); return JsonConvert.DeserializeObject(response); } catch (Exception) { return JsonConvert.DeserializeObject("{\"success\":\"false\"}"); } } /// <summary> /// Sends a message to the user over the trade chat. /// </summary> internal bool SendMessageWebCmd(string msg) { var data = new NameValueCollection (); data.Add ("sessionid", sessionIdEsc); data.Add ("message", msg); data.Add ("logpos", "" + LogPos); data.Add ("version", "" + Version); string result = Fetch (baseTradeURL + "chat", "POST", data); dynamic json = JsonConvert.DeserializeObject(result); return IsSuccess(json); } /// <summary> /// Adds a specified itom by its itemid. Since each itemid is /// unique to each item, you'd first have to find the item, or /// use AddItemByDefindex instead. /// </summary> /// <returns> /// Returns false if the item doesn't exist in the Bot's inventory, /// and returns true if it appears the item was added. /// </returns> internal bool AddItemWebCmd(ulong itemid, int slot,int appid,long contextid) { var data = new NameValueCollection (); data.Add ("sessionid", sessionIdEsc); data.Add("appid", "" + appid); data.Add ("contextid", "" + contextid); data.Add ("itemid", "" + itemid); data.Add ("slot", "" + slot); string result = Fetch(baseTradeURL + "additem", "POST", data); dynamic json = JsonConvert.DeserializeObject(result); return IsSuccess(json); } /// <summary> /// Removes an item by its itemid. Read AddItem about itemids. /// Returns false if the item isn't in the offered items, or /// true if it appears it succeeded. /// </summary> internal bool RemoveItemWebCmd(ulong itemid, int slot, int appid, long contextid) { var data = new NameValueCollection (); data.Add ("sessionid", sessionIdEsc); data.Add("appid", "" + appid); data.Add("contextid", "" + contextid); data.Add ("itemid", "" + itemid); data.Add ("slot", "" + slot); string result = Fetch (baseTradeURL + "removeitem", "POST", data); dynamic json = JsonConvert.DeserializeObject(result); return IsSuccess(json); } /// <summary> /// Sets the bot to a ready status. /// </summary> internal bool SetReadyWebCmd(bool ready) { var data = new NameValueCollection (); data.Add ("sessionid", sessionIdEsc); data.Add ("ready", ready ? "true" : "false"); data.Add ("version", "" + Version); string result = Fetch (baseTradeURL + "toggleready", "POST", data); dynamic json = JsonConvert.DeserializeObject(result); return IsSuccess(json); } /// <summary> /// Accepts the trade from the user. Returns a deserialized /// JSON object. /// </summary> internal bool AcceptTradeWebCmd() { var data = new NameValueCollection (); data.Add ("sessionid", sessionIdEsc); data.Add ("version", "" + Version); string response = Fetch (baseTradeURL + "confirm", "POST", data); dynamic json = JsonConvert.DeserializeObject(response); return IsSuccess(json); } /// <summary> /// Cancel the trade. This calls the OnClose handler, as well. /// </summary> internal bool CancelTradeWebCmd () { var data = new NameValueCollection (); data.Add ("sessionid", sessionIdEsc); string result = Fetch (baseTradeURL + "cancel", "POST", data); dynamic json = JsonConvert.DeserializeObject(result); return IsSuccess(json); } private bool IsSuccess(dynamic json) { if(json == null) return false; try { //Sometimes, the response looks like this: {"success":false,"results":{"success":11}} //I believe this is Steam's way of asking the trade window (which is actually a webpage) to refresh, following a large successful update return (json.success == "true" || (json.results != null && json.results.success == "11")); } catch(Exception) { return false; } } #endregion Trade Web API command methods string Fetch (string url, string method, NameValueCollection data = null) { return SteamWeb.Fetch (url, method, data); } private void Init() { sessionIdEsc = Uri.UnescapeDataString(SteamWeb.SessionId); Version = 1; baseTradeURL = String.Format (SteamTradeUrl, OtherSID.ConvertToUInt64()); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using RunnersTimeManagement.WebServer.Areas.HelpPage.Models; namespace RunnersTimeManagement.WebServer.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 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 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) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(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}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Copyright (c) rubicon IT GmbH, www.rubicon.eu // // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. rubicon licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. // using System; using System.Collections; using System.Diagnostics; using System.Reflection; using JetBrains.Annotations; // ReSharper disable once CheckNamespace namespace Remotion.Utilities { /// <summary> /// This utility class provides methods for checking arguments. /// </summary> /// <remarks> /// Some methods of this class return the value of the parameter. In some cases, this is useful because the value will be converted to another /// type: /// <code><![CDATA[ /// void foo (object o) /// { /// int i = ArgumentUtility.CheckNotNullAndType<int> ("o", o); /// } /// ]]></code> /// In some other cases, the input value is returned unmodified. This makes it easier to use the argument checks in calls to base class constructors /// or property setters: /// <code><![CDATA[ /// class MyType : MyBaseType /// { /// public MyType (string name) : base (ArgumentUtility.CheckNotNullOrEmpty ("name", name)) /// { /// } /// /// public override Name /// { /// set { base.Name = ArgumentUtility.CheckNotNullOrEmpty ("value", value); } /// } /// } /// ]]></code> /// </remarks> static partial class ArgumentUtility { [AssertionMethod] public static T CheckNotNull<T> ( [InvokerParameterName] string argumentName, [AssertionCondition (AssertionConditionType.IS_NOT_NULL)] [NoEnumeration] [CanBeNull] T actualValue) { // ReSharper disable CompareNonConstrainedGenericWithNull if (actualValue == null) // ReSharper restore CompareNonConstrainedGenericWithNull throw new ArgumentNullException (argumentName); return actualValue; } [Conditional ("DEBUG")] [AssertionMethod] public static void DebugCheckNotNull<T> ( [InvokerParameterName] string argumentName, [AssertionCondition (AssertionConditionType.IS_NOT_NULL)] [NoEnumeration] T actualValue) { CheckNotNull (argumentName, actualValue); } [AssertionMethod] public static string CheckNotNullOrEmpty ( [InvokerParameterName] string argumentName, [AssertionCondition (AssertionConditionType.IS_NOT_NULL)] string actualValue) { CheckNotNull (argumentName, actualValue); if (actualValue.Length == 0) throw CreateArgumentEmptyException (argumentName); return actualValue; } [Conditional ("DEBUG")] [AssertionMethod] public static void DebugCheckNotNullOrEmpty ( [InvokerParameterName] string argumentName, [AssertionCondition (AssertionConditionType.IS_NOT_NULL)] string actualValue) { CheckNotNullOrEmpty (argumentName, actualValue); } [AssertionMethod] public static T CheckNotNullOrEmpty<T> ( [InvokerParameterName] string argumentName, [AssertionCondition (AssertionConditionType.IS_NOT_NULL)] T enumerable) where T: IEnumerable { CheckNotNull (argumentName, enumerable); CheckNotEmpty (argumentName, enumerable); return enumerable; } [Conditional ("DEBUG")] [AssertionMethod] public static void DebugCheckNotNullOrEmpty<T> ( [InvokerParameterName] string argumentName, [AssertionCondition (AssertionConditionType.IS_NOT_NULL)] T enumerable) where T: IEnumerable { CheckNotNullOrEmpty (argumentName, enumerable); } [AssertionMethod] public static T CheckNotNullOrItemsNull<T> ( [InvokerParameterName] string argumentName, [AssertionCondition (AssertionConditionType.IS_NOT_NULL)] T enumerable) where T: IEnumerable { CheckNotNull (argumentName, enumerable); int i = 0; foreach (object item in enumerable) { if (item == null) throw CreateArgumentItemNullException (argumentName, i); ++i; } return enumerable; } [AssertionMethod] public static T CheckNotNullOrEmptyOrItemsNull<T> ( [InvokerParameterName] string argumentName, [AssertionCondition (AssertionConditionType.IS_NOT_NULL)] T enumerable) where T: IEnumerable { CheckNotNullOrItemsNull (argumentName, enumerable); CheckNotEmpty (argumentName, enumerable); return enumerable; } [AssertionMethod] public static string CheckNotEmpty ([InvokerParameterName] string argumentName, string actualValue) { if (actualValue != null && actualValue.Length == 0) throw CreateArgumentEmptyException (argumentName); return actualValue; } [AssertionMethod] public static T CheckNotEmpty<T> ([InvokerParameterName] string argumentName, T enumerable) where T: IEnumerable { // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (enumerable != null) { var collection = enumerable as ICollection; if (collection != null) { if (collection.Count == 0) throw CreateArgumentEmptyException (argumentName); else return enumerable; } IEnumerator enumerator = enumerable.GetEnumerator(); var disposableEnumerator = enumerator as IDisposable; using (disposableEnumerator) // using (null) is allowed in C# { if (!enumerator.MoveNext()) throw CreateArgumentEmptyException (argumentName); } } return enumerable; } [AssertionMethod] public static Guid CheckNotEmpty ([InvokerParameterName] string argumentName, Guid actualValue) { if (actualValue == Guid.Empty) throw CreateArgumentEmptyException (argumentName); return actualValue; } public static object CheckNotNullAndType ( [InvokerParameterName] string argumentName, [AssertionCondition (AssertionConditionType.IS_NOT_NULL)] [NoEnumeration] object actualValue, Type expectedType) { if (actualValue == null) throw new ArgumentNullException (argumentName); // ReSharper disable UseMethodIsInstanceOfType if (!expectedType.GetTypeInfo().IsAssignableFrom (actualValue.GetType().GetTypeInfo())) throw CreateArgumentTypeException (argumentName, actualValue.GetType(), expectedType); // ReSharper restore UseMethodIsInstanceOfType return actualValue; } ///// <summary>Returns the value itself if it is not <see langword="null"/> and of the specified value type.</summary> ///// <typeparam name="TExpected"> The type that <paramref name="actualValue"/> must have. </typeparam> ///// <exception cref="ArgumentNullException"> <paramref name="actualValue"/> is <see langword="null"/>.</exception> ///// <exception cref="ArgumentException"> <paramref name="actualValue"/> is an instance of another type (which is not a subclass of <typeparamref name="TExpected"/>).</exception> //public static TExpected CheckNotNullAndType<TExpected> (string argumentName, object actualValue) // where TExpected: class //{ // if (actualValue == null) // throw new ArgumentNullException (argumentName); // return CheckType<TExpected> (argumentName, actualValue); //} /// <summary>Returns the value itself if it is not <see langword="null"/> and of the specified value type.</summary> /// <typeparam name="TExpected"> The type that <paramref name="actualValue"/> must have. </typeparam> /// <exception cref="ArgumentNullException">The <paramref name="actualValue"/> is a <see langword="null"/>.</exception> /// <exception cref="ArgumentException">The <paramref name="actualValue"/> is an instance of another type.</exception> public static TExpected CheckNotNullAndType<TExpected> ( [InvokerParameterName] string argumentName, [AssertionCondition (AssertionConditionType.IS_NOT_NULL)] [NoEnumeration] object actualValue) // where TExpected: struct { if (actualValue == null) throw new ArgumentNullException (argumentName); if (! (actualValue is TExpected)) throw CreateArgumentTypeException (argumentName, actualValue.GetType(), typeof (TExpected)); return (TExpected) actualValue; } /// <summary>Checks of the <paramref name="actualValue"/> is of the <paramref name="expectedType"/>.</summary> /// <exception cref="ArgumentNullException">The <paramref name="actualValue"/> is a <see langword="null"/>.</exception> /// <exception cref="ArgumentException">The <paramref name="actualValue"/> is an instance of another type.</exception> [Conditional ("DEBUG")] [AssertionMethod] public static void DebugCheckNotNullAndType ( [InvokerParameterName] string argumentName, [AssertionCondition (AssertionConditionType.IS_NOT_NULL)] [NoEnumeration] object actualValue, Type expectedType) { CheckNotNullAndType (argumentName, actualValue, expectedType); } public static object CheckType ([InvokerParameterName] string argumentName, [NoEnumeration] object actualValue, Type expectedType) { // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (actualValue == null) { if (NullableTypeUtility.IsNullableType_NoArgumentCheck (expectedType)) return null; else throw CreateArgumentTypeException (argumentName, null, expectedType); } // ReSharper disable UseMethodIsInstanceOfType if (!expectedType.GetTypeInfo().IsAssignableFrom (actualValue.GetType().GetTypeInfo())) throw CreateArgumentTypeException (argumentName, actualValue.GetType(), expectedType); // ReSharper restore UseMethodIsInstanceOfType return actualValue; } /// <summary>Returns the value itself if it is of the specified type.</summary> /// <typeparam name="TExpected"> The type that <paramref name="actualValue"/> must have. </typeparam> /// <exception cref="ArgumentException"> /// <paramref name="actualValue"/> is an instance of another type (which is not a subtype of <typeparamref name="TExpected"/>).</exception> /// <exception cref="ArgumentNullException"> /// <paramref name="actualValue" /> is null and <typeparamref name="TExpected"/> cannot be null. </exception> /// <remarks> /// For non-nullable value types, you should use either <see cref="CheckNotNullAndType{TExpected}"/> or pass the type /// <see cref="Nullable{T}" /> instead. /// </remarks> public static TExpected CheckType<TExpected> ([InvokerParameterName] string argumentName, [NoEnumeration] object actualValue) { // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (actualValue == null) { try { return (TExpected) actualValue; } catch (NullReferenceException) { throw new ArgumentNullException (argumentName); } } if (!(actualValue is TExpected)) throw CreateArgumentTypeException (argumentName, actualValue.GetType(), typeof (TExpected)); return (TExpected) actualValue; } /// <summary>Checks whether <paramref name="actualType"/> is not <see langword="null"/> and can be assigned to <paramref name="expectedType"/>.</summary> /// <exception cref="ArgumentNullException">The <paramref name="actualType"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentException">The <paramref name="actualType"/> cannot be assigned to <paramref name="expectedType"/>.</exception> public static Type CheckNotNullAndTypeIsAssignableFrom ( [InvokerParameterName] string argumentName, [AssertionCondition (AssertionConditionType.IS_NOT_NULL)] Type actualType, [AssertionCondition (AssertionConditionType.IS_NOT_NULL)] Type expectedType) { if (actualType == null) throw new ArgumentNullException (argumentName); return CheckTypeIsAssignableFrom (argumentName, actualType, expectedType); } /// <summary>Checks whether <paramref name="actualType"/> can be assigned to <paramref name="expectedType"/>.</summary> /// <exception cref="ArgumentException">The <paramref name="actualType"/> cannot be assigned to <paramref name="expectedType"/>.</exception> public static Type CheckTypeIsAssignableFrom ( [InvokerParameterName] string argumentName, Type actualType, [AssertionCondition (AssertionConditionType.IS_NOT_NULL)] Type expectedType) { CheckNotNull ("expectedType", expectedType); // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (actualType != null) { if (!expectedType.GetTypeInfo().IsAssignableFrom (actualType.GetTypeInfo())) { string message = string.Format ( "Parameter '{0}' is a '{2}', which cannot be assigned to type '{1}'.", argumentName, expectedType, actualType); throw new ArgumentException (message, argumentName); } } return actualType; } /// <summary>Checks whether <paramref name="actualType"/> can be assigned to <paramref name="expectedType"/>.</summary> /// <exception cref="ArgumentException">The <paramref name="actualType"/> cannot be assigned to <paramref name="expectedType"/>.</exception> [Conditional ("DEBUG")] [AssertionMethod] public static void DebugCheckTypeIsAssignableFrom ( [InvokerParameterName] string argumentName, Type actualType, [AssertionCondition (AssertionConditionType.IS_NOT_NULL)] Type expectedType) { CheckTypeIsAssignableFrom (argumentName, actualType, expectedType); } /// <summary>Checks whether all items in <paramref name="collection"/> are of type <paramref name="itemType"/> or a null reference.</summary> /// <exception cref="ArgumentException"> If at least one element is not of the specified type or a derived type. </exception> public static T CheckItemsType<T> ([InvokerParameterName] string argumentName, T collection, Type itemType) where T: ICollection { // ReSharper disable CompareNonConstrainedGenericWithNull // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (collection != null) // ReSharper restore CompareNonConstrainedGenericWithNull { int index = 0; foreach (object item in collection) { // ReSharper disable UseMethodIsInstanceOfType if (item != null && !itemType.GetTypeInfo().IsAssignableFrom (item.GetType().GetTypeInfo())) throw CreateArgumentItemTypeException (argumentName, index, itemType, item.GetType()); // ReSharper restore UseMethodIsInstanceOfType ++index; } } return collection; } /// <summary>Checks whether all items in <paramref name="collection"/> are of type <paramref name="itemType"/> and not null references.</summary> /// <exception cref="ArgumentException"> If at least one element is not of the specified type or a derived type. </exception> /// <exception cref="ArgumentNullException"> If at least one element is a null reference. </exception> public static T CheckItemsNotNullAndType<T> ([InvokerParameterName] string argumentName, T collection, Type itemType) where T: ICollection { // ReSharper disable CompareNonConstrainedGenericWithNull // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (collection != null) // ReSharper restore CompareNonConstrainedGenericWithNull { int index = 0; foreach (object item in collection) { if (item == null) throw CreateArgumentItemNullException (argumentName, index); // ReSharper disable UseMethodIsInstanceOfType if (!itemType.GetTypeInfo().IsAssignableFrom (item.GetType().GetTypeInfo())) throw CreateArgumentItemTypeException (argumentName, index, itemType, item.GetType()); // ReSharper restore UseMethodIsInstanceOfType ++index; } } return collection; } public static ArgumentException CreateArgumentEmptyException ([InvokerParameterName] string argumentName) { return new ArgumentException (string.Format("Parameter '{0}' cannot be empty.", argumentName), argumentName); } public static ArgumentException CreateArgumentTypeException ([InvokerParameterName] string argumentName, Type actualType, Type expectedType) { // ReSharper disable once ConditionIsAlwaysTrueOrFalse string actualTypeName = actualType != null ? actualType.ToString() : "<null>"; // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (expectedType == null) { return new ArgumentException (string.Format ("Parameter '{0}' has unexpected type '{1}'.", argumentName, actualTypeName), argumentName); } else { return new ArgumentException ( string.Format ("Parameter '{0}' has type '{2}' when type '{1}' was expected.", argumentName, expectedType, actualTypeName), argumentName); } } public static ArgumentException CreateArgumentItemTypeException ( [InvokerParameterName] string argumentName, int index, Type expectedType, Type actualType) { return new ArgumentException ( string.Format ( "Item {0} of parameter '{1}' has the type '{2}' instead of '{3}'.", index, argumentName, actualType, expectedType), argumentName); } public static ArgumentNullException CreateArgumentItemNullException ([InvokerParameterName] string argumentName, int index) { return new ArgumentNullException (argumentName, string.Format ("Item {0} of parameter '{1}' is null.", index, argumentName)); } } }
// Amplify Shader Editor - Visual Shader Editing Tool // Copyright (c) Amplify Creations, Lda <info@amplify.pt> using UnityEngine; using UnityEditor; using System.Collections.Generic; namespace AmplifyShaderEditor { public enum WirePortDataType { OBJECT = 1 << 1, FLOAT = 1 << 2, FLOAT2 = 1 << 3, FLOAT3 = 1 << 4, FLOAT4 = 1 << 5, FLOAT3x3 = 1 << 6, FLOAT4x4 = 1 << 7, COLOR = 1 << 8, INT = 1 << 9, SAMPLER1D = 1 << 10, SAMPLER2D = 1 << 11, SAMPLER3D = 1 << 12, SAMPLERCUBE = 1 << 13 } [System.Serializable] public class WirePort { private const double PortClickTime = 0.2; private double m_lastTimeClicked = -1; private Vector2 m_labelSize; private Vector2 m_unscaledLabelSize; protected bool m_dirtyLabelSize = true; private bool m_isEditable = false; private bool m_editingName = false; private int m_portRestrictions = 0; [SerializeField] private Rect m_position; [SerializeField] protected int m_nodeId = -1; [SerializeField] protected int m_portId = -1; [SerializeField] protected int m_orderId = -1; [SerializeField] protected WirePortDataType m_dataType = WirePortDataType.FLOAT; [SerializeField] protected string m_name; [SerializeField] protected List<WireReference> m_externalReferences; [SerializeField] protected bool m_locked = false; [SerializeField] protected bool m_visible = true; [SerializeField] protected bool m_hasCustomColor = false; [SerializeField] protected Color m_customColor = Color.white; [SerializeField] protected Rect m_activePortArea; public WirePort( int nodeId, int portId, WirePortDataType dataType, string name, int orderId = -1 ) { m_nodeId = nodeId; m_portId = portId; m_orderId = orderId; m_dataType = dataType; m_name = name; m_externalReferences = new List<WireReference>(); } public virtual void Destroy() { m_externalReferences.Clear(); m_externalReferences = null; } public void CreatePortRestrictions( params WirePortDataType[] validTypes ) { if ( validTypes != null ) { for ( int i = 0; i < validTypes.Length; i++ ) { m_portRestrictions = m_portRestrictions | ( int)validTypes[ i ]; } } } public bool CheckValidType( WirePortDataType dataType ) { if ( m_portRestrictions == 0 ) { return true; } return ( m_portRestrictions & ( int ) dataType ) != 0; } public bool ConnectTo( WireReference port ) { if ( m_locked ) return false; if ( m_externalReferences.Contains( port ) ) return false; m_externalReferences.Add( port ); return true; } public bool ConnectTo( int nodeId, int portId ) { if ( m_locked ) return false; foreach ( WireReference reference in m_externalReferences ) { if ( reference.NodeId == nodeId && reference.PortId == portId ) { return false; } } m_externalReferences.Add( new WireReference( nodeId, portId, m_dataType, false ) ); return true; } public bool ConnectTo( int nodeId, int portId, WirePortDataType dataType, bool typeLocked ) { if ( m_locked ) return false; foreach ( WireReference reference in m_externalReferences ) { if ( reference.NodeId == nodeId && reference.PortId == portId ) { return false; } } m_externalReferences.Add( new WireReference( nodeId, portId, dataType, typeLocked ) ); return true; } public void DummyAdd( int nodeId, int portId ) { m_externalReferences.Insert( 0, new WireReference( nodeId, portId, WirePortDataType.OBJECT, false ) ); } public void DummyRemove() { m_externalReferences.RemoveAt( 0 ); } public WireReference GetConnection( int connID = 0 ) { if ( connID < m_externalReferences.Count ) return m_externalReferences[ connID ]; return null; } public void ChangeProperties( string newName, WirePortDataType newType, bool invalidateConnections ) { m_name = newName; if ( m_dataType != newType ) { DataType = newType; if ( invalidateConnections ) { InvalidateAllConnections(); } else { NotifyExternalRefencesOnChange(); } } } public void ChangeType( WirePortDataType newType, bool invalidateConnections ) { if ( m_dataType != newType ) { DataType = newType; if ( invalidateConnections ) { InvalidateAllConnections(); } else { NotifyExternalRefencesOnChange(); } } } public virtual void NotifyExternalRefencesOnChange() { } public void UpdateInfoOnExternalConn( int nodeId, int portId, WirePortDataType type ) { for ( int i = 0; i < m_externalReferences.Count; i++ ) { if ( m_externalReferences[ i ].NodeId == nodeId && m_externalReferences[ i ].PortId == portId ) { m_externalReferences[ i ].DataType = type; } } } public void InvalidateConnection( int nodeId, int portId ) { int id = -1; for ( int i = 0; i < m_externalReferences.Count; i++ ) { if ( m_externalReferences[ i ].NodeId == nodeId && m_externalReferences[ i ].PortId == portId ) { id = i; break; } } if ( id > -1 ) m_externalReferences.RemoveAt( id ); } public void RemoveInvalidConnections() { Debug.Log( "Cleaning invalid connections" ); List<WireReference> validConnections = new List<WireReference>(); for ( int i = 0; i < m_externalReferences.Count; i++ ) { if ( m_externalReferences[ i ].IsValid ) { validConnections.Add( m_externalReferences[ i ] ); } else { Debug.Log( "Detected invalid connection on node " + m_nodeId + " port " + m_portId ); } } m_externalReferences.Clear(); m_externalReferences = validConnections; } public void InvalidateAllConnections() { m_externalReferences.Clear(); } public virtual void FullDeleteConnections() { } public bool IsConnectedTo( int nodeId, int portId ) { if ( m_locked ) return false; for ( int i = 0; i < m_externalReferences.Count; i++ ) { if ( m_externalReferences[ i ].NodeId == nodeId && m_externalReferences[ i ].PortId == portId ) return true; } return false; } public WirePortDataType ConnectionType( int id = 0 ) { return ( id < m_externalReferences.Count ) ? m_externalReferences[ id ].DataType : DataType; } public bool CheckMatchConnectionType( int id = 0 ) { if ( id < m_externalReferences.Count ) return m_externalReferences[ id ].DataType == DataType; return false; } public void MatchPortToConnection( int id = 0 ) { if ( id < m_externalReferences.Count ) { DataType = m_externalReferences[ id ].DataType; } } public void ResetWireReferenceStatus() { for ( int i = 0; i < m_externalReferences.Count; i++ ) { m_externalReferences[ i ].WireStatus = WireStatus.Default; } } public bool InsideActiveArea( Vector2 pos ) { return m_activePortArea.Contains( pos ); } public void Click() { if ( m_isEditable ) { if ( ( EditorApplication.timeSinceStartup - m_lastTimeClicked ) < PortClickTime ) { m_editingName = true; GUI.FocusControl( "port" + m_nodeId.ToString() + m_portId.ToString() ); TextEditor te = ( TextEditor ) GUIUtility.GetStateObject( typeof( TextEditor ), GUIUtility.keyboardControl ); if ( te != null ) { te.SelectAll(); } } m_lastTimeClicked = EditorApplication.timeSinceStartup; } } public bool Draw( Rect textPos , GUIStyle style ) { bool changeFlag = false; if ( m_isEditable && m_editingName ) { textPos.width = m_labelSize.x; EditorGUI.BeginChangeCheck(); GUI.SetNextControlName( "port" + m_nodeId.ToString() + m_portId.ToString() ); m_name = GUI.TextField( textPos, m_name, style ); if ( EditorGUI.EndChangeCheck() ) { m_dirtyLabelSize = true; changeFlag = true; } if ( Event.current.isKey && ( Event.current.keyCode == KeyCode.Return || Event.current.keyCode == KeyCode.KeypadEnter ) ) { m_editingName = false; GUIUtility.keyboardControl = 0; } } else { GUI.Label( textPos, m_name, style ); } //GUI.Box( textPos, string.Empty ); return changeFlag; } public void ResetEditing() { m_editingName = false; } public virtual void ForceClearConnection() { } public bool IsConnected { get { return ( m_externalReferences.Count > 0 && !m_locked ); } } public List<WireReference> ExternalReferences { get { return m_externalReferences; } } public int ConnectionCount { get { return m_externalReferences.Count; } } public Rect Position { get { return m_position; } set { m_position = value; } } public int PortId { get { return m_portId; } set { m_portId = value; } } public int OrderId { get { return m_orderId; } set { m_orderId = value; } } public int NodeId { get { return m_nodeId; } set { m_nodeId = value; } } public virtual WirePortDataType DataType { get { return m_dataType; } set { m_dataType = value; } } public bool Visible { get { return m_visible; } set { m_visible = value; if ( !m_visible && IsConnected ) { ForceClearConnection(); } } } public bool Locked { get { return m_locked; } set { //if ( m_locked && IsConnected ) //{ // ForceClearConnection(); //} m_locked = value; } } public virtual string Name { get { return m_name; } set { m_name = value; m_dirtyLabelSize = true; } } public bool DirtyLabelSize { get { return m_dirtyLabelSize; } set { m_dirtyLabelSize = value; } } public bool HasCustomColor { get { return m_hasCustomColor; } } public Color CustomColor { get { return m_customColor; } set { m_hasCustomColor = true; m_customColor = value; } } public Rect ActivePortArea { get { return m_activePortArea; } set { m_activePortArea = value; } } public Vector2 LabelSize { get { return m_labelSize; } set { m_labelSize = value; } } public Vector2 UnscaledLabelSize { get { return m_unscaledLabelSize; } set { m_unscaledLabelSize = value; } } public bool IsEditable { get { return m_isEditable; } set { m_isEditable = value; } } public bool Available { get { return m_visible && !m_locked; } } public override string ToString() { string dump = ""; dump += "Order: " + m_orderId + "\n"; dump += "Name: " + m_name + "\n"; dump += " Type: " + m_dataType; dump += " NodeId : " + m_nodeId; dump += " PortId : " + m_portId; dump += "\nConnections:\n"; foreach ( WireReference wirePort in m_externalReferences ) { dump += wirePort + "\n"; } return dump; } } }
using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; namespace allverse3.Data.Migrations { public partial class CreateIdentitySchema : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "AspNetRoles", columns: table => new { Id = table.Column<string>(nullable: false), ConcurrencyStamp = table.Column<string>(nullable: true), Name = table.Column<string>(nullable: true), NormalizedName = table.Column<string>(maxLength: 256, nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoles", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetUserTokens", columns: table => new { UserId = table.Column<string>(nullable: false), LoginProvider = table.Column<string>(nullable: false), Name = table.Column<string>(nullable: false), Value = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); }); migrationBuilder.CreateTable( name: "AspNetUsers", columns: table => new { Id = table.Column<string>(nullable: false), AccessFailedCount = table.Column<int>(nullable: false), ConcurrencyStamp = table.Column<string>(nullable: true), Email = table.Column<string>(nullable: true), EmailConfirmed = table.Column<bool>(nullable: false), LockoutEnabled = table.Column<bool>(nullable: false), LockoutEnd = table.Column<DateTimeOffset>(nullable: true), NormalizedEmail = table.Column<string>(maxLength: 256, nullable: true), NormalizedUserName = table.Column<string>(maxLength: 256, nullable: true), PasswordHash = table.Column<string>(nullable: true), PhoneNumber = table.Column<string>(nullable: true), PhoneNumberConfirmed = table.Column<bool>(nullable: false), SecurityStamp = table.Column<string>(nullable: true), TwoFactorEnabled = table.Column<bool>(nullable: false), UserName = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUsers", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetRoleClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Autoincrement", true), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true), RoleId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Autoincrement", true), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetUserClaims_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserLogins", columns: table => new { LoginProvider = table.Column<string>(nullable: false), ProviderKey = table.Column<string>(nullable: false), ProviderDisplayName = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); table.ForeignKey( name: "FK_AspNetUserLogins_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserRoles", columns: table => new { UserId = table.Column<string>(nullable: false), RoleId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "RoleNameIndex", table: "AspNetRoles", column: "NormalizedName"); migrationBuilder.CreateIndex( name: "IX_AspNetRoleClaims_RoleId", table: "AspNetRoleClaims", column: "RoleId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserClaims_UserId", table: "AspNetUserClaims", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserLogins_UserId", table: "AspNetUserLogins", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_RoleId", table: "AspNetUserRoles", column: "RoleId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_UserId", table: "AspNetUserRoles", column: "UserId"); migrationBuilder.CreateIndex( name: "EmailIndex", table: "AspNetUsers", column: "NormalizedEmail"); migrationBuilder.CreateIndex( name: "UserNameIndex", table: "AspNetUsers", column: "NormalizedUserName"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "AspNetRoleClaims"); migrationBuilder.DropTable( name: "AspNetUserClaims"); migrationBuilder.DropTable( name: "AspNetUserLogins"); migrationBuilder.DropTable( name: "AspNetUserRoles"); migrationBuilder.DropTable( name: "AspNetUserTokens"); migrationBuilder.DropTable( name: "AspNetRoles"); migrationBuilder.DropTable( name: "AspNetUsers"); } } }
using UnityEngine; using System.Collections; using Rewired; using UnityEngine.UI; [RequireComponent(typeof(MoveController))] public class Player : MonoBehaviour { public Animator animator; public GameObject AttackCollider; //public ISkill[] Skills = new ISkill[4]; //Do not set Strength Agility or Intelligence below 1, it will cause problems when they are multiplied //with starting values of the ares they are used in. public float Strength; public float Agility; public float Intelligence; private bool isGrounded = true; private bool isMoving = false; public float jumpHeight = 4; public float timeToJumpApex = .4f; public float horizontalMoveSpeed = 6; public float verticalMoveSpeed = 10; public int playerId; // The Rewired player id of this character private float accelerationTimeAirborne = .2f; private float accelerationTimeGrounded = .1f; private bool isNotStunned = true; private bool isInvincible = false; private IPlayerState state; private IAttack attackState; private float invTime, initialRegenTime, regenTick; private float knockBackResistance, knockBackReset, knockBackCounter; private float flinchResistance, flinchReset, flinchCounter; private float gravity; private float jumpVelocity; private Vector3 velocity; private float velocityXSmoothing; private float velocityZSmoothing; private MoveController controller; // private CrowdControllable crowdControllable; private Health health; [System.NonSerialized] // Don't serialize this so the value is lost on an editor script recompile. private bool initialized; private Rewired.Player playerRewired; private Text text; public float bossHP = 10; private bool blink; private float blinkTime; void Start() { state = new StandingState(); attackState = new IdleAttackState(); animator = GetComponent<Animator>(); AttackCollider.SetActive(false); health = GetComponent<Health>(); controller = GetComponent<MoveController>(); gravity = -(2 * jumpHeight) / Mathf.Pow(timeToJumpApex, 2) / 3; jumpVelocity = Mathf.Abs(gravity) * timeToJumpApex; print("Gravity: " + gravity + " Jump Velocity: " + jumpVelocity); initialRegenTime = 6; regenTick = 2; knockBackResistance = 10; knockBackCounter = 0; knockBackReset = 0; flinchResistance = 10; flinchCounter = 0; flinchReset = 0; text = GameObject.Find("HealthText").GetComponent<Text>(); text.text = text.GetComponent<Score>().modX(0).ToString(); blink = false; blinkTime = 0; } void Update() { if (!ReInput.isReady) return; // Exit if Rewired isn't ready. This would only happen during a script recompile in the editor. if (!initialized) Initialize(); // Reinitialize after a recompile in the editor if(blink) { GetComponent<SpriteRenderer>().enabled = !GetComponent<SpriteRenderer>().enabled; blinkTime -= Time.deltaTime; if (blinkTime <= 0) { GetComponent<SpriteRenderer>().enabled = true; blink = false; } } if (controller.collisions.above || controller.collisions.below) { velocity.y = 0; } if (initialRegenTime > 6) { if (regenTick > 2) { regenTick = 0; health.Regen(); } } //Invincibility timer if (invTime >= 0) { if (invTime != 0) { isInvincible = true; invTime -= Time.deltaTime; } } else { isInvincible = false; invTime = 0; } Vector2 input = new Vector2(playerRewired.GetAxisRaw("MoveHorizontal"), playerRewired.GetAxisRaw("MoveVertical")); float horiz = 0; float vert = 0; if (Input.GetKey(KeyCode.A)) horiz = -1; else if (Input.GetKey(KeyCode.D)) horiz = 1; if (Input.GetKey(KeyCode.W)) vert = 1; else if (Input.GetKey(KeyCode.S)) vert = -1; //Vector2 input = new Vector2(horiz, vert); HandleInput(); ReadyMove(input); if (input.x == 0 && input.y == 0) { isMoving = false; } else { isMoving = true; } if (knockBackCounter > 0) { knockBackReset += Time.deltaTime; if (knockBackReset >= 5) { knockBackReset = 0; knockBackCounter = 0; } } if (flinchCounter > 0) { flinchReset += Time.deltaTime; if (flinchReset >= 2) { // flinchReset = 0; // flinchCounter = 0; } } initialRegenTime += Time.deltaTime; regenTick += Time.deltaTime; UpdateState(); } //Reset hitReset when hit public void SetInvTime(float time) { invTime = time; initialRegenTime = 0; } public void setBlink() { blink = true; if (blinkTime <= 0) blinkTime = 1; } public void SetAct(bool x) { isNotStunned = x; } public bool GetInvincible() { return isInvincible; } public void SetInvincible(bool x) { isInvincible = x; } public void SetStrength(int strength) { if(strength > 0) { Strength = strength; } else { Strength = 1; } } public float GetStrength() { return Strength; } public void SetAgility(int agility) { if(agility > 0) { Agility = agility; } else { Agility = 1; } } public float GetAgility() { return Agility; } public void SetIntelligence(int intelligence) { if(intelligence > 0) { Intelligence = intelligence; } else { Intelligence = 1; } } public float GetIntelligence() { return Intelligence; } public float GetKBResist() { return knockBackResistance; } public void ModifyKBCount(float set, float multiplier = 1) { knockBackCounter += set; knockBackCounter *= multiplier; } public bool GetKnockable() { if (knockBackCounter >= knockBackResistance) { return true; } return false; } public void ResetKB() { knockBackReset = 0; } public float GetFlinchResist() { return flinchResistance; } public void ModifyFlinchCount(float set, float multiplier = 1) { flinchCounter += set; flinchCounter *= multiplier; } public bool GetFlinchable() { Debug.Log(flinchCounter + " vs " + flinchResistance); if (flinchCounter >= flinchResistance) { return true; } return false; } public void ResetFlinch() { flinchReset = 0; } private void HandleInput() { IPlayerState newState = state.HandleInput(this); if (newState != null) { state.ExitState(this); state = newState; state.EnterState(this); } IAttack newAttackState = attackState.HandleInput(this); if (newAttackState != null) { attackState.ExitState(this); attackState = newAttackState; attackState.EnterState(this); } } private void UpdateState() { state.UpdateState(this); attackState.UpdateState(this); } private void ReadyMove(Vector2 input) { velocity.y += gravity * Time.deltaTime; float targetVelocityX = input.x * horizontalMoveSpeed * Agility; float targetVelocityZ = input.y * verticalMoveSpeed * Agility; velocity.x = Mathf.SmoothDamp(velocity.x, targetVelocityX, ref velocityXSmoothing, (controller.collisions.below) ? accelerationTimeGrounded : accelerationTimeAirborne); velocity.z = Mathf.SmoothDamp(velocity.z, targetVelocityZ, ref velocityZSmoothing, (controller.collisions.below) ? accelerationTimeGrounded : accelerationTimeAirborne); controller.Move(velocity * Time.deltaTime, input); } public void SetIsGrounded(bool isPlayerOnGround) { isGrounded = isPlayerOnGround; } public bool GetIsGrounded() { return isGrounded; } public bool GetIsMoving() { return isMoving; } public MoveController GetMoveController() { return controller; } public void EndJump() { velocity.y = 0; } public void Jump() { velocity.y = jumpVelocity; } public GameObject GetAttackCollider() { return AttackCollider; } private void Initialize() { // Get the Rewired Player object for this player. playerRewired = ReInput.players.GetPlayer(playerId); initialized = true; } private void UseSkill1() { //Skills[0].UseSkill(gameObject); } private void UseSkill2() { // Skills[1].UseSkill(gameObject); } private void UseSkill3() { //Skills[2].UseSkill(gameObject); } private void UseSkill4() { //Skills[3].UseSkill(gameObject); } }
// Copyright 2007-2010 Portland State University, University of Wisconsin-Madison // Author: Robert Scheller, Ben Sulman using Landis.Core; using Landis.SpatialModeling; using Edu.Wisc.Forest.Flel.Util; using Landis.Library.InitialCommunities; using System.Collections.Generic; using Landis.Library.LeafBiomassCohorts; using Landis.Library.Climate; using System; //using Landis.Cohorts; namespace Landis.Extension.Succession.NetEcosystemCN { /// <summary> /// The initial live and dead biomass at a site. /// </summary> public class InitialBiomass { private ISiteCohorts cohorts; private Layer surfaceDeadWood; private Layer surfaceStructural; private Layer surfaceMetabolic; private Layer soilDeadWood; private Layer soilStructural; private Layer soilMetabolic; private Layer som1surface; private Layer som1soil; private Layer som2; private Layer som3; private double mineralN; private double cohortLeafC; private double cohortFRootC; private double cohortLeafN; private double cohortFRootN; private double cohortWoodC; private double cohortCRootC; private double cohortWoodN; private double cohortCRootN; //--------------------------------------------------------------------- /// <summary> /// The site's initial cohorts. /// </summary> public ISiteCohorts Cohorts { get { return cohorts; } } public Layer SurfaceDeadWood { get { return surfaceDeadWood; } } public Layer SoilDeadWood { get { return soilDeadWood; } } public Layer SurfaceStructural { get { return surfaceStructural ; } } public Layer SoilStructural { get { return soilStructural ; } } public Layer SurfaceMetabolic { get { return surfaceMetabolic ; } } public Layer SoilMetabolic { get { return soilMetabolic ; } } public Layer SOM1surface { get { return som1surface ; } } public Layer SOM1soil { get { return som1soil ; } } public Layer SOM2 { get { return som2; } } public Layer SOM3 { get { return som3; } } public double MineralN { get { return mineralN; } } public double CohortLeafC { get { return cohortLeafC; } } public double CohortFRootC { get { return cohortFRootC; } } public double CohortLeafN { get { return cohortLeafN; } } public double CohortFRootN { get { return cohortFRootN; } } public double CohortWoodC { get { return cohortWoodC; } } public double CohortCRootC { get { return cohortCRootC; } } public double CohortWoodN { get { return cohortWoodN; } } public double CohortCRootN { get { return cohortCRootN; } } //--------------------------------------------------------------------- private InitialBiomass(ISiteCohorts cohorts, Layer surfaceDeadWood, Layer surfaceStructural, Layer surfaceMetabolic, Layer soilDeadWood, Layer soilStructural, Layer soilMetabolic, Layer som1surface, Layer som1soil, Layer som2, Layer som3, double mineralN, double cohortLeafC, double cohortFRootC, double cohortLeafN, double cohortFRootN, double cohortWoodC, double cohortCRootC, double cohortWoodN, double cohortCRootN ) { this.cohorts = cohorts; this.surfaceDeadWood = surfaceDeadWood; this.surfaceStructural = surfaceStructural; this.surfaceMetabolic = surfaceMetabolic; this.soilDeadWood = soilDeadWood; this.soilStructural = soilStructural; this.soilMetabolic = soilMetabolic; this.som1surface = som1surface; this.som1soil = som1soil; this.som2 = som2; this.som3 = som3; this.mineralN = mineralN; this.cohortLeafC = cohortLeafC; this.cohortFRootC = cohortFRootC; this.cohortLeafN = cohortLeafN; this.cohortFRootN = cohortFRootN; this.cohortWoodC = cohortWoodC; this.cohortCRootC = cohortCRootC; this.cohortWoodN = cohortWoodN; this.cohortCRootN = cohortCRootN; } //--------------------------------------------------------------------- public static SiteCohorts Clone(ISiteCohorts site_cohorts) { SiteCohorts clone = new SiteCohorts(); foreach (ISpeciesCohorts speciesCohorts in site_cohorts) foreach (ICohort cohort in speciesCohorts) clone.AddNewCohort(cohort.Species, cohort.Age, cohort.WoodBiomass, cohort.LeafBiomass); return clone; } //--------------------------------------------------------------------- private static IDictionary<uint, InitialBiomass> initialSites; // Initial site biomass for each unique pair of initial // community and ecoregion; Key = 32-bit unsigned integer where // high 16-bits is the map code of the initial community and the // low 16-bits is the ecoregion's map code private static IDictionary<uint, List<Landis.Library.AgeOnlyCohorts.ICohort>> sortedCohorts; // Age cohorts for an initial community sorted from oldest to // youngest. Key = initial community's map code private static ushort successionTimestep; //--------------------------------------------------------------------- private static uint ComputeKey(uint initCommunityMapCode, uint ecoregionMapCode) { return (uint) ((initCommunityMapCode << 16) | ecoregionMapCode); } //--------------------------------------------------------------------- static InitialBiomass() { initialSites = new Dictionary<uint, InitialBiomass>(); sortedCohorts = new Dictionary<uint, List<Landis.Library.AgeOnlyCohorts.ICohort>>(); } //--------------------------------------------------------------------- /// <summary> /// Initializes this class. /// </summary> /// <param name="timestep"> /// The plug-in's timestep. It is used for growing biomass cohorts. /// </param> public static void Initialize(int timestep) { successionTimestep = (ushort) timestep; } //--------------------------------------------------------------------- /// <summary> /// Computes the initial biomass at a site. /// </summary> /// <param name="site"> /// The selected site. /// </param> /// <param name="initialCommunity"> /// The initial community of age cohorts at the site. /// </param> public static InitialBiomass Compute(ActiveSite site, ICommunity initialCommunity) { IEcoregion ecoregion = PlugIn.ModelCore.Ecoregion[site]; if (!ecoregion.Active) { string mesg = string.Format("Initial community {0} is located on a non-active ecoregion {1}", initialCommunity.MapCode, ecoregion.Name); throw new System.ApplicationException(mesg); } uint key = ComputeKey(initialCommunity.MapCode, ecoregion.MapCode); InitialBiomass initialBiomass; if (initialSites.TryGetValue(key, out initialBiomass)) return initialBiomass; // If we don't have a sorted list of age cohorts for the initial // community, make the list List<Landis.Library.AgeOnlyCohorts.ICohort> sortedAgeCohorts; if (! sortedCohorts.TryGetValue(initialCommunity.MapCode, out sortedAgeCohorts)) { sortedAgeCohorts = SortCohorts(initialCommunity.Cohorts); sortedCohorts[initialCommunity.MapCode] = sortedAgeCohorts; } ISiteCohorts cohorts = MakeBiomassCohorts(sortedAgeCohorts, site); initialBiomass = new InitialBiomass( cohorts, SiteVars.SurfaceDeadWood[site], SiteVars.SurfaceStructural[site], SiteVars.SurfaceMetabolic[site], SiteVars.SoilDeadWood[site], SiteVars.SoilStructural[site], SiteVars.SoilMetabolic[site], SiteVars.SOM1surface[site], SiteVars.SOM1soil[site], SiteVars.SOM2[site], SiteVars.SOM3[site], SiteVars.MineralN[site], SiteVars.CohortLeafC[site], SiteVars.CohortFRootC[site], SiteVars.CohortLeafN[site], SiteVars.CohortFRootN[site], SiteVars.CohortWoodC[site], SiteVars.CohortCRootC[site], SiteVars.CohortWoodN[site], SiteVars.CohortCRootN[site] ); initialSites[key] = initialBiomass; return initialBiomass; } //--------------------------------------------------------------------- /// <summary> /// Makes a list of age cohorts in an initial community sorted from /// oldest to youngest. /// </summary> public static List<Landis.Library.AgeOnlyCohorts.ICohort> SortCohorts(List<Landis.Library.AgeOnlyCohorts.ISpeciesCohorts> sppCohorts) { List<Landis.Library.AgeOnlyCohorts.ICohort> cohorts = new List<Landis.Library.AgeOnlyCohorts.ICohort>(); foreach (Landis.Library.AgeOnlyCohorts.ISpeciesCohorts speciesCohorts in sppCohorts) { foreach (Landis.Library.AgeOnlyCohorts.ICohort cohort in speciesCohorts) { cohorts.Add(cohort); //PlugIn.ModelCore.UI.WriteLine("ADDED: {0} {1}.", cohort.Species.Name, cohort.Age); } } cohorts.Sort(Landis.Library.AgeOnlyCohorts.Util.WhichIsOlderCohort); return cohorts; } //--------------------------------------------------------------------- /// <summary> /// A method that computes the initial biomass for a new cohort at a /// site based on the existing cohorts. /// </summary> public delegate float[] ComputeMethod(ISpecies species, ISiteCohorts siteCohorts, ActiveSite site); //--------------------------------------------------------------------- /// <summary> /// Grows the cohorts during spin-up /// Makes the set of biomass cohorts at a site based on the age cohorts /// at the site, using a specified method for computing a cohort's /// initial biomass. /// </summary> /// <param name="ageCohorts"> /// A sorted list of age cohorts, from oldest to youngest. /// </param> /// <param name="site"> /// Site where cohorts are located. /// </param> /// <param name="initialBiomassMethod"> /// The method for computing the initial biomass for a new cohort. /// </param> public static ISiteCohorts MakeBiomassCohorts(List<Landis.Library.AgeOnlyCohorts.ICohort> ageCohorts, ActiveSite site, ComputeMethod initialBiomassMethod) { IEcoregion ecoregion = PlugIn.ModelCore.Ecoregion[site]; //if (Climate.Spinup_AllData.Count >= ageCohorts[0].Age) //try //{ //PlugIn.ModelCore.UI.WriteLine("Making Biomass Cohorts using spin-up climate data"); SiteVars.Cohorts[site] = new Library.LeafBiomassCohorts.SiteCohorts(); if (ageCohorts.Count == 0) return SiteVars.Cohorts[site]; int indexNextAgeCohort = 0; // The index in the list of sorted age cohorts of the next // cohort to be considered // Loop through time from -N to 0 where N is the oldest cohort. // So we're going from the time when the oldest cohort was "born" // to the present time (= 0). Because the age of any age cohort // is a multiple of the succession timestep, we go from -N to 0 // by that timestep. NOTE: the case where timestep = 1 requires // special treatment because if we start at time = -N with a // cohort with age = 1, then at time = 0, its age will N+1 not N. // Therefore, when timestep = 1, the ending time is -1. //int endTime = (successionTimestep == 1) ? -1 : -1; //PlugIn.ModelCore.UI.WriteLine(" Ageing initial cohorts. Oldest cohorts={0} yrs, succession timestep={1}, endTime={2}.", ageCohorts[0].Age, successionTimestep, endTime); for (int time = -(ageCohorts[0].Age); time <= -1; time += successionTimestep) { //PlugIn.ModelCore.UI.WriteLine(" Ageing initial cohorts. Oldest cohorts={0} yrs, succession timestep={1}.", ageCohorts[0].Age, successionTimestep); EcoregionData.SetSingleAnnualClimate(ecoregion, time + ageCohorts[0].Age, Climate.Phase.SpinUp_Climate); //the spinup climate array is sorted from oldest to newest years // Add those cohorts that were born at the current year while (indexNextAgeCohort < ageCohorts.Count && ageCohorts[indexNextAgeCohort].Age == -time) { ISpecies species = ageCohorts[indexNextAgeCohort].Species; float[] initialBiomass = initialBiomassMethod(species, SiteVars.Cohorts[site], site); SiteVars.Cohorts[site].AddNewCohort(ageCohorts[indexNextAgeCohort].Species, 1, initialBiomass[0], initialBiomass[1]); indexNextAgeCohort++; } Main.Run(site, successionTimestep, true); } return SiteVars.Cohorts[site]; } //--------------------------------------------------------------------- /// <summary> /// Makes the set of biomass cohorts at a site based on the age cohorts /// at the site, using the default method for computing a cohort's /// initial biomass. /// </summary> /// <param name="ageCohorts"> /// A sorted list of age cohorts, from oldest to youngest. /// </param> /// <param name="site"> /// Site where cohorts are located. /// </param> public static ISiteCohorts MakeBiomassCohorts(List<Landis.Library.AgeOnlyCohorts.ICohort> ageCohorts, ActiveSite site) { return MakeBiomassCohorts(ageCohorts, site, CohortBiomass.InitialBiomass); } } }
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; using Norm.Configuration; namespace Norm.BSON { /// <summary> /// BSON Deserializer /// </summary> public class BsonDeserializer : BsonSerializerBase { private static readonly Type _IEnumerableType = typeof(IEnumerable); private static readonly Type _IDictionaryType = typeof(IDictionary<,>); private readonly static IDictionary<BSONTypes, Type> _typeMap = new Dictionary<BSONTypes, Type> { {BSONTypes.Int32, typeof(int)}, {BSONTypes.Int64, typeof (long)}, {BSONTypes.Boolean, typeof (bool)}, {BSONTypes.String, typeof (string)}, {BSONTypes.Double, typeof(double)}, {BSONTypes.Binary, typeof (byte[])}, {BSONTypes.Regex, typeof (Regex)}, {BSONTypes.DateTime, typeof (DateTime)}, {BSONTypes.MongoOID, typeof(ObjectId)} }; private readonly BinaryReader _reader; private Document _current; /// <summary> /// Initializes a new instance of the <see cref="BsonDeserializer"/> class. /// </summary> /// <param retval="reader">The reader.</param> private BsonDeserializer(BinaryReader reader) { _reader = reader; } /// <summary> /// Deserializes the specified object data. /// </summary> /// <typeparam retval="T"></typeparam> /// <param retval="objectData">The object data.</param> /// <returns></returns> public static T Deserialize<T>(byte[] objectData) where T : class { IDictionary<WeakReference, Expando> outprops = new Dictionary<WeakReference, Expando>(); return Deserialize<T>(objectData, ref outprops); } /// <summary> /// Deserializes the specified object data. /// </summary> /// <typeparam retval="T"></typeparam> /// <param retval="objectData">The object data.</param> /// <param retval="outProps">The out props.</param> /// <returns></returns> public static T Deserialize<T>(byte[] objectData, ref IDictionary<WeakReference, Expando> outProps) { using (var ms = new MemoryStream()) { ms.Write(objectData, 0, objectData.Length); ms.Position = 0; return Deserialize<T>(new BinaryReader(ms)); } } /// <summary> /// Deserializes the specified object data. /// </summary> /// <typeparam retval="T"></typeparam> /// <param retval="objectData">The object data.</param> /// <param retval="outProps">The out props.</param> /// <returns></returns> public static T Deserialize<T>(int length, BinaryReader reader, ref IDictionary<WeakReference, Expando> outProps) { return Deserialize<T>(reader, length); } /// <summary> /// Deserializes the specified stream. /// </summary> /// <typeparam retval="T"></typeparam> /// <param retval="stream">The stream.</param> /// <returns></returns> private static T Deserialize<T>(BinaryReader stream) { return Deserialize<T>(stream, stream.ReadInt32()); } private static T Deserialize<T>(BinaryReader stream, int length) { var deserializer = new BsonDeserializer(stream); T retval = default(T); try { retval = deserializer.Read<T>(length); } catch (Exception ex) { int toRead = deserializer._current.Length - deserializer._current.Digested; deserializer._reader.ReadBytes(toRead); throw ex; } return retval; } private T Read<T>(int length) { NewDocument(length); var @object = (T)DeserializeValue(typeof(T), BSONTypes.Object); // traverse the object T and apply the DefaultValue to the properties that have them return @object; } /// <summary> /// Reads the specified document forward by the input value. /// </summary> /// <param retval="read">Read length.</param> private void Read(int read) { _current.Digested += read; } /// <summary> /// Determines whether there is more to read. /// </summary> /// <returns> /// <c>true</c> if this instance is read; otherwise, <c>false</c>. /// </returns> private bool IsDone() { var isDone = _current.Digested + 1 == _current.Length; if (isDone) { _reader.ReadByte(); // EOO var old = _current; _current = old.Parent; if (_current != null) { Read(old.Length); } } return isDone; } /// <summary> /// Creates a new document. /// </summary> /// <param retval="length">The document length.</param> private void NewDocument(int length) { var old = _current; _current = new Document { Length = length, Parent = old, Digested = 4 }; } /// <summary> /// Deserializes the value. /// </summary> /// <param retval="type">The type.</param> /// <param retval="storedType">Type of the stored.</param> /// <returns></returns> private object DeserializeValue(Type type, BSONTypes storedType) { return DeserializeValue(type, storedType, null); } /// <summary> /// Applies optional type conversion and deserializes the value. /// </summary> /// <param retval="type">The type.</param> /// <param retval="storedType">Type of the stored.</param> /// <param retval="container">The container.</param> /// <returns></returns> private object DeserializeValue(Type type, BSONTypes storedType, object container) { IBsonTypeConverter converter = Configuration.GetTypeConverterFor(type); if (converter != null) { Type serializedType = converter.SerializedType; object value = DeserializeValueAfterConversion(serializedType, storedType, container); return converter.ConvertFromBson(value); } else { return DeserializeValueAfterConversion(type, storedType, container); } } /// <summary> /// Deserializes the value after any type conversion has been applied. /// </summary> /// <param name="type">The type.</param> /// <param name="storedType">Type of the stored.</param> /// <param name="container">The container.</param> /// <returns></returns> private object DeserializeValueAfterConversion(Type type, BSONTypes storedType, object container) { if (storedType == BSONTypes.Null) { return null; } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { type = Nullable.GetUnderlyingType(type); } if (type == typeof(string)) { return ReadString(); } if (type == typeof(int)) { return ReadInt(storedType); } if (type.IsEnum) { return ReadEnum(type, storedType); } if (type == typeof(float)) { Read(8); return (float)_reader.ReadDouble(); } if (storedType == BSONTypes.Binary) { return ReadBinary(); } if (_IEnumerableType.IsAssignableFrom(type) || storedType == BSONTypes.Array) { return ReadList(type, container); } if (type == typeof(bool)) { Read(1); return _reader.ReadBoolean(); } if (type == typeof(DateTime)) { return BsonHelper.EPOCH.AddMilliseconds(ReadLong(BSONTypes.Int64)); } if (type == typeof(ObjectId)) { Read(12); return new ObjectId(_reader.ReadBytes(12)); } if (type == typeof(long)) { return ReadLong(storedType); } if (type == typeof(double)) { Read(8); return _reader.ReadDouble(); } if (type == typeof(Regex)) { return ReadRegularExpression(); } if (type == typeof(ScopedCode)) { return ReadScopedCode(); } if (type == typeof(Expando)) { return ReadFlyweight(); } return ReadObject(type); } /// <summary> /// Reads an object. /// </summary> /// <param retval="type">The object type.</param> /// <returns></returns> private object ReadObject(Type type) { bool processedNonTypeProperties = false; object instance = null; ReflectionHelper typeHelper = null; if (type == typeof(Object)) { //override the requested type so that some reasonable things happen. type = typeof(Expando); } if (type.IsInterface == false && type.IsAbstract == false) { instance = Activator.CreateInstance(type, true); typeHelper = ReflectionHelper.GetHelperForType(type); typeHelper.ApplyDefaultValues(instance); } while (true) { var storageType = ReadType(); var name = ReadName(); if (name == "$err" || name == "errmsg") { HandleError((string)DeserializeValue(typeof(string), BSONTypes.String)); } // This should work, because the serializer always serialises this property first if (name == "__type") { if (processedNonTypeProperties) throw new MongoException("Found type declaration after processing properties - data loss would occur - the object has been incorrectly serialized"); var typeName = ReadString(); type = Type.GetType(typeName, true); typeHelper = ReflectionHelper.GetHelperForType(type); instance = Activator.CreateInstance(type, true); typeHelper.ApplyDefaultValues(instance); continue; } if (instance == null) { throw new MongoException("Could not find the type to instantiate in the document, and " + type.Name + " is an interface or abstract type. Add a MongoDiscriminatedAttribute to the type or base type, or try to work with a concrete type next time."); } processedNonTypeProperties = true; var property = (name == "_id" || name == "$id") ? typeHelper.FindIdProperty() : typeHelper.FindProperty(name); if (property == null && !typeHelper.IsExpando) { throw new MongoException(string.Format("Deserialization failed: type {0} does not have a property named {1}", type.FullName, name)); } var isNull = false; if (storageType == BSONTypes.Object) { var length = _reader.ReadInt32(); if (length == 5) { _reader.ReadByte(); //eoo Read(5); isNull = true; } else { NewDocument(length); } } object container = null; if (property != null && property.Setter == null) { container = property.Getter(instance); } var propertyType = property != null ? property.Type : _typeMap.ContainsKey(storageType) ? _typeMap[storageType] : typeof(object); var value = isNull ? null : DeserializeValue(propertyType, storageType, container); if (property == null) { ((IExpando)instance)[name] = value; } else if (container == null && value != null) { property.Setter(instance, value); } if (IsDone()) { break; } } return instance; } /// <summary> /// Reads a list. /// </summary> /// <param retval="listType">Type of the list.</param> /// <param retval="existingContainer">The existing container.</param> /// <returns></returns> private object ReadList(Type listType, object existingContainer) { if (IsDictionary(listType)) { return ReadDictionary(listType, existingContainer); } //If we just got an untyped object here, we don't know what we have, but we know its an array. //So deserialize it to a list of Expandos. if (listType == typeof(Object)) { listType = typeof(List<Expando>); } NewDocument(_reader.ReadInt32()); var itemType = ListHelper.GetListItemType(listType); var isObject = typeof(object) == itemType; var wrapper = BaseWrapper.Create(listType, itemType, existingContainer); while (!IsDone()) { var storageType = ReadType(); ReadName(); if (storageType == BSONTypes.Object) { NewDocument(_reader.ReadInt32()); } var specificItemType = isObject ? _typeMap[storageType] : itemType; var value = DeserializeValue(specificItemType, storageType); wrapper.Add(value); } return wrapper.Collection; } /// <summary> /// Determines whether the specified type is a dictionary. /// </summary> /// <param retval="type">The type.</param> /// <returns> /// <c>true</c> if the specified type is a dictionary; otherwise, <c>false</c>. /// </returns> private static bool IsDictionary(Type type) { var types = new List<Type>(type.GetInterfaces()); types.Insert(0, type); foreach (var interfaceType in types) { if (interfaceType.IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IDictionary<,>)) { return true; } } return false; } /// <summary> /// Reads a dictionary. /// </summary> /// <param retval="listType">Type of the list.</param> /// <param retval="existingContainer">The existing container.</param> /// <returns></returns> private object ReadDictionary(Type listType, object existingContainer) { var valueType = ListHelper.GetDictionarValueType(listType); var container = existingContainer == null ? ListHelper.CreateDictionary(listType, ListHelper.GetDictionarKeyType(listType), valueType) : (IDictionary)existingContainer; while (!IsDone()) { var storageType = ReadType(); var key = ReadName(); if (storageType == BSONTypes.Object) { NewDocument(_reader.ReadInt32()); } var value = DeserializeValue(valueType, storageType); container.Add(key, value); } return container; } /// <summary> /// Reads binary. /// </summary> /// <returns></returns> private object ReadBinary() { var length = _reader.ReadInt32(); var subType = _reader.ReadByte(); Read(5 + length); if (subType == 0) { return _reader.ReadBytes(length); } if (subType == 2) { return _reader.ReadBytes(_reader.ReadInt32()); } if (subType == 3) { return new Guid(_reader.ReadBytes(length)); } throw new MongoException("No support for binary type: " + subType); } /// <summary> /// Reads a retval. /// </summary> /// <returns></returns> private string ReadName() { var buffer = new List<byte>(128); //todo: use a pool to prevent fragmentation byte b; while ((b = _reader.ReadByte()) > 0) { buffer.Add(b); } Read(buffer.Count + 1); return Encoding.UTF8.GetString(buffer.ToArray()); } /// <summary> /// Reads a string. /// </summary> /// <returns></returns> private string ReadString() { var length = _reader.ReadInt32(); var buffer = _reader.ReadBytes(length - 1); //todo: again, look at fragementation prevention _reader.ReadByte(); //null; Read(4 + length); return Encoding.UTF8.GetString(buffer); } /// <summary> /// Reads ag int. /// </summary> /// <param retval="storedType">Type of the stored.</param> /// <returns></returns> private int ReadInt(BSONTypes storedType) { switch (storedType) { case BSONTypes.Int32: Read(4); return _reader.ReadInt32(); case BSONTypes.Int64: Read(8); return (int)_reader.ReadInt64(); case BSONTypes.Double: Read(8); return (int)_reader.ReadDouble(); default: throw new MongoException("Could not create an int from " + storedType); } } /// <summary> /// Reads a long. /// </summary> /// <param retval="storedType">Type of the stored.</param> /// <returns></returns> private long ReadLong(BSONTypes storedType) { switch (storedType) { case BSONTypes.Int32: Read(4); return _reader.ReadInt32(); case BSONTypes.Int64: Read(8); return _reader.ReadInt64(); case BSONTypes.Double: Read(8); return (long)_reader.ReadDouble(); default: throw new MongoException("Could not create an int64 from " + storedType); } } /// <summary> /// Reads an enum. /// </summary> /// <param retval="type">The type.</param> /// <param retval="storedType">Type of the stored.</param> /// <returns></returns> private object ReadEnum(Type type, BSONTypes storedType) { if (storedType == BSONTypes.Int64) { return Enum.Parse(type, ReadLong(storedType).ToString(), false); } return Enum.Parse(type, ReadInt(storedType).ToString(), false); } /// <summary> /// Reads the regular expression. /// </summary> /// <returns></returns> private object ReadRegularExpression() { var pattern = ReadName(); var optionsString = ReadName(); var options = RegexOptions.None; if (optionsString.Contains("e")) options = options | RegexOptions.ECMAScript; if (optionsString.Contains("i")) options = options | RegexOptions.IgnoreCase; if (optionsString.Contains("l")) options = options | RegexOptions.CultureInvariant; if (optionsString.Contains("m")) options = options | RegexOptions.Multiline; if (optionsString.Contains("s")) options = options | RegexOptions.Singleline; if (optionsString.Contains("w")) options = options | RegexOptions.IgnorePatternWhitespace; if (optionsString.Contains("x")) options = options | RegexOptions.ExplicitCapture; return new Regex(pattern, options); } /// <summary> /// Reads a type. /// </summary> /// <returns></returns> private BSONTypes ReadType() { Read(1); return (BSONTypes)_reader.ReadByte(); } /// <summary> /// Reads scoped code. /// </summary> /// <returns></returns> private ScopedCode ReadScopedCode() { _reader.ReadInt32(); //length Read(4); var name = ReadString(); NewDocument(_reader.ReadInt32()); return new ScopedCode { CodeString = name, Scope = DeserializeValue(typeof(Expando), BSONTypes.Object) }; } /// <summary> /// Reads a flyweight. /// </summary> /// <returns></returns> private Expando ReadFlyweight() { var flyweight = new Expando(); while (true) { var storageType = ReadType(); var name = ReadName(); if (name == "$err" || name == "errmsg") { HandleError((string)DeserializeValue(typeof(string), BSONTypes.String)); } if (storageType == BSONTypes.Object) { NewDocument(_reader.ReadInt32()); } var propertyType = _typeMap.ContainsKey(storageType) ? _typeMap[storageType] : typeof(object); var value = DeserializeValue(propertyType, storageType); flyweight.Set(name, value); if (IsDone()) { break; } } return flyweight; } /// <summary> /// Handles ab error. /// </summary> /// <param retval="message">The message.</param> private static void HandleError(string message) { //TODO: this should flush the rest of the bytes off of the incoming stream, right now this is a BUG! throw new MongoException(message); } } }
/* * Copyright (2011) Intel Corporation and Sandia Corporation. Under the * terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the * U.S. Government retains certain rights in this software. * * 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 Intel Corporation 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 INTEL OR ITS * 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.Reflection; using System.Text; using System.Timers; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; using WaterWars; using WaterWars.Events; using WaterWars.Models; using WaterWars.Views.Interactions; using WaterWars.Views.Widgets.Behaviours; using WaterWars.Views.Widgets; namespace WaterWars.Views { public class HudView : WaterWarsView { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected const string GAME_STARTED_MSG = "Game started."; protected const string BUILD_PHASE_STARTED_MSG = "Build Phase Started."; protected const string WATER_PHASE_STARTED_MSG = "Water Phase Started."; protected const string REVENUE_PHASE_STARTED_MSG = "Revenue Phase Started. Please wait while calculations are made."; protected const string GAME_RESET_MSG = "GAME RESET."; protected const string GAME_ENDED_MSG = "GAME ENDED."; protected const string PLAYER_TURN_ENDED_MSG = "{0} ended their turn."; public const string IN_WORLD_NAME = "Water Wars HUD"; public const string MONEY_BUTTON = "money-button"; public const string LAND_BUTTON = "land-button"; public const string WATER_BUTTON = "water-button"; // public const string MARKET_BUTTON = "market-button"; public const string STATUS_BUTTON = "status-button"; public const string PHASE_BUTTON = "phase-button"; public const string TIME_REMAINING_BUTTON = "time-remaining-button"; public const string END_TURN_BUTTON = "end-turn-button"; public const string SHOW_BROWSER_BUTTON = "show-browser-button"; public const string TICKER_BUTTON = "ticker-button"; protected MoneyButton m_moneyButton; protected LandButton m_landButton; protected WaterButton m_waterButton; public OsButton m_statusButton; // protected MarketButton m_marketButton; protected PhaseButton m_phaseButton; protected TimeRemainingButton m_timeRemainingButton; protected EndTurnButton m_endTurnButton; protected ShowBrowserButton m_showBrowserButton; protected TickerButton m_tickerButton; public UUID UserId { get; private set; } public uint RootLocalId { get; private set; } public int Money { set { m_moneyButton.Money = value; } } public int DevelopmentRightsOwned { set { m_landButton.DevelopmentRightsOwned = value; } } public int Water { set { m_waterButton.Water = value; } } public int WaterEntitlement { set { m_waterButton.WaterEntitlement = value; } } /// <value> /// Expressed in seconds /// </value> public int TimeRemaining { set { m_timeRemainingButton.TimeRemaining = value; } } public string Status { set { m_statusButton.LabelBehaviour.Text = value; } } // public bool EnableSellWater { set { m_marketButton.Enabled = value; } } public bool EnableEndTurn { set { m_endTurnButton.Enabled = value; } } public HudView(WaterWarsController controller, Scene scene, UUID userId) : base(controller, scene) { UserId = userId; m_controller.EventManager.OnStateStarted += ProcessStateStarted; m_controller.EventManager.OnPlayerEndedTurn += ProcessPlayerEndTurn; m_controller.EventManager.OnGameAssetSoldToEconomy += ProcessGameAssetSoldToEconomy; } public override void Close() { m_controller.EventManager.OnStateStarted -= ProcessStateStarted; m_controller.EventManager.OnPlayerEndedTurn -= ProcessPlayerEndTurn; m_controller.EventManager.OnGameAssetSoldToEconomy -= ProcessGameAssetSoldToEconomy; m_moneyButton.Close(); m_landButton.Close(); m_waterButton.Close(); // m_marketButton.Close(); m_statusButton.Close(); m_timeRemainingButton.Close(); m_endTurnButton.Close(); m_tickerButton.Close(); m_showBrowserButton.Close(); // We won't actually propogate close since we shouldn't kill the hud prims - the viewer has to do this! //base.Close(); } protected override void RegisterPart(SceneObjectPart part) { if (part.Name == MONEY_BUTTON) m_moneyButton = new MoneyButton(m_controller, part); else if (part.Name == LAND_BUTTON) m_landButton = new LandButton(m_controller, part); else if (part.Name == WATER_BUTTON) m_waterButton = new WaterButton(m_controller, part); // else if (part.Name == MARKET_BUTTON) // m_marketButton = new MarketButton(m_controller, part); else if (part.Name == STATUS_BUTTON) m_statusButton = new StatusButton(m_controller, part); else if (part.Name == PHASE_BUTTON) m_phaseButton = new PhaseButton(m_controller, part); else if (part.Name == TIME_REMAINING_BUTTON) m_timeRemainingButton = new TimeRemainingButton(m_controller, part); else if (part.Name == END_TURN_BUTTON) m_endTurnButton = new EndTurnButton(m_controller, part, UserId); else if (part.Name == SHOW_BROWSER_BUTTON) m_showBrowserButton = new ShowBrowserButton(m_controller, part, UserId); else if (part.Name == TICKER_BUTTON) m_tickerButton = new TickerButton(m_controller, part); if (part.IsRoot) { RootLocalId = part.LocalId; // XXX: Nasty nasty nasty hack to resolve an issue where attached non-root prims do not always appear // SceneObjectGroup group = part.ParentGroup; // group.HasGroupChanged = true; // group.ScheduleGroupForFullUpdate(); } } protected void ProcessStateStarted(GameStateType type) { string msg = null; if (type == GameStateType.Game_Starting) msg = GAME_STARTED_MSG; // We won't show the build phase started message because this will obscure the revenue details message. // The start of the game is taken care of by the game started message. // else if (type == GameStateType.Build) // msg = BUILD_PHASE_STARTED_MSG; else if (type == GameStateType.Water) msg = WATER_PHASE_STARTED_MSG; else if (type == GameStateType.Revenue) msg = REVENUE_PHASE_STARTED_MSG; else if (type == GameStateType.Game_Ended) msg = GAME_ENDED_MSG; if (msg != null) m_controller.Events.Post(UserId, msg, EventLevel.All); } protected void ProcessPlayerEndTurn(Player p) { m_controller.Events.Post(UserId, string.Format(PLAYER_TURN_ENDED_MSG, p.Name), EventLevel.Crawl); if (p.Uuid != UserId) return; EnableEndTurn = false; } protected void ProcessGameAssetSoldToEconomy(AbstractGameAsset ga, Player p, int price) { if (p.Uuid != UserId) return; DevelopmentRightsOwned = p.DevelopmentRightsOwned.Count; Money = p.Money; Water = p.Water; WaterEntitlement = p.WaterEntitlement; m_statusButton.SendAlert( p.Uuid, "You just sold {0} to the market for {1}{2}", ga.Name, WaterWarsConstants.MONEY_UNIT, price); } public void AddTextToTick(string text) { m_tickerButton.AddTextToTick(text); } public void SetTickerFromPreviousHud(HudView oldHud) { m_tickerButton.m_visibleTickText = oldHud.m_tickerButton.m_visibleTickText; m_tickerButton.m_bufferedTickText = oldHud.m_tickerButton.m_bufferedTickText; } /// <summary> /// The money display on the hud /// </summary> public class MoneyButton : WaterWarsButton { public int Money { set { LabelBehaviour.Text = string.Format("Money\n{0}{1}", WaterWarsConstants.MONEY_UNIT, value); } } public MoneyButton(WaterWarsController controller, SceneObjectPart part) : base(controller, part, new FixedTextureBehaviour()) { Money = 0; } } public class LandButton : WaterWarsButton { public const string LABEL_FORMAT = "Parcels owned\n{0}"; public int DevelopmentRightsOwned { // set { LabelBehaviour.Text = string.Format(LABEL_FORMAT, value, ((value != 1) ? "s" : "")); } set { LabelBehaviour.Text = string.Format(LABEL_FORMAT, value); } } public LandButton(WaterWarsController controller, SceneObjectPart part) : base(controller, part, new FixedTextureBehaviour()) {} } public class WaterButton : WaterWarsButton { public int Water { set { m_water = value; UpdateLabel(); } } protected int m_water; public int WaterEntitlement { set { m_waterEntitlement = value; UpdateLabel(); } } protected int m_waterEntitlement; public WaterButton(WaterWarsController controller, SceneObjectPart part) : base(controller, part, new FixedTextureBehaviour()) { Water = 0; WaterEntitlement = 0; } protected void UpdateLabel() { if (m_controller.Game.State == GameStateType.Build) LabelBehaviour.Text = string.Format("Rights owned\n{0}", WaterWarsUtils.GetWaterUnitsText(m_waterEntitlement)); else LabelBehaviour.Text = string.Format("Available for use\n{0}", WaterWarsUtils.GetWaterUnitsText(m_water)); } } /// <summary> /// Tells the player what game phase we're in. /// </summary> public class PhaseButton : WaterWarsButton { public PhaseButton(WaterWarsController controller, SceneObjectPart part) : base(controller, part, new FixedTextureBehaviour()) { UpdateLabel(m_controller.Game.State); m_controller.EventManager.OnStateStarted += UpdateLabel; } protected void UpdateLabel(GameStateType newState) { LabelBehaviour.Text = string.Format("Phase\n{0}", newState.ToString().ToUpper()); } public override void Close() { m_controller.EventManager.OnStateStarted -= UpdateLabel; base.Close(); } } /// <summary> /// Tell the user how much time they have remaining in this phase. /// </summary> public class TimeRemainingButton : WaterWarsButton { public const string LABEL_FORMAT = "Time remaining\n{0:D2}:{1:D2}:{2:D2}"; public int TimeRemaining { get { return m_timeRemaining; } set { m_timeRemaining = value; UpdateLabel(); } } protected int m_timeRemaining; public TimeRemainingButton(WaterWarsController controller, SceneObjectPart part) : base(controller, part, new FixedTextureBehaviour()) { TimeRemaining = 0; } protected void UpdateLabel() { int hours = TimeRemaining / 3600; int secondsRemainder = TimeRemaining % 3600; int minutes = secondsRemainder / 60; int seconds = secondsRemainder % 60; LabelBehaviour.Text = string.Format(LABEL_FORMAT, hours, minutes, seconds); } } public class EndTurnButton : WaterWarsButton { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public EndTurnButton(WaterWarsController controller, SceneObjectPart part, UUID playerId) : base(controller, part, new FadeInAndOutBehaviour()) { DisplayBehaviour.Text = "end turn"; OnClick += delegate(Vector3 offsetPos, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs) { Util.FireAndForget(delegate { controller.State.EndTurn(playerId); }); }; } } public class ShowBrowserButton : WaterWarsButton { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected UUID m_playerId; public ShowBrowserButton(WaterWarsController controller, SceneObjectPart part, UUID playerId) : base(controller, part, new FadeInAndOutBehaviour()) { m_playerId = playerId; OnClick += delegate(Vector3 offsetPos, IClientAPI remoteClient, SurfaceTouchEventArgs surfaceArgs) { OpenMediaBrowser(); }; controller.EventManager.OnStateStarted += OnStateChange; Enabled = true; } protected void OnStateChange(GameStateType newState) { if (newState == GameStateType.Game_Starting && m_controller.Game.Players.ContainsKey(m_playerId)) OpenMediaBrowser(); } public void OpenMediaBrowser() { // TODO: At the moment we assume that the webserver is on the same machine as the sim. However, // at some point this needs to become more configurable string hostName = Part.ParentGroup.Scene.RegionInfo.ExternalHostName; UUID loginToken = m_controller.ViewerWebServices.PlayerServices.CreateLoginToken(m_playerId); string url = string.Format("http://{0}/waterwars?selfId={1}&loginToken={2}", hostName, m_playerId, loginToken); DialogModule.SendUrlToUser( m_playerId, Part.Name, Part.UUID, Part.OwnerID, false, "Click \"Go to page\" to open the Water Wars User Interface", url); } public override void Close() { // No need to remove OnClick since the part is going away anyway m_controller.EventManager.OnStateStarted -= OnStateChange; } } public class TickerButton : WaterWarsButton { /// <value> /// Text that separates crawls. /// </value> public string CrawlSeperator { get { return m_crawlSeperator; } set { m_crawlSeperator = value; m_emptyLead = new String(' ', m_crawlSeperator.Length); } } protected string m_crawlSeperator; protected Timer m_timer = new Timer(100); /// <value> /// Number of characters available in the ticker. /// </value> protected int m_widthAvailable = 150; /// <value> /// The text shown when the crawler is empty /// </value> protected string m_emptyCrawler; /// <value> /// Text shown when the lead part of the crawler (where new crawls are introduced) is empty. /// </value> protected string m_emptyLead = string.Empty; /// <value> /// The tick text that is visible /// </value> protected internal StringBuilder m_visibleTickText; /// <value> /// Tick text waiting to become visible /// </value> protected internal StringBuilder m_bufferedTickText = new StringBuilder(); public TickerButton(WaterWarsController controller, SceneObjectPart part) : base(controller, part, new FixedTextureBehaviour()) { m_emptyCrawler = new string(' ', m_widthAvailable); m_visibleTickText = new StringBuilder(m_emptyCrawler); CrawlSeperator = " ... "; // AddTextToTick("Shall I compare thee to a summer's day? Thou art more lovely and more temperate." // + " Rough winds do shake the darling buds of May. And summer's lease hath all too short a date." // + " Sometime too hot the eye of heaven shines. And often is his gold complexion dimm'd." // + " And every fair from fair somtimes declines. By chance, or nature's changing course, untrimm'd."); m_controller.EventManager.OnStateStarted += OnStateStarted; m_timer.Elapsed += new ElapsedEventHandler(OnTimedEvent); m_timer.Start(); } public override void Close() { m_controller.EventManager.OnStateStarted -= OnStateStarted; m_timer.Stop(); base.Close(); } protected void OnStateStarted(GameStateType newState) { if (newState != GameStateType.Game_Resetting) return; ClearText(); } protected void OnTimedEvent(object source, ElapsedEventArgs e) { lock (m_visibleTickText) { // If we have some text to display or we need to blank the crawler then update the display if (!(m_visibleTickText.ToString() == m_emptyCrawler && LabelBehaviour.Text == m_emptyCrawler)) LabelBehaviour.Text = m_visibleTickText.ToString(); if (m_bufferedTickText.Length != 0) { m_visibleTickText.Remove(0, 1); m_visibleTickText.Append(m_bufferedTickText[0]); m_bufferedTickText.Remove(0, 1); } else if (m_visibleTickText.ToString() != m_emptyCrawler) { m_visibleTickText.Remove(0, 1); m_visibleTickText.Append(" "); } } } public void AddTextToTick(string text) { lock (m_visibleTickText) { if ( m_bufferedTickText.Length > 0 || m_bufferedTickText.Length == 0 && !m_visibleTickText.ToString().EndsWith(m_emptyLead)) m_bufferedTickText.Append(CrawlSeperator); m_bufferedTickText.Append(text); } } /// <summary> /// Clear the visible and buffered text. /// </summary> public void ClearText() { lock (m_visibleTickText) { m_bufferedTickText.Length = 0; m_visibleTickText.Length = 0; m_visibleTickText.Append(m_emptyCrawler); } } } public class StatusButton : WaterWarsButton { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public StatusButton(WaterWarsController controller, SceneObjectPart part) : base(controller, part, 1471, new FixedTextureBehaviour()) { Enabled = true; // XXX: Temporarily enable so that it will pass on chat to the interaction hanging off it } } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Symbology.Forms.dll // Description: The Windows Forms user interface layer for the DotSpatial.Symbology library. // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 5/22/2009 11:21:12 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace DotSpatial.Symbology.Forms { /// <summary> /// GradientControl /// </summary> [DefaultEvent("PositionChanging")] public class TwoColorSlider : Control { /// <summary> /// Occurs as the user is adjusting the positions on either of the sliders /// </summary> public event EventHandler PositionChanging; /// <summary> /// Occurs after the user has finished adjusting the positions of either of the sliders and has released control /// </summary> public event EventHandler PositionChanged; #region Private Variables private float _dx; private bool _inverted; private TwoColorHandle _leftHandle; private float _max; private Color _maxColor; private float _min; private Color _minColor; private TwoColorHandle _rightHandle; #endregion #region Constructors /// <summary> /// Creates a new instance of GradientControl /// </summary> public TwoColorSlider() { _min = 0; _max = 360; _leftHandle = new TwoColorHandle(this); _leftHandle.Position = .2F; _leftHandle.IsLeft = true; _rightHandle = new TwoColorHandle(this); _rightHandle.Position = .8F; } #endregion #region Methods /// <summary> /// Uses the saturation of the specified values to set the left and right values for this slider. /// </summary> /// <param name="startColor">The color that specifies the left saturation</param> /// <param name="endColor">The color that specifies the right saturation</param> public void SetSaturation(Color startColor, Color endColor) { float sStart = startColor.GetSaturation(); float sEnd = endColor.GetSaturation(); _inverted = sEnd < sStart; LeftValue = sStart; RightValue = sEnd; } /// <summary> /// Uses the lightness of hte specified values ot set the left and right values for this slider /// </summary> /// <param name="startColor">The color that specifies the left lightness</param> /// <param name="endColor">The color that specifies the right lightness</param> public void SetLightness(Color startColor, Color endColor) { float lStart = startColor.GetBrightness(); float lEnd = endColor.GetBrightness(); _inverted = lEnd < lStart; LeftValue = lStart; RightValue = lEnd; } #endregion #region Properties /// <summary> /// Gets or sets the inverted values. /// </summary> public bool Inverted { get { return _inverted; } set { _inverted = value; Invalidate(); } } /// <summary> /// Gets or sets the floating point position of the left slider. This must range /// between 0 and 1, and to the left of the right slider, (therefore with a value lower than the right slider.) /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Content), TypeConverter(typeof(ExpandableObjectConverter))] public TwoColorHandle LeftHandle { get { return _leftHandle; } set { _leftHandle = value; } } /// <summary> /// The value represented by the left handle, taking into account /// whether or not the slider has been reversed. /// </summary> public float LeftValue { get { if (_inverted) { return _max - _leftHandle.Position; } return _leftHandle.Position; } set { if (_inverted) { _leftHandle.Position = _max - value; return; } _leftHandle.Position = value; } } /// <summary> /// The value represented by the right handle, taking into account /// whether or not the slider has been reversed. /// </summary> public float RightValue { get { if (_inverted) { return _max - (_rightHandle.Position); } return _rightHandle.Position; } set { if (_inverted) { _rightHandle.Position = _max - value; return; } _rightHandle.Position = value; } } /// <summary> /// Gets or sets the floating point position of the right slider. This must range /// between 0 and 1, and to the right of the left slider. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Content), TypeConverter(typeof(ExpandableObjectConverter))] public TwoColorHandle RightHandle { get { return _rightHandle; } set { _rightHandle = value; } } /// <summary> /// Gets or sets the color associated with the maximum value. /// </summary> [Description("Gets or sets the color associated with the maximum value.")] public Color MaximumColor { get { return _inverted ? _minColor : _maxColor; } set { if (_inverted) { _minColor = value; } else { _maxColor = value; } Invalidate(); } } /// <summary> /// Gets or sets the maximum allowed value for the slider. /// </summary> [Description("Gets or sets the maximum allowed value for the slider.")] public float Maximum { get { return _max; } set { _max = value; if (_max < _rightHandle.Position) _rightHandle.Position = _max; if (_max < _leftHandle.Position) _leftHandle.Position = _max; } } /// <summary> /// Gets or sets the minimum allowed value for the slider. /// </summary> [Description("Gets or sets the minimum allowed value for the slider.")] public float Minimum { get { return _min; } set { _min = value; if (_leftHandle.Position < _min) _leftHandle.Position = _min; if (_rightHandle.Position < _min) _rightHandle.Position = _min; } } /// <summary> /// Gets or sets the color associated with the minimum color /// </summary> [Description("Gets or sets the color associated with the minimum value")] public Color MinimumColor { get { if (_inverted) return _maxColor; return _minColor; } set { if (_inverted) { _maxColor = value; } else { _minColor = value; } Invalidate(); } } #endregion #region Protected Methods /// <summary> /// Prevent flicker /// </summary> /// <param name="pevent"></param> protected override void OnPaintBackground(PaintEventArgs pevent) { //base.OnPaintBackground(pevent); } /// <summary> /// Draw the clipped portion /// </summary> /// <param name="e"></param> protected override void OnPaint(PaintEventArgs e) { Rectangle clip = e.ClipRectangle; if (clip.IsEmpty) clip = ClientRectangle; Bitmap bmp = new Bitmap(clip.Width, clip.Height); Graphics g = Graphics.FromImage(bmp); g.TranslateTransform(-clip.X, -clip.Y); g.Clip = new Region(clip); g.Clear(BackColor); g.SmoothingMode = SmoothingMode.AntiAlias; OnDraw(g, clip); g.Dispose(); e.Graphics.DrawImage(bmp, clip, new Rectangle(0, 0, clip.Width, clip.Height), GraphicsUnit.Pixel); } /// <summary> /// Controls the actual drawing for this gradient slider control. /// </summary> /// <param name="g"></param> /// <param name="clipRectangle"></param> protected virtual void OnDraw(Graphics g, Rectangle clipRectangle) { GraphicsPath gp = new GraphicsPath(); Rectangle innerRect = new Rectangle(_leftHandle.Width, 3, Width - 1 - _rightHandle.Width - _leftHandle.Width, Height - 1 - 6); gp.AddRoundedRectangle(innerRect, 2); if (Width == 0 || Height == 0) return; // Create a rounded gradient effect as the backdrop that other colors will be drawn to LinearGradientBrush silver = new LinearGradientBrush(ClientRectangle, BackColor.Lighter(.2F), BackColor.Darker(.6F), LinearGradientMode.Vertical); g.FillPath(silver, gp); silver.Dispose(); LinearGradientBrush lgb = new LinearGradientBrush(innerRect, MinimumColor, MaximumColor, LinearGradientMode.Horizontal); g.FillPath(lgb, gp); lgb.Dispose(); g.DrawPath(Pens.Gray, gp); gp.Dispose(); if (Enabled) { _leftHandle.Draw(g); _rightHandle.Draw(g); } } /// <summary> /// Initiates slider dragging /// </summary> /// <param name="e"></param> protected override void OnMouseDown(MouseEventArgs e) { if (e.Button == MouseButtons.Left && Enabled) { Rectangle l = _leftHandle.GetBounds(); if (l.Contains(e.Location) && _leftHandle.Visible) { _dx = _leftHandle.GetBounds().Right - e.X; _leftHandle.IsDragging = true; } Rectangle r = _rightHandle.GetBounds(); if (r.Contains(e.Location) && _rightHandle.Visible) { _dx = e.X - _rightHandle.GetBounds().Left; _rightHandle.IsDragging = true; } } base.OnMouseDown(e); } /// <summary> /// Handles slider dragging /// </summary> /// <param name="e"></param> protected override void OnMouseMove(MouseEventArgs e) { float w = Width - _leftHandle.Width; if (_rightHandle.IsDragging) { float x = e.X - _dx; int min = 0; if (_leftHandle.Visible) min = _leftHandle.Width; if (x > w) x = w; if (x < min) x = min; _rightHandle.Position = _min + (x / w) * (_max - _min); if (_leftHandle.Visible) { if (_leftHandle.Position > _rightHandle.Position) { _leftHandle.Position = _rightHandle.Position; } } OnPositionChanging(); } if (_leftHandle.IsDragging) { float x = e.X + _dx; int max = Width; if (_rightHandle.Visible) max = Width - _rightHandle.Width; if (x > max) x = max; if (x < 0) x = 0; _leftHandle.Position = _min + (x / w) * (_max - _min); if (_rightHandle.Visible) { if (_rightHandle.Position < _leftHandle.Position) { _rightHandle.Position = _leftHandle.Position; } } OnPositionChanging(); } Invalidate(); base.OnMouseMove(e); } /// <summary> /// Handles the mouse up situation /// </summary> /// <param name="e"></param> protected override void OnMouseUp(MouseEventArgs e) { if (e.Button == MouseButtons.Left) { if (_rightHandle.IsDragging) _rightHandle.IsDragging = false; if (_leftHandle.IsDragging) _leftHandle.IsDragging = false; OnPositionChanged(); } base.OnMouseUp(e); } /// <summary> /// Fires the Position Changing event while either slider is being dragged /// </summary> protected virtual void OnPositionChanging() { if (PositionChanging != null) PositionChanging(this, EventArgs.Empty); } /// <summary> /// Fires the Position Changed event after sliders are released /// </summary> protected virtual void OnPositionChanged() { if (PositionChanged != null) PositionChanged(this, EventArgs.Empty); } #endregion } }
using System.CommandLine; using System.CommandLine.Invocation; using System.CommandLine.Parsing; using System.Security.Cryptography; using Meziantou.Framework.Globbing; namespace Meziantou.Framework.Html.Tool; internal static class Program { private static Task<int> Main(string[] args) { var rootCommand = new RootCommand(); AddReplaceValueCommand(rootCommand); AddAppendVersionCommand(rootCommand); return rootCommand.InvokeAsync(args); } private static void AddReplaceValueCommand(RootCommand rootCommand) { var replaceValueCommand = new Command("replace-value") { new Option<string>( "--single-file", description: "Path of the file to update") { IsRequired = false }, new Option<string>( "--file-pattern", description: "Glob pattern to find files to update") { IsRequired = false }, new Option<string>( "--xpath", "XPath to the elements/attributes to replace") { IsRequired = true }, new Option<string>( "--new-value", "New value for the elements/attributes") { IsRequired = true }, }; replaceValueCommand.Description = "Replace element/attribute values in an html file"; replaceValueCommand.Handler = CommandHandler.Create((string? singleFile, string? filePattern, string xpath, string newValue) => ReplaceValue(singleFile, filePattern, xpath, newValue)); rootCommand.AddCommand(replaceValueCommand); } private static async Task<int> ReplaceValue(string? filePath, string? globPattern, string xpath, string newValue) { if (!string.IsNullOrEmpty(filePath)) { await UpdateFileAsync(filePath, xpath, newValue); } if (!string.IsNullOrEmpty(globPattern)) { if (!Glob.TryParse(globPattern, GlobOptions.None, out var glob)) { await Console.Error.WriteLineAsync($"Glob pattern '{globPattern}' is invalid"); return -1; } foreach (var file in glob.EnumerateFiles(Environment.CurrentDirectory)) { await UpdateFileAsync(file, xpath, newValue); } } return 0; static async Task UpdateFileAsync(string file, string xpath, string newValue) { var doc = new HtmlDocument(); await using (var stream = File.OpenRead(file)) { doc.Load(stream); } var count = 0; var nodes = doc.SelectNodes(xpath); foreach (var node in nodes) { node.Value = newValue; count++; } doc.Save(file, doc.DetectedEncoding ?? doc.StreamEncoding); Console.WriteLine(FormattableString.Invariant($"Updated {count} nodes in '{file}'")); } } private static void AddAppendVersionCommand(RootCommand rootCommand) { var command = new Command("append-version") { new Option<string>( "--single-file", description: "Path of the file to update") { IsRequired = false }, new Option<string>( "--file-pattern", description: "Glob pattern to find files to update") { IsRequired = false }, }; command.Description = "Append version to style / script URLs"; command.Handler = CommandHandler.Create(async (string? singleFile, string? filePattern) => { if (!string.IsNullOrEmpty(singleFile)) { await UpdateFileAsync(singleFile).ConfigureAwait(false); } if (!string.IsNullOrEmpty(filePattern)) { if (!Glob.TryParse(filePattern, GlobOptions.None, out var glob)) { await Console.Error.WriteLineAsync($"Glob pattern '{filePattern}' is invalid"); return -1; } foreach (var f in glob.EnumerateFiles(Environment.CurrentDirectory)) { await UpdateFileAsync(f).ConfigureAwait(false); } } return 0; static async Task UpdateFileAsync(string file) { var doc = new HtmlDocument(); await using (var stream = File.OpenRead(file)) { doc.Load(stream); } var count = 0; var nodes = doc.SelectNodes("//@src|//@href"); foreach (var node in nodes) { if (string.IsNullOrWhiteSpace(node.Value)) continue; // Only consider relative path if (node.Value.Contains("://", StringComparison.Ordinal) && node.Value.StartsWith("//", StringComparison.Ordinal)) continue; string? uriPath = null; string? uriQuery = null; string? uriHash = null; var hashIndex = node.Value.IndexOf('#', StringComparison.Ordinal); var queryIndex = node.Value.IndexOf('?', StringComparison.Ordinal); if (hashIndex >= 0 && queryIndex > hashIndex) { queryIndex = -1; } if (queryIndex >= 0 || hashIndex >= 0) { uriPath = node.Value[0..(queryIndex >= 0 ? queryIndex : hashIndex)]; if (queryIndex >= 0) { if (hashIndex >= 0) { uriQuery = node.Value[queryIndex..hashIndex]; } else { uriQuery = node.Value[queryIndex..]; } } if (hashIndex >= 0) { uriHash = node.Value[hashIndex..]; } } else { uriPath = node.Value; } var parentFolder = Path.GetDirectoryName(file); var assetPath = parentFolder is not null ? Path.Combine(parentFolder, uriPath) : uriPath; if (!File.Exists(assetPath)) continue; var bytes = await File.ReadAllBytesAsync(assetPath).ConfigureAwait(false); #pragma warning disable CA1308 // Normalize strings to uppercase var hash = Convert.ToHexString(SHA512.HashData(bytes))[0..6].ToLowerInvariant(); #pragma warning restore CA1308 if (uriQuery is null) { uriQuery = "?v=" + hash; } else { var index = uriQuery.IndexOf("&v=", StringComparison.Ordinal); if (index < 0) { index = uriQuery.IndexOf("?v=", StringComparison.Ordinal); } if (index >= 0) { var endIndex = uriQuery.IndexOf('&', index + 1); if (endIndex < 0) { uriQuery = uriQuery[0..index] + (index == 0 ? '?' : '&') + "v=" + hash; } else { uriQuery = uriQuery[0..index] + (index == 0 ? '?' : '&') + "v=" + hash + uriQuery[endIndex..]; } } else { uriQuery += "&v=" + hash; } } node.Value = uriPath + uriQuery + uriHash; count++; } if (count > 0) { doc.Save(file, doc.DetectedEncoding ?? doc.StreamEncoding); } Console.WriteLine(FormattableString.Invariant($"Updated {count} nodes in '{file}'")); } }); rootCommand.AddCommand(command); } }
using System; using ChainUtils.BouncyCastle.Crypto.Parameters; namespace ChainUtils.BouncyCastle.Crypto { /** * A wrapper class that allows block ciphers to be used to process data in * a piecemeal fashion. The BufferedBlockCipher outputs a block only when the * buffer is full and more data is being added, or on a doFinal. * <p> * Note: in the case where the underlying cipher is either a CFB cipher or an * OFB one the last block may not be a multiple of the block size. * </p> */ public class BufferedBlockCipher : BufferedCipherBase { internal byte[] buf; internal int bufOff; internal bool forEncryption; internal IBlockCipher cipher; /** * constructor for subclasses */ protected BufferedBlockCipher() { } /** * Create a buffered block cipher without padding. * * @param cipher the underlying block cipher this buffering object wraps. * false otherwise. */ public BufferedBlockCipher( IBlockCipher cipher) { if (cipher == null) throw new ArgumentNullException("cipher"); this.cipher = cipher; buf = new byte[cipher.GetBlockSize()]; bufOff = 0; } public override string AlgorithmName { get { return cipher.AlgorithmName; } } /** * 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. */ // Note: This doubles as the Init in the event that this cipher is being used as an IWrapper public override void Init( bool forEncryption, ICipherParameters parameters) { this.forEncryption = forEncryption; var pwr = parameters as ParametersWithRandom; if (pwr != null) parameters = pwr.Parameters; Reset(); cipher.Init(forEncryption, parameters); } /** * return the blocksize for the underlying cipher. * * @return the blocksize for the underlying cipher. */ public override int GetBlockSize() { return cipher.GetBlockSize(); } /** * 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) { var total = length + bufOff; var leftOver = total % buf.Length; return total - leftOver; } /** * return the 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) { // Note: Can assume IsPartialBlockOkay is true for purposes of this calculation return length + bufOff; } /** * 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) { buf[bufOff++] = input; if (bufOff == buf.Length) { if ((outOff + buf.Length) > output.Length) throw new DataLengthException("output buffer too short"); bufOff = 0; return cipher.ProcessBlock(buf, 0, output, outOff); } return 0; } public override byte[] ProcessByte( byte input) { var outLength = GetUpdateOutputSize(1); var outBytes = outLength > 0 ? new byte[outLength] : null; var pos = ProcessByte(input, outBytes, 0); if (outLength > 0 && pos < outLength) { var tmp = new byte[pos]; Array.Copy(outBytes, 0, tmp, 0, pos); outBytes = tmp; } return outBytes; } public override byte[] ProcessBytes( byte[] input, int inOff, int length) { if (input == null) throw new ArgumentNullException("input"); if (length < 1) return null; var outLength = GetUpdateOutputSize(length); var outBytes = outLength > 0 ? new byte[outLength] : null; var pos = ProcessBytes(input, inOff, length, outBytes, 0); if (outLength > 0 && pos < outLength) { var tmp = new byte[pos]; Array.Copy(outBytes, 0, tmp, 0, pos); outBytes = tmp; } return outBytes; } /** * 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 < 1) { if (length < 0) throw new ArgumentException("Can't have a negative input length!"); return 0; } var blockSize = GetBlockSize(); var outLength = GetUpdateOutputSize(length); if (outLength > 0) { if ((outOff + outLength) > output.Length) { throw new DataLengthException("output buffer too short"); } } var resultLen = 0; var gapLen = buf.Length - bufOff; if (length > gapLen) { Array.Copy(input, inOff, buf, bufOff, gapLen); resultLen += cipher.ProcessBlock(buf, 0, output, outOff); bufOff = 0; length -= gapLen; inOff += gapLen; while (length > buf.Length) { resultLen += cipher.ProcessBlock(input, inOff, output, outOff + resultLen); length -= blockSize; inOff += blockSize; } } Array.Copy(input, inOff, buf, bufOff, length); bufOff += length; if (bufOff == buf.Length) { resultLen += cipher.ProcessBlock(buf, 0, output, outOff + resultLen); bufOff = 0; } return resultLen; } public override byte[] DoFinal() { var outBytes = EmptyBuffer; var length = GetOutputSize(0); if (length > 0) { outBytes = new byte[length]; var pos = DoFinal(outBytes, 0); if (pos < outBytes.Length) { var tmp = new byte[pos]; Array.Copy(outBytes, 0, tmp, 0, pos); outBytes = tmp; } } else { Reset(); } return outBytes; } public override byte[] DoFinal( byte[] input, int inOff, int inLen) { if (input == null) throw new ArgumentNullException("input"); var length = GetOutputSize(inLen); var outBytes = EmptyBuffer; if (length > 0) { outBytes = new byte[length]; var pos = (inLen > 0) ? ProcessBytes(input, inOff, inLen, outBytes, 0) : 0; pos += DoFinal(outBytes, pos); if (pos < outBytes.Length) { var tmp = new byte[pos]; Array.Copy(outBytes, 0, tmp, 0, pos); outBytes = tmp; } } else { Reset(); } return outBytes; } /** * Process the last block in the buffer. * * @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 the input is not block size aligned and should be. * @exception InvalidOperationException if the underlying cipher is not * initialised. * @exception InvalidCipherTextException if padding is expected and not found. * @exception DataLengthException if the input is not block size * aligned. */ public override int DoFinal( byte[] output, int outOff) { try { if (bufOff != 0) { if (!cipher.IsPartialBlockOkay) { throw new DataLengthException("data not block size aligned"); } if (outOff + bufOff > output.Length) { throw new DataLengthException("output buffer too short for DoFinal()"); } // NB: Can't copy directly, or we may write too much output cipher.ProcessBlock(buf, 0, buf, 0); Array.Copy(buf, 0, output, outOff, bufOff); } return bufOff; } finally { Reset(); } } /** * Reset the buffer and cipher. After resetting the object is in the same * state as it was after the last init (if there was one). */ public override void Reset() { Array.Clear(buf, 0, buf.Length); bufOff = 0; cipher.Reset(); } } }
// *********************************************************************** // Copyright (c) 2007-2015 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.IO; using System.Collections.Generic; using System.Text; using System.Threading; using System.Reflection; using System.Diagnostics; using System.Security; using System.Security.Policy; using System.Security.Principal; using NUnit.Common; using NUnit.Engine.Internal; namespace NUnit.Engine.Services { /// <summary> /// The DomainManager class handles the creation and unloading /// of domains as needed and keeps track of all existing domains. /// </summary> public class DomainManager : Service { static Logger log = InternalTrace.GetLogger(typeof(DomainManager)); // Default settings used if SettingsService is unavailable private string _shadowCopyPath = Path.Combine(NUnitConfiguration.NUnitBinDirectory, "ShadowCopyCache"); private PrincipalPolicy _principalPolicy = PrincipalPolicy.UnauthenticatedPrincipal; private bool _setPrincipalPolicy = false; #region Create and Unload Domains /// <summary> /// Construct an application domain for running a test package /// </summary> /// <param name="package">The TestPackage to be run</param> public AppDomain CreateDomain( TestPackage package ) { AppDomainSetup setup = CreateAppDomainSetup(package); string domainName = "test-domain-" + package.Name; // Setup the Evidence Evidence evidence = new Evidence(AppDomain.CurrentDomain.Evidence); if (evidence.Count == 0) { Zone zone = new Zone(SecurityZone.MyComputer); evidence.AddHost(zone); Assembly assembly = Assembly.GetExecutingAssembly(); Url url = new Url(assembly.CodeBase); evidence.AddHost(url); Hash hash = new Hash(assembly); evidence.AddHost(hash); } log.Info("Creating AppDomain " + domainName); AppDomain runnerDomain = AppDomain.CreateDomain(domainName, evidence, setup); // Set PrincipalPolicy for the domain if called for in the settings if (_setPrincipalPolicy) runnerDomain.SetPrincipalPolicy(_principalPolicy); return runnerDomain; } // Made separate and public for testing public AppDomainSetup CreateAppDomainSetup(TestPackage package) { AppDomainSetup setup = new AppDomainSetup(); if (package.SubPackages.Count == 1) package = package.SubPackages[0]; //For parallel tests, we need to use distinct application name setup.ApplicationName = "Tests" + "_" + Environment.TickCount; FileInfo testFile = package.FullName != null && package.FullName != string.Empty ? new FileInfo(package.FullName) : null; string appBase = package.GetSetting(PackageSettings.BasePath, string.Empty); string configFile = package.GetSetting(PackageSettings.ConfigurationFile, string.Empty); string binPath = package.GetSetting(PackageSettings.PrivateBinPath, string.Empty); if (testFile != null) { if (appBase == null || appBase == string.Empty) appBase = testFile.DirectoryName; if (configFile == null || configFile == string.Empty) configFile = testFile.Name + ".config"; // Setting the target framework is only supported when running with // multiple AppDomains, one per assembly. SetTargetFramework(testFile.FullName, setup); } else { if (appBase == null || appBase == string.Empty) appBase = GetCommonAppBase(package.SubPackages); // TODO: What about config file for multiple assemblies? } char lastChar = appBase[appBase.Length - 1]; if (lastChar != Path.DirectorySeparatorChar && lastChar != Path.AltDirectorySeparatorChar) appBase += Path.DirectorySeparatorChar; setup.ApplicationBase = appBase; // TODO: Check whether Mono still needs full path to config file... setup.ConfigurationFile = appBase != null && configFile != null ? Path.Combine(appBase, configFile) : configFile; if (package.GetSetting(PackageSettings.AutoBinPath, binPath == string.Empty)) binPath = GetPrivateBinPath(appBase, package.SubPackages); setup.PrivateBinPath = binPath; if (package.GetSetting("ShadowCopyFiles", false)) { setup.ShadowCopyFiles = "true"; setup.ShadowCopyDirectories = appBase; setup.CachePath = GetCachePath(); } else setup.ShadowCopyFiles = "false"; return setup; } public void Unload(AppDomain domain) { new DomainUnloader(domain).Unload(); } #endregion #region Nested DomainUnloader Class class DomainUnloader { private Thread thread; private AppDomain domain; public DomainUnloader(AppDomain domain) { this.domain = domain; } public void Unload() { string domainName; try { domainName = "UNKNOWN";//domain.FriendlyName; } catch (AppDomainUnloadedException) { return; } log.Info("Unloading AppDomain " + domainName); thread = new Thread(new ThreadStart(UnloadOnThread)); thread.Start(); if (!thread.Join(30000)) { log.Error("Unable to unload AppDomain {0}, Unload thread timed out", domainName); thread.Abort(); } } private void UnloadOnThread() { bool shadowCopy = false; string cachePath = null; string domainName = "UNKNOWN"; try { shadowCopy = domain.ShadowCopyFiles; cachePath = domain.SetupInformation.CachePath; domainName = domain.FriendlyName; AppDomain.Unload(domain); } catch (Exception ex) { // We assume that the tests did something bad and just leave // the orphaned AppDomain "out there". // TODO: Something useful. log.Error("Unable to unload AppDomain " + domainName, ex); } finally { if (shadowCopy && cachePath != null) DeleteCacheDir(new DirectoryInfo(cachePath)); } } } #endregion #region Helper Methods /// <summary> /// Get the location for caching and delete any old cache info /// </summary> private string GetCachePath() { int processId = Process.GetCurrentProcess().Id; long ticks = DateTime.Now.Ticks; string cachePath = Path.Combine( _shadowCopyPath, processId.ToString() + "_" + ticks.ToString() ); try { DirectoryInfo dir = new DirectoryInfo(cachePath); if(dir.Exists) dir.Delete(true); } catch( Exception ex) { throw new ApplicationException( string.Format( "Invalid cache path: {0}",cachePath ), ex ); } return cachePath; } /// <summary> /// Helper method to delete the cache dir. This method deals /// with a bug that occurs when files are marked read-only /// and deletes each file separately in order to give better /// exception information when problems occur. /// /// TODO: This entire method is problematic. Should we be doing it? /// </summary> /// <param name="cacheDir"></param> private static void DeleteCacheDir( DirectoryInfo cacheDir ) { // Debug.WriteLine( "Modules:"); // foreach( ProcessModule module in Process.GetCurrentProcess().Modules ) // Debug.WriteLine( module.ModuleName ); if(cacheDir.Exists) { foreach( DirectoryInfo dirInfo in cacheDir.GetDirectories() ) DeleteCacheDir( dirInfo ); foreach( FileInfo fileInfo in cacheDir.GetFiles() ) { fileInfo.Attributes = FileAttributes.Normal; try { fileInfo.Delete(); } catch( Exception ex ) { Debug.WriteLine( string.Format( "Error deleting {0}, {1}", fileInfo.Name, ex.Message ) ); } } cacheDir.Attributes = FileAttributes.Normal; try { cacheDir.Delete(); } catch( Exception ex ) { Debug.WriteLine( string.Format( "Error deleting {0}, {1}", cacheDir.Name, ex.Message ) ); } } } private bool IsTestDomain(AppDomain domain) { return domain.FriendlyName.StartsWith( "test-domain-" ); } public static string GetCommonAppBase(IList<TestPackage> packages) { var assemblies = new List<string>(); foreach (var package in packages) assemblies.Add(package.FullName); return GetCommonAppBase(assemblies); } public static string GetCommonAppBase(IList<string> assemblies) { string commonBase = null; foreach (string assembly in assemblies) { string dir = Path.GetDirectoryName(Path.GetFullPath(assembly)); if (commonBase == null) commonBase = dir; else while (!PathUtils.SamePathOrUnder(commonBase, dir) && commonBase != null) commonBase = Path.GetDirectoryName(commonBase); } return commonBase; } public static string GetPrivateBinPath(string basePath, IList<TestPackage> packages) { var assemblies = new List<string>(); foreach (var package in packages) assemblies.Add(package.FullName); return GetPrivateBinPath(basePath, assemblies); } public static string GetPrivateBinPath(string basePath, IList<string> assemblies) { List<string> dirList = new List<string>(); StringBuilder sb = new StringBuilder(200); foreach( string assembly in assemblies ) { string dir = PathUtils.RelativePath( Path.GetFullPath(basePath), Path.GetDirectoryName( Path.GetFullPath(assembly) ) ); if ( dir != null && dir != string.Empty && dir != "." && !dirList.Contains( dir ) ) { dirList.Add( dir ); if ( sb.Length > 0 ) sb.Append( Path.PathSeparator ); sb.Append( dir ); } } return sb.Length == 0 ? null : sb.ToString(); } public void DeleteShadowCopyPath() { if ( Directory.Exists( _shadowCopyPath ) ) Directory.Delete( _shadowCopyPath, true ); } #endregion #region Service Overrides public override void StartService() { try { // DomainManager has a soft dependency on the SettingsService. // If it's not available, default values are used. var settings = ServiceContext.GetService<ISettings>(); if (settings != null) { var pathSetting = settings.GetSetting("Options.TestLoader.ShadowCopyPath", ""); if (pathSetting != "") _shadowCopyPath = Environment.ExpandEnvironmentVariables(pathSetting); _setPrincipalPolicy = settings.GetSetting("Options.TestLoader.SetPrincipalPolicy", false); _principalPolicy = settings.GetSetting("Options.TestLoader.PrincipalPolicy", PrincipalPolicy.UnauthenticatedPrincipal); } Status = ServiceStatus.Started; } catch { Status = ServiceStatus.Error; throw; } } // .NET versions greater than v4.0 report as v4.0, so look at // the TargetFrameworkAttribute on the assembly if it exists private static void SetTargetFramework(string assemblyPath, AppDomainSetup setup) { var property = typeof(AppDomainSetup).GetProperty("TargetFrameworkName", BindingFlags.Public | BindingFlags.Instance); // If property is null, .NET 4.5+ is not installed, so there is no need if (property != null) { var domain = AppDomain.CreateDomain("TargetFrameworkDomain"); try { var agentType = typeof(TargetFrameworkAgent); var agent = domain.CreateInstanceFromAndUnwrap(agentType.Assembly.CodeBase, agentType.FullName) as TargetFrameworkAgent; var targetFramework = agent.GetTargetFrameworkName(assemblyPath); if(!string.IsNullOrEmpty(targetFramework)) { property.SetValue(setup, targetFramework, null); } } finally { AppDomain.Unload(domain); } } } private class TargetFrameworkAgent : MarshalByRefObject { public string GetTargetFrameworkName(string assemblyPath) { // You can't get custom attributes when the assembly is loaded reflection only var testAssembly = Assembly.LoadFrom(assemblyPath); // This type exists on .NET 4.0+ var attrType = typeof(object).Assembly.GetType("System.Runtime.Versioning.TargetFrameworkAttribute"); var attrs = testAssembly.GetCustomAttributes(attrType, false); if (attrs.Length > 0) { var attr = attrs[0]; var type = attr.GetType(); var property = type.GetProperty("FrameworkName"); if (property != null) { return property.GetValue(attr, null) as string; } } return null; } } #endregion } }
/** * */ using System.Text; using DotNetXri.Client.Resolve.Exception; using System.Collections; using System.Text.RegularExpressions; namespace DotNetXri.Client.Resolve { //using java.util.Comparator; //using java.util.Hashtable; //using java.util.Iterator; //using java.util.Set; //using org.openxri.resolve.exception.IllegalTrustTypeException; /** * Encapsulates a media type in XRI Resolution. * Contains minimal business rules to recognize the 3 'built-in' types * used in XRI resolution: <code>application/xrds+xml</code>, * <code>application/xrd+xml</code> and <code>text/uri-list</code>. * * @author wtan * */ public class MimeType : Comparable { public const string PARAM_SEP = "sep"; public const string PARAM_REFS = "refs"; public const string PARAM_HTTPS = "https"; public const string PARAM_SAML = "saml"; public const string PARAM_CID = "cid"; public const string PARAM_URIC = "uric"; public const string PARAM_NO_DEFAULT_T = "nodefault_t"; public const string PARAM_NO_DEFAULT_P = "nodefault_p"; public const string PARAM_NO_DEFAULT_M = "nodefault_m"; /** * @deprecated */ public const string PARAM_TRUST = "trust"; public const string XRDS_XML = "application/xrds+xml"; public const string XRD_XML = "application/xrd+xml"; public const string URI_LIST = "text/uri-list"; // mime type protected string type = null; // media params protected Hashtable _params = null; // whatever was given to the parse method is saved here protected string original = null; /** * Creates a MimeType obj */ protected MimeType(string type, Hashtable _params, string original) { this.type = type; this._params = _params; this.original = original; } /** * Creates a MimeType obj with no params. * @param type all-lowercase string with no leading or trailing whitespace. */ public MimeType(string type) : this(type, new Hashtable(), type) { } /** * Retrieves the MIME parameter value for the given key * @param key * @return string the value if present (could be an empty string), or <code>null</code> if not present */ public string getParam(string key) { object val = _params[key]; if (val == null) return null; return (string)val; } /** * Gets the set of parameter keys * @return */ public ICollection paramKeys() { return _params.Keys; } /** * Compares the content of this obj with the candidate. Both must have the same type and same parameter values. * @param m * @return */ public bool Equals(MimeType m) { if (!type.Equals(m.type)) return false; // if the main type is the special type (XRDS document), we use different rules to match if (type.Equals(XRDS_XML)) { try { // look for all three parameters: https, saml, and trust // but the latter is only used if either https or saml is absent string myTrust = (string)this._params[PARAM_TRUST]; TrustType myTT = null; if (myTrust != null) myTT = new TrustType(myTrust); string myHTTPS = (string)this._params[PARAM_HTTPS]; string mySAML = (string)this._params[PARAM_SAML]; if (myHTTPS == null && myTT != null) { myHTTPS = myTT.isHTTPS() ? "true" : "false"; } if (mySAML == null && myTT != null) { mySAML = myTT.isSAML() ? "true" : "false"; } string itsTrust = (string)m._params[PARAM_TRUST]; TrustType itsTT = null; if (itsTrust != null) itsTT = new TrustType(itsTrust); string itsHTTPS = (string)m._params[PARAM_HTTPS]; string itsSAML = (string)m._params[PARAM_SAML]; if (itsHTTPS == null && itsTT != null) { itsHTTPS = itsTT.isHTTPS() ? "true" : "false"; } if (itsSAML == null && itsTT != null) { itsSAML = itsTT.isSAML() ? "true" : "false"; } if (myHTTPS.Equals(itsHTTPS) && mySAML.Equals(itsSAML)) return true; // else, fall through } catch (IllegalTrustTypeException) { // ignore } } // must have the same number of parameters if (_params.Count != m._params.Count) return false; // check each param ICollection keys = _params.Keys; IEnumerator i = keys.GetEnumerator(); while (i.MoveNext()) { string k = (string)i.Current; string v1 = (string)_params[k]; string v2 = (string)m._params[k]; if (v2 == null) { // key does not exist in m._params return false; } if (!v1.Equals(v2)) return false; } return true; } public bool Equals(object o) { return this.Equals((MimeType)o); } /** * This compares two objects and return their weigted order based on the q parameter */ public int compareTo(object o) { MimeType m2 = (MimeType)o; float q1 = 1.0f; float q2 = 1.0f; try { q1 = float.Parse(this.getParam("q")); } catch (System.Exception) { } try { q2 = float.Parse(m2.getParam("q")); } catch (System.Exception) { } return (int)((q2 - q1) * 1000); } /** * Tests to see if this <code>MimeType</code> has the same type as the simple type * <code>mtype</code>. If this <code>MimeType</code> has sub-parameters, they are ignored. */ public bool isType(string mtype) { return type.Equals(mtype.ToLower()); } /** * Tests to see if this <code>MimeType</code> has the same type as <code>m</code> and * that every parameter of <code>m</code> must be present and has the same value in this * <code>MimeType</code>. * @param m * @return */ public bool isSuperSetOf(MimeType m) { if (!type.Equals(m.type)) return false; // must have equal or more parameters than candidate if (_params.Count < m._params.Count) return false; // check each param ICollection keys = m._params.Keys; IEnumerator i = keys.GetEnumerator(); while (i.MoveNext()) { string k = (string)i.Current; string v1 = (string)_params[k]; string v2 = (string)m._params[k]; if (v1 == null) { // key does not exist in this obj's _params return false; } if (!v1.Equals(v2)) return false; } return true; } /** * Parses a HTTP Accept or Content-Type header value into the type and params components * @param typeStr * @return Returns a new <code>MimeType</code> obj. */ public static MimeType parse(string typeStr) { if (typeStr == null) return null; string[] parts = Regex.Split(typeStr, "\\s*;\\s*"); string typeVal = parts[0].Trim().ToLower(); Hashtable _params = new Hashtable(); for (int i = 1; i < parts.Length; i++) { if (parts[i].Length == 0) continue; // ignore blank parts string[] kvpair = Regex.Split(parts[i], "\\s*=\\s*"); string val = (kvpair.Length > 1) ? kvpair[1] : ""; _params[kvpair[0].ToLower()] = val.Trim(); } if (isXriResMediaType(typeVal)) { setXriResDefaultParams(_params); } return new MimeType(typeVal, _params, typeStr); } public bool isValidXriResMediaType() { return isXriResMediaType(type); } /** * @return Returns the type. */ public string getType() { return type; } /** * @return Returns the original type string (as given to <code>parse</code>.) */ public override string ToString() { return original; } /** * @return Returns the normalized string suitable for use in Accept and Content-Type headers. */ public string toNormalizedString() { StringBuilder sb = new StringBuilder(type); IEnumerator ki = _params.Keys.GetEnumerator(); while (ki.MoveNext()) { string key = (string)ki.Current; string val = (string)_params[key]; sb.Append(';'); sb.Append(key); sb.Append('='); sb.Append(val); } return sb.ToString(); } private static bool isXriResMediaType(string v) { return (v.Equals(XRDS_XML) || v.Equals(XRD_XML) || v.Equals(URI_LIST)); } private static void setXriResDefaultParams(Hashtable _params) { //string val = null; if (_params[PARAM_TRUST] == null && _params[PARAM_HTTPS] == null && _params[PARAM_SAML] == null) { _params[PARAM_HTTPS] = "false"; _params[PARAM_SAML] = "false"; } } public static void main(string[] args) { MimeType m1 = MimeType.parse("application/xrdS+xml"); MimeType m2 = MimeType.parse("application/xrds+xml;trust=none"); MimeType m3 = MimeType.parse("application/xrds+xml;sep=true"); MimeType m4 = MimeType.parse("application/xRds+xml;sep=true;refs=true;trust=none"); MimeType m5 = MimeType.parse("application/Xrds+xml;trust=https"); MimeType m6 = MimeType.parse("application/xrds+xml;trust=https;refs=true;refs=false"); MimeType m7 = MimeType.parse("text/plain;trust=https;refs=true;refs=false"); if (!m1.Equals(m2)) { Logger.Info("m1.Equals(m2) = " + m1.Equals(m2)); Logger.Info("m1 = " + m1.toNormalizedString()); Logger.Info("m2 = " + m2.toNormalizedString()); } if (!m1.isSuperSetOf(m2)) { Logger.Info("m1.isSuperSetOf(m2) = " + m1.isSuperSetOf(m2)); Logger.Info("m1 = " + m1.toNormalizedString()); Logger.Info("m2 = " + m2.toNormalizedString()); } if (!m4.isSuperSetOf(m3)) { Logger.Info("m4.isSuperSetOf(m3) = " + m4.isSuperSetOf(m3)); Logger.Info("m4 = " + m4.toNormalizedString()); Logger.Info("m3 = " + m3.toNormalizedString()); } if (m2.Equals(m5)) { Logger.Info("m2.isSuperSetOf(m5) = " + m2.isSuperSetOf(m5)); Logger.Info("m2 = " + m2.toNormalizedString()); Logger.Info("m5 = " + m5.toNormalizedString()); } if (m1.isSuperSetOf(m5)) { Logger.Info("m1.isSuperSetOf(m5) = " + m1.isSuperSetOf(m5)); Logger.Info("m1 = " + m1.toNormalizedString()); Logger.Info("m5 = " + m5.toNormalizedString()); } if (!m6.isSuperSetOf(m5)) { Logger.Info("m6.isSuperSetOf(m5) = " + m6.isSuperSetOf(m5)); Logger.Info("m6 = " + m6.toNormalizedString()); Logger.Info("m5 = " + m5.toNormalizedString()); } if (m6.isSuperSetOf(m7)) { Logger.Info("m6.isSuperSetOf(m7) = " + m6.isSuperSetOf(m7)); Logger.Info("m6 = " + m6.toNormalizedString()); Logger.Info("m7 = " + m7.toNormalizedString()); } } } }
//------------------------------------------------------------------------------ // <copyright file="XmlDiffNodes.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System; using System.IO; using System.Xml; using System.Text; using System.Diagnostics; namespace Microsoft.XmlDiffPatch { ////////////////////////////////////////////////////////////////// // XmlDiffNode // internal abstract class XmlDiffNode { // Fields // tree pointers internal XmlDiffParentNode _parent; internal XmlDiffNode _nextSibling; // original position among the other children internal int _position; // 'matching identical subtrees' algorithm fields: internal ulong _hashValue = 0; internal bool _bExpanded; // 'tree-to-tree comparison' algorithm fields: internal int _leftmostLeafIndex; internal bool _bKeyRoot; internal bool _bSomeDescendantMatches = false; #if DEBUG internal int _index = 0; #endif // internal bool _nodeOrDescendantMatches = false; // Constructors internal XmlDiffNode( int position ) { _parent = null; _nextSibling = null; _position = position; _bExpanded = false; } // Properties internal abstract XmlDiffNodeType NodeType { get; } internal int Position { get { return _position; } } internal bool IsKeyRoot { get { return _bKeyRoot; } } internal int Left { get { return _leftmostLeafIndex; } set { _leftmostLeafIndex = value; } } internal virtual XmlDiffNode FirstChildNode { get { return null; } } internal virtual bool HasChildNodes { get { return false; } } internal virtual int NodesCount { get { return 1; } set { Debug.Assert( value == 1 ); } } internal ulong HashValue { get { return _hashValue; } } internal virtual string OuterXml { get { StringWriter sw = new StringWriter(); XmlTextWriter xw = new XmlTextWriter( sw ); WriteTo( xw ); xw.Close(); return sw.ToString(); } } internal virtual string InnerXml { get { StringWriter sw = new StringWriter(); XmlTextWriter xw = new XmlTextWriter( sw ); WriteContentTo( xw ); xw.Close(); return sw.ToString(); } } internal virtual bool CanMerge { get { return true; } } // Methods // computes hash value of the node and stores it in the _hashValue variable internal abstract void ComputeHashValue( XmlHash xmlHash ); // compares the node to another one and returns the xmldiff operation for changing this node to the other one internal abstract XmlDiffOperation GetDiffOperation( XmlDiffNode changedNode, XmlDiff xmlDiff ); // compares the node to another one and returns true, if the nodes are identical; // on elements this method ignores namespace declarations internal virtual bool IsSameAs( XmlDiffNode node, XmlDiff xmlDiff ) { return GetDiffOperation( node, xmlDiff ) == XmlDiffOperation.Match; } // Abstract methods for outputing internal abstract void WriteTo( XmlWriter w ); internal abstract void WriteContentTo( XmlWriter w ); // Addressing internal virtual string GetRelativeAddress() { return Position.ToString(); } internal string GetAbsoluteAddress() { string address = GetRelativeAddress(); XmlDiffNode ancestor = _parent; while ( ancestor.NodeType != XmlDiffNodeType.Document ) { address = ancestor.GetRelativeAddress() + "/" + address; ancestor = ancestor._parent; } return "/" + address; } static internal string GetRelativeAddressOfInterval( XmlDiffNode firstNode, XmlDiffNode lastNode ) { Debug.Assert( firstNode._parent == lastNode._parent ); if ( firstNode == lastNode ) return firstNode.GetRelativeAddress(); else { if ( firstNode._parent._firstChildNode == firstNode && lastNode._nextSibling == null ) return "*"; else return firstNode.Position.ToString() + "-" + lastNode.Position.ToString(); } } #if DEBUG internal abstract void Dump( string indent ); #endif } ////////////////////////////////////////////////////////////////// // XmlDiffParentNode // internal abstract class XmlDiffParentNode : XmlDiffNode { // Fields // first node in the list of attributes AND children internal XmlDiffNode _firstChildNode; // number of nodes in the subtree rooted at this node private int _nodesCount; // number of child nodes - calculated on demand private int _childNodesCount = -1; // flag if the node contains only element children (this is used by addressing) internal bool _elementChildrenOnly; internal bool _bDefinesNamespaces; internal override bool HasChildNodes { get { return (_firstChildNode != null); } } internal override int NodesCount { get { return _nodesCount; } set { Debug.Assert( value > 0 ); _nodesCount = value; } } internal int ChildNodesCount { get { if ( _childNodesCount == -1 ) { int count = 0; for ( XmlDiffNode child = _firstChildNode; child != null; child = child._nextSibling ) count++; _childNodesCount = count; } return _childNodesCount; } } // Constructor internal XmlDiffParentNode( int position ) : base ( position ) { _firstChildNode = null; _nodesCount = 1; _elementChildrenOnly = true; _bDefinesNamespaces = false; _hashValue = 0; } // Properties internal override XmlDiffNode FirstChildNode { get { return _firstChildNode; } } // Methods internal virtual void InsertChildNodeAfter( XmlDiffNode childNode, XmlDiffNode newChildNode ) { Debug.Assert( newChildNode != null ); Debug.Assert( ! ( newChildNode is XmlDiffAttributeOrNamespace ) ); Debug.Assert( childNode == null || childNode._parent == this ); #if DEBUG if ( newChildNode.NodeType == XmlDiffNodeType.Attribute ) Debug.Assert( childNode == null || childNode.NodeType == XmlDiffNodeType.Attribute || childNode.NodeType == XmlDiffNodeType.Namespace ); #endif newChildNode._parent = this; if ( childNode == null ) { newChildNode._nextSibling = _firstChildNode; _firstChildNode = newChildNode; } else { newChildNode._nextSibling = childNode._nextSibling; childNode._nextSibling = newChildNode; } Debug.Assert( newChildNode.NodesCount > 0 ); _nodesCount += newChildNode.NodesCount; if ( newChildNode.NodeType != XmlDiffNodeType.Element && !(newChildNode is XmlDiffAttributeOrNamespace ) ) _elementChildrenOnly = false; } #if DEBUG protected void DumpChildren( string indent ) { XmlDiffNode curChild = _firstChildNode; while ( curChild != null ) { curChild.Dump( indent ); curChild = curChild._nextSibling; } } #endif } ////////////////////////////////////////////////////////////////// // XmlDiffElement // internal class XmlDiffElement : XmlDiffParentNode { // Fields string _localName; string _prefix; string _ns; // attribute & namespace nodes internal XmlDiffAttributeOrNamespace _attributes = null; internal ulong _allAttributesHash = 0; // xor combination of hash values of all attributes and namespace nodes internal ulong _attributesHashAH = 0; // xol combination of hash values of attributes and namespace nodes beginning with 'a'-'h' internal ulong _attributesHashIQ = 0; // xol combination of hash values of attributes and namespace nodes beginning with 'i'-'q' internal ulong _attributesHashRZ = 0; // xol combination of hash values of attributes and namespace nodes beginning with 'r'-'z' // Constructors internal XmlDiffElement( int position, string localName, string prefix, string ns ) : base( position ) { Debug.Assert( localName != null ); Debug.Assert( prefix != null ); Debug.Assert( ns != null ); _localName = localName; _prefix = prefix; _ns = ns; } // Properties internal override XmlDiffNodeType NodeType { get { return XmlDiffNodeType.Element; } } internal string LocalName { get { return _localName; } } internal string NamespaceURI { get { return _ns; } } internal string Prefix { get { return _prefix; } } internal string Name { get { if ( _prefix.Length > 0 ) return _prefix + ":" + _localName; else return _localName; } } // Methods // computes hash value of the node and stores it in the _hashValue variable internal override void ComputeHashValue( XmlHash xmlHash ) { Debug.Assert( _hashValue == 0 ); _hashValue = xmlHash.ComputeHashXmlDiffElement( this ); } // compares the node to another one and returns the xmldiff operation for changing this node to the other internal override XmlDiffOperation GetDiffOperation( XmlDiffNode changedNode, XmlDiff xmlDiff ) { Debug.Assert( changedNode != null ); if ( changedNode.NodeType != XmlDiffNodeType.Element ) return XmlDiffOperation.Undefined; XmlDiffElement changedElement = (XmlDiffElement)changedNode; // name bool bNameMatches = false; if ( LocalName == changedElement.LocalName ) { if ( xmlDiff.IgnoreNamespaces ) bNameMatches = true; else { if ( NamespaceURI == changedElement.NamespaceURI && ( xmlDiff.IgnorePrefixes || Prefix == changedElement.Prefix ) ) { bNameMatches = true; } } } // attributes if ( changedElement._allAttributesHash == _allAttributesHash ) return bNameMatches ? XmlDiffOperation.Match : XmlDiffOperation.ChangeElementName; int n = ( changedElement._attributesHashAH == _attributesHashAH ? 0 : 1 ) + ( changedElement._attributesHashIQ == _attributesHashIQ ? 0 : 1 ) + ( changedElement._attributesHashRZ == _attributesHashRZ ? 0 : 1 ); Debug.Assert( (int)XmlDiffOperation.ChangeElementName + 1 == (int)XmlDiffOperation.ChangeElementAttr1 ); Debug.Assert( (int)XmlDiffOperation.ChangeElementAttr1 + 1 == (int)XmlDiffOperation.ChangeElementAttr2 ); Debug.Assert( (int)XmlDiffOperation.ChangeElementAttr2 + 1 == (int)XmlDiffOperation.ChangeElementAttr3 ); Debug.Assert( (int)XmlDiffOperation.ChangeElementAttr3 + 1 == (int)XmlDiffOperation.ChangeElementNameAndAttr1 ); Debug.Assert( (int)XmlDiffOperation.ChangeElementNameAndAttr1 + 1 == (int)XmlDiffOperation.ChangeElementNameAndAttr2 ); Debug.Assert( (int)XmlDiffOperation.ChangeElementNameAndAttr2 + 1 == (int)XmlDiffOperation.ChangeElementNameAndAttr3 ); Debug.Assert( n != 0 ); if ( bNameMatches ) return (XmlDiffOperation)( ((int)XmlDiffOperation.ChangeElementName) + n ); else return (XmlDiffOperation)( ((int)XmlDiffOperation.ChangeElementAttr3) + n ); } // compares the node to another one and returns true, if the nodes are identical; // on elements this method ignores namespace declarations internal override bool IsSameAs( XmlDiffNode node, XmlDiff xmlDiff ) { // check node type Debug.Assert( node != null ); if ( node.NodeType != XmlDiffNodeType.Element ) return false; XmlDiffElement element = (XmlDiffElement)node; // check element name if ( LocalName != element.LocalName ) return false; else if ( !xmlDiff.IgnoreNamespaces ) if ( NamespaceURI != element.NamespaceURI ) return false; else if ( !xmlDiff.IgnorePrefixes ) if ( Prefix != element.Prefix ) return false; // ignore namespace definitions - should be first in the list of attributes XmlDiffAttributeOrNamespace attr1 = _attributes; while ( attr1 != null && attr1.NodeType == XmlDiffNodeType.Namespace ) attr1 = (XmlDiffAttributeOrNamespace) attr1._nextSibling; XmlDiffAttributeOrNamespace attr2 = _attributes; while ( attr2 != null && attr2.NodeType == XmlDiffNodeType.Namespace ) attr2 = (XmlDiffAttributeOrNamespace) attr2._nextSibling; // check attributes while ( attr1 != null && attr2 != null ) { if ( !attr1.IsSameAs( attr2, xmlDiff ) ) return false; attr1 = (XmlDiffAttributeOrNamespace) attr1._nextSibling; attr2 = (XmlDiffAttributeOrNamespace) attr2._nextSibling; } return attr1 == null && attr2 == null; } internal void InsertAttributeOrNamespace( XmlDiffAttributeOrNamespace newAttrOrNs ) { Debug.Assert( newAttrOrNs != null ); newAttrOrNs._parent = this; XmlDiffAttributeOrNamespace curAttr = _attributes; XmlDiffAttributeOrNamespace prevAttr = null; while ( curAttr != null && XmlDiffDocument.OrderAttributesOrNamespaces( curAttr, newAttrOrNs ) <= 0 ) { prevAttr = curAttr; curAttr = (XmlDiffAttributeOrNamespace)curAttr._nextSibling; } if ( prevAttr == null ) { newAttrOrNs._nextSibling = _attributes; _attributes = newAttrOrNs; } else { newAttrOrNs._nextSibling = prevAttr._nextSibling; prevAttr._nextSibling = newAttrOrNs; } // hash Debug.Assert( newAttrOrNs.HashValue != 0 ); _allAttributesHash += newAttrOrNs.HashValue; char firstLetter; if ( newAttrOrNs.NodeType == XmlDiffNodeType.Attribute ) firstLetter = ((XmlDiffAttribute)newAttrOrNs).LocalName[0]; else { XmlDiffNamespace nsNode = (XmlDiffNamespace)newAttrOrNs; firstLetter = ( nsNode.Prefix == string.Empty ) ? 'A' : nsNode.Prefix[0]; } firstLetter = char.ToUpper( firstLetter ); if ( firstLetter >= 'R' ) { _attributesHashRZ += newAttrOrNs.HashValue; } else if ( firstLetter >= 'I' ) { _attributesHashIQ += newAttrOrNs.HashValue; } else { _attributesHashAH += newAttrOrNs.HashValue; } if ( newAttrOrNs.NodeType == XmlDiffNodeType.Namespace ) _bDefinesNamespaces = true; } // Overriden abstract methods for outputting internal override void WriteTo( XmlWriter w ) { w.WriteStartElement( Prefix, LocalName, NamespaceURI ); XmlDiffAttributeOrNamespace attr = _attributes; while ( attr != null ) { attr.WriteTo( w ); attr = (XmlDiffAttributeOrNamespace) attr._nextSibling; } WriteContentTo( w ); w.WriteEndElement(); } internal override void WriteContentTo( XmlWriter w ) { XmlDiffNode child = _firstChildNode; while ( child != null ) { child.WriteTo( w ); child = child._nextSibling; } } #if DEBUG internal override void Dump( string indent ) { Trace.Write( indent + "(" + _index + ") <" + Name ); XmlDiffAttributeOrNamespace attr = _attributes; while ( attr != null ) { attr.Dump( indent ); attr = (XmlDiffAttributeOrNamespace)attr._nextSibling; } Trace.WriteLine( "> " ); DumpChildren( indent + " " ); } #endif } ////////////////////////////////////////////////////////////////// // XmlDiffAttributeOrNamespace // internal abstract class XmlDiffAttributeOrNamespace : XmlDiffNode { // Constructor internal XmlDiffAttributeOrNamespace( ) : base( 0 ) { } // Properties internal abstract string LocalName { get; } internal abstract string NamespaceURI { get; } internal abstract string Prefix { get; } internal abstract string Value { get; } } ////////////////////////////////////////////////////////////////// // XmlDiffAttribute // internal class XmlDiffAttribute : XmlDiffAttributeOrNamespace { // Fields string _localName; string _prefix; string _ns; string _value; // Constructor internal XmlDiffAttribute( string localName, string prefix, string ns, string value ) : base( ) { Debug.Assert( localName != null ); Debug.Assert( prefix != null ); Debug.Assert( ns != null ); Debug.Assert( value != null ); _localName = localName; _prefix = prefix; _ns = ns; _value = value; } // Properties internal override XmlDiffNodeType NodeType { get { return XmlDiffNodeType.Attribute; } } internal override string LocalName { get { return _localName; } } internal override string NamespaceURI { get { return _ns; } } internal override string Prefix { get { return _prefix; } } internal string Name { get { if ( _prefix.Length > 0 ) return _prefix + ":" + _localName; else return _localName; } } internal override string Value { get { return _value; } } internal override bool CanMerge { get { return false; } } // Methods // computes hash value of the node and stores it in the _hashValue variable internal override void ComputeHashValue( XmlHash xmlHash ) { Debug.Assert( _hashValue == 0 ); _hashValue = xmlHash.HashAttribute( _localName, _prefix, _ns, _value ); } // compares the node to another one and returns true, if the nodes are identical; // on elements this method ignores namespace declarations internal override bool IsSameAs( XmlDiffNode node, XmlDiff xmlDiff ) { Debug.Assert( node.NodeType == XmlDiffNodeType.Attribute ); XmlDiffAttribute attr = (XmlDiffAttribute) node; return ( LocalName == attr.LocalName && ( xmlDiff.IgnoreNamespaces || NamespaceURI == attr.NamespaceURI ) && ( xmlDiff.IgnorePrefixes || Prefix == attr.Prefix ) && Value == attr.Value ); } // compares the node to another one and returns the xmldiff operation for changing this node to the other internal override XmlDiffOperation GetDiffOperation( XmlDiffNode changedNode, XmlDiff xmlDiff ) { Debug.Assert( false, "This method should be never called." ); return XmlDiffOperation.Undefined; } // Overriden abstract methods for outputting internal override void WriteTo( XmlWriter w ) { w.WriteStartAttribute( Prefix, LocalName, NamespaceURI ); WriteContentTo( w ); w.WriteEndAttribute(); } internal override void WriteContentTo( XmlWriter w ) { w.WriteString( Value ); } // Addressing internal override string GetRelativeAddress() { return "@" + Name; } #if DEBUG internal override void Dump( string indent ) { Trace.Write( " " + Name + "=" + Value ); } #endif } ////////////////////////////////////////////////////////////////// // XmlDiffNamespace // internal class XmlDiffNamespace : XmlDiffAttributeOrNamespace { // Fields string _prefix; string _namespaceURI; // Constructor internal XmlDiffNamespace( string prefix, string namespaceURI ) : base( ) { Debug.Assert( prefix != null ); Debug.Assert( namespaceURI != null ); _prefix = prefix; _namespaceURI = namespaceURI; } // Properties internal override XmlDiffNodeType NodeType { get { return XmlDiffNodeType.Namespace; } } internal override string Prefix { get { return _prefix; } } internal override string NamespaceURI { get { return _namespaceURI; } } internal override string LocalName { get { return string.Empty; } } internal override string Value { get { return string.Empty; } } internal string Name { get { if ( _prefix.Length > 0 ) return "xmlns:" + _prefix; else return "xmlns"; } } // Methods // computes hash value of the node and stores it in the _hashValue variable internal override void ComputeHashValue( XmlHash xmlHash ) { Debug.Assert( _hashValue == 0 ); _hashValue = xmlHash.HashNamespace( _prefix, _namespaceURI ); } // compares the node to another one and returns the xmldiff operation for changing this node to the other internal override XmlDiffOperation GetDiffOperation( XmlDiffNode changedNode, XmlDiff xmlDiff ) { Debug.Assert( false, "This method should be never called." ); return XmlDiffOperation.Undefined; } // Overriden abstract methods for outputting internal override void WriteTo( XmlWriter w ) { if ( Prefix == string.Empty ) { w.WriteAttributeString( string.Empty, "xmlns", XmlDiff.XmlnsNamespaceUri, NamespaceURI ); } else { w.WriteAttributeString( "xmlns", Prefix, XmlDiff.XmlnsNamespaceUri, NamespaceURI ); } } internal override void WriteContentTo( XmlWriter w ) { Debug.Assert( false ); } // Addressing internal override string GetRelativeAddress() { return "@" + Name; } #if DEBUG internal override void Dump( string indent ) { Trace.WriteLine( indent + "xmlns:" + Prefix + "=" + NamespaceURI ); } #endif } ////////////////////////////////////////////////////////////////// // XmlDiffER // internal class XmlDiffER : XmlDiffNode { // Fields string _name; // Constructor internal XmlDiffER( int position, string name ) : base ( position ) { _name = name; } // Properties internal override XmlDiffNodeType NodeType { get { return XmlDiffNodeType.EntityReference; } } internal string Name { get { return _name; } } internal override bool CanMerge { get { return false; } } // Methods // computes hash value of the node and stores it in the _hashValue variable internal override void ComputeHashValue( XmlHash xmlHash ) { Debug.Assert( _hashValue == 0 ); _hashValue = xmlHash.HashER( _name ); } // compares the node to another one and returns the xmldiff operation for changing this node to the other internal override XmlDiffOperation GetDiffOperation( XmlDiffNode changedNode, XmlDiff xmlDiff ) { Debug.Assert( changedNode != null ); if ( changedNode.NodeType != XmlDiffNodeType.EntityReference ) return XmlDiffOperation.Undefined; if ( Name == ((XmlDiffER)changedNode).Name ) return XmlDiffOperation.Match; else return XmlDiffOperation.ChangeER; } // Overriden abstract methods for outputing internal override void WriteTo( XmlWriter w ) { w.WriteEntityRef( this._name ); } internal override void WriteContentTo( XmlWriter w ) {} #if DEBUG internal override void Dump( string indent ) { Trace.WriteLine( indent + "(" + _index + ") &" + Name ); } #endif } ////////////////////////////////////////////////////////////////// // XmlDiffCharData // internal class XmlDiffCharData : XmlDiffNode { // Fields string _value; XmlDiffNodeType _nodeType; // Constructor internal XmlDiffCharData( int position, string value, XmlDiffNodeType nodeType ) : base( position ) { _value = value; _nodeType = nodeType; } // Properties internal override XmlDiffNodeType NodeType { get { return _nodeType; } } internal string Value { get { return this._value; } } // Methods // computes hash value of the node and stores it in the _hashValue variable internal override void ComputeHashValue( XmlHash xmlHash ) { Debug.Assert( _hashValue == 0 ); _hashValue = xmlHash.HashCharacterNode( (XmlNodeType)(int)_nodeType, _value ); } // compares the node to another one and returns the xmldiff operation for changing this node to the other internal override XmlDiffOperation GetDiffOperation( XmlDiffNode changedNode, XmlDiff xmlDiff ) { Debug.Assert( changedNode != null ); if ( NodeType != changedNode.NodeType ) return XmlDiffOperation.Undefined; XmlDiffCharData changedCD = changedNode as XmlDiffCharData; if ( changedCD == null ) return XmlDiffOperation.Undefined; if ( Value == changedCD.Value ) return XmlDiffOperation.Match; else return XmlDiffOperation.ChangeCharacterData; } // Overriden abstract methods for outputing internal override void WriteTo( XmlWriter w ) { switch ( _nodeType ) { case XmlDiffNodeType.Comment: w.WriteComment( Value ); break; case XmlDiffNodeType.CDATA: w.WriteCData( Value ); break; case XmlDiffNodeType.SignificantWhitespace: case XmlDiffNodeType.Text: w.WriteString( Value ); break; default : Debug.Assert( false, "Wrong type for text-like node : " + this._nodeType.ToString() ); break; } } internal override void WriteContentTo( XmlWriter w ) {} #if DEBUG internal override void Dump( string indent ) { switch ( _nodeType ) { case XmlDiffNodeType.SignificantWhitespace: case XmlDiffNodeType.Text: Trace.WriteLine( indent + "(" + _index + ") '" + Value + "'" ); break; case XmlDiffNodeType.Comment: Trace.WriteLine( indent + "(" + _index + ") <!--" + Value + "-->" ); break; case XmlDiffNodeType.CDATA: Trace.WriteLine( indent + "(" + _index + ") <![CDATA[" + Value + "]]>" ); break; default: Debug.Assert( false ); break; } } #endif } ////////////////////////////////////////////////////////////////// // XmlDiffPI // internal class XmlDiffPI : XmlDiffCharData { // Fields string _name; // Constructor internal XmlDiffPI( int position, string name, string value ) : base( position, value, XmlDiffNodeType.ProcessingInstruction ) { _name = name; } // Properties internal string Name { get { return _name; } } // Methods // computes the hash value of the node and saves it into the _hashValue field internal override void ComputeHashValue( XmlHash xmlHash ) { Debug.Assert( _hashValue == 0 ); _hashValue = xmlHash.HashPI( Name, Value ); } // compares the node to another one and returns the xmldiff operation for changing this node to the other internal override XmlDiffOperation GetDiffOperation( XmlDiffNode changedNode, XmlDiff xmlDiff ) { Debug.Assert( changedNode != null ); if ( changedNode.NodeType != XmlDiffNodeType.ProcessingInstruction ) return XmlDiffOperation.Undefined; XmlDiffPI changedPI = (XmlDiffPI)changedNode; if ( Name == changedPI.Name ) { if ( Value == changedPI.Value ) return XmlDiffOperation.Match; else return XmlDiffOperation.ChangePI; } else { if ( Value == changedPI.Value ) return XmlDiffOperation.ChangePI; else return XmlDiffOperation.Undefined; } } internal override void WriteTo( XmlWriter w ) { w.WriteProcessingInstruction( Name, Value ); } internal override void WriteContentTo( XmlWriter w ) {} #if DEBUG internal override void Dump( string indent ) { Trace.WriteLine( indent + "(" + _index + ") <?" + Name + " " + Value + "?>" ); } #endif } ////////////////////////////////////////////////////////////////// // XmlDiffShrankNode // internal class XmlDiffShrankNode : XmlDiffNode { // Fields // interval of nodes it represents internal XmlDiffNode _firstNode; internal XmlDiffNode _lastNode; // matching nodes in target/source tree XmlDiffShrankNode _matchingShrankNode; // address string _localAddress; // 'move' operation id ulong _opid; // Constructor internal XmlDiffShrankNode( XmlDiffNode firstNode, XmlDiffNode lastNode ) : base ( -1 ) { Debug.Assert( firstNode != null ); Debug.Assert( lastNode != null ); Debug.Assert( firstNode.Position <= lastNode.Position ); Debug.Assert( firstNode.NodeType != XmlDiffNodeType.Attribute || (firstNode.NodeType == XmlDiffNodeType.Attribute && firstNode == lastNode ) ); _firstNode = firstNode; _lastNode = lastNode; _matchingShrankNode = null; // hash value XmlDiffNode curNode = firstNode; for (;;) { _hashValue += ( _hashValue << 7 ) + curNode.HashValue; if ( curNode == lastNode ) break; curNode = curNode._nextSibling; } _localAddress = DiffgramOperation.GetRelativeAddressOfNodeset( _firstNode, _lastNode ); } // Properties internal override XmlDiffNodeType NodeType { get { return XmlDiffNodeType.ShrankNode; } } internal XmlDiffShrankNode MatchingShrankNode { get { return _matchingShrankNode; } set { Debug.Assert( value != null ); Debug.Assert( _matchingShrankNode == null ); _matchingShrankNode = value; } } internal ulong MoveOperationId { get { if ( _opid == 0 ) _opid = MatchingShrankNode._opid; return _opid; } set { Debug.Assert( _opid == 0 ); _opid = value; } } internal override bool CanMerge { get { return false; } } // Methods // computes the hash value of the node and saves it into the _hashValue field internal override void ComputeHashValue( XmlHash xmlHash ) { Debug.Assert( false, "This method should bever be called." ); } // compares the node to another one and returns the xmldiff operation for changing this node to the other internal override XmlDiffOperation GetDiffOperation( XmlDiffNode changedNode, XmlDiff xmlDiff ) { Debug.Assert( changedNode != null ); if ( changedNode.NodeType != XmlDiffNodeType.ShrankNode ) return XmlDiffOperation.Undefined; if ( _hashValue == ((XmlDiffShrankNode)changedNode)._hashValue ) return XmlDiffOperation.Match; else return XmlDiffOperation.Undefined; } internal override void WriteTo( XmlWriter w ) { WriteContentTo( w ); } internal override void WriteContentTo( XmlWriter w ) { XmlDiffNode curNode = _firstNode; for (;;) { curNode.WriteTo( w ); if ( curNode == _lastNode ) break; curNode = curNode._nextSibling; } } // Addressing internal override string GetRelativeAddress() { return _localAddress; } #if DEBUG internal override void Dump( string indent ) { Trace.Write( indent + "(" + _index + ") shrank nodes: " ); XmlDiffNode curNode = _firstNode; for (;;) { Trace.Write( curNode.OuterXml ); if ( curNode == _lastNode ) break; curNode = curNode._nextSibling; } Trace.Write( "\n" ); } #endif } ////////////////////////////////////////////////////////////////// // XmlDiffXmlDeclaration // internal class XmlDiffXmlDeclaration : XmlDiffNode { // Fields string _value; // Constructors internal XmlDiffXmlDeclaration( int position, string value ) : base( position ) { Debug.Assert( value != null ); _value = value; } // Properties internal override XmlDiffNodeType NodeType { get { return XmlDiffNodeType.XmlDeclaration; } } internal string Value { get { return _value; } } // Methods // computes the hash value of the node and saves it into the _hashValue field internal override void ComputeHashValue( XmlHash xmlHash ) { Debug.Assert( _hashValue == 0 ); _hashValue = xmlHash.HashXmlDeclaration( _value ); } // compares the node to another one and returns the xmldiff operation for changing this node to the other internal override XmlDiffOperation GetDiffOperation( XmlDiffNode changedNode, XmlDiff xmlDiff ) { Debug.Assert( changedNode != null ); if ( changedNode.NodeType != XmlDiffNodeType.XmlDeclaration ) return XmlDiffOperation.Undefined; if ( Value == ((XmlDiffXmlDeclaration)changedNode).Value ) return XmlDiffOperation.Match; else return XmlDiffOperation.ChangeXmlDeclaration; } // Overriden abstract methods for outputting internal override void WriteTo( XmlWriter w ) { w.WriteProcessingInstruction( "xml", _value ); } internal override void WriteContentTo( XmlWriter w ) { } #if DEBUG internal override void Dump( string indent ) { Trace.WriteLine( indent + "(" + _index + ") <?xml " + Value + "?>" ); } #endif } ////////////////////////////////////////////////////////////////// // XmlDiffDoctypeDeclaration // internal class XmlDiffDocumentType : XmlDiffNode { // Fields string _name; string _publicId; string _systemId; string _subset; // Constructors internal XmlDiffDocumentType( int position, string name, string publicId, string systemId, string subset ) : base( position ) { Debug.Assert( name != null ); _name = name; _publicId = publicId; _systemId = systemId; _subset = subset; } // Properties internal override XmlDiffNodeType NodeType { get { return XmlDiffNodeType.DocumentType; } } internal string Name { get { return _name; } } internal string PublicId { get { return _publicId; } } internal string SystemId { get { return _systemId; } } internal string Subset { get { return _subset; } } // Methods // computes the hash value of the node and saves it into the _hashValue field internal override void ComputeHashValue( XmlHash xmlHash ) { Debug.Assert( _hashValue == 0 ); _hashValue = xmlHash.HashDocumentType( _name, _publicId, _systemId, _subset ); } // compares the node to another one and returns the xmldiff operation for changing this node to the other internal override XmlDiffOperation GetDiffOperation( XmlDiffNode changedNode, XmlDiff xmlDiff ) { Debug.Assert( changedNode != null ); if ( changedNode.NodeType != XmlDiffNodeType.DocumentType ) return XmlDiffOperation.Undefined; XmlDiffDocumentType changedDocType = (XmlDiffDocumentType)changedNode; if ( Name == changedDocType.Name && PublicId == changedDocType.PublicId && SystemId == changedDocType.SystemId && Subset == changedDocType.Subset ) { return XmlDiffOperation.Match; } else { return XmlDiffOperation.ChangeDTD; } } // Overriden abstract methods for outputting internal override void WriteTo( XmlWriter w ) { w.WriteDocType( _name, string.Empty, string.Empty, _subset ); } internal override void WriteContentTo( XmlWriter w ) { } #if DEBUG internal override void Dump( string indent ) { Trace.WriteLine( indent + "(" + _index + ") " + Name + "(SYSTEM '" + SystemId + "', PUBLIC '" + PublicId + "') [ " + Subset + " ]" ); } #endif } }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.IO; namespace FileSystemTest { public class GetExtension : IMFTestInterface { [SetUp] public InitializeResult Initialize() { Log.Comment("Adding set up for the tests"); return InitializeResult.ReadyToGo; } [TearDown] public void CleanUp() { } #region helper methods private bool TestGetExtension(string path, string expected) { string result = Path.GetExtension(path); Log.Comment("Path: '" + path + "'"); Log.Comment("Expected: '" + expected + "'"); if (result != expected) { Log.Exception("Got: '" + result + "'"); return false; } return true; } #endregion helper methods #region Test Cases [TestMethod] public MFTestResults Null() { MFTestResults result = MFTestResults.Pass; try { if (!TestGetExtension(null, null)) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults StringEmpty() { MFTestResults result = MFTestResults.Pass; try { if (!TestGetExtension(String.Empty, String.Empty)) { return MFTestResults.Fail; } if (!TestGetExtension("", "")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults PathNoExtension() { MFTestResults result = MFTestResults.Pass; try { if (!TestGetExtension("\\jabba\\de\\hutt", "")) { return MFTestResults.Fail; } if (!TestGetExtension("jabba\\de\\hutt", "")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults MultiDots() { MFTestResults result = MFTestResults.Pass; try { if (!TestGetExtension("luke.......sky....", "")) { return MFTestResults.Fail; } if (!TestGetExtension("luke.sky.Walker...", "")) { return MFTestResults.Fail; } if (!TestGetExtension(@"luke.sky.Walker.\..", "")) { return MFTestResults.Fail; } if (!TestGetExtension(@"lukeskyWalker\.", "")) { return MFTestResults.Fail; } if (!TestGetExtension(@"luke.sky.Walker.", "")) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ValidExension() { MFTestResults result = MFTestResults.Pass; try { if (!TestGetExtension(@"dir1\dir2\file.1", ".1")) { return MFTestResults.Fail; } if (!TestGetExtension(@"\sd1\dir1\dir2\file.to", ".to")) { return MFTestResults.Fail; } if (!TestGetExtension(@"\sd1\dir1\dir2\file.txt", ".txt")) { return MFTestResults.Fail; } //File name has special chars, but valid extension if (!TestGetExtension(@"foo.bar.fkl;fkds92-509450-4359.$#%()#%().%#(%)_#(%_).cool", ".cool")) { return MFTestResults.Fail; } //Extension has special chars string extension = ".$#@$_)+_)!@@!!@##&_$)#_"; if (!TestGetExtension("foo" + extension, extension)) { return MFTestResults.Fail; } if (!TestGetExtension(@"\sd1\dir1\dir2\file.longextensionname", ".longextensionname")) { return MFTestResults.Fail; } string verylong = "." + new string('x', 256); if (!TestGetExtension(@"\sd1\dir1\dir2\file" + verylong, verylong)) { return MFTestResults.Fail; } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } [TestMethod] public MFTestResults ArgumentExceptionTests() { MFTestResults result = MFTestResults.Pass; try { foreach (char invalidChar in Path.GetInvalidPathChars()) { try { Log.Comment("Invalid char ascii val = " + (int)invalidChar); string path = new string(new char[] { invalidChar, 'b', 'a', 'd', '.', invalidChar, 'p', 'a', 't', 'h', invalidChar }); string dir = Path.GetExtension(path); if ((path.Length == 0) && (dir.Length == 0)) { /// If path is empty string, returned value is also empty string (same behavior in desktop) /// no exception thrown. } else { Log.Exception("Expected Argument exception for '" + path + "' but got: '" + dir + "'"); return MFTestResults.Fail; } } catch (ArgumentException ae) { /* pass case */ Log.Comment( "Got correct exception: " + ae.Message ); } } } catch (Exception ex) { Log.Exception("Unexpected exception: " + ex.Message); return MFTestResults.Fail; } return result; } #endregion Test Cases public MFTestMethod[] Tests { get { return new MFTestMethod[] { new MFTestMethod( Null, "Null" ), new MFTestMethod( StringEmpty, "StringEmpty" ), new MFTestMethod( PathNoExtension, "PathNoExtension" ), new MFTestMethod( MultiDots, "MultiDots" ), new MFTestMethod( ValidExension, "ValidExension" ), new MFTestMethod( ArgumentExceptionTests, "ArgumentExceptionTests" ), }; } } } }
#region LGPL License /* Axiom Game Engine Library Copyright (C) 2003 Axiom Project Team The overall design, and a majority of the core engine and rendering code contained within this library is a derivative of the open source Object Oriented Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net. Many thanks to the OGRE team for maintaining such a high quality project. The math library included in this project, in addition to being a derivative of the works of Ogre, also include derivative work of the free portion of the Wild Magic mathematics source code that is distributed with the excellent book Game Engine Design. http://www.wild-magic.com/ This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Collections.Generic; using System.Globalization; namespace Axiom.MathLib { /// <summary> /// Standard 3-dimensional vector. /// </summary> /// <remarks> /// A direction in 3D space represented as distances along the 3 /// orthoganal axes (x, y, z). Note that positions, directions and /// scaling factors can be represented by a vector, depending on how /// you interpret the values. /// </remarks> [StructLayout(LayoutKind.Sequential)] public struct Vector3 { #region Fields /// <summary>X component.</summary> public float x; /// <summary>Y component.</summary> public float y; /// <summary>Z component.</summary> public float z; private static readonly Vector3 positiveInfinityVector = new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity); public static Vector3 PositiveInfinity { get { return positiveInfinityVector; } } private static readonly Vector3 negativeInfinityVector = new Vector3(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity); public static Vector3 NegativeInfinity { get { return negativeInfinityVector; } } private static readonly Vector3 invalidVector = new Vector3(float.NaN, float.NaN, float.NaN); public static Vector3 Invalid { get { return invalidVector; } } private static readonly Vector3 zeroVector = new Vector3(0.0f, 0.0f, 0.0f); private static readonly Vector3 unitX = new Vector3(1.0f, 0.0f, 0.0f); private static readonly Vector3 unitY = new Vector3(0.0f, 1.0f, 0.0f); private static readonly Vector3 unitZ = new Vector3(0.0f, 0.0f, 1.0f); private static readonly Vector3 negativeUnitX = new Vector3(-1.0f, 0.0f, 0.0f); private static readonly Vector3 negativeUnitY = new Vector3(0.0f, -1.0f, 0.0f); private static readonly Vector3 negativeUnitZ = new Vector3(0.0f, 0.0f, -1.0f); private static readonly Vector3 unitVector = new Vector3(1.0f, 1.0f, 1.0f); #endregion #region Constructors /// <summary> /// Creates a new 3 dimensional Vector. /// </summary> public Vector3(float x, float y, float z) { this.x = x; this.y = y; this.z = z; } /// <summary> /// Creates a new 3 dimensional Vector. /// </summary> public Vector3(float unitDimension) : this(unitDimension, unitDimension, unitDimension) { } private Vector3(string parsableText) { if(parsableText == null) throw new ArgumentException("The parsableText parameter cannot be null."); string[] vals = parsableText.TrimStart('(','[','<').TrimEnd(')',']','>').Split(','); if(vals.Length != 3) throw new FormatException(string.Format("Cannot parse the text '{0}' because it does not have 3 parts separated by commas in the form (x,y,z) with optional parenthesis.",parsableText)); try { x = float.Parse(vals[0].Trim()); y = float.Parse(vals[1].Trim()); z = float.Parse(vals[2].Trim()); } catch(Exception) { throw new FormatException("The parts of the vectors must be decimal numbers"); } } /// <summary> /// Creates a new 3 dimensional Vector. /// </summary> public Vector3(float[] coordinates) { if(coordinates.Length != 3) throw new ArgumentException("The coordinates array must be of length 3 to specify the x, y, and z coordinates."); this.x = coordinates[0]; this.y = coordinates[1]; this.z = coordinates[2]; } #endregion /// <summary> /// Used when to assign a Vector3 by reference /// </summary> /// <param name="result"></param> /// <param name="source"></param> /// <returns></returns> public static void AssignRef (ref Vector3 result, ref Vector3 source) { result.x = source.x; result.y = source.y; result.z = source.z; } /// <summary> /// User to compare two Vector3 instances for equality. /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns>true or false</returns> public static bool EqualsRef(ref Vector3 left, ref Vector3 right) { return (left.x == right.x && left.y == right.y && left.z == right.z); } /// <summary> /// Used when a Vector3 is multiplied by another vector. /// </summary> /// <param name="result"></param> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static void MultiplyRef (ref Vector3 result, ref Vector3 left, ref Vector3 right) { result.x = left.x * right.x; result.y = left.y * right.y; result.z = left.z * right.z; } /// <summary> /// Used to divide a vector by a scalar value. /// </summary> /// <param name="result"></param> /// <param name="left"></param> /// <param name="scalar"></param> /// <returns></returns> public static void DivideRef (ref Vector3 result, ref Vector3 left, float scalar) { Debug.Assert(scalar != 0.0f, "Cannot divide a Vector3 by zero."); // get the inverse of the scalar up front to avoid doing multiple divides later float inverse = 1.0f / scalar; result.x = left.x * inverse; result.y = left.y * inverse; result.z = left.z * inverse; } /// <summary> /// Used when a Vector3 is divided by another vector. /// </summary> /// <param name="result"></param> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static void DivideRef (ref Vector3 result, ref Vector3 left, ref Vector3 right) { result.x = left.x / right.x; result.y = left.y / right.y; result.z = left.z / right.z; } /// <summary> /// Used when a Vector3 is added to another Vector3. /// </summary> /// <param name="result"></param> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static void AddRef (ref Vector3 result, ref Vector3 left, ref Vector3 right) { result.x = left.x + right.x; result.y = left.y + right.y; result.z = left.z + right.z; } /// <summary> /// Used when a Vector3 is subtraced from another Vector3. /// </summary> /// <param name="result"></param> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static void SubtractRef (ref Vector3 result, ref Vector3 left, ref Vector3 right) { result.x = left.x - right.x; result.y = left.y - right.y; result.z = left.z - right.z; } /// <summary> /// Used when a Vector3 is multiplied by a scalar value. /// </summary> /// <param name="result"></param> /// <param name="left"></param> /// <param name="scalar"></param> /// <returns></returns> public static void MultiplyRef (ref Vector3 result, ref Vector3 left, float scalar) { result.x = left.x * scalar; result.y = left.y * scalar; result.z = left.z * scalar; } /// <summary> /// Used to divide a vector by a scalar value. /// </summary> /// <param name="result"></param> /// <param name="left"></param> /// <param name="scalar"></param> /// <returns></returns> public static void DivideRef (ref Vector3 result, Vector3 left, float scalar) { Debug.Assert(scalar != 0.0f, "Cannot divide a Vector3 by zero."); // get the inverse of the scalar up front to avoid doing multiple divides later float inverse = 1.0f / scalar; result.x = left.x * inverse; result.y = left.y * inverse; result.z = left.z * inverse; } #region Overloaded operators + CLS compliant method equivalents /// <summary> /// Used to divide a vector by a scalar value. /// </summary> /// <param name="left"></param> /// <param name="scalar"></param> /// <returns></returns> public static Vector3 operator / (Vector3 left, float scalar) { Debug.Assert(scalar != 0.0f, "Cannot divide a Vector3 by zero."); Vector3 vector = new Vector3(); // get the inverse of the scalar up front to avoid doing multiple divides later float inverse = 1.0f / scalar; vector.x = left.x * inverse; vector.y = left.y * inverse; vector.z = left.z * inverse; return vector; } /// <summary> /// User to compare two Vector3 instances for equality. /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns>true or false</returns> public static bool operator == (Vector3 left, Vector3 right) { return (left.x == right.x && left.y == right.y && left.z == right.z); } /// <summary> /// User to compare two Vector3 instances for inequality. /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns>true or false</returns> public static bool operator != (Vector3 left, Vector3 right) { return (left.x != right.x || left.y != right.y || left.z != right.z); } /// <summary> /// Used when a Vector3 is multiplied by another vector. /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static Vector3 Multiply (Vector3 left, Vector3 right) { return left * right; } /// <summary> /// Used when a Vector3 is multiplied by another vector. /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static Vector3 operator * (Vector3 left, Vector3 right) { return new Vector3(left.x * right.x, left.y * right.y, left.z * right.z); } /// <summary> /// Used to divide a vector by a scalar value. /// </summary> /// <param name="left"></param> /// <param name="scalar"></param> /// <returns></returns> public static Vector3 Divide (Vector3 left, float scalar) { return left / scalar; } /// <summary> /// Used when a Vector3 is divided by another vector. /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static Vector3 operator / (Vector3 left, Vector3 right) { return new Vector3(left.x / right.x, left.y / right.y, left.z / right.z); } /// <summary> /// Used when a Vector3 is divided by another vector. /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static Vector3 Divide (Vector3 left, Vector3 right) { return left / right; } /// <summary> /// Used when a Vector3 is added to another Vector3. /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static Vector3 Add (Vector3 left, Vector3 right) { return left + right; } /// <summary> /// Used when a Vector3 is added to another Vector3. /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static Vector3 operator + (Vector3 left, Vector3 right) { return new Vector3(left.x + right.x, left.y + right.y, left.z + right.z); } /// <summary> /// Used when a Vector3 is multiplied by a scalar value. /// </summary> /// <param name="left"></param> /// <param name="scalar"></param> /// <returns></returns> public static Vector3 Multiply (Vector3 left, float scalar) { return left * scalar; } /// <summary> /// Used when a Vector3 is multiplied by a scalar value. /// </summary> /// <param name="left"></param> /// <param name="scalar"></param> /// <returns></returns> public static Vector3 operator * (Vector3 left, float scalar) { return new Vector3(left.x * scalar, left.y * scalar, left.z * scalar); } /// <summary> /// Used when a scalar value is multiplied by a Vector3. /// </summary> /// <param name="scalar"></param> /// <param name="right"></param> /// <returns></returns> public static Vector3 Multiply (float scalar, Vector3 right) { return scalar * right; } /// <summary> /// Used when a scalar value is multiplied by a Vector3. /// </summary> /// <param name="scalar"></param> /// <param name="right"></param> /// <returns></returns> public static Vector3 operator * (float scalar, Vector3 right) { return new Vector3(right.x * scalar, right.y * scalar, right.z * scalar); } /// <summary> /// Used to subtract a Vector3 from another Vector3. /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static Vector3 Subtract (Vector3 left, Vector3 right) { return left - right; } /// <summary> /// Used to subtract a Vector3 from another Vector3. /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static Vector3 operator - (Vector3 left, Vector3 right) { return new Vector3(left.x - right.x, left.y - right.y, left.z - right.z); } /// <summary> /// Used to negate the elements of a vector. /// </summary> /// <param name="left"></param> /// <returns></returns> public static Vector3 Negate (Vector3 left) { return -left; } /// <summary> /// Used to negate the elements of a vector. /// </summary> /// <param name="left"></param> /// <returns></returns> public static Vector3 operator - (Vector3 left) { return new Vector3(-left.x, -left.y, -left.z); } /// <summary> /// Returns true if the vector's scalar components are all smaller /// that the ones of the vector it is compared against. /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator > (Vector3 left, Vector3 right) { return (left.x > right.x && left.y > right.y && left.z > right.z); } /// <summary> /// Returns true if the vector's scalar components are all greater /// that the ones of the vector it is compared against. /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public static bool operator < (Vector3 left, Vector3 right) { return (left.x < right.x && left.y < right.y && left.z < right.z); } /// <summary> /// /// </summary> /// <param name="vec3"></param> /// <returns></returns> public static explicit operator Vector4 (Vector3 vec3) { return new Vector4(vec3.x, vec3.y, vec3.z, 1.0f); } /// <summary> /// Used to access a Vector by index 0 = x, 1 = y, 2 = z. /// </summary> /// <remarks> /// Uses unsafe pointer arithmetic to reduce the code required. /// </remarks> public float this[int index] { get { switch(index) { case 0: return x; case 1: return y; case 2: return z; default: throw new ArgumentOutOfRangeException("Indexer boundaries overrun in Vector3, index must be from 0 to 2"); } } set { switch(index) { case 0: x = value; break; case 1: y = value; break; case 2: z = value; break; default: throw new ArgumentOutOfRangeException("Indexer boundaries overrun in Vector3, index must be from 0 to 2"); } } } #endregion #region Public methods public object[] ToObjectArray() { return new object[] { x, y, z }; } public float[] ToArray() { return new float[] { x, y, z }; } public bool IsAnyComponentGreaterThan(Vector3 vector) { return (this.x > vector.x || this.y > vector.y || this.z > vector.z); } public bool IsAnyComponentGreaterThanOrEqualTo(Vector3 vector) { return (this.x >= vector.x || this.y >= vector.y || this.z >= vector.z); } public bool IsAnyComponentLessThan(Vector3 vector) { return (this.x < vector.x || this.y < vector.y || this.z < vector.z); } public bool IsAnyComponentLessThanOrEqualTo(Vector3 vector) { return (this.x <= vector.x || this.y <= vector.y || this.z <= vector.z); } public Vector3 Offset(float x, float y, float z) { return new Vector3(this.x + x, this.y + y, this.z + z); } /// <summary> /// Performs a Dot Product operation on 2 vectors, which produces the angle between them. /// </summary> /// <param name="vector">The vector to perform the Dot Product against.</param> /// <returns>The angle between the 2 vectors.</returns> public float Dot(Vector3 vector) { return (float)x * vector.x + y * vector.y + z * vector.z; } /// <summary> /// Performs a Cross Product operation on 2 vectors, which returns a vector that is perpendicular /// to the intersection of the 2 vectors. Useful for finding face normals. /// </summary> /// <param name="vector">A vector to perform the Cross Product against.</param> /// <returns>A new Vector3 perpedicular to the 2 original vectors.</returns> public Vector3 Cross(Vector3 vector) { return new Vector3( (this.y * vector.z) - (this.z * vector.y), (this.z * vector.x) - (this.x * vector.z), (this.x * vector.y) - (this.y * vector.x) ); } /// <summary> /// Finds a vector perpendicular to this one. /// </summary> /// <returns></returns> public Vector3 Perpendicular() { Vector3 result = this.Cross(Vector3.UnitX); // check length if(result.LengthSquared < float.Epsilon) { // This vector is the Y axis multiplied by a scalar, so we have to use another axis result = this.Cross(Vector3.UnitY); } return result; } public static Vector3 SymmetricRandom() { return SymmetricRandom(1f, 1f, 1f); } public static Vector3 SymmetricRandom(Vector3 maxComponentMagnitude) { return SymmetricRandom(maxComponentMagnitude.x, maxComponentMagnitude.y, maxComponentMagnitude.z); } public static Vector3 SymmetricRandom(float maxComponentMagnitude) { return SymmetricRandom(maxComponentMagnitude, maxComponentMagnitude, maxComponentMagnitude); } public static Vector3 SymmetricRandom(float xMult, float yMult, float zMult) { return new Vector3( (xMult == 0)? 0: xMult * MathUtil.SymmetricRandom(), (yMult == 0)? 0: yMult * MathUtil.SymmetricRandom(), (zMult == 0)? 0: zMult * MathUtil.SymmetricRandom() ); } /// <summary> /// /// </summary> /// <param name="angle"></param> /// <param name="up"></param> /// <returns></returns> public Vector3 RandomDeviant(float angle, Vector3 up) { Vector3 newUp = Vector3.Zero; if(up == Vector3.Zero) newUp = this.Perpendicular(); else newUp = up; // rotate up vector by random amount around this Quaternion q = Quaternion.FromAngleAxis(MathUtil.UnitRandom() * MathUtil.TWO_PI, this); newUp = q * newUp; // finally, rotate this by given angle around randomized up vector q = Quaternion.FromAngleAxis(angle, newUp); return q * this; } /// <summary> /// Finds the midpoint between the supplied Vector and this vector. /// </summary> /// <param name="vector"></param> /// <returns></returns> public Vector3 MidPoint(Vector3 vector) { return new Vector3( (this.x + vector.x) / 2f, (this.y + vector.y) / 2f, (this.z + vector.z) / 2f); } /// <summary> /// Compares the supplied vector and updates it's x/y/z components of they are higher in value. /// </summary> /// <param name="compare"></param> public void Ceil(Vector3 compare) { if(compare.x > x) x = compare.x; if(compare.y > y) y = compare.y; if(compare.z > z) z = compare.z; } /// <summary> /// Compares the supplied vector and updates it's x/y/z components of they are lower in value. /// </summary> /// <param name="compare"></param> /// <returns></returns> public void Floor(Vector3 compare) { if(compare.x < x) x = compare.x; if(compare.y < y) y = compare.y; if(compare.z < z) z = compare.z; } public bool AllComponentsLessThan(float limit) { return Math.Abs(x) < limit && Math.Abs(y) < limit && Math.Abs(z) < limit; } public bool DifferenceLessThan(Vector3 other, float limit) { return Math.Abs(x - other.x) < limit && Math.Abs(y - other.y) < limit && Math.Abs(z - other.z) < limit; } /// <summary> /// Gets the shortest arc quaternion to rotate this vector to the destination vector. /// </summary> /// <remarks> /// Don't call this if you think the dest vector can be close to the inverse /// of this vector, since then ANY axis of rotation is ok. /// </remarks> public Quaternion GetRotationTo(Vector3 destination) { // Based on Stan Melax's article in Game Programming Gems Quaternion q = new Quaternion(); Vector3 v0 = new Vector3(this.x, this.y, this.z); Vector3 v1 = destination; // normalize both vectors v0.Normalize(); v1.Normalize(); // get the cross product of the vectors Vector3 c = v0.Cross(v1); // If the cross product approaches zero, we get unstable because ANY axis will do // when v0 == -v1 float d = v0.Dot(v1); // If dot == 1, vectors are the same if (d >= 1.0f) { return Quaternion.Identity; } float s = MathUtil.Sqrt( (1+d) * 2 ); float inverse = 1 / s; q.x = c.x * inverse; q.y = c.y * inverse; q.z = c.z * inverse; q.w = s * 0.5f; return q; } /// <summary> /// Gets the shortest arc quaternion to rotate this vector /// to the destination vector. /// </summary> /// <remarks> /// If you call this with a dest vector that is close to the inverse /// of this vector, we will rotate 180 degrees around the 'fallbackAxis' /// (if specified, or a generated axis if not) since in this case /// ANY axis of rotation is valid. /// </remarks> public Quaternion GetRotationTo(Vector3 destination, Vector3 fallbackAxis) { // Based on Stan Melax's article in Game Programming Gems Quaternion q = new Quaternion(); Vector3 v0 = new Vector3(this.x, this.y, this.z); Vector3 v1 = destination; // normalize both vectors v0.Normalize(); v1.Normalize(); // get the cross product of the vectors Vector3 c = v0.Cross(v1); // If the cross product approaches zero, we get unstable because ANY axis will do // when v0 == -v1 float d = v0.Dot(v1); // If dot == 1, vectors are the same if (d >= 1.0f) { return Quaternion.Identity; } if (d < (1e-6f - 1.0f)) { if (fallbackAxis != Vector3.Zero) // rotate 180 degrees about the fallback axis q = Quaternion.FromAngleAxis((float)Math.PI, fallbackAxis); else { // Generate an axis Vector3 axis = Vector3.UnitX.Cross(this); if (axis.IsZero) // pick another if colinear axis = Vector3.UnitY.Cross(this); axis.Normalize(); q = Quaternion.FromAngleAxis((float)Math.PI, axis); } } else { float s = MathUtil.Sqrt( (1+d) * 2 ); float inverse = 1 / s; q.x = c.x * inverse; q.y = c.y * inverse; q.z = c.z * inverse; q.w = s * 0.5f; q.Normalize(); } return q; } public Vector3 ToNormalized() { Vector3 vec = this; vec.Normalize(); return vec; } /// <summary> /// Normalizes the vector. /// </summary> /// <remarks> /// This method normalises the vector such that it's /// length / magnitude is 1. The result is called a unit vector. /// <p/> /// This function will not crash for zero-sized vectors, but there /// will be no changes made to their components. /// </remarks> /// <returns>The previous length of the vector.</returns> public float Normalize() { float length = MathUtil.Sqrt( this.x * this.x + this.y * this.y + this.z * this.z ); // Will also work for zero-sized vectors, but will change nothing if ( length > float.Epsilon ) { float inverseLength = 1.0f / length; this.x *= inverseLength; this.y *= inverseLength; this.z *= inverseLength; } return length; } /// <summary> /// Calculates a reflection vector to the plane with the given normal. /// </summary> /// <remarks> /// Assumes this vector is pointing AWAY from the plane, invert if not. /// </remarks> /// <param name="normal">Normal vector on which this vector will be reflected.</param> /// <returns></returns> public Vector3 Reflect(Vector3 normal) { return this - 2 * this.Dot(normal) * normal; } #endregion #region Public properties public bool IsZero { get { return this.x == 0f && this.y == 0f && this.z == 0f; } } /// <summary> /// Gets the length (magnitude) of this Vector3. The Sqrt operation is expensive, so /// only use this if you need the exact length of the Vector. If vector lengths are only going /// to be compared, use LengthSquared instead. /// </summary> public float Length { get { return MathUtil.Sqrt(this.x * this.x + this.y * this.y + this.z * this.z); } } /// <summary> /// Returns the length (magnitude) of the vector squared. /// </summary> public float LengthSquared { get { return (this.x * this.x + this.y * this.y + this.z * this.z); } } #endregion #region Static Constant Properties /// <summary> /// Gets a Vector3 with all components set to 0. /// </summary> public static Vector3 Zero { get { return zeroVector; } } /// <summary> /// Gets a Vector3 with all components set to 1. /// </summary> public static Vector3 UnitScale { get { return unitVector; } } /// <summary> /// Gets a Vector3 with the X set to 1, and the others set to 0. /// </summary> public static Vector3 UnitX { get { return unitX; } } /// <summary> /// Gets a Vector3 with the Y set to 1, and the others set to 0. /// </summary> public static Vector3 UnitY { get { return unitY; } } /// <summary> /// Gets a Vector3 with the Z set to 1, and the others set to 0. /// </summary> public static Vector3 UnitZ { get { return unitZ; } } /// <summary> /// Gets a Vector3 with the X set to -1, and the others set to 0. /// </summary> public static Vector3 NegativeUnitX { get { return negativeUnitX; } } /// <summary> /// Gets a Vector3 with the Y set to -1, and the others set to 0. /// </summary> public static Vector3 NegativeUnitY { get { return negativeUnitY; } } /// <summary> /// Gets a Vector3 with the Z set to -1, and the others set to 0. /// </summary> public static Vector3 NegativeUnitZ { get { return negativeUnitZ; } } #endregion #region Object overloads /// <summary> /// Overrides the Object.ToString() method to provide a text representation of /// a Vector3. /// </summary> /// <returns>A string representation of a vector3.</returns> public override string ToString() { return string.Format("({0}, {1}, {2})", this.x, this.y, this.z); } public string ToParsableText() { return ToString(); } /// <summary> /// Overrides the Object.ToString() method to provide a text representation of /// a Vector3. /// </summary> /// <returns>A string representation of a vector3.</returns> public string ToIntegerString() { return string.Format("({0}, {1}, {2})", (int)this.x, (int)this.y, (int)this.z); } /// <summary> /// Overrides the Object.ToString() method to provide a text representation of /// a Vector3. /// </summary> /// <returns>A string representation of a vector3.</returns> public string ToString(bool shortenDecmialPlaces) { if(shortenDecmialPlaces) return string.Format("({0:0.##}, {1:0.##} ,{2:0.##})", this.x, this.y, this.z); return ToString(); } public static Vector3 Parse(string text) { return new Vector3(text); } /// <summary> /// Provides a unique hash code based on the member variables of this /// class. This should be done because the equality operators (==, !=) /// have been overriden by this class. /// <p/> /// The standard implementation is a simple XOR operation between all local /// member variables. /// </summary> /// <returns></returns> public override int GetHashCode() { return x.GetHashCode() ^ y.GetHashCode() ^ z.GetHashCode(); } /// <summary> /// Compares this Vector to another object. This should be done because the /// equality operators (==, !=) have been overriden by this class. /// </summary> /// <param name="obj"></param> /// <returns></returns> public override bool Equals(object obj) { return (obj is Vector3) && (this == (Vector3)obj); } #endregion } }
#region File Description //----------------------------------------------------------------------------- // SkinnedModelProcessor.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using System.IO; using System.Collections.Generic; using System.ComponentModel; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content.Pipeline; using Microsoft.Xna.Framework.Content.Pipeline.Graphics; using Microsoft.Xna.Framework.Content.Pipeline.Processors; using GameEngine; #endregion namespace SkinnedModelPipeline { /// <summary> /// Custom processor extends the builtin framework ModelProcessor class, /// adding animation support. /// </summary> [ContentProcessor] public class SkinnedModelProcessor : ModelProcessor { /// <summary> /// The main Process method converts an intermediate format content pipeline /// NodeContent tree to a ModelContent object with embedded animation data. /// </summary> public override ModelContent Process(NodeContent input, ContentProcessorContext context) { ValidateMesh(input, context, null); // Find the skeleton. BoneContent skeleton = MeshHelper.FindSkeleton(input); if (skeleton == null) throw new InvalidContentException("Input skeleton not found."); // We don't want to have to worry about different parts of the model being // in different local coordinate systems, so let's just bake everything. FlattenTransforms(input, skeleton); // Read the bind pose and skeleton hierarchy data. IList<BoneContent> bones = MeshHelper.FlattenSkeleton(skeleton); if (bones.Count > SkinnedEffect.MaxBones) { throw new InvalidContentException(string.Format( "Skeleton has {0} bones, but the maximum supported is {1}.", bones.Count, SkinnedEffect.MaxBones)); } List<Matrix> bindPose = new List<Matrix>(); List<Matrix> inverseBindPose = new List<Matrix>(); List<int> skeletonHierarchy = new List<int>(); foreach (BoneContent bone in bones) { bindPose.Add(bone.Transform); inverseBindPose.Add(Matrix.Invert(bone.AbsoluteTransform)); skeletonHierarchy.Add(bones.IndexOf(bone.Parent as BoneContent)); } // Convert animation data to our runtime format. Dictionary<string, AnimationClip> animationClips; animationClips = ProcessAnimations(skeleton.Animations, bones); // Chain to the base ModelProcessor class so it can convert the model data. ModelContent model = base.Process(input, context); // Store our custom animation data in the Tag property of the model. model.Tag = new SkinningData(animationClips, bindPose, inverseBindPose, skeletonHierarchy); return model; } /// <summary> /// Converts an intermediate format content pipeline AnimationContentDictionary /// object to our runtime AnimationClip format. /// </summary> static Dictionary<string, AnimationClip> ProcessAnimations( AnimationContentDictionary animations, IList<BoneContent> bones) { // Build up a table mapping bone names to indices. Dictionary<string, int> boneMap = new Dictionary<string, int>(); for (int i = 0; i < bones.Count; i++) { string boneName = bones[i].Name; if (!string.IsNullOrEmpty(boneName)) boneMap.Add(boneName, i); } // Convert each animation in turn. Dictionary<string, AnimationClip> animationClips; animationClips = new Dictionary<string, AnimationClip>(); foreach (KeyValuePair<string, AnimationContent> animation in animations) { AnimationClip processed = ProcessAnimation(animation.Value, boneMap); animationClips.Add(animation.Key, processed); } if (animationClips.Count == 0) { throw new InvalidContentException( "Input file does not contain any animations."); } return animationClips; } /// <summary> /// Converts an intermediate format content pipeline AnimationContent /// object to our runtime AnimationClip format. /// </summary> static AnimationClip ProcessAnimation(AnimationContent animation, Dictionary<string, int> boneMap) { List<Keyframe> keyframes = new List<Keyframe>(); // For each input animation channel. foreach (KeyValuePair<string, AnimationChannel> channel in animation.Channels) { // Look up what bone this channel is controlling. int boneIndex; if (!boneMap.TryGetValue(channel.Key, out boneIndex)) { throw new InvalidContentException(string.Format( "Found animation for bone '{0}', " + "which is not part of the skeleton.", channel.Key)); } // Convert the keyframe data. foreach (AnimationKeyframe keyframe in channel.Value) { keyframes.Add(new Keyframe(boneIndex, keyframe.Time, keyframe.Transform)); } } // Sort the merged keyframes by time. keyframes.Sort(CompareKeyframeTimes); if (keyframes.Count == 0) throw new InvalidContentException("Animation has no keyframes."); if (animation.Duration <= TimeSpan.Zero) throw new InvalidContentException("Animation has a zero duration."); return new AnimationClip(animation.Duration, keyframes); } /// <summary> /// Comparison function for sorting keyframes into ascending time order. /// </summary> static int CompareKeyframeTimes(Keyframe a, Keyframe b) { return a.Time.CompareTo(b.Time); } /// <summary> /// Makes sure this mesh contains the kind of data we know how to animate. /// </summary> static void ValidateMesh(NodeContent node, ContentProcessorContext context, string parentBoneName) { MeshContent mesh = node as MeshContent; if (mesh != null) { // Validate the mesh. if (parentBoneName != null) { context.Logger.LogWarning(null, null, "Mesh {0} is a child of bone {1}. SkinnedModelProcessor " + "does not correctly handle meshes that are children of bones.", mesh.Name, parentBoneName); } if (!MeshHasSkinning(mesh)) { context.Logger.LogWarning(null, null, "Mesh {0} has no skinning information, so it has been deleted.", mesh.Name); mesh.Parent.Children.Remove(mesh); return; } } else if (node is BoneContent) { // If this is a bone, remember that we are now looking inside it. parentBoneName = node.Name; } // Recurse (iterating over a copy of the child collection, // because validating children may delete some of them). foreach (NodeContent child in new List<NodeContent>(node.Children)) ValidateMesh(child, context, parentBoneName); } /// <summary> /// Checks whether a mesh contains skininng information. /// </summary> static bool MeshHasSkinning(MeshContent mesh) { foreach (GeometryContent geometry in mesh.Geometry) { if (!geometry.Vertices.Channels.Contains(VertexChannelNames.Weights())) return false; } return true; } /// <summary> /// Bakes unwanted transforms into the model geometry, /// so everything ends up in the same coordinate system. /// </summary> static void FlattenTransforms(NodeContent node, BoneContent skeleton) { foreach (NodeContent child in node.Children) { // Don't process the skeleton, because that is special. if (child == skeleton) continue; // Bake the local transform into the actual geometry. MeshHelper.TransformScene(child, child.Transform); // Having baked it, we can now set the local // coordinate system back to identity. child.Transform = Matrix.Identity; // Recurse. FlattenTransforms(child, skeleton); } } /// <summary> /// Force all the materials to use our skinned model effect. /// </summary> [DefaultValue(MaterialProcessorDefaultEffect.SkinnedEffect)] public override MaterialProcessorDefaultEffect DefaultEffect { get { return MaterialProcessorDefaultEffect.SkinnedEffect; } set { } } } }
// *********************************************************************** // Copyright (c) 2014 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using NUnit.Common; using NUnit.Framework; using NUnit.Framework.Internal; #if !SILVERLIGHT && !PORTABLE using NUnitLite; #endif namespace NUnit.Tests { namespace Assemblies { /// <summary> /// Constant definitions for the mock-assembly dll. /// </summary> public class MockAssembly { public const int Classes = 9; public const int NamespaceSuites = 6; // assembly, NUnit, Tests, Assemblies, Singletons, TestAssembly public const int Tests = MockTestFixture.Tests + Singletons.OneTestCase.Tests + TestAssembly.MockTestFixture.Tests + IgnoredFixture.Tests + ExplicitFixture.Tests + BadFixture.Tests + FixtureWithTestCases.Tests + ParameterizedFixture.Tests + GenericFixtureConstants.Tests + CDataTestFixure.Tests + TestNameEscaping.Tests; public const int Suites = MockTestFixture.Suites + Singletons.OneTestCase.Suites + TestAssembly.MockTestFixture.Suites + IgnoredFixture.Suites + ExplicitFixture.Suites + BadFixture.Suites + FixtureWithTestCases.Suites + ParameterizedFixture.Suites + GenericFixtureConstants.Suites + CDataTestFixure.Suites + TestNameEscaping.Suites + NamespaceSuites; public const int Nodes = Tests + Suites; public const int ExplicitFixtures = 1; public const int SuitesRun = Suites - ExplicitFixtures; public const int Ignored = MockTestFixture.Ignored + IgnoredFixture.Tests; public const int Explicit = MockTestFixture.Explicit + ExplicitFixture.Tests; public const int Skipped = Ignored + Explicit; public const int NotRun = Ignored + Explicit + NotRunnable; public const int TestsRun = Tests - NotRun; public const int ResultCount = Tests - Explicit; public const int Errors = MockTestFixture.Errors; public const int Failures = MockTestFixture.Failures + CDataTestFixure.Failures; public const int NotRunnable = MockTestFixture.NotRunnable + BadFixture.Tests; public const int ErrorsAndFailures = Errors + Failures + NotRunnable; public const int Inconclusive = MockTestFixture.Inconclusive; public const int Success = TestsRun - Errors - Failures - Inconclusive; public const int Categories = MockTestFixture.Categories; #if !SILVERLIGHT && !PORTABLE public static readonly string AssemblyPath = AssemblyHelper.GetAssemblyPath(typeof(MockAssembly).Assembly); public static void Main(string[] args) { new AutoRun().Execute(args); } #endif } [TestFixture(Description="Fake Test Fixture")] [Category("FixtureCategory")] public class MockTestFixture { public const int Tests = 11; public const int Suites = 1; public const int Ignored = 1; public const int Explicit = 1; public const int NotRun = Ignored + Explicit; public const int TestsRun = Tests - NotRun; public const int ResultCount = Tests - Explicit; public const int Failures = 1; public const int Errors = 1; public const int NotRunnable = 2; public const int ErrorsAndFailures = Errors + Failures + NotRunnable; public const int Inconclusive = 1; public const int Categories = 5; public const int MockCategoryTests = 2; [Test(Description="Mock Test #1")] public void MockTest1() {} [Test] [Category("MockCategory")] [Property("Severity","Critical")] [Description("This is a really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really, really long description")] public void MockTest2() {} [Test] [Category("MockCategory")] [Category("AnotherCategory")] public void MockTest3() { Assert.Pass("Succeeded!"); } [Test] protected static void MockTest5() {} [Test] public void FailingTest() { Assert.Fail("Intentional failure"); } [Test, Property("TargetMethod", "SomeClassName"), Property("Size", 5), /*Property("TargetType", typeof( System.Threading.Thread ))*/] public void TestWithManyProperties() {} [Test] [Ignore("ignoring this test method for now")] [Category("Foo")] public void MockTest4() {} [Test, Explicit] [Category( "Special" )] public void ExplicitlyRunTest() {} [Test] public void NotRunnableTest( int a, int b) { } [Test] public void InconclusiveTest() { Assert.Inconclusive("No valid data"); } [Test] public void TestWithException() { MethodThrowsException(); } private void MethodThrowsException() { throw new Exception("Intentional Exception"); } } } namespace Singletons { [TestFixture] public class OneTestCase { public const int Tests = 1; public const int Suites = 1; [Test] public virtual void TestCase() {} } } namespace TestAssembly { [TestFixture] public class MockTestFixture { public const int Tests = 1; public const int Suites = 1; [Test] public void MyTest() { } } } [TestFixture, Ignore("BECAUSE")] public class IgnoredFixture { public const int Tests = 3; public const int Suites = 1; [Test] public void Test1() { } [Test] public void Test2() { } [Test] public void Test3() { } } [TestFixture,Explicit] public class ExplicitFixture { public const int Tests = 2; public const int Suites = 1; public const int Nodes = Tests + Suites; [Test] public void Test1() { } [Test] public void Test2() { } } [TestFixture] public class BadFixture { public const int Tests = 1; public const int Suites = 1; public BadFixture(int val) { } [Test] public void SomeTest() { } } [TestFixture] public class FixtureWithTestCases { public const int Tests = 4; public const int Suites = 3; [TestCase(2, 2, ExpectedResult=4)] [TestCase(9, 11, ExpectedResult=20)] public int MethodWithParameters(int x, int y) { return x+y; } [TestCase(2, 4)] [TestCase(9.2, 11.7)] public void GenericMethod<T>(T x, T y) { } } [TestFixture(5)] [TestFixture(42)] public class ParameterizedFixture { public const int Tests = 4; public const int Suites = 3; public ParameterizedFixture(int num) { } [Test] public void Test1() { } [Test] public void Test2() { } } public class GenericFixtureConstants { public const int Tests = 4; public const int Suites = 3; } [TestFixture(5)] [TestFixture(11.5)] public class GenericFixture<T> { public GenericFixture(T num){ } [Test] public void Test1() { } [Test] public void Test2() { } } [TestFixture] public class CDataTestFixure { public const int Tests = 4; public const int Suites = 1; public const int Failures = 2; [Test] public void DemonstrateIllegalSequenceInSuccessMessage() { Assert.Pass("Deliberate failure to illustrate ]]> in message "); } [Test] public void DemonstrateIllegalSequenceAtEndOfSuccessMessage() { Assert.Pass("The CDATA was: <![CDATA[ My <xml> ]]>"); } [Test] public void DemonstrateIllegalSequenceInFailureMessage() { Assert.Fail("Deliberate failure to illustrate ]]> in message "); } [Test] public void DemonstrateIllegalSequenceAtEndOfFailureMessage() { Assert.Fail("The CDATA was: <![CDATA[ My <xml> ]]>"); } } [TestFixture] public class TestNameEscaping { public const int Tests = 10; public const int Suites = 2; [TestCase("< left bracket")] [TestCase("> right bracket")] [TestCase("'single quote'")] [TestCase("\"double quote\"")] [TestCase("&amp")] public void MustBeEscaped(string str) { } [TestCase("< left bracket", TestName = "<")] [TestCase("> right bracket", TestName = ">")] [TestCase("'single quote'", TestName = "'")] [TestCase("double quote", TestName = "\"")] [TestCase("amp", TestName = "&")] public void MustBeEscaped_CustomName(string str) { } } }
// // NetworkIO.cs // // Authors: // Alan McGovern alan.mcgovern@gmail.com // // Copyright (C) 2008 Alan McGovern // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // namespace OctoTorrent.Client { using System; using System.Collections.Generic; using System.Threading; using Connections; using Messages; using Common; public delegate void AsyncIOCallback (bool succeeded, int transferred, object state); public delegate void AsyncMessageReceivedCallback (bool succeeded, PeerMessage message, object state); internal class AsyncConnectState { public AsyncConnectState(TorrentManager manager, Peer peer, IConnection connection) { Manager = manager; Peer = peer; Connection = connection; } public IConnection Connection; public TorrentManager Manager; public Peer Peer; } internal partial class NetworkIO { // The biggest message is a PieceMessage which is 16kB + some overhead // so send in chunks of 2kB + a little so we do 8 transfers per piece. private const int ChunkLength = 2048 + 32; private static readonly Queue<AsyncIOState> ReceiveQueue = new Queue<AsyncIOState>(); private static readonly Queue<AsyncIOState> SendQueue = new Queue<AsyncIOState>(); private static readonly ICache<AsyncConnectState> ConnectCache = new Cache<AsyncConnectState>(true).Synchronize(); private static readonly ICache<AsyncIOState> TransferCache = new Cache<AsyncIOState>(true).Synchronize(); private static readonly AsyncCallback EndConnectCallback = EndConnect; private static readonly AsyncCallback EndReceiveCallback = EndReceive; private static readonly AsyncCallback EndSendCallback = EndSend; static NetworkIO() { ClientEngine.MainLoop.QueueTimeout(TimeSpan.FromMilliseconds(100), delegate { lock (SendQueue) { int count = SendQueue.Count; for (int i = 0; i < count; i++) SendOrEnqueue (SendQueue.Dequeue ()); } lock (ReceiveQueue) { int count = ReceiveQueue.Count; for (int i = 0; i < count; i++) ReceiveOrEnqueue (ReceiveQueue.Dequeue ()); } return true; }); } static int halfOpens; public static int HalfOpens { get { return halfOpens; } } public static void EnqueueConnect (IConnection connection, AsyncIOCallback callback, object state) { var data = ConnectCache.Dequeue ().Initialise (connection, callback, state); try { var result = connection.BeginConnect (EndConnectCallback, data); Interlocked.Increment (ref halfOpens); ClientEngine.MainLoop.QueueTimeout (TimeSpan.FromSeconds (10), delegate { if (!result.IsCompleted) connection.Dispose (); return false; }); } catch { callback (false, 0, state); ConnectCache.Enqueue (data); } } public static void EnqueueReceive (IConnection connection, byte[] buffer, int offset, int count, IRateLimiter rateLimiter, ConnectionMonitor peerMonitor, ConnectionMonitor managerMonitor, AsyncIOCallback callback, object state) { var data = TransferCache.Dequeue ().Initialise (connection, buffer, offset, count, callback, state, rateLimiter, peerMonitor, managerMonitor); lock (ReceiveQueue) ReceiveOrEnqueue (data); } public static void EnqueueSend (IConnection connection, byte[] buffer, int offset, int count, IRateLimiter rateLimiter, ConnectionMonitor peerMonitor, ConnectionMonitor managerMonitor, AsyncIOCallback callback, object state) { var data = TransferCache.Dequeue ().Initialise (connection, buffer, offset, count, callback, state, rateLimiter, peerMonitor, managerMonitor); lock (SendQueue) SendOrEnqueue (data); } static void EndConnect (IAsyncResult result) { var data = (AsyncConnectState) result.AsyncState; try { Interlocked.Decrement (ref halfOpens); data.Connection.EndConnect (result); data.Callback (true, 0, data.State); } catch { data.Callback (false, 0, data.State); } finally { ConnectCache.Enqueue (data); } } static void EndReceive (IAsyncResult result) { var data = (AsyncIOState) result.AsyncState; try { int transferred = data.Connection.EndReceive (result); if (transferred == 0) { data.Callback (false, 0, data.State); TransferCache.Enqueue (data); } else { if (data.PeerMonitor != null) data.PeerMonitor.BytesReceived (transferred, data.TransferType); if (data.ManagerMonitor != null) data.ManagerMonitor.BytesReceived (transferred, data.TransferType); data.Offset += transferred; data.Remaining -= transferred; if (data.Remaining == 0) { data.Callback (true, data.Count, data.State); TransferCache.Enqueue (data); } else { lock (ReceiveQueue) ReceiveOrEnqueue (data); } } } catch { data.Callback (false, 0, data.State); TransferCache.Enqueue (data); } } private static void EndSend(IAsyncResult result) { var data = (AsyncIOState) result.AsyncState; try { var transferred = data.Connection.EndSend(result); if (transferred == 0) { data.Callback(false, 0, data.State); TransferCache.Enqueue(data); } else { if (data.PeerMonitor != null) data.PeerMonitor.BytesSent(transferred, data.TransferType); if (data.ManagerMonitor != null) data.ManagerMonitor.BytesSent(transferred, data.TransferType); data.Offset += transferred; data.Remaining -= transferred; if (data.Remaining == 0) { data.Callback(true, data.Count, data.State); TransferCache.Enqueue(data); } else { lock (SendQueue) SendOrEnqueue(data); } } } catch { data.Callback(false, 0, data.State); TransferCache.Enqueue(data); } } static void ReceiveOrEnqueue (AsyncIOState data) { int count = Math.Min (ChunkLength, data.Remaining); if (data.RateLimiter == null || data.RateLimiter.TryProcess (1)) { try { data.Connection.BeginReceive (data.Buffer, data.Offset, count, EndReceiveCallback, data); } catch { data.Callback (false, 0, data.State); TransferCache.Enqueue (data); } } else { ReceiveQueue.Enqueue (data); } } private static void SendOrEnqueue(AsyncIOState data) { var count = Math.Min(ChunkLength, data.Remaining); if (data.RateLimiter == null || data.RateLimiter.TryProcess(1)) { try { data.Connection.BeginSend(data.Buffer, data.Offset, count, EndSendCallback, data); } catch { data.Callback(false, 0, data.State); TransferCache.Enqueue(data); } } else { SendQueue.Enqueue(data); } } } }
/* | Version 10.1.84 | Copyright 2013 Esri | | Licensed under the Apache License, Version 2.0 (the "License"); | you may not use this file except in compliance with the License. | You may obtain a copy of the License at | | http://www.apache.org/licenses/LICENSE-2.0 | | Unless required by applicable law or agreed to in writing, software | distributed under the License is distributed on an "AS IS" BASIS, | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | See the License for the specific language governing permissions and | limitations under the License. */ using System; using System.Diagnostics; using System.Runtime.Serialization; using System.Runtime.Serialization.Json; using System.IO; using System.Text; using System.Collections.Generic; namespace ESRI.ArcLogistics.Routing.Json { /// <summary> /// JsonSerializeHelper class. /// </summary> internal class JsonSerializeHelper { #region public methods /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Serializes JSON object. /// </summary> /// <param name="obj">Object to serialize.</param> /// <returns> /// String in JSON format. /// </returns> public static string Serialize(object obj) { Debug.Assert(obj != null); DataContractJsonSerializer serializer = new DataContractJsonSerializer( obj.GetType()); return _Serialize(serializer, obj); } /// <summary> /// Serializes JSON object. /// </summary> /// <param name="obj">Object to serialize.</param> /// <param name="knownTypes"> /// Types that may be present in the object graph. /// </param> /// <returns> /// String in JSON format. /// </returns> public static string Serialize(object obj, IEnumerable<Type> knownTypes) { Debug.Assert(obj != null); Debug.Assert(knownTypes != null); DataContractJsonSerializer serializer = new DataContractJsonSerializer( obj.GetType(), knownTypes); return _Serialize(serializer, obj); } /// <summary> /// Serializes JSON object. /// </summary> /// <param name="obj"> /// Object to serialize. /// </param> /// <param name="doPostProcessing"> /// A boolean value indicating whether post-processing should be /// performed. /// </param> /// <param name="knownTypes"> /// Types that may be present in the object graph. Can be null. /// </param> /// <returns> /// String in JSON format. /// </returns> public static string Serialize(object obj, IEnumerable<Type> knownTypes, bool doPostProcessing) { Debug.Assert(obj != null); string json = null; if (knownTypes != null) json = Serialize(obj, knownTypes); else json = Serialize(obj); // post-processing if (doPostProcessing) json = JsonProcHelper.DoPostProcessing(json); return json; } /// <summary> /// Deserializes JSON object. /// </summary> /// <param name="json">String in JSON format.</param> /// <returns> /// Deserialized object. /// </returns> public static T Deserialize<T>(string json) { Debug.Assert(json != null); DataContractJsonSerializer serializer = new DataContractJsonSerializer( typeof(T)); return _Deserialize<T>(serializer, json); } /// <summary> /// Deserializes JSON object. /// </summary> /// <param name="json">String in JSON format.</param> /// <param name="knownTypes"> /// Types that may be present in the object graph. /// </param> /// <returns> /// Deserialized object. /// </returns> public static T Deserialize<T>(string json, IEnumerable<Type> knownTypes) { Debug.Assert(json != null); Debug.Assert(knownTypes != null); DataContractJsonSerializer serializer = new DataContractJsonSerializer( typeof(T), knownTypes); return _Deserialize<T>(serializer, json); } /// <summary> /// Deserializes JSON object. /// </summary> /// <param name="json">String in JSON format.</param> /// <param name="doPreProcessing"> /// A boolean value indicating whether pre-processing should be /// performed. /// </param> /// <param name="knownTypes"> /// Types that may be present in the object graph. Can be null. /// </param> /// <returns> /// Deserialized object. /// </returns> public static T Deserialize<T>(string json, IEnumerable<Type> knownTypes, bool doPreProcessing) { Debug.Assert(json != null); // pre-processing if (doPreProcessing) json = JsonProcHelper.DoPreProcessing(json); T obj; if (knownTypes != null) obj = Deserialize<T>(json, knownTypes); else obj = Deserialize<T>(json); return obj; } /// <summary> /// Deserializes response JSON object. /// </summary> /// <param name="json">String in JSON format.</param> /// <param name="knownTypes"> /// Types that may be present in the object graph. Can be null. /// </param> /// <returns> /// Deserialized object. /// </returns> public static T DeserializeResponse<T>(string json, IEnumerable<Type> knownTypes) { // validate response string if (String.IsNullOrEmpty(json)) throw new SerializationException(Properties.Messages.Error_InvalidJsonResponseString); T obj = default(T); // check if response string contains error data if (JsonProcHelper.IsFaultResponse(json)) { // deserialize error object GPFaultResponse errorObj = Deserialize<GPFaultResponse>(json); // create response object obj = Activator.CreateInstance<T>(); // set error data IFaultInfo fault = obj as IFaultInfo; if (fault != null) fault.FaultInfo = errorObj.Error; } else { // deserialize response object obj = Deserialize<T>(json, knownTypes, true); } return obj; } /// <summary> /// Returns a boolean value indicating whether SerializationInfo /// object contains property with specified name. /// </summary> public static bool ContainsProperty(string name, SerializationInfo info) { bool found = false; SerializationInfoEnumerator en = info.GetEnumerator(); while (en.MoveNext()) { if (en.Name.Equals(name)) { found = true; break; } } return found; } #endregion public methods #region private methods /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// private static string _Serialize(DataContractJsonSerializer serializer, object obj) { Debug.Assert(serializer != null); Debug.Assert(obj != null); string json = null; using (MemoryStream ms = new MemoryStream()) { serializer.WriteObject(ms, obj); json = Encoding.UTF8.GetString(ms.ToArray()); } return json; } private static T _Deserialize<T>(DataContractJsonSerializer serializer, string json) { Debug.Assert(serializer != null); Debug.Assert(json != null); T obj = default(T); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) { obj = (T)serializer.ReadObject(ms); } return obj; } #endregion private methods } internal class JS1 { /// <summary> /// Deserializes object of the specified type from JSON string. /// </summary> /// <param name="type">The type of object to be deserialized.</param> /// <param name="json">The JSON string containing serialized object.</param> /// <param name="knownTypes">Collection of types that may be present in the object /// graph.</param> /// <param name="doPreProcessing">A value indicating whether pre-processing should be /// performed.</param> /// <returns>A reference to the deserialized object.</returns> public static object Deserialize( Type type, string json, IEnumerable<Type> knownTypes, bool doPreProcessing) { Debug.Assert(type != null); Debug.Assert(json != null); if (doPreProcessing) { json = JsonProcHelper.DoPreProcessing(json); } var serializer = new DataContractJsonSerializer(type, knownTypes); return _Deserialize(serializer, json); } private static object _Deserialize( DataContractJsonSerializer serializer, string json) { Debug.Assert(serializer != null); Debug.Assert(json != null); var obj = default(object); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) { obj = serializer.ReadObject(ms); } return obj; } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Rooms Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class SMDataSet : EduHubDataSet<SM> { /// <inheritdoc /> public override string Name { get { return "SM"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal SMDataSet(EduHubContext Context) : base(Context) { Index_CAMPUS = new Lazy<NullDictionary<int?, IReadOnlyList<SM>>>(() => this.ToGroupedNullDictionary(i => i.CAMPUS)); Index_FACULTY = new Lazy<NullDictionary<string, IReadOnlyList<SM>>>(() => this.ToGroupedNullDictionary(i => i.FACULTY)); Index_ROOM = new Lazy<Dictionary<string, SM>>(() => this.ToDictionary(i => i.ROOM)); Index_STAFF_CODE = new Lazy<NullDictionary<string, IReadOnlyList<SM>>>(() => this.ToGroupedNullDictionary(i => i.STAFF_CODE)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="SM" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="SM" /> fields for each CSV column header</returns> internal override Action<SM, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<SM, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "ROOM": mapper[i] = (e, v) => e.ROOM = v; break; case "TITLE": mapper[i] = (e, v) => e.TITLE = v; break; case "SEATING": mapper[i] = (e, v) => e.SEATING = v == null ? (short?)null : short.Parse(v); break; case "DESCRIPTION": mapper[i] = (e, v) => e.DESCRIPTION = v; break; case "ROOM_TYPE": mapper[i] = (e, v) => e.ROOM_TYPE = v; break; case "FACULTY": mapper[i] = (e, v) => e.FACULTY = v; break; case "AREA_CODE": mapper[i] = (e, v) => e.AREA_CODE = v; break; case "CAMPUS": mapper[i] = (e, v) => e.CAMPUS = v == null ? (int?)null : int.Parse(v); break; case "STAFF_CODE": mapper[i] = (e, v) => e.STAFF_CODE = v; break; case "COMMENTA": mapper[i] = (e, v) => e.COMMENTA = v; break; case "BOARD": mapper[i] = (e, v) => e.BOARD = v; break; case "BLACKOUT": mapper[i] = (e, v) => e.BLACKOUT = v; break; case "NORMAL_ALLOTMENT": mapper[i] = (e, v) => e.NORMAL_ALLOTMENT = v == null ? (short?)null : short.Parse(v); break; case "GROUP_INDICATOR": mapper[i] = (e, v) => e.GROUP_INDICATOR = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="SM" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="SM" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="SM" /> entities</param> /// <returns>A merged <see cref="IEnumerable{SM}"/> of entities</returns> internal override IEnumerable<SM> ApplyDeltaEntities(IEnumerable<SM> Entities, List<SM> DeltaEntities) { HashSet<string> Index_ROOM = new HashSet<string>(DeltaEntities.Select(i => i.ROOM)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.ROOM; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_ROOM.Remove(entity.ROOM); if (entity.ROOM.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<NullDictionary<int?, IReadOnlyList<SM>>> Index_CAMPUS; private Lazy<NullDictionary<string, IReadOnlyList<SM>>> Index_FACULTY; private Lazy<Dictionary<string, SM>> Index_ROOM; private Lazy<NullDictionary<string, IReadOnlyList<SM>>> Index_STAFF_CODE; #endregion #region Index Methods /// <summary> /// Find SM by CAMPUS field /// </summary> /// <param name="CAMPUS">CAMPUS value used to find SM</param> /// <returns>List of related SM entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SM> FindByCAMPUS(int? CAMPUS) { return Index_CAMPUS.Value[CAMPUS]; } /// <summary> /// Attempt to find SM by CAMPUS field /// </summary> /// <param name="CAMPUS">CAMPUS value used to find SM</param> /// <param name="Value">List of related SM entities</param> /// <returns>True if the list of related SM entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByCAMPUS(int? CAMPUS, out IReadOnlyList<SM> Value) { return Index_CAMPUS.Value.TryGetValue(CAMPUS, out Value); } /// <summary> /// Attempt to find SM by CAMPUS field /// </summary> /// <param name="CAMPUS">CAMPUS value used to find SM</param> /// <returns>List of related SM entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SM> TryFindByCAMPUS(int? CAMPUS) { IReadOnlyList<SM> value; if (Index_CAMPUS.Value.TryGetValue(CAMPUS, out value)) { return value; } else { return null; } } /// <summary> /// Find SM by FACULTY field /// </summary> /// <param name="FACULTY">FACULTY value used to find SM</param> /// <returns>List of related SM entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SM> FindByFACULTY(string FACULTY) { return Index_FACULTY.Value[FACULTY]; } /// <summary> /// Attempt to find SM by FACULTY field /// </summary> /// <param name="FACULTY">FACULTY value used to find SM</param> /// <param name="Value">List of related SM entities</param> /// <returns>True if the list of related SM entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByFACULTY(string FACULTY, out IReadOnlyList<SM> Value) { return Index_FACULTY.Value.TryGetValue(FACULTY, out Value); } /// <summary> /// Attempt to find SM by FACULTY field /// </summary> /// <param name="FACULTY">FACULTY value used to find SM</param> /// <returns>List of related SM entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SM> TryFindByFACULTY(string FACULTY) { IReadOnlyList<SM> value; if (Index_FACULTY.Value.TryGetValue(FACULTY, out value)) { return value; } else { return null; } } /// <summary> /// Find SM by ROOM field /// </summary> /// <param name="ROOM">ROOM value used to find SM</param> /// <returns>Related SM entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SM FindByROOM(string ROOM) { return Index_ROOM.Value[ROOM]; } /// <summary> /// Attempt to find SM by ROOM field /// </summary> /// <param name="ROOM">ROOM value used to find SM</param> /// <param name="Value">Related SM entity</param> /// <returns>True if the related SM entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByROOM(string ROOM, out SM Value) { return Index_ROOM.Value.TryGetValue(ROOM, out Value); } /// <summary> /// Attempt to find SM by ROOM field /// </summary> /// <param name="ROOM">ROOM value used to find SM</param> /// <returns>Related SM entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public SM TryFindByROOM(string ROOM) { SM value; if (Index_ROOM.Value.TryGetValue(ROOM, out value)) { return value; } else { return null; } } /// <summary> /// Find SM by STAFF_CODE field /// </summary> /// <param name="STAFF_CODE">STAFF_CODE value used to find SM</param> /// <returns>List of related SM entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SM> FindBySTAFF_CODE(string STAFF_CODE) { return Index_STAFF_CODE.Value[STAFF_CODE]; } /// <summary> /// Attempt to find SM by STAFF_CODE field /// </summary> /// <param name="STAFF_CODE">STAFF_CODE value used to find SM</param> /// <param name="Value">List of related SM entities</param> /// <returns>True if the list of related SM entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindBySTAFF_CODE(string STAFF_CODE, out IReadOnlyList<SM> Value) { return Index_STAFF_CODE.Value.TryGetValue(STAFF_CODE, out Value); } /// <summary> /// Attempt to find SM by STAFF_CODE field /// </summary> /// <param name="STAFF_CODE">STAFF_CODE value used to find SM</param> /// <returns>List of related SM entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<SM> TryFindBySTAFF_CODE(string STAFF_CODE) { IReadOnlyList<SM> value; if (Index_STAFF_CODE.Value.TryGetValue(STAFF_CODE, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a SM table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SM]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[SM]( [ROOM] varchar(4) NOT NULL, [TITLE] varchar(30) NULL, [SEATING] smallint NULL, [DESCRIPTION] varchar(40) NULL, [ROOM_TYPE] varchar(1) NULL, [FACULTY] varchar(10) NULL, [AREA_CODE] varchar(4) NULL, [CAMPUS] int NULL, [STAFF_CODE] varchar(4) NULL, [COMMENTA] varchar(MAX) NULL, [BOARD] varchar(4) NULL, [BLACKOUT] varchar(1) NULL, [NORMAL_ALLOTMENT] smallint NULL, [GROUP_INDICATOR] varchar(1) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [SM_Index_ROOM] PRIMARY KEY CLUSTERED ( [ROOM] ASC ) ); CREATE NONCLUSTERED INDEX [SM_Index_CAMPUS] ON [dbo].[SM] ( [CAMPUS] ASC ); CREATE NONCLUSTERED INDEX [SM_Index_FACULTY] ON [dbo].[SM] ( [FACULTY] ASC ); CREATE NONCLUSTERED INDEX [SM_Index_STAFF_CODE] ON [dbo].[SM] ( [STAFF_CODE] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SM]') AND name = N'SM_Index_CAMPUS') ALTER INDEX [SM_Index_CAMPUS] ON [dbo].[SM] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SM]') AND name = N'SM_Index_FACULTY') ALTER INDEX [SM_Index_FACULTY] ON [dbo].[SM] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SM]') AND name = N'SM_Index_STAFF_CODE') ALTER INDEX [SM_Index_STAFF_CODE] ON [dbo].[SM] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SM]') AND name = N'SM_Index_CAMPUS') ALTER INDEX [SM_Index_CAMPUS] ON [dbo].[SM] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SM]') AND name = N'SM_Index_FACULTY') ALTER INDEX [SM_Index_FACULTY] ON [dbo].[SM] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SM]') AND name = N'SM_Index_STAFF_CODE') ALTER INDEX [SM_Index_STAFF_CODE] ON [dbo].[SM] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SM"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="SM"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SM> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<string> Index_ROOM = new List<string>(); foreach (var entity in Entities) { Index_ROOM.Add(entity.ROOM); } builder.AppendLine("DELETE [dbo].[SM] WHERE"); // Index_ROOM builder.Append("[ROOM] IN ("); for (int index = 0; index < Index_ROOM.Count; index++) { if (index != 0) builder.Append(", "); // ROOM var parameterROOM = $"@p{parameterIndex++}"; builder.Append(parameterROOM); command.Parameters.Add(parameterROOM, SqlDbType.VarChar, 4).Value = Index_ROOM[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the SM data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SM data set</returns> public override EduHubDataSetDataReader<SM> GetDataSetDataReader() { return new SMDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the SM data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the SM data set</returns> public override EduHubDataSetDataReader<SM> GetDataSetDataReader(List<SM> Entities) { return new SMDataReader(new EduHubDataSetLoadedReader<SM>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class SMDataReader : EduHubDataSetDataReader<SM> { public SMDataReader(IEduHubDataSetReader<SM> Reader) : base (Reader) { } public override int FieldCount { get { return 17; } } public override object GetValue(int i) { switch (i) { case 0: // ROOM return Current.ROOM; case 1: // TITLE return Current.TITLE; case 2: // SEATING return Current.SEATING; case 3: // DESCRIPTION return Current.DESCRIPTION; case 4: // ROOM_TYPE return Current.ROOM_TYPE; case 5: // FACULTY return Current.FACULTY; case 6: // AREA_CODE return Current.AREA_CODE; case 7: // CAMPUS return Current.CAMPUS; case 8: // STAFF_CODE return Current.STAFF_CODE; case 9: // COMMENTA return Current.COMMENTA; case 10: // BOARD return Current.BOARD; case 11: // BLACKOUT return Current.BLACKOUT; case 12: // NORMAL_ALLOTMENT return Current.NORMAL_ALLOTMENT; case 13: // GROUP_INDICATOR return Current.GROUP_INDICATOR; case 14: // LW_DATE return Current.LW_DATE; case 15: // LW_TIME return Current.LW_TIME; case 16: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 1: // TITLE return Current.TITLE == null; case 2: // SEATING return Current.SEATING == null; case 3: // DESCRIPTION return Current.DESCRIPTION == null; case 4: // ROOM_TYPE return Current.ROOM_TYPE == null; case 5: // FACULTY return Current.FACULTY == null; case 6: // AREA_CODE return Current.AREA_CODE == null; case 7: // CAMPUS return Current.CAMPUS == null; case 8: // STAFF_CODE return Current.STAFF_CODE == null; case 9: // COMMENTA return Current.COMMENTA == null; case 10: // BOARD return Current.BOARD == null; case 11: // BLACKOUT return Current.BLACKOUT == null; case 12: // NORMAL_ALLOTMENT return Current.NORMAL_ALLOTMENT == null; case 13: // GROUP_INDICATOR return Current.GROUP_INDICATOR == null; case 14: // LW_DATE return Current.LW_DATE == null; case 15: // LW_TIME return Current.LW_TIME == null; case 16: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // ROOM return "ROOM"; case 1: // TITLE return "TITLE"; case 2: // SEATING return "SEATING"; case 3: // DESCRIPTION return "DESCRIPTION"; case 4: // ROOM_TYPE return "ROOM_TYPE"; case 5: // FACULTY return "FACULTY"; case 6: // AREA_CODE return "AREA_CODE"; case 7: // CAMPUS return "CAMPUS"; case 8: // STAFF_CODE return "STAFF_CODE"; case 9: // COMMENTA return "COMMENTA"; case 10: // BOARD return "BOARD"; case 11: // BLACKOUT return "BLACKOUT"; case 12: // NORMAL_ALLOTMENT return "NORMAL_ALLOTMENT"; case 13: // GROUP_INDICATOR return "GROUP_INDICATOR"; case 14: // LW_DATE return "LW_DATE"; case 15: // LW_TIME return "LW_TIME"; case 16: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "ROOM": return 0; case "TITLE": return 1; case "SEATING": return 2; case "DESCRIPTION": return 3; case "ROOM_TYPE": return 4; case "FACULTY": return 5; case "AREA_CODE": return 6; case "CAMPUS": return 7; case "STAFF_CODE": return 8; case "COMMENTA": return 9; case "BOARD": return 10; case "BLACKOUT": return 11; case "NORMAL_ALLOTMENT": return 12; case "GROUP_INDICATOR": return 13; case "LW_DATE": return 14; case "LW_TIME": return 15; case "LW_USER": return 16; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== /*============================================================ ** ** Class: Math ** ** ** Purpose: Some floating-point math operations ** ** ===========================================================*/ namespace System { //This class contains only static members and doesn't require serialization. using System; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Diagnostics.Contracts; public static class Math { private static double doubleRoundLimit = 1e16d; private const int maxRoundingDigits = 15; // This table is required for the Round function which can specify the number of digits to round to private static double[] roundPower10Double = new double[] { 1E0, 1E1, 1E2, 1E3, 1E4, 1E5, 1E6, 1E7, 1E8, 1E9, 1E10, 1E11, 1E12, 1E13, 1E14, 1E15 }; public const double PI = 3.14159265358979323846; public const double E = 2.7182818284590452354; [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Acos(double d); [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Asin(double d); [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Atan(double d); [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Atan2(double y,double x); public static Decimal Ceiling(Decimal d) { return Decimal.Ceiling(d); } [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Ceiling(double a); [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Cos (double d); [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Cosh(double value); public static Decimal Floor(Decimal d) { return Decimal.Floor(d); } [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Floor(double d); [System.Security.SecuritySafeCritical] // auto-generated private static unsafe double InternalRound(double value, int digits, MidpointRounding mode) { if (Abs(value) < doubleRoundLimit) { Double power10 = roundPower10Double[digits]; value *= power10; if (mode == MidpointRounding.AwayFromZero) { double fraction = SplitFractionDouble(&value); if (Abs(fraction) >= 0.5d) { value += Sign(fraction); } } else { // On X86 this can be inlined to just a few instructions value = Round(value); } value /= power10; } return value; } [System.Security.SecuritySafeCritical] // auto-generated private unsafe static double InternalTruncate(double d) { SplitFractionDouble(&d); return d; } [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Sin(double a); [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Tan(double a); [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Sinh(double value); [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Tanh(double value); [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Round(double a); public static double Round(double value, int digits) { if ((digits < 0) || (digits > maxRoundingDigits)) throw new ArgumentOutOfRangeException("digits", Environment.GetResourceString("ArgumentOutOfRange_RoundingDigits")); Contract.EndContractBlock(); return InternalRound(value, digits, MidpointRounding.ToEven); } public static double Round(double value, MidpointRounding mode) { return Round(value, 0, mode); } public static double Round(double value, int digits, MidpointRounding mode) { if ((digits < 0) || (digits > maxRoundingDigits)) throw new ArgumentOutOfRangeException("digits", Environment.GetResourceString("ArgumentOutOfRange_RoundingDigits")); if (mode < MidpointRounding.ToEven || mode > MidpointRounding.AwayFromZero) { throw new ArgumentException(Environment.GetResourceString("Argument_InvalidEnumValue", mode, "MidpointRounding"), "mode"); } Contract.EndContractBlock(); return InternalRound(value, digits, mode); } public static Decimal Round(Decimal d) { return Decimal.Round(d,0); } public static Decimal Round(Decimal d, int decimals) { return Decimal.Round(d,decimals); } public static Decimal Round(Decimal d, MidpointRounding mode) { return Decimal.Round(d, 0, mode); } public static Decimal Round(Decimal d, int decimals, MidpointRounding mode) { return Decimal.Round(d, decimals, mode); } [System.Security.SecurityCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static unsafe extern double SplitFractionDouble(double* value); public static Decimal Truncate(Decimal d) { return Decimal.Truncate(d); } public static double Truncate(double d) { return InternalTruncate(d); } [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Sqrt(double d); [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Log (double d); [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Log10(double d); [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Exp(double d); [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern double Pow(double x, double y); public static double IEEERemainder(double x, double y) { if (Double.IsNaN(x)) { return x; // IEEE 754-2008: NaN payload must be preserved } if (Double.IsNaN(y)) { return y; // IEEE 754-2008: NaN payload must be preserved } double regularMod = x % y; if (Double.IsNaN(regularMod)) { return Double.NaN; } if (regularMod == 0) { if (Double.IsNegative(x)) { return Double.NegativeZero; } } double alternativeResult; alternativeResult = regularMod - (Math.Abs(y) * Math.Sign(x)); if (Math.Abs(alternativeResult) == Math.Abs(regularMod)) { double divisionResult = x/y; double roundedResult = Math.Round(divisionResult); if (Math.Abs(roundedResult) > Math.Abs(divisionResult)) { return alternativeResult; } else { return regularMod; } } if (Math.Abs(alternativeResult) < Math.Abs(regularMod)) { return alternativeResult; } else { return regularMod; } } /*================================Abs========================================= **Returns the absolute value of it's argument. ============================================================================*/ [CLSCompliant(false)] #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static sbyte Abs(sbyte value) { if (value >= 0) return value; else return AbsHelper(value); } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif private static sbyte AbsHelper(sbyte value) { Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (hack for JIT inlining)"); if (value == SByte.MinValue) throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum")); Contract.EndContractBlock(); return ((sbyte)(-value)); } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static short Abs(short value) { if (value >= 0) return value; else return AbsHelper(value); } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif private static short AbsHelper(short value) { Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (hack for JIT inlining)"); if (value == Int16.MinValue) throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum")); Contract.EndContractBlock(); return (short) -value; } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static int Abs(int value) { if (value >= 0) return value; else return AbsHelper(value); } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif private static int AbsHelper(int value) { Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (hack for JIT inlining)"); if (value == Int32.MinValue) throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum")); Contract.EndContractBlock(); return -value; } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static long Abs(long value) { if (value >= 0) return value; else return AbsHelper(value); } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif private static long AbsHelper(long value) { Contract.Requires(value < 0, "AbsHelper should only be called for negative values! (hack for JIT inlining)"); if (value == Int64.MinValue) throw new OverflowException(Environment.GetResourceString("Overflow_NegateTwosCompNum")); Contract.EndContractBlock(); return -value; } [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] extern public static float Abs(float value); // This is special code to handle NaN (We need to make sure NaN's aren't // negated). In CSharp, the else clause here should always be taken if // value is NaN, since the normal case is taken if and only if value < 0. // To illustrate this completely, a compiler has translated this into: // "load value; load 0; bge; ret -value ; ret value". // The bge command branches for comparisons with the unordered NaN. So // it runs the else case, which returns +value instead of negating it. // return (value < 0) ? -value : value; [System.Security.SecuritySafeCritical] // auto-generated [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] extern public static double Abs(double value); // This is special code to handle NaN (We need to make sure NaN's aren't // negated). In CSharp, the else clause here should always be taken if // value is NaN, since the normal case is taken if and only if value < 0. // To illustrate this completely, a compiler has translated this into: // "load value; load 0; bge; ret -value ; ret value". // The bge command branches for comparisons with the unordered NaN. So // it runs the else case, which returns +value instead of negating it. // return (value < 0) ? -value : value; #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static Decimal Abs(Decimal value) { return Decimal.Abs(value); } /*================================MAX========================================= **Returns the larger of val1 and val2 ============================================================================*/ [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static sbyte Max(sbyte val1, sbyte val2) { return (val1>=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static byte Max(byte val1, byte val2) { return (val1>=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static short Max(short val1, short val2) { return (val1>=val2)?val1:val2; } [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static ushort Max(ushort val1, ushort val2) { return (val1>=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static int Max(int val1, int val2) { return (val1>=val2)?val1:val2; } [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static uint Max(uint val1, uint val2) { return (val1>=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static long Max(long val1, long val2) { return (val1>=val2)?val1:val2; } [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static ulong Max(ulong val1, ulong val2) { return (val1>=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static float Max(float val1, float val2) { if (val1 > val2) return val1; if (Single.IsNaN(val1)) return val1; return val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static double Max(double val1, double val2) { if (val1 > val2) return val1; if (Double.IsNaN(val1)) return val1; return val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static Decimal Max(Decimal val1, Decimal val2) { return Decimal.Max(val1,val2); } /*================================MIN========================================= **Returns the smaller of val1 and val2. ============================================================================*/ [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static sbyte Min(sbyte val1, sbyte val2) { return (val1<=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static byte Min(byte val1, byte val2) { return (val1<=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static short Min(short val1, short val2) { return (val1<=val2)?val1:val2; } [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static ushort Min(ushort val1, ushort val2) { return (val1<=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static int Min(int val1, int val2) { return (val1<=val2)?val1:val2; } [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static uint Min(uint val1, uint val2) { return (val1<=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static long Min(long val1, long val2) { return (val1<=val2)?val1:val2; } [CLSCompliant(false)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static ulong Min(ulong val1, ulong val2) { return (val1<=val2)?val1:val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static float Min(float val1, float val2) { if (val1 < val2) return val1; if (Single.IsNaN(val1)) return val1; return val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static double Min(double val1, double val2) { if (val1 < val2) return val1; if (Double.IsNaN(val1)) return val1; return val2; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static Decimal Min(Decimal val1, Decimal val2) { return Decimal.Min(val1,val2); } /*=====================================Log====================================== ** ==============================================================================*/ public static double Log(double a, double newBase) { if (Double.IsNaN(a)) { return a; // IEEE 754-2008: NaN payload must be preserved } if (Double.IsNaN(newBase)) { return newBase; // IEEE 754-2008: NaN payload must be preserved } if (newBase == 1) return Double.NaN; if (a != 1 && (newBase == 0 || Double.IsPositiveInfinity(newBase))) return Double.NaN; return (Log(a)/Log(newBase)); } // Sign function for VB. Returns -1, 0, or 1 if the sign of the number // is negative, 0, or positive. Throws for floating point NaN's. [CLSCompliant(false)] #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static int Sign(sbyte value) { if (value < 0) return -1; else if (value > 0) return 1; else return 0; } // Sign function for VB. Returns -1, 0, or 1 if the sign of the number // is negative, 0, or positive. Throws for floating point NaN's. #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static int Sign(short value) { if (value < 0) return -1; else if (value > 0) return 1; else return 0; } // Sign function for VB. Returns -1, 0, or 1 if the sign of the number // is negative, 0, or positive. Throws for floating point NaN's. #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static int Sign(int value) { if (value < 0) return -1; else if (value > 0) return 1; else return 0; } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static int Sign(long value) { if (value < 0) return -1; else if (value > 0) return 1; else return 0; } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static int Sign (float value) { if (value < 0) return -1; else if (value > 0) return 1; else if (value == 0) return 0; throw new ArithmeticException(Environment.GetResourceString("Arithmetic_NaN")); } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static int Sign(double value) { if (value < 0) return -1; else if (value > 0) return 1; else if (value == 0) return 0; throw new ArithmeticException(Environment.GetResourceString("Arithmetic_NaN")); } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static int Sign(Decimal value) { if (value < 0) return -1; else if (value > 0) return 1; else return 0; } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static long BigMul(int a, int b) { return ((long)a) * b; } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static int DivRem(int a, int b, out int result) { result = a%b; return a/b; } #if !FEATURE_CORECLR [TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")] #endif public static long DivRem(long a, long b, out long result) { result = a%b; return a/b; } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using Newtonsoft.Json; using NUnit.Framework; using QuantConnect.Logging; using QuantConnect.Securities; namespace QuantConnect.Tests.Common.Securities { [TestFixture] public class SymbolPropertiesDatabaseTests { [Test] public void LoadsLotSize() { var db = SymbolPropertiesDatabase.FromDataFolder(); var symbol = Symbol.Create("EURGBP", SecurityType.Forex, Market.FXCM); var symbolProperties = db.GetSymbolProperties(symbol.ID.Market, symbol, symbol.SecurityType, "GBP"); Assert.AreEqual(symbolProperties.LotSize, 1000); } [Test] public void LoadsQuoteCurrency() { var db = SymbolPropertiesDatabase.FromDataFolder(); var symbol = Symbol.Create("EURGBP", SecurityType.Forex, Market.FXCM); var symbolProperties = db.GetSymbolProperties(symbol.ID.Market, symbol, symbol.SecurityType, "GBP"); Assert.AreEqual(symbolProperties.QuoteCurrency, "GBP"); } [Test] public void LoadsMinimumOrderSize() { var db = SymbolPropertiesDatabase.FromDataFolder(); var bitfinexSymbol = Symbol.Create("BTCUSD", SecurityType.Crypto, Market.Bitfinex); var bitfinexSymbolProperties = db.GetSymbolProperties(bitfinexSymbol.ID.Market, bitfinexSymbol, bitfinexSymbol.SecurityType, "USD"); var binanceSymbol = Symbol.Create("BTCEUR", SecurityType.Crypto, Market.Binance); var binanceSymbolProperties = db.GetSymbolProperties(binanceSymbol.ID.Market, binanceSymbol, binanceSymbol.SecurityType, "EUR"); var gdaxSymbol = Symbol.Create("BTCGBP", SecurityType.Crypto, Market.GDAX); var gdaxSymbolProperties = db.GetSymbolProperties(gdaxSymbol.ID.Market, gdaxSymbol, gdaxSymbol.SecurityType, "GBP"); var krakenSymbol = Symbol.Create("BTCCAD", SecurityType.Crypto, Market.Kraken); var krakenSymbolProperties = db.GetSymbolProperties(krakenSymbol.ID.Market, krakenSymbol, krakenSymbol.SecurityType, "CAD"); Assert.AreEqual(bitfinexSymbolProperties.MinimumOrderSize, 0.00006m); Assert.AreEqual(binanceSymbolProperties.MinimumOrderSize, 10m); // in quote currency, MIN_NOTIONAL Assert.AreEqual(gdaxSymbolProperties.MinimumOrderSize, 0.0001m); Assert.AreEqual(krakenSymbolProperties.MinimumOrderSize, 0.0001m); } [TestCase("KE", Market.CBOT, 100)] [TestCase("ZC", Market.CBOT, 100)] [TestCase("ZL", Market.CBOT, 100)] [TestCase("ZO", Market.CBOT, 100)] [TestCase("ZS", Market.CBOT, 100)] [TestCase("ZW", Market.CBOT, 100)] [TestCase("CB", Market.CME, 100)] [TestCase("DY", Market.CME, 100)] [TestCase("GF", Market.CME, 100)] [TestCase("GNF", Market.CME, 100)] [TestCase("HE", Market.CME, 100)] [TestCase("LE", Market.CME, 100)] [TestCase("CSC", Market.CME, 1)] public void LoadsPriceMagnifier(string ticker, string market, int expectedPriceMagnifier) { var db = SymbolPropertiesDatabase.FromDataFolder(); var symbol = Symbol.Create(ticker, SecurityType.Future, market); var symbolProperties = db.GetSymbolProperties(symbol.ID.Market, symbol, symbol.SecurityType, "USD"); Assert.AreEqual(expectedPriceMagnifier, symbolProperties.PriceMagnifier); var futureOption = Symbol.CreateOption(symbol, symbol.ID.Market, OptionStyle.American, OptionRight.Call, 1, new DateTime(2021, 10, 14)); var symbolPropertiesFop = db.GetSymbolProperties(futureOption.ID.Market, futureOption, futureOption.SecurityType, "USD"); Assert.AreEqual(expectedPriceMagnifier, symbolPropertiesFop.PriceMagnifier); } [Test] public void LoadsDefaultLotSize() { var defaultSymbolProperties = SymbolProperties.GetDefault(Currencies.USD); Assert.AreEqual(defaultSymbolProperties.LotSize, 1); } [TestCase(Market.FXCM, SecurityType.Forex)] [TestCase(Market.Oanda, SecurityType.Forex)] [TestCase(Market.GDAX, SecurityType.Crypto)] [TestCase(Market.Bitfinex, SecurityType.Crypto)] public void BaseCurrencyIsNotEqualToQuoteCurrency(string market, SecurityType securityType) { var db = SymbolPropertiesDatabase.FromDataFolder(); var spList = db.GetSymbolPropertiesList(market, securityType).ToList(); Assert.IsNotEmpty(spList); foreach (var kvp in spList) { var quoteCurrency = kvp.Value.QuoteCurrency; var baseCurrency = kvp.Key.Symbol.Substring(0, kvp.Key.Symbol.Length - quoteCurrency.Length); Assert.AreNotEqual(baseCurrency, quoteCurrency); } } [Test] public void CustomEntriesStoredAndFetched() { var database = SymbolPropertiesDatabase.FromDataFolder(); var ticker = "BTC"; var properties = SymbolProperties.GetDefault("USD"); // Set the entry Assert.IsTrue(database.SetEntry(Market.USA, ticker, SecurityType.Base, properties)); // Fetch the entry to ensure we can access it with the ticker var fetchedProperties = database.GetSymbolProperties(Market.USA, ticker, SecurityType.Base, "USD"); Assert.AreSame(properties, fetchedProperties); } [TestCase(Market.FXCM, SecurityType.Cfd)] [TestCase(Market.Oanda, SecurityType.Cfd)] [TestCase(Market.CFE, SecurityType.Future)] [TestCase(Market.CBOT, SecurityType.Future)] [TestCase(Market.CME, SecurityType.Future)] [TestCase(Market.COMEX, SecurityType.Future)] [TestCase(Market.ICE, SecurityType.Future)] [TestCase(Market.NYMEX, SecurityType.Future)] [TestCase(Market.SGX, SecurityType.Future)] [TestCase(Market.HKFE, SecurityType.Future)] public void GetSymbolPropertiesListIsNotEmpty(string market, SecurityType securityType) { var db = SymbolPropertiesDatabase.FromDataFolder(); var spList = db.GetSymbolPropertiesList(market, securityType).ToList(); Assert.IsNotEmpty(spList); } [TestCase(Market.USA, SecurityType.Equity)] [TestCase(Market.USA, SecurityType.Option)] public void GetSymbolPropertiesListHasOneRow(string market, SecurityType securityType) { var db = SymbolPropertiesDatabase.FromDataFolder(); var spList = db.GetSymbolPropertiesList(market, securityType).ToList(); Assert.AreEqual(1, spList.Count); Assert.IsTrue(spList[0].Key.Symbol.Contains("*")); } #region GDAX brokerage [Test, Explicit] public void FetchSymbolPropertiesFromGdax() { const string urlCurrencies = "https://api.pro.coinbase.com/currencies"; const string urlProducts = "https://api.pro.coinbase.com/products"; var sb = new StringBuilder(); using (var wc = new WebClient()) { var jsonCurrencies = wc.DownloadString(urlCurrencies); var rowsCurrencies = JsonConvert.DeserializeObject<List<GdaxCurrency>>(jsonCurrencies); var currencyDescriptions = rowsCurrencies.ToDictionary(x => x.Id, x => x.Name); var jsonProducts = wc.DownloadString(urlProducts); var rowsProducts = JsonConvert.DeserializeObject<List<GdaxProduct>>(jsonProducts); foreach (var row in rowsProducts.OrderBy(x => x.Id)) { string baseDescription, quoteDescription; if (!currencyDescriptions.TryGetValue(row.BaseCurrency, out baseDescription)) { baseDescription = row.BaseCurrency; } if (!currencyDescriptions.TryGetValue(row.QuoteCurrency, out quoteDescription)) { quoteDescription = row.QuoteCurrency; } sb.AppendLine("gdax," + $"{row.BaseCurrency}{row.QuoteCurrency}," + "crypto," + $"{baseDescription}-{quoteDescription}," + $"{row.QuoteCurrency}," + "1," + $"{row.QuoteIncrement.NormalizeToStr()}," + $"{row.BaseIncrement.NormalizeToStr()}," + $"{row.Id}"); } } Log.Trace(sb.ToString()); } private class GdaxCurrency { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("min_size")] public decimal MinSize { get; set; } } private class GdaxProduct { [JsonProperty("id")] public string Id { get; set; } [JsonProperty("base_currency")] public string BaseCurrency { get; set; } [JsonProperty("quote_currency")] public string QuoteCurrency { get; set; } [JsonProperty("base_min_size")] public decimal BaseMinSize { get; set; } [JsonProperty("base_max_size")] public decimal BaseMaxSize { get; set; } [JsonProperty("quote_increment")] public decimal QuoteIncrement { get; set; } [JsonProperty("base_increment")] public decimal BaseIncrement { get; set; } [JsonProperty("display_name")] public string DisplayName { get; set; } [JsonProperty("min_market_funds")] public decimal MinMarketFunds { get; set; } [JsonProperty("max_market_funds")] public decimal MaxMarketFunds { get; set; } [JsonProperty("margin_enabled")] public bool MarginEnabled { get; set; } [JsonProperty("post_only")] public bool PostOnly { get; set; } [JsonProperty("limit_only")] public bool LimitOnly { get; set; } [JsonProperty("cancel_only")] public bool CancelOnly { get; set; } [JsonProperty("trading_disabled")] public bool TradingDisabled { get; set; } [JsonProperty("status")] public string Status { get; set; } [JsonProperty("status_message")] public string StatusMessage { get; set; } } #endregion #region Bitfinex brokerage [Test, Explicit] public void FetchSymbolPropertiesFromBitfinex() { const string urlExchangePairs = "https://api-pub.bitfinex.com/v2/conf/pub:list:pair:exchange"; const string urlMarginPairs = "https://api-pub.bitfinex.com/v2/conf/pub:list:pair:margin"; const string urlCurrencyMap = "https://api-pub.bitfinex.com/v2/conf/pub:map:currency:sym"; const string urlCurrencyLabels = "https://api-pub.bitfinex.com/v2/conf/pub:map:currency:label"; const string urlSymbolDetails = "https://api.bitfinex.com/v1/symbols_details"; var sb = new StringBuilder(); using (var wc = new WebClient()) { var jsonExchangePairs = wc.DownloadString(urlExchangePairs); var exchangePairs = JsonConvert.DeserializeObject<List<List<string>>>(jsonExchangePairs)[0]; var jsonMarginPairs = wc.DownloadString(urlMarginPairs); var marginPairs = JsonConvert.DeserializeObject<List<List<string>>>(jsonMarginPairs)[0]; var jsonCurrencyMap = wc.DownloadString(urlCurrencyMap); var rowsCurrencyMap = JsonConvert.DeserializeObject<List<List<List<string>>>>(jsonCurrencyMap)[0]; var currencyMap = rowsCurrencyMap .ToDictionary(row => row[0], row => row[1].ToUpperInvariant()); var jsonCurrencyLabels = wc.DownloadString(urlCurrencyLabels); var rowsCurrencyLabels = JsonConvert.DeserializeObject<List<List<List<string>>>>(jsonCurrencyLabels)[0]; var currencyLabels = rowsCurrencyLabels .ToDictionary(row => row[0], row => row[1]); var jsonSymbolDetails = wc.DownloadString(urlSymbolDetails); var symbolDetails = JsonConvert.DeserializeObject<List<BitfinexSymbolDetails>>(jsonSymbolDetails); var minimumPriceIncrements = symbolDetails .ToDictionary(x => x.Pair.ToUpperInvariant(), x => (decimal)Math.Pow(10, -x.PricePrecision)); foreach (var pair in exchangePairs.Union(marginPairs).OrderBy(x => x)) { string baseCurrency, quoteCurrency; if (pair.Contains(":")) { var parts = pair.Split(':'); baseCurrency = parts[0]; quoteCurrency = parts[1]; } else if (pair.Length == 6) { baseCurrency = pair.Substring(0, 3); quoteCurrency = pair.Substring(3); } else { // should never happen Log.Trace($"Skipping pair with unknown format: {pair}"); continue; } string baseDescription, quoteDescription; if (!currencyLabels.TryGetValue(baseCurrency, out baseDescription)) { Log.Trace($"Base currency description not found: {baseCurrency}"); baseDescription = baseCurrency; } if (!currencyLabels.TryGetValue(quoteCurrency, out quoteDescription)) { Log.Trace($"Quote currency description not found: {quoteCurrency}"); quoteDescription = quoteCurrency; } var description = baseDescription + "-" + quoteDescription; string newBaseCurrency, newQuoteCurrency; if (currencyMap.TryGetValue(baseCurrency, out newBaseCurrency)) { baseCurrency = newBaseCurrency; } if (currencyMap.TryGetValue(quoteCurrency, out newQuoteCurrency)) { quoteCurrency = newQuoteCurrency; } // skip test symbols if (quoteCurrency.StartsWith("TEST")) { continue; } var leanTicker = $"{baseCurrency}{quoteCurrency}"; decimal minimumPriceIncrement; if (!minimumPriceIncrements.TryGetValue(pair, out minimumPriceIncrement)) { minimumPriceIncrement = 0.00001m; } const decimal lotSize = 0.00000001m; sb.AppendLine("bitfinex," + $"{leanTicker}," + "crypto," + $"{description}," + $"{quoteCurrency}," + "1," + $"{minimumPriceIncrement.NormalizeToStr()}," + $"{lotSize.NormalizeToStr()}," + $"t{pair}"); } } Log.Trace(sb.ToString()); } private class BitfinexSymbolDetails { [JsonProperty("pair")] public string Pair { get; set; } [JsonProperty("price_precision")] public int PricePrecision { get; set; } [JsonProperty("initial_margin")] public decimal InitialMargin { get; set; } [JsonProperty("minimum_margin")] public decimal MinimumMargin { get; set; } [JsonProperty("maximum_order_size")] public decimal MaximumOrderSize { get; set; } [JsonProperty("minimum_order_size")] public decimal MinimumOrderSize { get; set; } [JsonProperty("expiration")] public string Expiration { get; set; } } #endregion [TestCase("ES", Market.CME, 50, 0.25)] [TestCase("ZB", Market.CBOT, 1000, 0.015625)] [TestCase("ZW", Market.CBOT, 5000, 0.00125)] [TestCase("SI", Market.COMEX, 5000, 0.001)] public void ReadsFuturesOptionsEntries(string ticker, string market, int expectedMultiplier, double expectedMinimumPriceFluctuation) { var future = Symbol.CreateFuture(ticker, market, SecurityIdentifier.DefaultDate); var option = Symbol.CreateOption( future, market, default(OptionStyle), default(OptionRight), default(decimal), SecurityIdentifier.DefaultDate); var db = SymbolPropertiesDatabase.FromDataFolder(); var results = db.GetSymbolProperties(market, option, SecurityType.FutureOption, "USD"); Assert.AreEqual((decimal)expectedMultiplier, results.ContractMultiplier); Assert.AreEqual((decimal)expectedMinimumPriceFluctuation, results.MinimumPriceVariation); } [TestCase("index")] [TestCase("indexoption")] [TestCase("bond")] [TestCase("swap")] public void HandlesUnknownSecurityType(string securityType) { var line = string.Join(",", "usa", "ABCXYZ", securityType, "Example Asset", "USD", "100", "0.01", "1"); SecurityDatabaseKey key; Assert.DoesNotThrow(() => TestingSymbolPropertiesDatabase.TestFromCsvLine(line, out key)); } [Test] public void HandlesEmptyOrderSizePriceMagnifierCorrectly() { var line = string.Join(",", "usa", "ABC", "equity", "Example Asset", "USD", "100", "0.01", "1", "", ""); var result = TestingSymbolPropertiesDatabase.TestFromCsvLine(line, out _); Assert.IsNull(result.MinimumOrderSize); Assert.AreEqual(1, result.PriceMagnifier); } private class TestingSymbolPropertiesDatabase : SymbolPropertiesDatabase { public TestingSymbolPropertiesDatabase(string file) : base(file) { } public static SymbolProperties TestFromCsvLine(string line, out SecurityDatabaseKey key) { return FromCsvLine(line, out key); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #if XMLCHARTYPE_GEN_RESOURCE #undef XMLCHARTYPE_USE_RESOURCE #endif //#define XMLCHARTYPE_USE_RESOURCE // load the character properties from resources (XmlCharType.bin must be linked to assembly) //#define XMLCHARTYPE_GEN_RESOURCE // generate the character properties into XmlCharType.bin #if XMLCHARTYPE_GEN_RESOURCE || XMLCHARTYPE_USE_RESOURCE using System.IO; using System.Reflection; #endif using System.Threading; using System.Diagnostics; namespace System.Xml { /// <internalonly/> /// <devdoc> /// The XmlCharType class is used for quick character type recognition /// which is optimized for the first 127 ascii characters. /// </devdoc> #if XMLCHARTYPE_USE_RESOURCE unsafe internal struct XmlCharType { #else internal struct XmlCharType { #endif // Surrogate constants internal const int SurHighStart = 0xd800; // 1101 10xx internal const int SurHighEnd = 0xdbff; internal const int SurLowStart = 0xdc00; // 1101 11xx internal const int SurLowEnd = 0xdfff; internal const int SurMask = 0xfc00; // 1111 11xx #if XML10_FIFTH_EDITION // Characters defined in the XML 1.0 Fifth Edition // Whitespace chars -- Section 2.3 [3] // Star NCName characters -- Section 2.3 [4] (NameStartChar characters without ':') // NCName characters -- Section 2.3 [4a] (NameChar characters without ':') // Character data characters -- Section 2.2 [2] // Public ID characters -- Section 2.3 [13] // Characters defined in the XML 1.0 Fourth Edition // NCNameCharacters -- Appending B: Characters Classes in XML 1.0 4th edition and earlier - minus the ':' char per the Namespaces in XML spec // Letter characters -- Appending B: Characters Classes in XML 1.0 4th edition and earlier // This appendix has been deprecated in XML 1.0 5th edition, but we still need to use // the Letter and NCName definitions from the 4th edition in some places because of backwards compatibility internal const int fWhitespace = 1; internal const int fLetter = 2; internal const int fNCStartNameSC = 4; // SC = Single Char internal const int fNCNameSC = 8; // SC = Single Char internal const int fCharData = 16; internal const int fNCNameXml4e = 32; // NCName char according to the XML 1.0 4th edition internal const int fText = 64; internal const int fAttrValue = 128; // name surrogate constants private const int s_NCNameSurCombinedStart = 0x10000; private const int s_NCNameSurCombinedEnd = 0xEFFFF; private const int s_NCNameSurHighStart = SurHighStart + ((s_NCNameSurCombinedStart - 0x10000) / 1024); private const int s_NCNameSurHighEnd = SurHighStart + ((s_NCNameSurCombinedEnd - 0x10000) / 1024); private const int s_NCNameSurLowStart = SurLowStart + ((s_NCNameSurCombinedStart - 0x10000) % 1024); private const int s_NCNameSurLowEnd = SurLowStart + ((s_NCNameSurCombinedEnd - 0x10000) % 1024); #else // Characters defined in the XML 1.0 Fourth Edition // Whitespace chars -- Section 2.3 [3] // Letters -- Appendix B [84] // Starting NCName characters -- Section 2.3 [5] (Starting Name characters without ':') // NCName characters -- Section 2.3 [4] (Name characters without ':') // Character data characters -- Section 2.2 [2] // PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%] Section 2.3 of spec internal const int fWhitespace = 1; internal const int fLetter = 2; internal const int fNCStartNameSC = 4; internal const int fNCNameSC = 8; internal const int fCharData = 16; internal const int fNCNameXml4e = 32; internal const int fText = 64; internal const int fAttrValue = 128; #endif // bitmap for public ID characters - 1 bit per character 0x0 - 0x80; no character > 0x80 is a PUBLIC ID char private const string s_PublicIdBitmap = "\u2400\u0000\uffbb\uafff\uffff\u87ff\ufffe\u07ff"; // size of XmlCharType table private const uint CharPropertiesSize = (uint)char.MaxValue + 1; #if !XMLCHARTYPE_USE_RESOURCE || XMLCHARTYPE_GEN_RESOURCE internal const string s_Whitespace = "\u0009\u000a\u000d\u000d\u0020\u0020"; #if XML10_FIFTH_EDITION // StartNameChar without ':' -- see Section 2.3 production [4] const string s_NCStartName = "\u0041\u005a\u005f\u005f\u0061\u007a\u00c0\u00d6" + "\u00d8\u00f6\u00f8\u02ff\u0370\u037d\u037f\u1fff" + "\u200c\u200d\u2070\u218f\u2c00\u2fef\u3001\ud7ff" + "\uf900\ufdcf\ufdf0\ufffd"; // NameChar without ':' -- see Section 2.3 production [4a] const string s_NCName = "\u002d\u002e\u0030\u0039\u0041\u005a\u005f\u005f" + "\u0061\u007a\u00b7\u00b7\u00c0\u00d6\u00d8\u00f6" + "\u00f8\u037d\u037f\u1fff\u200c\u200d\u203f\u2040" + "\u2070\u218f\u2c00\u2fef\u3001\ud7ff\uf900\ufdcf" + "\ufdf0\ufffd"; #else const string s_NCStartName = "\u0041\u005a\u005f\u005f\u0061\u007a" + "\u00c0\u00d6\u00d8\u00f6\u00f8\u0131\u0134\u013e" + "\u0141\u0148\u014a\u017e\u0180\u01c3\u01cd\u01f0" + "\u01f4\u01f5\u01fa\u0217\u0250\u02a8\u02bb\u02c1" + "\u0386\u0386\u0388\u038a\u038c\u038c\u038e\u03a1" + "\u03a3\u03ce\u03d0\u03d6\u03da\u03da\u03dc\u03dc" + "\u03de\u03de\u03e0\u03e0\u03e2\u03f3\u0401\u040c" + "\u040e\u044f\u0451\u045c\u045e\u0481\u0490\u04c4" + "\u04c7\u04c8\u04cb\u04cc\u04d0\u04eb\u04ee\u04f5" + "\u04f8\u04f9\u0531\u0556\u0559\u0559\u0561\u0586" + "\u05d0\u05ea\u05f0\u05f2\u0621\u063a\u0641\u064a" + "\u0671\u06b7\u06ba\u06be\u06c0\u06ce\u06d0\u06d3" + "\u06d5\u06d5\u06e5\u06e6\u0905\u0939\u093d\u093d" + "\u0958\u0961\u0985\u098c\u098f\u0990\u0993\u09a8" + "\u09aa\u09b0\u09b2\u09b2\u09b6\u09b9\u09dc\u09dd" + "\u09df\u09e1\u09f0\u09f1\u0a05\u0a0a\u0a0f\u0a10" + "\u0a13\u0a28\u0a2a\u0a30\u0a32\u0a33\u0a35\u0a36" + "\u0a38\u0a39\u0a59\u0a5c\u0a5e\u0a5e\u0a72\u0a74" + "\u0a85\u0a8b\u0a8d\u0a8d\u0a8f\u0a91\u0a93\u0aa8" + "\u0aaa\u0ab0\u0ab2\u0ab3\u0ab5\u0ab9\u0abd\u0abd" + "\u0ae0\u0ae0\u0b05\u0b0c\u0b0f\u0b10\u0b13\u0b28" + "\u0b2a\u0b30\u0b32\u0b33\u0b36\u0b39\u0b3d\u0b3d" + "\u0b5c\u0b5d\u0b5f\u0b61\u0b85\u0b8a\u0b8e\u0b90" + "\u0b92\u0b95\u0b99\u0b9a\u0b9c\u0b9c\u0b9e\u0b9f" + "\u0ba3\u0ba4\u0ba8\u0baa\u0bae\u0bb5\u0bb7\u0bb9" + "\u0c05\u0c0c\u0c0e\u0c10\u0c12\u0c28\u0c2a\u0c33" + "\u0c35\u0c39\u0c60\u0c61\u0c85\u0c8c\u0c8e\u0c90" + "\u0c92\u0ca8\u0caa\u0cb3\u0cb5\u0cb9\u0cde\u0cde" + "\u0ce0\u0ce1\u0d05\u0d0c\u0d0e\u0d10\u0d12\u0d28" + "\u0d2a\u0d39\u0d60\u0d61\u0e01\u0e2e\u0e30\u0e30" + "\u0e32\u0e33\u0e40\u0e45\u0e81\u0e82\u0e84\u0e84" + "\u0e87\u0e88\u0e8a\u0e8a\u0e8d\u0e8d\u0e94\u0e97" + "\u0e99\u0e9f\u0ea1\u0ea3\u0ea5\u0ea5\u0ea7\u0ea7" + "\u0eaa\u0eab\u0ead\u0eae\u0eb0\u0eb0\u0eb2\u0eb3" + "\u0ebd\u0ebd\u0ec0\u0ec4\u0f40\u0f47\u0f49\u0f69" + "\u10a0\u10c5\u10d0\u10f6\u1100\u1100\u1102\u1103" + "\u1105\u1107\u1109\u1109\u110b\u110c\u110e\u1112" + "\u113c\u113c\u113e\u113e\u1140\u1140\u114c\u114c" + "\u114e\u114e\u1150\u1150\u1154\u1155\u1159\u1159" + "\u115f\u1161\u1163\u1163\u1165\u1165\u1167\u1167" + "\u1169\u1169\u116d\u116e\u1172\u1173\u1175\u1175" + "\u119e\u119e\u11a8\u11a8\u11ab\u11ab\u11ae\u11af" + "\u11b7\u11b8\u11ba\u11ba\u11bc\u11c2\u11eb\u11eb" + "\u11f0\u11f0\u11f9\u11f9\u1e00\u1e9b\u1ea0\u1ef9" + "\u1f00\u1f15\u1f18\u1f1d\u1f20\u1f45\u1f48\u1f4d" + "\u1f50\u1f57\u1f59\u1f59\u1f5b\u1f5b\u1f5d\u1f5d" + "\u1f5f\u1f7d\u1f80\u1fb4\u1fb6\u1fbc\u1fbe\u1fbe" + "\u1fc2\u1fc4\u1fc6\u1fcc\u1fd0\u1fd3\u1fd6\u1fdb" + "\u1fe0\u1fec\u1ff2\u1ff4\u1ff6\u1ffc\u2126\u2126" + "\u212a\u212b\u212e\u212e\u2180\u2182\u3007\u3007" + "\u3021\u3029\u3041\u3094\u30a1\u30fa\u3105\u312c" + "\u4e00\u9fa5\uac00\ud7a3"; const string s_NCName = "\u002d\u002e\u0030\u0039\u0041\u005a\u005f\u005f" + "\u0061\u007a\u00b7\u00b7\u00c0\u00d6\u00d8\u00f6" + "\u00f8\u0131\u0134\u013e\u0141\u0148\u014a\u017e" + "\u0180\u01c3\u01cd\u01f0\u01f4\u01f5\u01fa\u0217" + "\u0250\u02a8\u02bb\u02c1\u02d0\u02d1\u0300\u0345" + "\u0360\u0361\u0386\u038a\u038c\u038c\u038e\u03a1" + "\u03a3\u03ce\u03d0\u03d6\u03da\u03da\u03dc\u03dc" + "\u03de\u03de\u03e0\u03e0\u03e2\u03f3\u0401\u040c" + "\u040e\u044f\u0451\u045c\u045e\u0481\u0483\u0486" + "\u0490\u04c4\u04c7\u04c8\u04cb\u04cc\u04d0\u04eb" + "\u04ee\u04f5\u04f8\u04f9\u0531\u0556\u0559\u0559" + "\u0561\u0586\u0591\u05a1\u05a3\u05b9\u05bb\u05bd" + "\u05bf\u05bf\u05c1\u05c2\u05c4\u05c4\u05d0\u05ea" + "\u05f0\u05f2\u0621\u063a\u0640\u0652\u0660\u0669" + "\u0670\u06b7\u06ba\u06be\u06c0\u06ce\u06d0\u06d3" + "\u06d5\u06e8\u06ea\u06ed\u06f0\u06f9\u0901\u0903" + "\u0905\u0939\u093c\u094d\u0951\u0954\u0958\u0963" + "\u0966\u096f\u0981\u0983\u0985\u098c\u098f\u0990" + "\u0993\u09a8\u09aa\u09b0\u09b2\u09b2\u09b6\u09b9" + "\u09bc\u09bc\u09be\u09c4\u09c7\u09c8\u09cb\u09cd" + "\u09d7\u09d7\u09dc\u09dd\u09df\u09e3\u09e6\u09f1" + "\u0a02\u0a02\u0a05\u0a0a\u0a0f\u0a10\u0a13\u0a28" + "\u0a2a\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39" + "\u0a3c\u0a3c\u0a3e\u0a42\u0a47\u0a48\u0a4b\u0a4d" + "\u0a59\u0a5c\u0a5e\u0a5e\u0a66\u0a74\u0a81\u0a83" + "\u0a85\u0a8b\u0a8d\u0a8d\u0a8f\u0a91\u0a93\u0aa8" + "\u0aaa\u0ab0\u0ab2\u0ab3\u0ab5\u0ab9\u0abc\u0ac5" + "\u0ac7\u0ac9\u0acb\u0acd\u0ae0\u0ae0\u0ae6\u0aef" + "\u0b01\u0b03\u0b05\u0b0c\u0b0f\u0b10\u0b13\u0b28" + "\u0b2a\u0b30\u0b32\u0b33\u0b36\u0b39\u0b3c\u0b43" + "\u0b47\u0b48\u0b4b\u0b4d\u0b56\u0b57\u0b5c\u0b5d" + "\u0b5f\u0b61\u0b66\u0b6f\u0b82\u0b83\u0b85\u0b8a" + "\u0b8e\u0b90\u0b92\u0b95\u0b99\u0b9a\u0b9c\u0b9c" + "\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8\u0baa\u0bae\u0bb5" + "\u0bb7\u0bb9\u0bbe\u0bc2\u0bc6\u0bc8\u0bca\u0bcd" + "\u0bd7\u0bd7\u0be7\u0bef\u0c01\u0c03\u0c05\u0c0c" + "\u0c0e\u0c10\u0c12\u0c28\u0c2a\u0c33\u0c35\u0c39" + "\u0c3e\u0c44\u0c46\u0c48\u0c4a\u0c4d\u0c55\u0c56" + "\u0c60\u0c61\u0c66\u0c6f\u0c82\u0c83\u0c85\u0c8c" + "\u0c8e\u0c90\u0c92\u0ca8\u0caa\u0cb3\u0cb5\u0cb9" + "\u0cbe\u0cc4\u0cc6\u0cc8\u0cca\u0ccd\u0cd5\u0cd6" + "\u0cde\u0cde\u0ce0\u0ce1\u0ce6\u0cef\u0d02\u0d03" + "\u0d05\u0d0c\u0d0e\u0d10\u0d12\u0d28\u0d2a\u0d39" + "\u0d3e\u0d43\u0d46\u0d48\u0d4a\u0d4d\u0d57\u0d57" + "\u0d60\u0d61\u0d66\u0d6f\u0e01\u0e2e\u0e30\u0e3a" + "\u0e40\u0e4e\u0e50\u0e59\u0e81\u0e82\u0e84\u0e84" + "\u0e87\u0e88\u0e8a\u0e8a\u0e8d\u0e8d\u0e94\u0e97" + "\u0e99\u0e9f\u0ea1\u0ea3\u0ea5\u0ea5\u0ea7\u0ea7" + "\u0eaa\u0eab\u0ead\u0eae\u0eb0\u0eb9\u0ebb\u0ebd" + "\u0ec0\u0ec4\u0ec6\u0ec6\u0ec8\u0ecd\u0ed0\u0ed9" + "\u0f18\u0f19\u0f20\u0f29\u0f35\u0f35\u0f37\u0f37" + "\u0f39\u0f39\u0f3e\u0f47\u0f49\u0f69\u0f71\u0f84" + "\u0f86\u0f8b\u0f90\u0f95\u0f97\u0f97\u0f99\u0fad" + "\u0fb1\u0fb7\u0fb9\u0fb9\u10a0\u10c5\u10d0\u10f6" + "\u1100\u1100\u1102\u1103\u1105\u1107\u1109\u1109" + "\u110b\u110c\u110e\u1112\u113c\u113c\u113e\u113e" + "\u1140\u1140\u114c\u114c\u114e\u114e\u1150\u1150" + "\u1154\u1155\u1159\u1159\u115f\u1161\u1163\u1163" + "\u1165\u1165\u1167\u1167\u1169\u1169\u116d\u116e" + "\u1172\u1173\u1175\u1175\u119e\u119e\u11a8\u11a8" + "\u11ab\u11ab\u11ae\u11af\u11b7\u11b8\u11ba\u11ba" + "\u11bc\u11c2\u11eb\u11eb\u11f0\u11f0\u11f9\u11f9" + "\u1e00\u1e9b\u1ea0\u1ef9\u1f00\u1f15\u1f18\u1f1d" + "\u1f20\u1f45\u1f48\u1f4d\u1f50\u1f57\u1f59\u1f59" + "\u1f5b\u1f5b\u1f5d\u1f5d\u1f5f\u1f7d\u1f80\u1fb4" + "\u1fb6\u1fbc\u1fbe\u1fbe\u1fc2\u1fc4\u1fc6\u1fcc" + "\u1fd0\u1fd3\u1fd6\u1fdb\u1fe0\u1fec\u1ff2\u1ff4" + "\u1ff6\u1ffc\u20d0\u20dc\u20e1\u20e1\u2126\u2126" + "\u212a\u212b\u212e\u212e\u2180\u2182\u3005\u3005" + "\u3007\u3007\u3021\u302f\u3031\u3035\u3041\u3094" + "\u3099\u309a\u309d\u309e\u30a1\u30fa\u30fc\u30fe" + "\u3105\u312c\u4e00\u9fa5\uac00\ud7a3"; #endif const string s_CharData = "\u0009\u000a\u000d\u000d\u0020\ud7ff\ue000\ufffd"; const string s_PublicID = "\u000a\u000a\u000d\u000d\u0020\u0021\u0023\u0025" + "\u0027\u003b\u003d\u003d\u003f\u005a\u005f\u005f" + "\u0061\u007a"; const string s_Text = // TextChar = CharData - { 0xA | 0xD | '<' | '&' | 0x9 | ']' | 0xDC00 - 0xDFFF } "\u0020\u0025\u0027\u003b\u003d\u005c\u005e\ud7ff\ue000\ufffd"; const string s_AttrValue = // AttrValueChar = CharData - { 0xA | 0xD | 0x9 | '<' | '>' | '&' | '\'' | '"' | 0xDC00 - 0xDFFF } "\u0020\u0021\u0023\u0025\u0028\u003b\u003d\u003d\u003f\ud7ff\ue000\ufffd"; // // XML 1.0 Fourth Edition definitions for name characters // const string s_LetterXml4e = "\u0041\u005a\u0061\u007a\u00c0\u00d6\u00d8\u00f6" + "\u00f8\u0131\u0134\u013e\u0141\u0148\u014a\u017e" + "\u0180\u01c3\u01cd\u01f0\u01f4\u01f5\u01fa\u0217" + "\u0250\u02a8\u02bb\u02c1\u0386\u0386\u0388\u038a" + "\u038c\u038c\u038e\u03a1\u03a3\u03ce\u03d0\u03d6" + "\u03da\u03da\u03dc\u03dc\u03de\u03de\u03e0\u03e0" + "\u03e2\u03f3\u0401\u040c\u040e\u044f\u0451\u045c" + "\u045e\u0481\u0490\u04c4\u04c7\u04c8\u04cb\u04cc" + "\u04d0\u04eb\u04ee\u04f5\u04f8\u04f9\u0531\u0556" + "\u0559\u0559\u0561\u0586\u05d0\u05ea\u05f0\u05f2" + "\u0621\u063a\u0641\u064a\u0671\u06b7\u06ba\u06be" + "\u06c0\u06ce\u06d0\u06d3\u06d5\u06d5\u06e5\u06e6" + "\u0905\u0939\u093d\u093d\u0958\u0961\u0985\u098c" + "\u098f\u0990\u0993\u09a8\u09aa\u09b0\u09b2\u09b2" + "\u09b6\u09b9\u09dc\u09dd\u09df\u09e1\u09f0\u09f1" + "\u0a05\u0a0a\u0a0f\u0a10\u0a13\u0a28\u0a2a\u0a30" + "\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59\u0a5c" + "\u0a5e\u0a5e\u0a72\u0a74\u0a85\u0a8b\u0a8d\u0a8d" + "\u0a8f\u0a91\u0a93\u0aa8\u0aaa\u0ab0\u0ab2\u0ab3" + "\u0ab5\u0ab9\u0abd\u0abd\u0ae0\u0ae0\u0b05\u0b0c" + "\u0b0f\u0b10\u0b13\u0b28\u0b2a\u0b30\u0b32\u0b33" + "\u0b36\u0b39\u0b3d\u0b3d\u0b5c\u0b5d\u0b5f\u0b61" + "\u0b85\u0b8a\u0b8e\u0b90\u0b92\u0b95\u0b99\u0b9a" + "\u0b9c\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8\u0baa" + "\u0bae\u0bb5\u0bb7\u0bb9\u0c05\u0c0c\u0c0e\u0c10" + "\u0c12\u0c28\u0c2a\u0c33\u0c35\u0c39\u0c60\u0c61" + "\u0c85\u0c8c\u0c8e\u0c90\u0c92\u0ca8\u0caa\u0cb3" + "\u0cb5\u0cb9\u0cde\u0cde\u0ce0\u0ce1\u0d05\u0d0c" + "\u0d0e\u0d10\u0d12\u0d28\u0d2a\u0d39\u0d60\u0d61" + "\u0e01\u0e2e\u0e30\u0e30\u0e32\u0e33\u0e40\u0e45" + "\u0e81\u0e82\u0e84\u0e84\u0e87\u0e88\u0e8a\u0e8a" + "\u0e8d\u0e8d\u0e94\u0e97\u0e99\u0e9f\u0ea1\u0ea3" + "\u0ea5\u0ea5\u0ea7\u0ea7\u0eaa\u0eab\u0ead\u0eae" + "\u0eb0\u0eb0\u0eb2\u0eb3\u0ebd\u0ebd\u0ec0\u0ec4" + "\u0f40\u0f47\u0f49\u0f69\u10a0\u10c5\u10d0\u10f6" + "\u1100\u1100\u1102\u1103\u1105\u1107\u1109\u1109" + "\u110b\u110c\u110e\u1112\u113c\u113c\u113e\u113e" + "\u1140\u1140\u114c\u114c\u114e\u114e\u1150\u1150" + "\u1154\u1155\u1159\u1159\u115f\u1161\u1163\u1163" + "\u1165\u1165\u1167\u1167\u1169\u1169\u116d\u116e" + "\u1172\u1173\u1175\u1175\u119e\u119e\u11a8\u11a8" + "\u11ab\u11ab\u11ae\u11af\u11b7\u11b8\u11ba\u11ba" + "\u11bc\u11c2\u11eb\u11eb\u11f0\u11f0\u11f9\u11f9" + "\u1e00\u1e9b\u1ea0\u1ef9\u1f00\u1f15\u1f18\u1f1d" + "\u1f20\u1f45\u1f48\u1f4d\u1f50\u1f57\u1f59\u1f59" + "\u1f5b\u1f5b\u1f5d\u1f5d\u1f5f\u1f7d\u1f80\u1fb4" + "\u1fb6\u1fbc\u1fbe\u1fbe\u1fc2\u1fc4\u1fc6\u1fcc" + "\u1fd0\u1fd3\u1fd6\u1fdb\u1fe0\u1fec\u1ff2\u1ff4" + "\u1ff6\u1ffc\u2126\u2126\u212a\u212b\u212e\u212e" + "\u2180\u2182\u3007\u3007\u3021\u3029\u3041\u3094" + "\u30a1\u30fa\u3105\u312c\u4e00\u9fa5\uac00\ud7a3"; const string s_NCNameXml4e = "\u002d\u002e\u0030\u0039\u0041\u005a\u005f\u005f" + "\u0061\u007a\u00b7\u00b7\u00c0\u00d6\u00d8\u00f6" + "\u00f8\u0131\u0134\u013e\u0141\u0148\u014a\u017e" + "\u0180\u01c3\u01cd\u01f0\u01f4\u01f5\u01fa\u0217" + "\u0250\u02a8\u02bb\u02c1\u02d0\u02d1\u0300\u0345" + "\u0360\u0361\u0386\u038a\u038c\u038c\u038e\u03a1" + "\u03a3\u03ce\u03d0\u03d6\u03da\u03da\u03dc\u03dc" + "\u03de\u03de\u03e0\u03e0\u03e2\u03f3\u0401\u040c" + "\u040e\u044f\u0451\u045c\u045e\u0481\u0483\u0486" + "\u0490\u04c4\u04c7\u04c8\u04cb\u04cc\u04d0\u04eb" + "\u04ee\u04f5\u04f8\u04f9\u0531\u0556\u0559\u0559" + "\u0561\u0586\u0591\u05a1\u05a3\u05b9\u05bb\u05bd" + "\u05bf\u05bf\u05c1\u05c2\u05c4\u05c4\u05d0\u05ea" + "\u05f0\u05f2\u0621\u063a\u0640\u0652\u0660\u0669" + "\u0670\u06b7\u06ba\u06be\u06c0\u06ce\u06d0\u06d3" + "\u06d5\u06e8\u06ea\u06ed\u06f0\u06f9\u0901\u0903" + "\u0905\u0939\u093c\u094d\u0951\u0954\u0958\u0963" + "\u0966\u096f\u0981\u0983\u0985\u098c\u098f\u0990" + "\u0993\u09a8\u09aa\u09b0\u09b2\u09b2\u09b6\u09b9" + "\u09bc\u09bc\u09be\u09c4\u09c7\u09c8\u09cb\u09cd" + "\u09d7\u09d7\u09dc\u09dd\u09df\u09e3\u09e6\u09f1" + "\u0a02\u0a02\u0a05\u0a0a\u0a0f\u0a10\u0a13\u0a28" + "\u0a2a\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39" + "\u0a3c\u0a3c\u0a3e\u0a42\u0a47\u0a48\u0a4b\u0a4d" + "\u0a59\u0a5c\u0a5e\u0a5e\u0a66\u0a74\u0a81\u0a83" + "\u0a85\u0a8b\u0a8d\u0a8d\u0a8f\u0a91\u0a93\u0aa8" + "\u0aaa\u0ab0\u0ab2\u0ab3\u0ab5\u0ab9\u0abc\u0ac5" + "\u0ac7\u0ac9\u0acb\u0acd\u0ae0\u0ae0\u0ae6\u0aef" + "\u0b01\u0b03\u0b05\u0b0c\u0b0f\u0b10\u0b13\u0b28" + "\u0b2a\u0b30\u0b32\u0b33\u0b36\u0b39\u0b3c\u0b43" + "\u0b47\u0b48\u0b4b\u0b4d\u0b56\u0b57\u0b5c\u0b5d" + "\u0b5f\u0b61\u0b66\u0b6f\u0b82\u0b83\u0b85\u0b8a" + "\u0b8e\u0b90\u0b92\u0b95\u0b99\u0b9a\u0b9c\u0b9c" + "\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8\u0baa\u0bae\u0bb5" + "\u0bb7\u0bb9\u0bbe\u0bc2\u0bc6\u0bc8\u0bca\u0bcd" + "\u0bd7\u0bd7\u0be7\u0bef\u0c01\u0c03\u0c05\u0c0c" + "\u0c0e\u0c10\u0c12\u0c28\u0c2a\u0c33\u0c35\u0c39" + "\u0c3e\u0c44\u0c46\u0c48\u0c4a\u0c4d\u0c55\u0c56" + "\u0c60\u0c61\u0c66\u0c6f\u0c82\u0c83\u0c85\u0c8c" + "\u0c8e\u0c90\u0c92\u0ca8\u0caa\u0cb3\u0cb5\u0cb9" + "\u0cbe\u0cc4\u0cc6\u0cc8\u0cca\u0ccd\u0cd5\u0cd6" + "\u0cde\u0cde\u0ce0\u0ce1\u0ce6\u0cef\u0d02\u0d03" + "\u0d05\u0d0c\u0d0e\u0d10\u0d12\u0d28\u0d2a\u0d39" + "\u0d3e\u0d43\u0d46\u0d48\u0d4a\u0d4d\u0d57\u0d57" + "\u0d60\u0d61\u0d66\u0d6f\u0e01\u0e2e\u0e30\u0e3a" + "\u0e40\u0e4e\u0e50\u0e59\u0e81\u0e82\u0e84\u0e84" + "\u0e87\u0e88\u0e8a\u0e8a\u0e8d\u0e8d\u0e94\u0e97" + "\u0e99\u0e9f\u0ea1\u0ea3\u0ea5\u0ea5\u0ea7\u0ea7" + "\u0eaa\u0eab\u0ead\u0eae\u0eb0\u0eb9\u0ebb\u0ebd" + "\u0ec0\u0ec4\u0ec6\u0ec6\u0ec8\u0ecd\u0ed0\u0ed9" + "\u0f18\u0f19\u0f20\u0f29\u0f35\u0f35\u0f37\u0f37" + "\u0f39\u0f39\u0f3e\u0f47\u0f49\u0f69\u0f71\u0f84" + "\u0f86\u0f8b\u0f90\u0f95\u0f97\u0f97\u0f99\u0fad" + "\u0fb1\u0fb7\u0fb9\u0fb9\u10a0\u10c5\u10d0\u10f6" + "\u1100\u1100\u1102\u1103\u1105\u1107\u1109\u1109" + "\u110b\u110c\u110e\u1112\u113c\u113c\u113e\u113e" + "\u1140\u1140\u114c\u114c\u114e\u114e\u1150\u1150" + "\u1154\u1155\u1159\u1159\u115f\u1161\u1163\u1163" + "\u1165\u1165\u1167\u1167\u1169\u1169\u116d\u116e" + "\u1172\u1173\u1175\u1175\u119e\u119e\u11a8\u11a8" + "\u11ab\u11ab\u11ae\u11af\u11b7\u11b8\u11ba\u11ba" + "\u11bc\u11c2\u11eb\u11eb\u11f0\u11f0\u11f9\u11f9" + "\u1e00\u1e9b\u1ea0\u1ef9\u1f00\u1f15\u1f18\u1f1d" + "\u1f20\u1f45\u1f48\u1f4d\u1f50\u1f57\u1f59\u1f59" + "\u1f5b\u1f5b\u1f5d\u1f5d\u1f5f\u1f7d\u1f80\u1fb4" + "\u1fb6\u1fbc\u1fbe\u1fbe\u1fc2\u1fc4\u1fc6\u1fcc" + "\u1fd0\u1fd3\u1fd6\u1fdb\u1fe0\u1fec\u1ff2\u1ff4" + "\u1ff6\u1ffc\u20d0\u20dc\u20e1\u20e1\u2126\u2126" + "\u212a\u212b\u212e\u212e\u2180\u2182\u3005\u3005" + "\u3007\u3007\u3021\u302f\u3031\u3035\u3041\u3094" + "\u3099\u309a\u309d\u309e\u30a1\u30fa\u30fc\u30fe" + "\u3105\u312c\u4e00\u9fa5\uac00\ud7a3"; #endif // static lock for XmlCharType class private static object s_Lock; private static object StaticLock { get { if (s_Lock == null) { object o = new object(); Interlocked.CompareExchange<object>(ref s_Lock, o, null); } return s_Lock; } } #if XMLCHARTYPE_USE_RESOURCE private static volatile byte* s_CharProperties; internal byte* charProperties; static void InitInstance() { lock ( StaticLock ) { if ( s_CharProperties != null ) { return; } UnmanagedMemoryStream memStream = (UnmanagedMemoryStream)Assembly.GetExecutingAssembly().GetManifestResourceStream( "XmlCharType.bin" ); Debug.Assert( memStream.Length == CharPropertiesSize ); byte* chProps = memStream.PositionPointer; Thread.MemoryBarrier(); // For weak memory models (IA64) s_CharProperties = chProps; } } #else // !XMLCHARTYPE_USE_RESOURCE private static volatile byte[] s_CharProperties; internal byte[] charProperties; static void InitInstance() { lock (StaticLock) { if (s_CharProperties != null) { return; } byte[] chProps = new byte[CharPropertiesSize]; SetProperties(chProps, s_Whitespace, fWhitespace); SetProperties(chProps, s_LetterXml4e, fLetter); SetProperties(chProps, s_NCStartName, fNCStartNameSC); SetProperties(chProps, s_NCName, fNCNameSC); SetProperties(chProps, s_CharData, fCharData); SetProperties(chProps, s_NCNameXml4e, fNCNameXml4e); SetProperties(chProps, s_Text, fText); SetProperties(chProps, s_AttrValue, fAttrValue); s_CharProperties = chProps; } } private static void SetProperties(byte[] chProps, string ranges, byte value) { for (int p = 0; p < ranges.Length; p += 2) { for (int i = ranges[p], last = ranges[p + 1]; i <= last; i++) { chProps[i] |= value; } } } #endif #if XMLCHARTYPE_USE_RESOURCE private XmlCharType( byte* charProperties ) { #else private XmlCharType(byte[] charProperties) { #endif Debug.Assert(s_CharProperties != null); this.charProperties = charProperties; } public static XmlCharType Instance { get { if (s_CharProperties == null) { InitInstance(); } return new XmlCharType(s_CharProperties); } } // NOTE: This method will not be inlined (because it uses byte* charProperties) public bool IsWhiteSpace(char ch) { return (charProperties[ch] & fWhitespace) != 0; } // NOTE: This method will not be inlined (because it uses byte* charProperties) public bool IsNCNameSingleChar(char ch) { return (charProperties[ch] & fNCNameSC) != 0; } #if XML10_FIFTH_EDITION public bool IsNCNameSurrogateChar(string str, int index) { if (index + 1 >= str.Length) { return false; } return InRange(str[index], s_NCNameSurHighStart, s_NCNameSurHighEnd) && InRange(str[index + 1], s_NCNameSurLowStart, s_NCNameSurLowEnd); } // Surrogate characters for names are the same for NameChar and StartNameChar, // so this method can be used for both public bool IsNCNameSurrogateChar(char lowChar, char highChar) { return InRange(highChar, s_NCNameSurHighStart, s_NCNameSurHighEnd) && InRange(lowChar, s_NCNameSurLowStart, s_NCNameSurLowEnd); } public bool IsNCNameHighSurrogateChar(char highChar) { return InRange(highChar, s_NCNameSurHighStart, s_NCNameSurHighEnd); } public bool IsNCNameLowSurrogateChar(char lowChar) { return InRange(lowChar, s_NCNameSurLowStart, s_NCNameSurLowEnd); } #endif // NOTE: This method will not be inlined (because it uses byte* charProperties) public bool IsStartNCNameSingleChar(char ch) { return (charProperties[ch] & fNCStartNameSC) != 0; } public bool IsNameSingleChar(char ch) { return IsNCNameSingleChar(ch) || ch == ':'; } #if XML10_FIFTH_EDITION public bool IsNameSurrogateChar(char lowChar, char highChar) { return IsNCNameSurrogateChar(lowChar, highChar); } #endif public bool IsStartNameSingleChar(char ch) { return IsStartNCNameSingleChar(ch) || ch == ':'; } // NOTE: This method will not be inlined (because it uses byte* charProperties) public bool IsCharData(char ch) { return (charProperties[ch] & fCharData) != 0; } // [13] PubidChar ::= #x20 | #xD | #xA | [a-zA-Z0-9] | [-'()+,./:=?;!*#@$_%] Section 2.3 of spec public bool IsPubidChar(char ch) { if (ch < (char)0x80) { return (s_PublicIdBitmap[ch >> 4] & (1 << (ch & 0xF))) != 0; } return false; } // TextChar = CharData - { 0xA, 0xD, '<', '&', ']' } // NOTE: This method will not be inlined (because it uses byte* charProperties) internal bool IsTextChar(char ch) { return (charProperties[ch] & fText) != 0; } // AttrValueChar = CharData - { 0xA, 0xD, 0x9, '<', '>', '&', '\'', '"' } // NOTE: This method will not be inlined (because it uses byte* charProperties) internal bool IsAttributeValueChar(char ch) { return (charProperties[ch] & fAttrValue) != 0; } // XML 1.0 Fourth Edition definitions // // NOTE: This method will not be inlined (because it uses byte* charProperties) public bool IsLetter(char ch) { return (charProperties[ch] & fLetter) != 0; } // NOTE: This method will not be inlined (because it uses byte* charProperties) // This method uses the XML 4th edition name character ranges public bool IsNCNameCharXml4e(char ch) { return (charProperties[ch] & fNCNameXml4e) != 0; } // This method uses the XML 4th edition name character ranges public bool IsStartNCNameCharXml4e(char ch) { return IsLetter(ch) || ch == '_'; } // This method uses the XML 4th edition name character ranges public bool IsNameCharXml4e(char ch) { return IsNCNameCharXml4e(ch) || ch == ':'; } // This method uses the XML 4th edition name character ranges public bool IsStartNameCharXml4e(char ch) { return IsStartNCNameCharXml4e(ch) || ch == ':'; } // Digit methods public static bool IsDigit(char ch) { return InRange(ch, 0x30, 0x39); } // Surrogate methods internal static bool IsHighSurrogate(int ch) { return InRange(ch, SurHighStart, SurHighEnd); } internal static bool IsLowSurrogate(int ch) { return InRange(ch, SurLowStart, SurLowEnd); } internal static bool IsSurrogate(int ch) { return InRange(ch, SurHighStart, SurLowEnd); } internal static int CombineSurrogateChar(int lowChar, int highChar) { return (lowChar - SurLowStart) | ((highChar - SurHighStart) << 10) + 0x10000; } internal bool IsOnlyWhitespace(string str) { return IsOnlyWhitespaceWithPos(str) == -1; } // Character checking on strings internal int IsOnlyWhitespaceWithPos(string str) { if (str != null) { for (int i = 0; i < str.Length; i++) { if ((charProperties[str[i]] & fWhitespace) == 0) { return i; } } } return -1; } internal int IsOnlyCharData(string str) { if (str != null) { for (int i = 0; i < str.Length; i++) { if ((charProperties[str[i]] & fCharData) == 0) { if (i + 1 >= str.Length || !(XmlCharType.IsHighSurrogate(str[i]) && XmlCharType.IsLowSurrogate(str[i + 1]))) { return i; } else { i++; } } } } return -1; } static internal bool IsOnlyDigits(string str, int startPos, int len) { Debug.Assert(str != null); Debug.Assert(startPos + len <= str.Length); Debug.Assert(startPos <= str.Length); for (int i = startPos; i < startPos + len; i++) { if (!IsDigit(str[i])) { return false; } } return true; } internal int IsPublicId(string str) { if (str != null) { for (int i = 0; i < str.Length; i++) { if (!IsPubidChar(str[i])) { return i; } } } return -1; } // This method tests whether a value is in a given range with just one test; start and end should be constants private static bool InRange(int value, int start, int end) { Debug.Assert(start <= end); return (uint)(value - start) <= (uint)(end - start); } #if XMLCHARTYPE_GEN_RESOURCE // // Code for generating XmlCharType.bin table and s_PublicIdBitmap // // build command line: csc XmlCharType.cs /d:XMLCHARTYPE_GEN_RESOURCE // public static void Main(string[] args) { try { InitInstance(); // generate PublicId bitmap ushort[] bitmap = new ushort[0x80 >> 4]; for (int i = 0; i < s_PublicID.Length; i += 2) { for (int j = s_PublicID[i], last = s_PublicID[i + 1]; j <= last; j++) { bitmap[j >> 4] |= (ushort)(1 << (j & 0xF)); } } Console.Write("private const string s_PublicIdBitmap = \""); for (int i = 0; i < bitmap.Length; i++) { Console.Write("\\u{0:x4}", bitmap[i]); } Console.WriteLine("\";"); Console.WriteLine(); string fileName = (args.Length == 0) ? "XmlCharType.bin" : args[0]; Console.Write("Writing XmlCharType character properties to {0}...", fileName); FileStream fs = new FileStream(fileName, FileMode.Create); for (int i = 0; i < CharPropertiesSize; i += 4096) { fs.Write(s_CharProperties, i, 4096); } fs.Close(); Console.WriteLine("done."); } catch (Exception e) { Console.WriteLine(); Console.WriteLine("Exception: {0}", e.Message); } } #endif } }
using System; using System.Collections; using System.IO; using BigMath; using Raksha.Asn1; using Raksha.Asn1.Ess; using Raksha.Asn1.Pkcs; using Raksha.Asn1.Tsp; using Raksha.Asn1.X509; using Raksha.Cms; using Raksha.Crypto; using Raksha.Math; using Raksha.Security; using Raksha.Security.Certificates; using Raksha.Utilities; using Raksha.X509; using Raksha.X509.Store; namespace Raksha.Tsp { public class TimeStampTokenGenerator { private int accuracySeconds = -1; private int accuracyMillis = -1; private int accuracyMicros = -1; private bool ordering = false; private GeneralName tsa = null; private string tsaPolicyOID; private AsymmetricKeyParameter key; private X509Certificate cert; private string digestOID; private Asn1.Cms.AttributeTable signedAttr; private Asn1.Cms.AttributeTable unsignedAttr; private IX509Store x509Certs; private IX509Store x509Crls; /** * basic creation - only the default attributes will be included here. */ public TimeStampTokenGenerator( AsymmetricKeyParameter key, X509Certificate cert, string digestOID, string tsaPolicyOID) : this(key, cert, digestOID, tsaPolicyOID, null, null) { } /** * create with a signer with extra signed/unsigned attributes. */ public TimeStampTokenGenerator( AsymmetricKeyParameter key, X509Certificate cert, string digestOID, string tsaPolicyOID, Asn1.Cms.AttributeTable signedAttr, Asn1.Cms.AttributeTable unsignedAttr) { this.key = key; this.cert = cert; this.digestOID = digestOID; this.tsaPolicyOID = tsaPolicyOID; this.unsignedAttr = unsignedAttr; TspUtil.ValidateCertificate(cert); // // Add the ESSCertID attribute // IDictionary signedAttrs; if (signedAttr != null) { signedAttrs = signedAttr.ToDictionary(); } else { signedAttrs = Platform.CreateHashtable(); } try { byte[] hash = DigestUtilities.CalculateDigest("SHA-1", cert.GetEncoded()); EssCertID essCertid = new EssCertID(hash); Asn1.Cms.Attribute attr = new Asn1.Cms.Attribute( PkcsObjectIdentifiers.IdAASigningCertificate, new DerSet(new SigningCertificate(essCertid))); signedAttrs[attr.AttrType] = attr; } catch (CertificateEncodingException e) { throw new TspException("Exception processing certificate.", e); } catch (SecurityUtilityException e) { throw new TspException("Can't find a SHA-1 implementation.", e); } this.signedAttr = new Asn1.Cms.AttributeTable(signedAttrs); } public void SetCertificates( IX509Store certificates) { this.x509Certs = certificates; } public void SetCrls( IX509Store crls) { this.x509Crls = crls; } public void SetAccuracySeconds( int accuracySeconds) { this.accuracySeconds = accuracySeconds; } public void SetAccuracyMillis( int accuracyMillis) { this.accuracyMillis = accuracyMillis; } public void SetAccuracyMicros( int accuracyMicros) { this.accuracyMicros = accuracyMicros; } public void SetOrdering( bool ordering) { this.ordering = ordering; } public void SetTsa( GeneralName tsa) { this.tsa = tsa; } //------------------------------------------------------------------------------ public TimeStampToken Generate( TimeStampRequest request, BigInteger serialNumber, DateTime genTime) { DerObjectIdentifier digestAlgOID = new DerObjectIdentifier(request.MessageImprintAlgOid); AlgorithmIdentifier algID = new AlgorithmIdentifier(digestAlgOID, DerNull.Instance); MessageImprint messageImprint = new MessageImprint(algID, request.GetMessageImprintDigest()); Accuracy accuracy = null; if (accuracySeconds > 0 || accuracyMillis > 0 || accuracyMicros > 0) { DerInteger seconds = null; if (accuracySeconds > 0) { seconds = new DerInteger(accuracySeconds); } DerInteger millis = null; if (accuracyMillis > 0) { millis = new DerInteger(accuracyMillis); } DerInteger micros = null; if (accuracyMicros > 0) { micros = new DerInteger(accuracyMicros); } accuracy = new Accuracy(seconds, millis, micros); } DerBoolean derOrdering = null; if (ordering) { derOrdering = DerBoolean.GetInstance(ordering); } DerInteger nonce = null; if (request.Nonce != null) { nonce = new DerInteger(request.Nonce); } DerObjectIdentifier tsaPolicy = new DerObjectIdentifier(tsaPolicyOID); if (request.ReqPolicy != null) { tsaPolicy = new DerObjectIdentifier(request.ReqPolicy); } TstInfo tstInfo = new TstInfo(tsaPolicy, messageImprint, new DerInteger(serialNumber), new DerGeneralizedTime(genTime), accuracy, derOrdering, nonce, tsa, request.Extensions); try { CmsSignedDataGenerator signedDataGenerator = new CmsSignedDataGenerator(); byte[] derEncodedTstInfo = tstInfo.GetDerEncoded(); if (request.CertReq) { signedDataGenerator.AddCertificates(x509Certs); } signedDataGenerator.AddCrls(x509Crls); signedDataGenerator.AddSigner(key, cert, digestOID, signedAttr, unsignedAttr); CmsSignedData signedData = signedDataGenerator.Generate( PkcsObjectIdentifiers.IdCTTstInfo.Id, new CmsProcessableByteArray(derEncodedTstInfo), true); return new TimeStampToken(signedData); } catch (CmsException cmsEx) { throw new TspException("Error generating time-stamp token", cmsEx); } catch (IOException e) { throw new TspException("Exception encoding info", e); } catch (X509StoreException e) { throw new TspException("Exception handling CertStore", e); } // catch (InvalidAlgorithmParameterException e) // { // throw new TspException("Exception handling CertStore CRLs", e); // } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.Cci; using Microsoft.Cci.MutableCodeModel; using System.Diagnostics.Contracts; using Microsoft.CodeAnalysis.CSharp.Syntax; using R = Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols; namespace CSharp2CCI { internal class ExpressionVisitor : CSharpSyntaxVisitor<IExpression> { #region Fields private IMetadataHost host; SemanticModel semanticModel; ReferenceMapper mapper; private IMethodDefinition method; Dictionary<ILocalSymbol, ILocalDefinition> locals = new Dictionary<ILocalSymbol, ILocalDefinition>(); // TODO: need to make this a stack of local scopes! Dictionary<IMethodDefinition, List<IParameterDefinition>> parameters = new Dictionary<IMethodDefinition, List<IParameterDefinition>>(); // TODO: Clean up entries when not needed? private SyntaxTree tree; #endregion public ExpressionVisitor(IMetadataHost host, SemanticModel semanticModel, ReferenceMapper mapper, IMethodDefinition method) { this.host = host; this.semanticModel = semanticModel; this.mapper = mapper; this.method = method; this.parameters.Add(method, new List<IParameterDefinition>(method.Parameters)); this.tree = semanticModel.SyntaxTree; } internal void RegisterLocal(ILocalSymbol localSymbol, ILocalDefinition localDefinition) { this.locals[localSymbol] = localDefinition; } /// <summary> /// Returns a constant one to be used in pre-/post-fix increment/decrement operations /// </summary> private string LocalNumber(){ var s = localNumber.ToString(); localNumber++; return s; } int localNumber = 0; /// <summary> /// Tracks whether the left-hand side of an assignment is being translated. /// Makes a difference whether a property should be translated as a setter /// or a getter. /// </summary> private bool lhs; object GetConstantOneOfMatchingTypeForIncrementDecrement(ITypeDefinition targetType) { if (TypeHelper.TypesAreEquivalent(targetType, this.host.PlatformType.SystemChar)) return (char)1; else if (TypeHelper.TypesAreEquivalent(targetType, this.host.PlatformType.SystemInt8)) return (sbyte)1; else if (TypeHelper.TypesAreEquivalent(targetType, this.host.PlatformType.SystemUInt8)) return (byte)1; else if (TypeHelper.TypesAreEquivalent(targetType, this.host.PlatformType.SystemInt16)) return (short)1; else if (TypeHelper.TypesAreEquivalent(targetType, this.host.PlatformType.SystemUInt16)) return (ushort)1; return 1; } public override IExpression VisitLiteralExpression(LiteralExpressionSyntax node) { var o = this.semanticModel.GetTypeInfo(node); switch (node.CSharpKind()) { case SyntaxKind.NumericLiteralExpression: case SyntaxKind.CharacterLiteralExpression: case SyntaxKind.FalseLiteralExpression: case SyntaxKind.StringLiteralExpression: case SyntaxKind.TrueLiteralExpression: return new CompileTimeConstant() { Type = mapper.Map(o.Type), Value = node.Token.Value, }; case SyntaxKind.NullLiteralExpression: return new CompileTimeConstant() { Type = this.host.PlatformType.SystemObject, Value = null, }; default: throw new InvalidDataException("VisitPrimaryExpression passed an unknown node kind: " + node.CSharpKind()); } } public override IExpression VisitThisExpression(ThisExpressionSyntax node) { var o = this.semanticModel.GetTypeInfo(node); return new ThisReference() { Type = this.mapper.Map(o.Type), }; } public override IExpression VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) { var o = this.semanticModel.GetSymbolInfo(node); var s = o.Symbol as IMethodSymbol; if (s != null) { var m = (MethodDefinition)this.mapper.TranslateMetadata(s); var anonDelParameters = new List<IParameterDefinition>(m.Parameters); this.parameters.Add(m, anonDelParameters); IBlockStatement body; var b = node.Body; if (b is ExpressionSyntax) { var e = this.Visit(b); body = new BlockStatement() { Statements = new List<IStatement>() { new ReturnStatement() { Expression = e, } }, }; } else if (b is BlockSyntax) { var sv = new StatementVisitor(this.host, this.semanticModel, this.mapper, m, this); var b2 = (IBlockStatement) sv.Visit(b); body = b2; } else { throw new InvalidDataException("VisitSimpleLambdaExpression: unknown type of body"); } var anon = new AnonymousDelegate() { Body = body, CallingConvention = s.IsStatic ? CallingConvention.HasThis : CallingConvention.Default, Parameters = anonDelParameters, ReturnType = m.Type, Type = this.mapper.Map(this.semanticModel.GetTypeInfo(node).ConvertedType), }; return anon; } throw new InvalidDataException("VisitSimpleLambdaExpression couldn't find something to return"); } public override IExpression VisitPrefixUnaryExpression(PrefixUnaryExpressionSyntax node) { var o = this.semanticModel.GetTypeInfo(node); var t = this.mapper.Map(o.Type); var operand = this.Visit(node.Operand); UnaryOperation op = null; switch (node.CSharpKind()) { case SyntaxKind.BitwiseNotExpression: op = new OnesComplement(); break; case SyntaxKind.UnaryMinusExpression: op = new UnaryNegation(); op.Type = operand.Type; break; case SyntaxKind.PreDecrementExpression: case SyntaxKind.PreIncrementExpression: BinaryOperation bo; if (node.OperatorToken.CSharpKind() == SyntaxKind.MinusMinusToken) bo = new Subtraction(); else bo = new Addition(); object one = GetConstantOneOfMatchingTypeForIncrementDecrement(operand.Type.ResolvedType); // REVIEW: Do we really need to resolve? bo.LeftOperand = operand; bo.RightOperand = new CompileTimeConstant() { Type = operand.Type, Value = one, }; bo.Type = operand.Type; var assign = new Assignment() { Source = bo, Target = Helper.MakeTargetExpression(operand), Type = operand.Type, }; return assign; case SyntaxKind.LogicalNotExpression: op = new LogicalNot(); break; default: var typeName = node.GetType().ToString(); var msg = String.Format("Was unable to convert a {0} node to CCI because the kind '{1}' wasn't handled", typeName, node.CSharpKind().ToString()); throw new ConverterException(msg); } op.Operand = operand; return op; } public override IExpression VisitPostfixUnaryExpression(PostfixUnaryExpressionSyntax node) { var e = this.Visit(node.Operand); switch (node.OperatorToken.CSharpKind()) { case SyntaxKind.MinusMinusToken: case SyntaxKind.PlusPlusToken: var stmts = new List<IStatement>(); var temp = new LocalDefinition() { MethodDefinition = this.method, Name = this.host.NameTable.GetNameFor("__temp" + LocalNumber()), Type = e.Type, }; stmts.Add( new LocalDeclarationStatement(){ InitialValue = e, LocalVariable = temp, }); BinaryOperation bo; if (node.OperatorToken.CSharpKind() == SyntaxKind.MinusMinusToken) bo = new Subtraction(); else bo = new Addition(); object one = GetConstantOneOfMatchingTypeForIncrementDecrement(e.Type.ResolvedType); // REVIEW: Do we really need to resolve? bo.LeftOperand = e; bo.RightOperand = new CompileTimeConstant() { Type = e.Type, Value = one, }; bo.Type = e.Type; var assign = new Assignment() { Source = bo, Target = Helper.MakeTargetExpression(e), Type = e.Type, }; stmts.Add( new ExpressionStatement() { Expression = assign, }); var blockExpression = new BlockExpression() { BlockStatement = new BlockStatement() { Statements = stmts, }, Expression = new BoundExpression() { Definition = temp, Instance = null, Type = temp.Type }, Type = e.Type, }; return blockExpression; default: throw new InvalidDataException("VisitPostfixUnaryExpression: unknown operator token '" + node.OperatorToken.ValueText); } } public override IExpression VisitParenthesizedExpression(ParenthesizedExpressionSyntax node) { return this.Visit(node.Expression); } public override IExpression VisitObjectCreationExpression(ObjectCreationExpressionSyntax node) { var o = this.semanticModel.GetSymbolInfo(node); var s = o.Symbol; if (s != null) { IMethodSymbol ms = s as IMethodSymbol; var mr = this.mapper.Map(ms); var e = new CreateObjectInstance() { Locations = Helper.SourceLocation(this.tree, node), MethodToCall = mr, Type = mr.ContainingType, }; return e; } throw new InvalidDataException("VisitObjectCreationExpression couldn't find something to return"); } public override IExpression VisitMemberAccessExpression(MemberAccessExpressionSyntax node) { var o = this.semanticModel.GetSymbolInfo(node); IExpression instance = null; BoundExpression be = null; var onLHS = this.lhs; this.lhs = false; // only the right-most member is a l-value: all other member accesses are for r-value. var s = o.Symbol; if (s != null) { switch (s.Kind) { case SymbolKind.Method: IMethodSymbol ms = (IMethodSymbol)s; instance = null; if (!s.IsStatic) { instance = this.Visit(node.Expression); } var mr = this.mapper.Map(ms); be = new BoundExpression() { Definition = mr, Instance = instance, Locations = Helper.SourceLocation(this.tree, node), Type = mr.Type, }; return be; case SymbolKind.Field: IFieldSymbol fs = (IFieldSymbol)s; instance = null; if (!fs.IsStatic) { instance = this.Visit(node.Expression); } var fr = this.mapper.Map(fs); // Certain fields represent compile-time constants // REVIEW: Is this the right place to do this? // TODO: All the rest of the constants... if (fr.ContainingType.InternedKey == this.host.PlatformType.SystemInt32.InternedKey) { if (fr.Name.Value.Equals("MinValue")) { return new CompileTimeConstant() { Type = fr.Type, Value = Int32.MinValue, }; } else if (fr.Name.Value.Equals("MaxValue")) { return new CompileTimeConstant() { Type = fr.Type, Value = Int32.MaxValue, }; } } be = new BoundExpression() { Definition = fr, Instance = instance, Locations = Helper.SourceLocation(this.tree, node), Type = fr.Type, }; return be; case SymbolKind.Property: IPropertySymbol ps = (IPropertySymbol)s; instance = null; if (!ps.IsStatic) { instance = this.Visit(node.Expression); } var accessor = onLHS ? this.mapper.Map(ps.SetMethod) : this.mapper.Map(ps.GetMethod); if (!onLHS && MemberHelper.GetMemberSignature(accessor, NameFormattingOptions.None).Contains("Length")) { return new VectorLength() { Locations = Helper.SourceLocation(this.tree, node), Type = accessor.Type, Vector = instance, }; } return new MethodCall() { MethodToCall = accessor, IsStaticCall = ps.IsStatic, Locations = Helper.SourceLocation(this.tree, node), ThisArgument = instance, Type = accessor.Type, }; default: throw new InvalidDataException("VisitMemberAccessExpression: uknown definition kind: " + s.Kind); } } throw new InvalidDataException("VisitMemberAccessExpression couldn't find something to return"); } [ContractVerification(false)] public override IExpression VisitInvocationExpression(InvocationExpressionSyntax node) { var o = this.semanticModel.GetSymbolInfo(node); var args = new List<IExpression>(); foreach (var a in node.ArgumentList.Arguments) { var a_prime = this.Visit(a); args.Add(a_prime); } var s = o.Symbol; if (s != null) { IMethodSymbol ms = s as IMethodSymbol; IMethodReference mtc = this.mapper.Map(ms); IExpression thisArg; thisArg = null; if (!ms.IsStatic) { var be = (BoundExpression) this.Visit(node.Expression); thisArg = be.Instance; } //if (MemberHelper.GetMethodSignature(mtc, NameFormattingOptions.None).Contains("Length")) { // return new VectorLength() { // Type = mtc.Type, // Vector = thisArg, // }; //} var mc = new MethodCall() { Arguments = args, IsStaticCall = ms.IsStatic, Locations = Helper.SourceLocation(this.tree, node), MethodToCall = mtc, ThisArgument = thisArg, Type = mtc.Type, }; return mc; } throw new InvalidDataException("VisitInvocationExpression couldn't find something to return"); } public override IExpression VisitIdentifierName(IdentifierNameSyntax node) { var o = this.semanticModel.GetSymbolInfo(node); var s = o.Symbol; if (s != null) { switch (s.Kind) { case SymbolKind.Field: var f = this.mapper.Map(s as IFieldSymbol); var t = f.ContainingType; return new BoundExpression() { Definition = f, Instance = s.IsStatic ? null : new ThisReference() { Type = t, }, Type = f.Type, }; case SymbolKind.Parameter: var p = s as IParameterSymbol; var m = (IMethodDefinition) this.mapper.Map(p.ContainingSymbol as IMethodSymbol); var p_prime = this.parameters[m][p.Ordinal]; if (p_prime.IsIn) { return new BoundExpression() { Definition = p_prime, Instance = null, Locations = Helper.SourceLocation(this.tree, node), Type = p_prime.Type, }; } else if (p_prime.IsOut || p_prime.IsByReference) { var locs = Helper.SourceLocation(this.tree, node); return new AddressDereference() { Address = new BoundExpression() { Definition = p_prime, Instance = null, Locations = locs, Type = Microsoft.Cci.Immutable.ManagedPointerType.GetManagedPointerType(p_prime.Type, this.host.InternFactory), }, Locations = locs, Type = p_prime.Type, }; } else { throw new InvalidDataException("VisitIdentifierName given a parameter that is neither in, out, nor ref: " + p.Name); } case SymbolKind.Local: var l = s as ILocalSymbol; var l_prime = this.locals[l]; return new BoundExpression() { Definition = l_prime, Instance = null, Locations = Helper.SourceLocation(this.tree, node), Type = l_prime.Type, }; case SymbolKind.Method: var m2 = this.mapper.Map(s as IMethodSymbol); var t2 = m2.ContainingType; return new BoundExpression() { Definition = m2, Instance = s.IsStatic ? null : new ThisReference() { Type = t2, }, Type = t2, }; default: throw new InvalidDataException("VisitIdentifierName passed an unknown symbol kind: " + s.Kind); } } return CodeDummy.Expression; } public override IExpression VisitElementAccessExpression(ElementAccessExpressionSyntax node) { var indices = new List<IExpression>(); foreach (var i in node.ArgumentList.Arguments) { var i_prime = this.Visit(i); indices.Add(i_prime); } var indexedObject = this.Visit(node.Expression); // Can index an array var arrType = indexedObject.Type as IArrayTypeReference; if (arrType != null) { return new ArrayIndexer() { IndexedObject = indexedObject, Indices = indices, Locations = Helper.SourceLocation(this.tree, node), Type = arrType.ElementType, }; } // Otherwise the indexer represents a call to the setter or getter for the default indexed property // This shows that the target of the translator should really be the Ast model and not the CodeModel // because it already handles this sort of thing. if (TypeHelper.TypesAreEquivalent(indexedObject.Type, this.host.PlatformType.SystemString)) { return new MethodCall(){ Arguments = indices, IsVirtualCall = true, Locations = Helper.SourceLocation(this.tree, node), MethodToCall = TypeHelper.GetMethod(this.host.PlatformType.SystemString.ResolvedType, this.host.NameTable.GetNameFor("get_Chars"), this.host.PlatformType.SystemInt32), ThisArgument = indexedObject, Type = this.host.PlatformType.SystemChar, }; } throw new InvalidDataException("VisitElementAccessExpression couldn't find something to return"); } public override IExpression VisitConditionalExpression(ConditionalExpressionSyntax node) { var o = this.semanticModel.GetTypeInfo(node); var t = this.mapper.Map(o.Type); return new Conditional() { Condition = this.Visit(node.Condition), Locations = Helper.SourceLocation(this.tree, node), ResultIfFalse = this.Visit(node.WhenFalse), ResultIfTrue = this.Visit(node.WhenTrue), Type = t, }; } public override IExpression VisitCastExpression(CastExpressionSyntax node) { var o = this.semanticModel.GetTypeInfo(node); var t = this.mapper.Map(o.Type); var result = new Microsoft.Cci.MutableCodeModel.Conversion() { ValueToConvert = this.Visit(node.Expression), Type = t, TypeAfterConversion = t, }; return result; } public override IExpression VisitBinaryExpression(BinaryExpressionSyntax node) { var o = this.semanticModel.GetTypeInfo(node); var t = this.mapper.Map(o.Type); if (node.CSharpKind() == SyntaxKind.SimpleAssignmentExpression) this.lhs = true; var left = this.Visit(node.Left); this.lhs = false; var right = this.Visit(node.Right); BinaryOperation op = null; var locs = Helper.SourceLocation(this.tree, node); switch (node.CSharpKind()) { case SyntaxKind.AddAssignmentExpression: { var a = new Assignment() { Locations = locs, Source = new Addition() { LeftOperand = left, RightOperand =right, }, Target = Helper.MakeTargetExpression(left), Type = t, }; return a; } case SyntaxKind.AddExpression: op = new Addition(); break; case SyntaxKind.SimpleAssignmentExpression: { var mc = left as MethodCall; if (mc != null) { // then this is really o.P = e for some property P // and the property access has been translated into a call // to set_P. mc.Arguments = new List<IExpression> { right, }; return mc; } var be = left as BoundExpression; if (be != null) { var a = new Assignment() { Locations = locs, Source = right, Target = new TargetExpression() { Definition = be.Definition, Instance = be.Instance, Type = be.Type, }, Type = t, }; return a; } var arrayIndexer = left as ArrayIndexer; if (arrayIndexer != null) { var a = new Assignment() { Locations = locs, Source = right, Target = new TargetExpression() { Definition = arrayIndexer, Instance = arrayIndexer.IndexedObject, Type = right.Type, }, Type = t, }; return a; } var addressDereference = left as AddressDereference; if (addressDereference != null) { var a = new Assignment() { Locations = locs, Source = right, Target = new TargetExpression() { Definition = addressDereference, Instance = null, Type = t, }, Type = t, }; return a; } throw new InvalidDataException("VisitBinaryExpression: Can't figure out lhs in assignment" + left.Type.ToString()); } case SyntaxKind.BitwiseAndExpression: op = new BitwiseAnd(); break; case SyntaxKind.BitwiseOrExpression: op = new BitwiseOr(); break; case SyntaxKind.DivideExpression: op = new Division(); break; case SyntaxKind.EqualsExpression: op = new Equality(); break; case SyntaxKind.ExclusiveOrExpression: op = new ExclusiveOr(); break; case SyntaxKind.GreaterThanExpression: op = new GreaterThan(); break; case SyntaxKind.GreaterThanOrEqualExpression: op = new GreaterThanOrEqual(); break; case SyntaxKind.LeftShiftExpression: op = new LeftShift(); break; case SyntaxKind.LessThanExpression: op = new LessThan(); break; case SyntaxKind.LessThanOrEqualExpression: op = new LessThanOrEqual(); break; case SyntaxKind.LogicalAndExpression: return new Conditional() { Condition = left, Locations = locs, ResultIfTrue = right, ResultIfFalse = new CompileTimeConstant() { Type = t, Value = false }, Type = t, }; case SyntaxKind.LogicalOrExpression: return new Conditional() { Condition = left, Locations = Helper.SourceLocation(this.tree, node), ResultIfTrue = new CompileTimeConstant() { Type = t, Value = true }, ResultIfFalse = right, Type = t, }; case SyntaxKind.ModuloExpression: op = new Modulus(); break; case SyntaxKind.MultiplyExpression: op = new Multiplication(); break; case SyntaxKind.NotEqualsExpression: op = new NotEquality(); break; case SyntaxKind.RightShiftExpression: op = new RightShift(); break; case SyntaxKind.SubtractAssignmentExpression: { var a = new Assignment() { Locations = locs, Source = new Subtraction() { LeftOperand = left, RightOperand = right, }, Target = Helper.MakeTargetExpression(left), Type = t, }; return a; } case SyntaxKind.MultiplyAssignmentExpression: { var a = new Assignment() { Locations = locs, Source = new Multiplication() { LeftOperand = left, RightOperand = right, }, Target = Helper.MakeTargetExpression(left), Type = t, }; return a; } case SyntaxKind.DivideAssignmentExpression: { var a = new Assignment() { Locations = locs, Source = new Division() { LeftOperand = left, RightOperand = right, }, Target = Helper.MakeTargetExpression(left), Type = t, }; return a; } case SyntaxKind.ModuloAssignmentExpression: { var a = new Assignment() { Locations = locs, Source = new Modulus() { LeftOperand = left, RightOperand = right, }, Target = Helper.MakeTargetExpression(left), Type = t, }; return a; } case SyntaxKind.SubtractExpression: op = new Subtraction(); break; default: throw new InvalidDataException("VisitBinaryExpression: unknown node = " + node.CSharpKind()); } op.Locations = locs; op.LeftOperand = left; op.RightOperand = right; op.Type = t; return op; } // TODO: Handle multi-dimensional arrays public override IExpression VisitArrayCreationExpression(ArrayCreationExpressionSyntax node) { var o = this.semanticModel.GetSymbolInfo(node); var s = o.Symbol; var arrayType = node.Type; var elementType = this.mapper.Map(this.semanticModel.GetTypeInfo(arrayType.ElementType).Type); var arrayOfType = Microsoft.Cci.Immutable.Vector.GetVector(elementType, this.host.InternFactory); List<IExpression> inits = null; int size = 0; if (node.Initializer != null) { inits = new List<IExpression>(); foreach (var i in node.Initializer.Expressions) { var e = this.Visit(i); inits.Add(e); size++; } } var result = new CreateArray() { ElementType = elementType, Rank = 1, Type = arrayOfType, }; if (inits != null) { result.Initializers = inits; result.Sizes = new List<IExpression> { new CompileTimeConstant() { Value = size, }, }; } else { var rankSpecs = arrayType.RankSpecifiers; foreach (var r in rankSpecs) { foreach (var rs in r.Sizes) { var e = this.Visit(rs); result.Sizes = new List<IExpression> { e, }; break; } break; } } return result; } public override IExpression VisitArgument(ArgumentSyntax node) { var a = this.Visit(node.Expression); if (node.RefOrOutKeyword.CSharpKind() != SyntaxKind.None) { object def = a; IExpression instance = null; var be = a as IBoundExpression; if (be != null) { // REVIEW: Maybe it should always be a bound expression? def = be.Definition; instance = be.Instance; } a = new AddressOf() { Expression = new AddressableExpression() { Definition = def, Instance = instance, Locations = new List<ILocation>(a.Locations), }, Locations = new List<ILocation>(a.Locations), Type = Microsoft.Cci.Immutable.ManagedPointerType.GetManagedPointerType(a.Type, this.host.InternFactory), }; } return a; } public override IExpression DefaultVisit(SyntaxNode node) { // If you hit this, it means there was some sort of CS construct // that we haven't written a conversion routine for. Simply add // it above and rerun. var typeName = node.GetType().ToString(); var msg = String.Format("Was unable to convert a {0} node to CCI", typeName); throw new ConverterException(msg); } } }
using Signum.Engine.Basics; using Signum.Engine.Maps; using Signum.Utilities.Reflection; using System.Collections.Concurrent; using System.Text.Json; using System.Text.Json.Serialization; namespace Signum.Engine.Json; public class PropertyConverter { public readonly IPropertyValidator? PropertyValidator; public readonly Func<ModifiableEntity, object?>? GetValue; public readonly Action<ModifiableEntity, object?>? SetValue; public ReadJsonPropertyDelegate? CustomReadJsonProperty { get; set; } public WriteJsonPropertyDelegate? CustomWriteJsonProperty { get; set; } public bool AvoidValidate { get; set; } public PropertyConverter() { } public PropertyConverter(IPropertyValidator pv) { this.PropertyValidator = pv; GetValue = ReflectionTools.CreateGetter<ModifiableEntity, object?>(pv.PropertyInfo); SetValue = ReflectionTools.CreateSetter<ModifiableEntity, object?>(pv.PropertyInfo); } public override string ToString() { return this.PropertyValidator?.PropertyInfo.Name ?? ""; } internal bool IsNotNull() { var pi = this.PropertyValidator!.PropertyInfo; return pi.PropertyType.IsValueType && !pi.PropertyType.IsNullable(); } } public delegate void ReadJsonPropertyDelegate(ref Utf8JsonReader reader, ReadJsonPropertyContext ctx); public class ReadJsonPropertyContext { public ReadJsonPropertyContext(JsonSerializerOptions jsonSerializerOptions, PropertyConverter propertyConverter, ModifiableEntity entity, PropertyRoute parentPropertyRoute, EntityJsonConverterFactory factory) { JsonSerializerOptions = jsonSerializerOptions; PropertyConverter = propertyConverter; Entity = entity; ParentPropertyRoute = parentPropertyRoute; Factory = factory; } public JsonSerializerOptions JsonSerializerOptions { get; internal set; } public PropertyConverter PropertyConverter { get; internal set; } public ModifiableEntity Entity { get; internal set; } public PropertyRoute ParentPropertyRoute { get; internal set; } public EntityJsonConverterFactory Factory { get; set; } } public delegate void WriteJsonPropertyDelegate(Utf8JsonWriter writer, WriteJsonPropertyContext ctx); public class WriteJsonPropertyContext { public WriteJsonPropertyContext(ModifiableEntity entity, string lowerCaseName, PropertyConverter propertyConverter, PropertyRoute parentPropertyRoute, JsonSerializerOptions jsonSerializerOptions, EntityJsonConverterFactory factory) { Entity = entity; LowerCaseName = lowerCaseName; PropertyConverter = propertyConverter; ParentPropertyRoute = parentPropertyRoute; JsonSerializerOptions = jsonSerializerOptions; Factory = factory; } public ModifiableEntity Entity { get; internal set; } public string LowerCaseName { get; internal set; } public PropertyConverter PropertyConverter { get; internal set; } public PropertyRoute ParentPropertyRoute { get; internal set; } public JsonSerializerOptions JsonSerializerOptions { get; internal set; } public EntityJsonConverterFactory Factory { get; set; } } public static class EntityJsonConverter { } public enum EntityJsonConverterStrategy { /// <summary> /// Only the visible entites are serialized, when deserializing a retrieve is made to apply changes. Default for Web.Api Request / Response /// </summary> WebAPI, /// <summary> /// Serialized and deserialized as-is. Usefull for files and Auth Tokens. /// </summary> Full, } public class EntityJsonConverterFactory: JsonConverterFactory { public Polymorphic<Action<ModifiableEntity>> AfterDeserilization = new Polymorphic<Action<ModifiableEntity>>(); public Dictionary<Type, Func<ModifiableEntity>> CustomConstructor = new Dictionary<Type, Func<ModifiableEntity>>(); public Func<PropertyRoute, ModifiableEntity?, string?>? CanWritePropertyRoute; public Func<PropertyRoute, ModifiableEntity, string?>? CanReadPropertyRoute; public Func<PropertyInfo, Exception, string?> GetErrorMessage = (pi, ex) => "Unexpected error"; public void AssertCanWrite(PropertyRoute pr, ModifiableEntity? mod) { string? error = CanWritePropertyRoute.GetInvocationListTyped().Select(a => a(pr, mod)).NotNull().FirstOrDefault(); if (error != null) throw new UnauthorizedAccessException(error); } public EntityJsonConverterFactory() { AfterDeserilization.Register((ModifiableEntity e) => { }); } public ConcurrentDictionary<Type, Dictionary<string, PropertyConverter>> PropertyConverters = new ConcurrentDictionary<Type, Dictionary<string, PropertyConverter>>(); public Dictionary<string, PropertyConverter> GetPropertyConverters(Type type) { return PropertyConverters.GetOrAdd(type, _t => Validator.GetPropertyValidators(_t).Values .Where(pv => ShouldSerialize(pv.PropertyInfo)) .Select(pv => new PropertyConverter(pv)) .ToDictionary(a => a.PropertyValidator!.PropertyInfo.Name.FirstLower()) ); } protected virtual bool ShouldSerialize(PropertyInfo pi) { var ts = pi.GetCustomAttribute<InTypeScriptAttribute>(); if (ts != null) { var v = ts.GetInTypeScript(); if (v.HasValue) return v.Value; } if (pi.HasAttribute<HiddenPropertyAttribute>() || pi.HasAttribute<ExpressionFieldAttribute>()) return false; return true; } public virtual (PropertyRoute pr, ModifiableEntity? mod, PrimaryKey? rowId) GetCurrentPropertyRoute(ModifiableEntity mod) { var tup = EntityJsonContext.CurrentPropertyRouteAndEntity; if (mod is IRootEntity re) tup = (PropertyRoute.Root(mod.GetType()), mod, null); if (tup == null) { var embedded = (EmbeddedEntity)mod; var route = GetCurrentPropertyRouteEmbedded(embedded); return (route, embedded, null); } else if (tup.Value.pr.Type.ElementType() == mod.GetType()) tup = (tup.Value.pr.Add("Item"), null, null); //We have a custom MListConverter but not for other simple collections return tup.Value; } protected virtual PropertyRoute GetCurrentPropertyRouteEmbedded(EmbeddedEntity embedded) { throw new InvalidOperationException(@$"Impossible to determine PropertyRoute for {embedded.GetType().Name}."); } public virtual Type ResolveType(string typeStr, Type objectType) { if (objectType.Name == typeStr || Reflector.CleanTypeName(objectType) == typeStr) return objectType; var type = TypeLogic.GetType(typeStr); if (type.IsEnum) type = EnumEntity.Generate(type); if (!objectType.IsAssignableFrom(type)) throw new JsonException($"Type '{type.Name}' is not assignable to '{objectType.TypeName()}'"); return type; } public virtual EntityJsonConverterStrategy Strategy => EntityJsonConverterStrategy.Full; public override bool CanConvert(Type typeToConvert) { return typeof(IModifiableEntity).IsAssignableFrom(typeToConvert); } public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options) { return (JsonConverter)Activator.CreateInstance(typeof(EntityJsonConverter<>).MakeGenericType(typeToConvert), this)!; } static readonly AsyncLocal<string?> path = new AsyncLocal<string?>(); public static string? CurrentPath => path.Value; public static IDisposable SetPath(string newPart) { var oldPart = path.Value; path.Value = oldPart + newPart; return new Disposable(() => path.Value = oldPart); } } public class EntityJsonConverter<T> : JsonConverterWithExisting<T> where T : class, IModifiableEntity { public EntityJsonConverterFactory Factory { get; } public EntityJsonConverter(EntityJsonConverterFactory factory) { Factory = factory; } public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) { using (HeavyProfiler.LogNoStackTrace("WriteJson", () => value!.GetType().Name)) { var tup = Factory.GetCurrentPropertyRoute((ModifiableEntity)(IModifiableEntity)value!); ModifiableEntity mod = (ModifiableEntity)(IModifiableEntity)value!; writer.WriteStartObject(); if (mod is Entity entity) { writer.WriteString("Type", TypeLogic.TryGetCleanName(mod.GetType())); writer.WritePropertyName("id"); JsonSerializer.Serialize(writer, entity.IdOrNull?.Object, entity.IdOrNull?.Object.GetType() ?? typeof(object), options); if (entity.IsNew) { writer.WriteBoolean("isNew", true); } if (Schema.Current.Table(entity.GetType()).Ticks != null) { writer.WriteString("ticks", entity.Ticks.ToString()); } } else { writer.WriteString("Type", mod.GetType().Name); } if (!(mod is MixinEntity)) { writer.WriteString("toStr", mod.ToString()); } writer.WriteBoolean("modified", mod.Modified == ModifiedState.Modified || mod.Modified == ModifiedState.SelfModified); foreach (var kvp in Factory.GetPropertyConverters(value!.GetType())) { WriteJsonProperty(writer, options, mod, kvp.Key, kvp.Value, tup.pr); } var readonlyProps = Factory.GetPropertyConverters(value!.GetType()) .Where(kvp => kvp.Value.PropertyValidator?.IsPropertyReadonly(mod) == true) .Select(a => a.Key) .ToList(); if (readonlyProps.Any()) { writer.WritePropertyName("readonlyProperties"); JsonSerializer.Serialize(writer, readonlyProps, readonlyProps.GetType(), options); } if (mod.Mixins.Any()) { writer.WritePropertyName("mixins"); writer.WriteStartObject(); foreach (var m in mod.Mixins) { var prm = tup.pr.Add(m.GetType()); using (EntityJsonContext.SetCurrentPropertyRouteAndEntity((prm, m, null))) { writer.WritePropertyName(m.GetType().Name); JsonSerializer.Serialize(writer, m, options); } } writer.WriteEndObject(); } writer.WriteEndObject(); } } public void WriteJsonProperty(Utf8JsonWriter writer, JsonSerializerOptions options, ModifiableEntity mod, string lowerCaseName, PropertyConverter pc, PropertyRoute route) { if (pc.CustomWriteJsonProperty != null) { pc.CustomWriteJsonProperty(writer, new WriteJsonPropertyContext( entity : mod, lowerCaseName : lowerCaseName, propertyConverter : pc, parentPropertyRoute : route, jsonSerializerOptions: options, factory: this.Factory )); } else { var pr = route.Add(pc.PropertyValidator!.PropertyInfo); if (Factory.Strategy == EntityJsonConverterStrategy.WebAPI) { string? error = Factory.CanReadPropertyRoute?.Invoke(pr, mod); if (error != null) return; } using (EntityJsonContext.SetCurrentPropertyRouteAndEntity((pr, mod, null))) { writer.WritePropertyName(lowerCaseName); var val = pc.GetValue!(mod); if (val is null) writer.WriteNullValue(); else JsonSerializer.Serialize(writer, val, val.GetType(), options); } } } public override T? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, T? existingValue) { using (HeavyProfiler.LogNoStackTrace("ReadJson", () => typeToConvert.Name)) { if (reader.TokenType == JsonTokenType.Null) return null; using (EntityCache ec = new EntityCache()) { reader.Assert(JsonTokenType.StartObject); ModifiableEntity mod = GetEntity(ref reader, typeToConvert, existingValue, out bool markedAsModified); var tup = Factory.GetCurrentPropertyRoute(mod); var dic = Factory.GetPropertyConverters(mod.GetType()); using (EntityJsonContext.SetAllowDirectMListChanges(Factory.Strategy == EntityJsonConverterStrategy.Full || markedAsModified)) while (reader.TokenType == JsonTokenType.PropertyName) { var propertyName = reader.GetString()!; using (EntityJsonConverterFactory.SetPath("." + propertyName)) { if (propertyName == "mixins") { reader.Read(); reader.Assert(JsonTokenType.StartObject); reader.Read(); while (reader.TokenType == JsonTokenType.PropertyName) { var mixin = mod[reader.GetString()!]; reader.Read(); var converter = (IJsonConverterWithExisting)options.GetConverter(mixin.GetType()); using (EntityJsonContext.SetCurrentPropertyRouteAndEntity((tup.pr.Add(mixin.GetType()), mixin, null))) converter.Read(ref reader, mixin.GetType(), options, mixin); reader.Read(); } reader.Assert(JsonTokenType.EndObject); reader.Read(); } else if (propertyName == "readonlyProperties") { reader.Read(); JsonSerializer.Deserialize(ref reader, typeof(List<string>), options); reader.Read(); } else { PropertyConverter? pc = dic.TryGetC(propertyName); if (pc == null) { if (specialProps.Contains(propertyName)) throw new InvalidOperationException($"Property '{propertyName}' is a special property like {specialProps.ToString(a => $"'{a}'", ", ")}, and they can only be at the beginning of the Json object for performance reasons"); throw new KeyNotFoundException("Key '{0}' ({1}) not found on {2}".FormatWith(propertyName, propertyName.GetType().TypeName(), dic.GetType().TypeName())); } reader.Read(); ReadJsonProperty(ref reader, options, mod, pc, tup.pr, markedAsModified); reader.Read(); } } } reader.Assert(JsonTokenType.EndObject); Factory.AfterDeserilization.Invoke(mod); if(Factory.Strategy == EntityJsonConverterStrategy.Full) { if (!markedAsModified) mod.SetCleanModified(isSealed: false); } return (T)(IModifiableEntity)mod; } } } public void ReadJsonProperty(ref Utf8JsonReader reader, JsonSerializerOptions options, ModifiableEntity entity, PropertyConverter pc, PropertyRoute parentRoute, bool markedAsModified) { if (pc.CustomReadJsonProperty != null) { pc.CustomReadJsonProperty(ref reader, new ReadJsonPropertyContext( jsonSerializerOptions: options, entity : entity, parentPropertyRoute : parentRoute, propertyConverter : pc, factory: this.Factory )); } else { object? oldValue = pc.GetValue!(entity); var pi = pc.PropertyValidator!.PropertyInfo; var pr = parentRoute.Add(pi); using (EntityJsonContext.SetCurrentPropertyRouteAndEntity((pr, entity, null))) { try { object? newValue = options.GetConverter(pi.PropertyType) is IJsonConverterWithExisting converter ? converter.Read(ref reader, pi.PropertyType, options, oldValue) : JsonSerializer.Deserialize(ref reader, pi.PropertyType, options); if (newValue is DateTime dt) newValue = dt.FromUserInterface(); if (Factory.Strategy == EntityJsonConverterStrategy.Full) { pc.SetValue?.Invoke(entity, newValue); } else { if (pi.CanWrite) { if (!EntityJsonConverter<T>.IsEquals(newValue, oldValue)) { if (!markedAsModified && parentRoute.RootType.IsEntity()) { if (!pi.HasAttribute<IgnoreAttribute>()) { try { //Call attention of developer throw new InvalidOperationException($"'modified' is not set but '{pi.Name}' is modified"); } catch (Exception) { } } } else { Factory.AssertCanWrite(pr, entity); if (newValue == null && pc.IsNotNull()) { entity.SetTemporalError(pi, ValidationMessage._0IsNotSet.NiceToString(pi.NiceName())); return; } pc.SetValue?.Invoke(entity, newValue); } } } } } catch (Exception e) { switch (reader.TokenType) { //Probably won't be able to continue deserialization case JsonTokenType.None: case JsonTokenType.StartObject: case JsonTokenType.StartArray: case JsonTokenType.PropertyName: throw; //Probably will be able to continue case JsonTokenType.EndObject: case JsonTokenType.EndArray: case JsonTokenType.Comment: case JsonTokenType.String: case JsonTokenType.Number: case JsonTokenType.True: case JsonTokenType.False: case JsonTokenType.Null: default: { e.LogException(); entity.SetTemporalError(pi, this.Factory.GetErrorMessage(pi, e)); break; } } } } } } private static bool IsEquals(object? newValue, object? oldValue) { if (newValue is byte[] nba && oldValue is byte[] oba) return MemoryExtensions.SequenceEqual<byte>(nba, oba); if (newValue is DateTime ndt && oldValue is DateTime odt) return Math.Abs(ndt.Subtract(odt).TotalMilliseconds) < 10; //Json dates get rounded if (newValue is DateTimeOffset ndto && oldValue is DateTimeOffset odto) return Math.Abs(ndto.Subtract(odto).TotalMilliseconds) < 10; //Json dates get rounded return object.Equals(newValue, oldValue); } public ModifiableEntity GetEntity(ref Utf8JsonReader reader, Type objectType, IModifiableEntity? existingValue, out bool isModified) { IdentityInfo identityInfo = ReadIdentityInfo(ref reader); isModified = identityInfo.Modified == true; Type type = Factory.ResolveType(identityInfo.Type, objectType); if (typeof(MixinEntity).IsAssignableFrom(objectType)) { var mixin = (MixinEntity)existingValue!; return mixin; } if (identityInfo.IsNew == true) { var result = Factory.CustomConstructor.TryGetC(type)?.Invoke() ?? (ModifiableEntity)Activator.CreateInstance(type, nonPublic: true)!; if (identityInfo.Id != null) ((Entity)result).SetId(PrimaryKey.Parse(identityInfo.Id, type)); return result; } if (typeof(Entity).IsAssignableFrom(type)) { if (identityInfo.Id == null) throw new JsonException($"Missing Id and IsNew for {identityInfo} ({reader.CurrentState})"); var id = PrimaryKey.Parse(identityInfo.Id, type); if (existingValue != null && existingValue.GetType() == type) { Entity existingEntity = (Entity)existingValue; if (existingEntity.Id == id) { if (identityInfo.Ticks != null) { if (identityInfo.Modified == true && existingEntity.Ticks != identityInfo.Ticks.Value) throw new ConcurrencyException(type, id); existingEntity.Ticks = identityInfo.Ticks.Value; } return existingEntity; } } if (Factory.Strategy == EntityJsonConverterStrategy.WebAPI) { var retrievedEntity = Database.Retrieve(type, id); if (identityInfo.Ticks != null) { if (identityInfo.Modified == true && retrievedEntity.Ticks != identityInfo.Ticks.Value) throw new ConcurrencyException(type, id); retrievedEntity.Ticks = identityInfo.Ticks.Value; } return retrievedEntity; } else { var result = (Entity?)Factory.CustomConstructor.TryGetC(type)?.Invoke() ?? (Entity)Activator.CreateInstance(type, nonPublic: true)!; if (identityInfo.Id != null) ((Entity)result).SetId(PrimaryKey.Parse(identityInfo.Id, type)); if (!identityInfo.Modified!.Value) ((Entity)result).SetCleanModified(isSealed: false); if (identityInfo.IsNew != true) ((Entity)result).SetIsNew(false); if (identityInfo.Ticks != null) result.Ticks = identityInfo.Ticks.Value; return result; } } else //Embedded { var existingMod = (ModifiableEntity?)existingValue; if (existingMod == null || existingMod.GetType() != type) return (ModifiableEntity)Activator.CreateInstance(type, nonPublic: true)!; return existingMod; } } public IdentityInfo ReadIdentityInfo(ref Utf8JsonReader reader) { IdentityInfo info = new IdentityInfo(); reader.Read(); while (reader.TokenType == JsonTokenType.PropertyName) { var propName = reader.GetString(); switch (propName) { case "toStr": reader.Read(); info.ToStr = reader.GetString()!; break; case "id": { reader.Read(); info.Id = reader.GetLiteralValue()?.ToString(); } break; case "isNew": reader.Read(); info.IsNew = reader.GetBoolean(); break; case "Type": reader.Read(); info.Type = reader.GetString()!; break; case "ticks": reader.Read(); info.Ticks = long.Parse(reader.GetString()!); break; case "modified": reader.Read(); info.Modified = reader.GetBoolean(); break; default: goto finish; } reader.Read(); } finish: if (info.Type == null) throw new JsonException($"Expected member 'Type' not found in {reader.CurrentState}"); return info; } static readonly string[] specialProps = new string[] { "toStr", "id", "isNew", "Type", "ticks", "modified" }; } public struct IdentityInfo { public string? Id; public bool? IsNew; public bool? Modified; public string Type; public string ToStr; public long? Ticks; public override string ToString() { var newOrId = IsNew == true ? "New" : Id; if (Ticks != null) newOrId += $" (Ticks {Ticks})"; return $"{Type} {newOrId}: {ToStr}"; } }
using System; using System.Collections.Generic; using System.Text; using DCalcCore.Algorithm; using DCalcCore.Assemblers; using DCalcCore.Utilities; using DCalcCore.LoadBalancers; namespace DCalcCore.Threading { /// <summary> /// Multi-threaded work queue. This class is thread-safe. /// </summary> /// <typeparam name="LB">Load balancer to be used across threads.</typeparam> public sealed class ThreadedWorkQueue<LB> : IWorkQueue where LB : ILoadBalancer, new() { #region Private Fields private Int32 m_ThreadsSpawned; private List<WorkQueue> m_Workers = new List<WorkQueue>(); private LB m_LoadBalancer = new LB(); private String m_SyncRoot = "ThreadedWorkQueue Sync"; #endregion #region Private Methods /// <summary> /// Initializes all the workers. /// </summary> /// <param name="count">The count of threads to spawn.</param> private void InitWorkers(Int32 count) { for (Int32 i = 0; i < count; i++) { WorkQueue newQ = new WorkQueue(); newQ.QueuedWorkCompleted += workQueue_QueuedWorkCompleted; m_Workers.Add(newQ); m_LoadBalancer.RegisterObject(newQ); } } /// <summary> /// Handles the QueuedWorkCompleted event of a Work Queue control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="DCalcCore.Utilities.QueueEventArgs"/> instance containing the event data.</param> private void workQueue_QueuedWorkCompleted(Object sender, QueueEventArgs e) { /* Forward to the user */ if (QueuedWorkCompleted != null) QueuedWorkCompleted(sender, e); } #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="ThreadedWorkQueue"/> class. /// </summary> /// <param name="threadCount">The thread count.</param> public ThreadedWorkQueue(Int32 threadCount) { if (threadCount < 1) throw new ArgumentException("threadCount"); m_ThreadsSpawned = threadCount; InitWorkers(threadCount); } #endregion #region ThreadedWorkQueue Public Properties /// <summary> /// Gets the threads spawned. /// </summary> /// <value>The threads spawned.</value> public Int32 ThreadsSpawned { get { return m_ThreadsSpawned; } } #endregion #region IWorkQueue Members /// <summary> /// Queues the evaluation of a script. /// </summary> /// <param name="script">The script.</param> /// <param name="compiledScript">The compiled script.</param> /// <param name="inputSet">The input set.</param> public void QueueEvaluation(IScript script, ICompiledScript compiledScript, ScalarSet inputSet) { if (compiledScript == null) throw new ArgumentNullException("compiledScript"); if (script == null) throw new ArgumentNullException("script"); if (inputSet == null) throw new ArgumentNullException("inputSet"); lock (m_SyncRoot) { /* Select next queue (balanced) */ WorkQueue nextQueue = (WorkQueue)m_LoadBalancer.SelectObject(); nextQueue.QueueEvaluation(script, compiledScript, inputSet); } } /// <summary> /// Cancels the evaluation of a script. /// </summary> /// <param name="compiledScript">The compiled script.</param> /// <returns>All the sets that were cancelled.</returns> public ScalarSet[] CancelEvaluation(ICompiledScript compiledScript) { if (compiledScript == null) throw new ArgumentNullException("compiledScript"); lock (m_SyncRoot) { List<ScalarSet> cancelled = new List<ScalarSet>(); foreach (WorkQueue queue in m_Workers) { /* Cancel execution for this executive from all queues */ cancelled.AddRange(queue.CancelEvaluation(compiledScript)); } return cancelled.ToArray(); } } /// <summary> /// Starts this instance. /// </summary> public void Start() { lock (m_SyncRoot) { foreach (WorkQueue queue in m_Workers) { queue.Start(); } } } /// <summary> /// Stops this instance. /// </summary> public void Stop() { lock (m_SyncRoot) { foreach (WorkQueue queue in m_Workers) { queue.Stop(); } } } /// <summary> /// Aborts this instance. /// </summary> public void Abort() { lock (m_SyncRoot) { foreach (WorkQueue queue in m_Workers) { queue.Abort(); } /* Clear load balancer */ m_LoadBalancer.ResetBalance(); } } /// <summary> /// Occurs when queued work completed (a script was evaluated). /// </summary> public event QueueEventHandler QueuedWorkCompleted; #endregion #region IDisposable Members public void Dispose() { /* Abort all workers */ Abort(); } #endregion } }
//------------------------------------------------------------------------------ // <copyright file="XmlCharacterData.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ namespace System.Xml { using System.Diagnostics; using System.Text; using System.Xml.XPath; // Provides text-manipulation methods that are used by several classes. public abstract class XmlCharacterData : XmlLinkedNode { string data; //base(doc) will throw exception if doc is null. protected internal XmlCharacterData( string data, XmlDocument doc ): base( doc ) { this.data = data; } // Gets or sets the value of the node. public override String Value { get { return Data;} set { Data = value;} } // Gets or sets the concatenated values of the node and // all its children. public override string InnerText { get { return Value;} set { Value = value;} } // Contains this node's data. public virtual string Data { [System.Runtime.TargetedPatchingOptOutAttribute("Performance critical to inline across NGen image boundaries")] get { if (data != null) { return data; } else { return String.Empty; } } set { XmlNode parent = ParentNode; XmlNodeChangedEventArgs args = GetEventArgs( this, parent, parent, this.data, value, XmlNodeChangedAction.Change ); if (args != null) BeforeEvent( args ); data = value; if (args != null) AfterEvent( args ); } } // Gets the length of the data, in characters. public virtual int Length { get { if (data != null) { return data.Length; } return 0; } } // Retrieves a substring of the full string from the specified range. public virtual String Substring(int offset, int count) { int len = data != null ? data.Length : 0; if (len > 0) { if (len < (offset + count)) { count = len - offset; } return data.Substring( offset, count ); } return String.Empty; } // Appends the specified string to the end of the character // data of the node. public virtual void AppendData(String strData) { XmlNode parent = ParentNode; int capacity = data != null ? data.Length : 0; if (strData != null) capacity += strData.Length; string newValue = new StringBuilder( capacity ).Append( data ).Append( strData ).ToString(); XmlNodeChangedEventArgs args = GetEventArgs( this, parent, parent, data, newValue, XmlNodeChangedAction.Change ); if (args != null) BeforeEvent( args ); this.data = newValue; if (args != null) AfterEvent( args ); } // Insert the specified string at the specified character offset. public virtual void InsertData(int offset, string strData) { XmlNode parent = ParentNode; int capacity = data != null ? data.Length : 0; if (strData != null) capacity += strData.Length; string newValue = new StringBuilder( capacity ).Append( data ).Insert(offset, strData).ToString(); XmlNodeChangedEventArgs args = GetEventArgs( this, parent, parent, data, newValue, XmlNodeChangedAction.Change ); if (args != null) BeforeEvent( args ); this.data = newValue; if (args != null) AfterEvent( args ); } // Remove a range of characters from the node. public virtual void DeleteData(int offset, int count) { //Debug.Assert(offset >= 0 && offset <= Length); int len = data != null ? data.Length : 0; if (len > 0) { if (len < (offset + count)) { count = Math.Max ( len - offset, 0); } } string newValue = new StringBuilder( data ).Remove(offset, count).ToString(); XmlNode parent = ParentNode; XmlNodeChangedEventArgs args = GetEventArgs( this, parent, parent, data, newValue, XmlNodeChangedAction.Change ); if (args != null) BeforeEvent( args ); this.data = newValue; if (args != null) AfterEvent( args ); } // Replace the specified number of characters starting at the specified offset with the // specified string. public virtual void ReplaceData(int offset, int count, String strData) { //Debug.Assert(offset >= 0 && offset <= Length); int len = data != null ? data.Length : 0; if (len > 0) { if (len < (offset + count)) { count = Math.Max ( len - offset, 0); } } StringBuilder temp = new StringBuilder( data ).Remove( offset, count ); string newValue = temp.Insert( offset, strData ).ToString(); XmlNode parent = ParentNode; XmlNodeChangedEventArgs args = GetEventArgs( this, parent, parent, data, newValue, XmlNodeChangedAction.Change ); if (args != null) BeforeEvent( args ); this.data = newValue; if (args != null) AfterEvent( args ); } internal bool CheckOnData( string data ) { return XmlCharType.Instance.IsOnlyWhitespace( data ); } internal bool DecideXPNodeTypeForTextNodes(XmlNode node, ref XPathNodeType xnt) { //returns true - if all siblings of the node are processed else returns false. //The reference XPathNodeType argument being passed in is the watermark that //changes according to the siblings nodetype and will contain the correct //nodetype when it returns. Debug.Assert(XmlDocument.IsTextNode(node.NodeType) || (node.ParentNode != null && node.ParentNode.NodeType == XmlNodeType.EntityReference)); while (node != null) { switch (node.NodeType) { case XmlNodeType.Whitespace : break; case XmlNodeType.SignificantWhitespace : xnt = XPathNodeType.SignificantWhitespace; break; case XmlNodeType.Text : case XmlNodeType.CDATA: xnt = XPathNodeType.Text; return false; case XmlNodeType.EntityReference : if (!DecideXPNodeTypeForTextNodes(node.FirstChild, ref xnt)) { return false; } break; default : return false; } node = node.NextSibling; } return true; } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC Copyright (C) 2011 Peter Gill <peter@majorsilence.com> This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Drawing.Printing; using System.Xml; using System.IO; using RdlReader.Resources; using fyiReporting.RDL; using fyiReporting.RdlViewer; using System.Runtime.InteropServices; using System.Collections.Generic; namespace fyiReporting.RdlReader { using System.Diagnostics; using System.Linq; /// <summary> /// RdlReader is a application for displaying reports based on RDL. /// </summary> public partial class RdlReader : IMessageFilter { SortedList _RecentFiles = null; /// <summary> /// Uri, Parameter /// </summary> Dictionary<Uri, String> _CurrentFiles = null; // temporary variable for current files private RDL.NeedPassword _GetPassword; private string _DataSourceReferencePassword = null; private bool bMono; public RdlReader(bool mono) { bMono = mono; GetStartupState(); InitializeComponent(); BuildMenus(); // CustomReportItem load RdlEngineConfig.GetCustomReportTypes(); Application.AddMessageFilter(this); this.Closing += new System.ComponentModel.CancelEventHandler(this.RdlReader_Closing); _GetPassword = new RDL.NeedPassword(this.GetPassword); // open up the current files if any if (_CurrentFiles != null) { foreach (var dict in _CurrentFiles) { MDIChild mc = new MDIChild(this.ClientRectangle.Width * 3 / 4, this.ClientRectangle.Height * 3 / 4); mc.MdiParent = this; mc.Viewer.GetDataSourceReferencePassword = _GetPassword; mc.SourceFile = dict.Key; if (dict.Value != string.Empty) { mc.Parameters = dict.Value; } mc.Text = dict.Key.LocalPath; if (_CurrentFiles.Count == 1) { mc.WindowState = FormWindowState.Maximized; } mc.Show(); } _CurrentFiles = null; // don't need this any longer } } /// <summary> /// Handles mousewheel processing when window under mousewheel doesn't have focus /// </summary> /// <param name="m"></param> /// <returns></returns> public bool PreFilterMessage(ref Message m) { #if MONO return false; #else if (m.Msg == 0x20a) { // WM_MOUSEWHEEL, find the control at screen position m.LParam Point pos = new Point(m.LParam.ToInt32() & 0xffff, m.LParam.ToInt32() >> 16); IntPtr hWnd = WindowFromPoint(pos); if (hWnd != IntPtr.Zero && hWnd != m.HWnd && Control.FromHandle(hWnd) != null) { SendMessage(hWnd, m.Msg, m.WParam, m.LParam); return true; } } return false; #endif } #if MONO #else // P/Invoke declarations [DllImport("user32.dll")] private static extern IntPtr WindowFromPoint(Point pt); [DllImport("user32.dll")] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp); #endif /// <summary> /// Clean up any resources being used. /// </summary> string GetPassword() { if (_DataSourceReferencePassword != null) return _DataSourceReferencePassword; DataSourcePassword dlg = new DataSourcePassword(); if (dlg.ShowDialog() == DialogResult.OK) _DataSourceReferencePassword = dlg.PassPhrase; return _DataSourceReferencePassword; } #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> #endregion /// <summary> /// Uri, Parameters /// </summary> private static Dictionary<Uri, String> _startUpFiles; private const string SET_DEFAULT_PRINTER = "Default"; /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { bool bMono = false; string[] args = Environment.GetCommandLineArgs(); string reportFile = string.Empty; string parameters = string.Empty; string printerName = string.Empty; for (int i = 0; i < args.Length; i++) { string argValue = args[i]; if (argValue.ToLower() == "/m" || argValue.ToLower() == "-m") { // user want to run with mono simplifications bMono = true; } else if (argValue == "-r") { reportFile = args[i + 1]; if (System.IO.Path.GetDirectoryName(reportFile) == string.Empty) { // Try to find the file in the current working directory reportFile = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), System.IO.Path.GetFileName(reportFile)); } } else if (argValue == "-p") { parameters = args[i + 1]; } // if we have nothing or key after -print then we have to set printer by default else if (argValue == "-print") { if (args.Length > i + 1 && !args[i + 1].StartsWith("-")) { printerName = args[i + 1]; } else { printerName = SET_DEFAULT_PRINTER; } } } if (reportFile == string.Empty) { // keep backwards compatiablity from when it worked with only a filename being passed in if (args.Length > 1) { if (args[1].Length >= 5) { reportFile = args[1]; if (System.IO.Path.GetDirectoryName(reportFile) == string.Empty) { // Try to find the file in the current working directory reportFile = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), System.IO.Path.GetFileName(reportFile)); } } } } if (reportFile != string.Empty) { if (File.Exists(reportFile)) { if (!string.IsNullOrWhiteSpace(printerName)) { SilentPrint(reportFile, parameters, printerName); return; } _startUpFiles = new Dictionary<Uri, string>(); _startUpFiles.Add(new Uri(reportFile), parameters); } else { MessageBox.Show(string.Format(Strings.RdlReader_ShowD_ReportNotLoaded, reportFile), Strings.RdlReader_Show_MyFyiReporting, MessageBoxButtons.OK, MessageBoxIcon.Error); } } if (bMono == false) { Application.EnableVisualStyles(); Application.DoEvents(); // when Mono this goes into a loop } Application.Run(new RdlReader(bMono)); } public static void SilentPrint(string reportPath, string parameters, string printerName = null) { var rdlViewer = new fyiReporting.RdlViewer.RdlViewer(); rdlViewer.Visible = false; rdlViewer.SourceFile = new Uri(reportPath); rdlViewer.Parameters = parameters; rdlViewer.Rebuild(); var pd = new PrintDocument(); pd.DocumentName = rdlViewer.SourceFile.LocalPath; pd.PrinterSettings.FromPage = 1; pd.PrinterSettings.ToPage = rdlViewer.PageCount; pd.PrinterSettings.MaximumPage = rdlViewer.PageCount; pd.PrinterSettings.MinimumPage = 1; pd.DefaultPageSettings.Landscape = rdlViewer.PageWidth > rdlViewer.PageHeight; pd.PrintController = new StandardPrintController(); // convert pt to hundredths of an inch. pd.DefaultPageSettings.PaperSize = new PaperSize( "", (int)((rdlViewer.PageWidth / 72.27) * 100), (int)((rdlViewer.PageHeight / 72.27) * 100)); if (!string.IsNullOrWhiteSpace(printerName) && printerName != SET_DEFAULT_PRINTER) { pd.DefaultPageSettings.PrinterSettings.PrinterName = printerName; } try { if (pd.PrinterSettings.PrintRange == PrintRange.Selection) { pd.PrinterSettings.FromPage = rdlViewer.PageCurrent; } rdlViewer.Print(pd); } catch (Exception ex) { #if !DEBUG const string rdlreaderlog = "RdlReaderLog.txt"; if (!File.Exists(rdlreaderlog)) { File.Create(rdlreaderlog).Dispose(); } File.AppendAllLines( rdlreaderlog, new[] { string.Format("[{0}] {1}", DateTime.Now.ToString("dd.MM.yyyy H:mm:ss"), ex.Message) }); #endif Debug.WriteLine(Strings.RdlReader_ShowC_PrintError + ex.Message); } } private void BuildMenus() { // FILE MENU ToolStripMenuItem menuRecentItem = new ToolStripMenuItem(string.Empty); recentFilesToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { menuRecentItem }); fileToolStripMenuItem.DropDownOpening += new EventHandler(menuFile_Popup); // Intialize the recent file menu RecentFilesMenu(); // Edit menu editToolStripMenuItem.DropDownOpening += new EventHandler(this.menuEdit_Popup); // VIEW MENU pageLayoutToolStripMenuItem.DropDownOpening += new EventHandler(this.menuPL_Popup); viewToolStripMenuItem.DropDownOpening += new EventHandler(this.menuView_Popup); // Add the Window menu windowToolStripMenuItem.DropDownOpening += new EventHandler(this.menuWnd_Popup); // MAIN IsMdiContainer = true; } private void menuFile_Popup(object sender, EventArgs e) { // These menus require an MDIChild in order to work bool bEnable = this.MdiChildren.Length > 0 ? true : false; closeToolStripMenuItem.Enabled = bEnable; saveAsToolStripMenuItem.Enabled = bEnable; printToolStripMenuItem.Enabled = bEnable; // Recent File is enabled when there exists some files recentFilesToolStripMenuItem.Enabled = this._RecentFiles.Count <= 0 ? false : true; } private void menuFileClose_Click(object sender, EventArgs e) { MDIChild mc = this.ActiveMdiChild as MDIChild; if (mc != null) mc.Close(); } private void menuFileExit_Click(object sender, EventArgs e) { Environment.Exit(0); } private void menuFileOpen_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = Strings.RdlReader_menuFileOpen_Click_Filter; ofd.FilterIndex = 1; ofd.CheckFileExists = true; ofd.Multiselect = true; if (ofd.ShowDialog(this) == DialogResult.OK) { foreach (string file in ofd.FileNames) { CreateMDIChild(new Uri(file), false); } RecentFilesMenu(); } } private void menuRecentItem_Click(object sender, System.EventArgs e) { ToolStripMenuItem m = (ToolStripMenuItem)sender; Uri file = new Uri(m.Text.Substring(2)); CreateMDIChild(file, true); } // Create an MDI child. Only creates it if not already open private void CreateMDIChild(Uri file, bool bMenuUpdate) { MDIChild mcOpen = null; if (file != null) { foreach (MDIChild mc in this.MdiChildren) { if (file == mc.SourceFile) { // we found it mcOpen = mc; break; } } } if (mcOpen == null) { MDIChild mc = new MDIChild(this.ClientRectangle.Width * 3 / 4, this.ClientRectangle.Height * 3 / 4); mc.MdiParent = this; mc.Viewer.GetDataSourceReferencePassword = _GetPassword; mc.SourceFile = file; mc.Text = file == null ? string.Empty : file.LocalPath; NoteRecentFiles(file, bMenuUpdate); mc.Show(); } else mcOpen.Activate(); } private void menuFilePrint_Click(object sender, EventArgs e) { MDIChild mc = this.ActiveMdiChild as MDIChild; if (mc == null) return; if (printChild != null) // already printing { MessageBox.Show(Strings.RdlReader_ShowC_PrintOneFile); return; } printChild = mc; PrintDocument pd = new PrintDocument(); pd.DocumentName = mc.SourceFile.LocalPath; pd.PrinterSettings.FromPage = 1; pd.PrinterSettings.ToPage = mc.Viewer.PageCount; pd.PrinterSettings.MaximumPage = mc.Viewer.PageCount; pd.PrinterSettings.MinimumPage = 1; if (mc.Viewer.PageWidth > mc.Viewer.PageHeight) pd.DefaultPageSettings.Landscape = true; else pd.DefaultPageSettings.Landscape = false; PrintDialog dlg = new PrintDialog(); dlg.Document = pd; dlg.AllowSelection = true; dlg.AllowSomePages = true; if (dlg.ShowDialog() == DialogResult.OK) { try { if (pd.PrinterSettings.PrintRange == PrintRange.Selection) { pd.PrinterSettings.FromPage = mc.Viewer.PageCurrent; } mc.Viewer.Print(pd); } catch (Exception ex) { MessageBox.Show(Strings.RdlReader_ShowC_PrintError + ex.Message); } } printChild = null; } private void menuFileSaveAs_Click(object sender, EventArgs e) { MDIChild mc = this.ActiveMdiChild as MDIChild; if (mc == null) return; SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = Strings.RdlReader_menuFileSaveAs_Click_FilesFilter; sfd.FilterIndex = 1; Uri file = mc.SourceFile; if (file != null) { int index = file.LocalPath.LastIndexOf('.'); if (index > 1) sfd.FileName = file.LocalPath.Substring(0, index) + ".pdf"; else sfd.FileName = "*.pdf"; } else sfd.FileName = "*.pdf"; if (sfd.ShowDialog(this) != DialogResult.OK) return; // save the report in a rendered format string ext = null; int i = sfd.FileName.LastIndexOf('.'); if (i < 1) ext = string.Empty; else ext = sfd.FileName.Substring(i + 1).ToLower(); OutputPresentationType type = OutputPresentationType.Internal; switch (ext) { case "pdf": type = OutputPresentationType.PDF; break; case "xml": type = OutputPresentationType.XML; break; case "html": case "htm": type = OutputPresentationType.HTML; break; case "csv": type = OutputPresentationType.CSV; break; case "rtf": type = OutputPresentationType.RTF; break; case "mht": case "mhtml": type = OutputPresentationType.MHTML; break; case "xlsx": type = sfd.FilterIndex == 7 ? OutputPresentationType.ExcelTableOnly : OutputPresentationType.Excel2007; break; case "tif": case "tiff": type = OutputPresentationType.TIF; break; default: MessageBox.Show(this, String.Format(Strings.RdlReader_SaveG_NotValidFileType, sfd.FileName), Strings.RdlReader_SaveG_SaveAsError, MessageBoxButtons.OK, MessageBoxIcon.Error); break; } if (type == OutputPresentationType.TIF) { DialogResult dr = MessageBox.Show(this, Strings.RdlReader_ShowF_WantSaveColorsInTIF, Strings.RdlReader_ShowF_Export, MessageBoxButtons.YesNoCancel); if (dr == DialogResult.No) type = OutputPresentationType.TIFBW; else if (dr == DialogResult.Cancel) return; } if (type != OutputPresentationType.Internal) { try { mc.Viewer.SaveAs(sfd.FileName, type); } catch (Exception ex) { MessageBox.Show(this, ex.Message, Strings.RdlReader_SaveG_SaveAsError, MessageBoxButtons.OK, MessageBoxIcon.Error); } } return; } private void menuHelpAbout_Click(object sender, System.EventArgs ea) { DialogAbout dlg = new DialogAbout(); dlg.ShowDialog(); } private void menuCopy_Click(object sender, System.EventArgs ea) { MDIChild mc = this.ActiveMdiChild as MDIChild; if (mc == null || !mc.Viewer.CanCopy) return; mc.Viewer.Copy(); } private void menuFind_Click(object sender, System.EventArgs ea) { MDIChild mc = this.ActiveMdiChild as MDIChild; if (mc == null) return; if (!mc.Viewer.ShowFindPanel) mc.Viewer.ShowFindPanel = true; mc.Viewer.FindNext(); } private void menuSelection_Click(object sender, System.EventArgs ea) { MDIChild mc = this.ActiveMdiChild as MDIChild; if (mc == null) return; mc.Viewer.SelectTool = !mc.Viewer.SelectTool; } private void menuEdit_Popup(object sender, EventArgs e) { // These menus require an MDIChild in order to work bool bEnable = this.MdiChildren.Length > 0 ? true : false; copyToolStripMenuItem.Enabled = bEnable; findToolStripMenuItem.Enabled = bEnable; selectionToolToolStripMenuItem.Enabled = bEnable; if (!bEnable) return; MDIChild mc = this.ActiveMdiChild as MDIChild; copyToolStripMenuItem.Enabled = mc.Viewer.CanCopy; selectionToolToolStripMenuItem.Checked = mc.Viewer.SelectTool; } private void menuView_Popup(object sender, EventArgs e) { // These menus require an MDIChild in order to work bool bEnable = this.MdiChildren.Length > 0 ? true : false; zoomToToolStripMenuItem.Enabled = bEnable; actualSizeToolStripMenuItem.Enabled = bEnable; fitPageToolStripMenuItem.Enabled = bEnable; fitWidthToolStripMenuItem.Enabled = bEnable; pageLayoutToolStripMenuItem.Enabled = bEnable; if (!bEnable) return; // Now handle checking the correct sizing menu MDIChild mc = this.ActiveMdiChild as MDIChild; actualSizeToolStripMenuItem.Checked = fitPageToolStripMenuItem.Checked = fitWidthToolStripMenuItem.Checked = false; if (mc.Viewer.ZoomMode == ZoomEnum.FitWidth) fitWidthToolStripMenuItem.Checked = true; else if (mc.Viewer.ZoomMode == ZoomEnum.FitPage) fitPageToolStripMenuItem.Checked = true; else if (mc.Viewer.Zoom == 1) actualSizeToolStripMenuItem.Checked = true; } private void menuPL_Popup(object sender, EventArgs e) { MDIChild mc = this.ActiveMdiChild as MDIChild; if (mc == null) return; singlePageToolStripMenuItem.Checked = continuousToolStripMenuItem.Checked = facingToolStripMenuItem.Checked = continuousFacingToolStripMenuItem.Checked = false; ; switch (mc.Viewer.ScrollMode) { case ScrollModeEnum.Continuous: continuousToolStripMenuItem.Checked = true; break; case ScrollModeEnum.ContinuousFacing: continuousFacingToolStripMenuItem.Checked = true; break; case ScrollModeEnum.Facing: facingToolStripMenuItem.Checked = true; break; case ScrollModeEnum.SinglePage: singlePageToolStripMenuItem.Checked = true; break; } } private void menuPLZoomTo_Click(object sender, EventArgs e) { MDIChild mc = this.ActiveMdiChild as MDIChild; if (mc == null) return; ZoomTo dlg = new ZoomTo(mc.Viewer); dlg.StartPosition = FormStartPosition.CenterParent; dlg.ShowDialog(); } private void menuPLActualSize_Click(object sender, EventArgs e) { MDIChild mc = this.ActiveMdiChild as MDIChild; if (mc != null) mc.Viewer.Zoom = 1; } private void menuPLFitPage_Click(object sender, EventArgs e) { MDIChild mc = this.ActiveMdiChild as MDIChild; if (mc != null) mc.Viewer.ZoomMode = ZoomEnum.FitPage; } private void menuPLFitWidth_Click(object sender, EventArgs e) { MDIChild mc = this.ActiveMdiChild as MDIChild; if (mc != null) mc.Viewer.ZoomMode = ZoomEnum.FitWidth; } private void menuPLSinglePage_Click(object sender, EventArgs e) { MDIChild mc = this.ActiveMdiChild as MDIChild; if (mc != null) mc.Viewer.ScrollMode = ScrollModeEnum.SinglePage; } private void menuPLContinuous_Click(object sender, EventArgs e) { MDIChild mc = this.ActiveMdiChild as MDIChild; if (mc != null) mc.Viewer.ScrollMode = ScrollModeEnum.Continuous; } private void menuPLFacing_Click(object sender, EventArgs e) { MDIChild mc = this.ActiveMdiChild as MDIChild; if (mc != null) mc.Viewer.ScrollMode = ScrollModeEnum.Facing; } private void menuPLContinuousFacing_Click(object sender, EventArgs e) { MDIChild mc = this.ActiveMdiChild as MDIChild; if (mc != null) mc.Viewer.ScrollMode = ScrollModeEnum.ContinuousFacing; } private void menuWnd_Popup(object sender, EventArgs e) { // These menus require an MDIChild in order to work bool bEnable = this.MdiChildren.Length > 0 ? true : false; cascadeToolStripMenuItem.Enabled = bEnable; tileToolStripMenuItem.Enabled = bEnable; closeAllToolStripMenuItem.Enabled = bEnable; } private void menuWndCascade_Click(object sender, EventArgs e) { this.LayoutMdi(MdiLayout.Cascade); } private void menuWndCloseAll_Click(object sender, EventArgs e) { foreach (Form f in this.MdiChildren) { f.Close(); } } private void menuWndTileH_Click(object sender, EventArgs e) { this.LayoutMdi(MdiLayout.TileHorizontal); } private void menuWndTileV_Click(object sender, EventArgs e) { this.LayoutMdi(MdiLayout.TileVertical); } private void RdlReader_Closing(object sender, System.ComponentModel.CancelEventArgs e) { SaveStartupState(); } private void NoteRecentFiles(Uri name, bool bResetMenu) { if (name == null) { return; } if (_RecentFiles.ContainsValue(name.LocalPath)) { // need to move it to top of list; so remove old one int loc = _RecentFiles.IndexOfValue(name.LocalPath); _RecentFiles.RemoveAt(loc); } if (_RecentFiles.Count >= 5) { _RecentFiles.RemoveAt(0); // remove the first entry } _RecentFiles.Add(DateTime.Now, name.LocalPath); if (bResetMenu) RecentFilesMenu(); return; } private void RecentFilesMenu() { recentFilesToolStripMenuItem.DropDownItems.Clear(); int mi = 1; for (int i = _RecentFiles.Count - 1; i >= 0; i--) { string menuText = string.Format("&{0} {1}", mi++, (string)(_RecentFiles.GetValueList()[i])); ToolStripMenuItem m = new ToolStripMenuItem(menuText); m.Click += new EventHandler(this.menuRecentItem_Click); recentFilesToolStripMenuItem.DropDownItems.Add(m); } } private void GetStartupState() { string optFileName = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "readerstate.xml"); _RecentFiles = new SortedList(); _CurrentFiles = new Dictionary<Uri, string>(); if (_startUpFiles != null) { foreach (var dict in _startUpFiles) { _CurrentFiles.Add(dict.Key, dict.Value); } } try { XmlDocument xDoc = new XmlDocument(); xDoc.PreserveWhitespace = false; xDoc.Load(optFileName); XmlNode xNode; xNode = xDoc.SelectSingleNode("//readerstate"); // Loop thru all the child nodes foreach (XmlNode xNodeLoop in xNode.ChildNodes) { switch (xNodeLoop.Name) { case "RecentFiles": DateTime now = DateTime.Now; now = now.Subtract(new TimeSpan(0, 1, 0, 0, 0)); // subtract an hour foreach (XmlNode xN in xNodeLoop.ChildNodes) { string file = xN.InnerText.Trim(); if (File.Exists(file)) // only add it if it exists { _RecentFiles.Add(now, file); now = now.AddSeconds(1); } } break; case "CurrentFiles": if (_startUpFiles != null) break; // not add if startUpFiles exists foreach (XmlNode xN in xNodeLoop.ChildNodes) { string file = xN.InnerText.Trim(); if (File.Exists(file)) // only add it if it exists { if (_CurrentFiles.ContainsKey(new Uri(file)) == false) { _CurrentFiles.Add(new Uri(file), string.Empty); } } } break; default: break; } } } catch { // Didn't sucessfully get the startup state but don't really care } return; } private void SaveStartupState() { try { XmlDocument xDoc = new XmlDocument(); XmlProcessingInstruction xPI; xPI = xDoc.CreateProcessingInstruction("xml", "version='1.0' encoding='UTF-8'"); xDoc.AppendChild(xPI); XmlNode xDS = xDoc.CreateElement("readerstate"); xDoc.AppendChild(xDS); XmlNode xN; // Loop thru the current files XmlNode xFiles = xDoc.CreateElement("CurrentFiles"); xDS.AppendChild(xFiles); foreach (MDIChild mc in this.MdiChildren) { Uri file = mc.SourceFile; if (file == null) continue; xN = xDoc.CreateElement("file"); xN.InnerText = file.LocalPath; xFiles.AppendChild(xN); } // Loop thru recent files list xFiles = xDoc.CreateElement("RecentFiles"); xDS.AppendChild(xFiles); foreach (string f in _RecentFiles.Values) { xN = xDoc.CreateElement("file"); xN.InnerText = f; xFiles.AppendChild(xN); } string optFileName = AppDomain.CurrentDomain.BaseDirectory + "readerstate.xml"; xDoc.Save(optFileName); } catch { } // still want to leave even on error return; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // SortQueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Threading; namespace System.Linq.Parallel { /// <summary> /// The query operator for OrderBy and ThenBy. /// </summary> /// <typeparam name="TInputOutput"></typeparam> /// <typeparam name="TSortKey"></typeparam> internal sealed class SortQueryOperator<TInputOutput, TSortKey> : UnaryQueryOperator<TInputOutput, TInputOutput>, IOrderedEnumerable<TInputOutput> { private readonly Func<TInputOutput, TSortKey> _keySelector; // Key selector used when sorting. private readonly IComparer<TSortKey> _comparer; // Key comparison logic to use during sorting. //--------------------------------------------------------------------------------------- // Instantiates a new sort operator. // internal SortQueryOperator(IEnumerable<TInputOutput> source, Func<TInputOutput, TSortKey> keySelector, IComparer<TSortKey> comparer, bool descending) : base(source, true) { Debug.Assert(keySelector != null, "key selector must not be null"); _keySelector = keySelector; // If a comparer wasn't supplied, we use the default one for the key type. if (comparer == null) { _comparer = Util.GetDefaultComparer<TSortKey>(); } else { _comparer = comparer; } if (descending) { _comparer = new ReverseComparer<TSortKey>(_comparer); } SetOrdinalIndexState(OrdinalIndexState.Shuffled); } //--------------------------------------------------------------------------------------- // IOrderedEnumerable method for nesting an order by operator inside another. // IOrderedEnumerable<TInputOutput> IOrderedEnumerable<TInputOutput>.CreateOrderedEnumerable<TKey2>( Func<TInputOutput, TKey2> key2Selector, IComparer<TKey2> key2Comparer, bool descending) { key2Comparer = key2Comparer ?? Util.GetDefaultComparer<TKey2>(); if (descending) { key2Comparer = new ReverseComparer<TKey2>(key2Comparer); } IComparer<Pair<TSortKey, TKey2>> pairComparer = new PairComparer<TSortKey, TKey2>(_comparer, key2Comparer); Func<TInputOutput, Pair<TSortKey, TKey2>> pairKeySelector = (TInputOutput elem) => new Pair<TSortKey, TKey2>(_keySelector(elem), key2Selector(elem)); return new SortQueryOperator<TInputOutput, Pair<TSortKey, TKey2>>(Child, pairKeySelector, pairComparer, false); } //--------------------------------------------------------------------------------------- // Accessor the the key selector. // internal Func<TInputOutput, TSortKey> KeySelector { get { return _keySelector; } } //--------------------------------------------------------------------------------------- // Accessor the the key comparer. // internal IComparer<TSortKey> KeyComparer { get { return _comparer; } } //--------------------------------------------------------------------------------------- // Opens the current operator. This involves opening the child operator tree, enumerating // the results, sorting them, and then returning an enumerator that walks the result. // internal override QueryResults<TInputOutput> Open(QuerySettings settings, bool preferStriping) { QueryResults<TInputOutput> childQueryResults = Child.Open(settings, false); return new SortQueryOperatorResults<TInputOutput, TSortKey>(childQueryResults, this, settings, preferStriping); } internal override void WrapPartitionedStream<TKey>( PartitionedStream<TInputOutput, TKey> inputStream, IPartitionedStreamRecipient<TInputOutput> recipient, bool preferStriping, QuerySettings settings) { PartitionedStream<TInputOutput, TSortKey> outputStream = new PartitionedStream<TInputOutput, TSortKey>(inputStream.PartitionCount, this._comparer, OrdinalIndexState); for (int i = 0; i < outputStream.PartitionCount; i++) { outputStream[i] = new SortQueryOperatorEnumerator<TInputOutput, TKey, TSortKey>( inputStream[i], _keySelector, _comparer); } recipient.Receive<TSortKey>(outputStream); } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // internal override IEnumerable<TInputOutput> AsSequentialQuery(CancellationToken token) { IEnumerable<TInputOutput> wrappedChild = CancellableEnumerable.Wrap(Child.AsSequentialQuery(token), token); return wrappedChild.OrderBy(_keySelector, _comparer); } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return false; } } } internal class SortQueryOperatorResults<TInputOutput, TSortKey> : QueryResults<TInputOutput> { protected QueryResults<TInputOutput> _childQueryResults; // Results of the child query private SortQueryOperator<TInputOutput, TSortKey> _op; // Operator that generated these results private QuerySettings _settings; // Settings collected from the query private bool _preferStriping; // If the results are indexible, should we use striping when partitioning them internal SortQueryOperatorResults( QueryResults<TInputOutput> childQueryResults, SortQueryOperator<TInputOutput, TSortKey> op, QuerySettings settings, bool preferStriping) { _childQueryResults = childQueryResults; _op = op; _settings = settings; _preferStriping = preferStriping; } internal override bool IsIndexible { get { return false; } } internal override void GivePartitionedStream(IPartitionedStreamRecipient<TInputOutput> recipient) { _childQueryResults.GivePartitionedStream(new ChildResultsRecipient(recipient, _op, _settings)); } private class ChildResultsRecipient : IPartitionedStreamRecipient<TInputOutput> { private IPartitionedStreamRecipient<TInputOutput> _outputRecipient; private SortQueryOperator<TInputOutput, TSortKey> _op; private QuerySettings _settings; internal ChildResultsRecipient(IPartitionedStreamRecipient<TInputOutput> outputRecipient, SortQueryOperator<TInputOutput, TSortKey> op, QuerySettings settings) { _outputRecipient = outputRecipient; _op = op; _settings = settings; } public void Receive<TKey>(PartitionedStream<TInputOutput, TKey> childPartitionedStream) { _op.WrapPartitionedStream(childPartitionedStream, _outputRecipient, false, _settings); } } } //--------------------------------------------------------------------------------------- // This enumerator performs sorting based on a key selection and comparison routine. // internal class SortQueryOperatorEnumerator<TInputOutput, TKey, TSortKey> : QueryOperatorEnumerator<TInputOutput, TSortKey> { private readonly QueryOperatorEnumerator<TInputOutput, TKey> _source; // Data source to sort. private readonly Func<TInputOutput, TSortKey> _keySelector; // Key selector used when sorting. private readonly IComparer<TSortKey> _keyComparer; // Key comparison logic to use during sorting. //--------------------------------------------------------------------------------------- // Instantiates a new sort operator enumerator. // internal SortQueryOperatorEnumerator(QueryOperatorEnumerator<TInputOutput, TKey> source, Func<TInputOutput, TSortKey> keySelector, IComparer<TSortKey> keyComparer) { Debug.Assert(source != null); Debug.Assert(keySelector != null, "need a key comparer"); Debug.Assert(keyComparer != null, "expected a compiled operator"); _source = source; _keySelector = keySelector; _keyComparer = keyComparer; } //--------------------------------------------------------------------------------------- // Accessor for the key comparison routine. // public IComparer<TSortKey> KeyComparer { get { return _keyComparer; } } //--------------------------------------------------------------------------------------- // Moves to the next element in the sorted output. When called for the first time, the // descendents in the sort's child tree are executed entirely, the results accumulated // in memory, and the data sorted. // internal override bool MoveNext(ref TInputOutput currentElement, ref TSortKey currentKey) { Debug.Assert(_source != null); TKey keyUnused = default(TKey); if (!_source.MoveNext(ref currentElement, ref keyUnused)) { return false; } currentKey = _keySelector(currentElement); return true; } protected override void Dispose(bool disposing) { Debug.Assert(_source != null); _source.Dispose(); } } }
////////////////////////////////////////////////////////////////////////// // Code Named: VG-Ripper // -------------------------------------------------------------------------------------------------------------------- // <copyright file="Options.cs" company="The Watcher"> // Copyright (c) The Watcher Partial Rights Reserved. // This software is licensed under the MIT license. See license.txt for details. // </copyright> // <summary> // Code Named: VG-Ripper // Function : Extracts Images posted on RiP forums and attempts to fetch them to disk. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Ripper { using System; using System.Reflection; using System.Resources; using System.Windows.Forms; using Ripper.Core.Components; /// <summary> /// The Options Window /// </summary> public partial class Options : Form { /// <summary> /// The resource manager /// </summary> private ResourceManager resourceManager; /// <summary> /// Initializes a new instance of the <see cref="Options"/> class. /// </summary> public Options() { this.InitializeComponent(); this.LoadSettings(); } /// <summary> /// Set Options /// </summary> public void LoadSettings() { #if (RIPRIPPERX) checkBox9.Enabled = false; showTrayPopups.Enabled = false; checkBox10.Enabled = false; #endif var cacheController = CacheController.Instance(); // Load "Show Tray PopUps" Setting this.showTrayPopups.Checked = cacheController.UserSettings.ShowPopUps; // Load "Download Folder" Setting this.textBox2.Text = cacheController.UserSettings.DownloadFolder; // Load "Thread Limit" Setting this.numericUDThreads.Text = cacheController.UserSettings.ThreadLimit.ToString(); ThreadManager.GetInstance().SetThreadThreshHold(Convert.ToInt32(this.numericUDThreads.Text)); // min. Image Count for Thanks this.numericUDThanks.Text = cacheController.UserSettings.MinImageCount.ToString(); // Load "Create Subdirctories" Setting this.checkBox1.Checked = cacheController.UserSettings.SubDirs; // Load "Automaticly Thank You Button" Setting if (cacheController.UserSettings.AutoThank) { this.checkBox8.Checked = true; } else { this.checkBox8.Checked = false; this.numericUDThanks.Enabled = false; } // Load "Clipboard Watch" Setting this.checkBox10.Checked = cacheController.UserSettings.ClipBWatch; // Load "Always on Top" Setting this.checkBox5.Checked = cacheController.UserSettings.TopMost; this.TopMost = cacheController.UserSettings.TopMost; // Load "Download each post in its own folder" Setting this.mDownInSepFolderChk.Checked = cacheController.UserSettings.DownInSepFolder; if (!this.checkBox1.Checked) { this.mDownInSepFolderChk.Checked = false; this.mDownInSepFolderChk.Enabled = false; } // Load "Save Ripped posts for checking" Setting this.saveHistoryChk.Checked = cacheController.UserSettings.SavePids; // Load "Show Downloads Complete PopUp" Setting this.checkBox9.Checked = cacheController.UserSettings.ShowCompletePopUp; // Load Show Last Download Image Setting this.checkBox11.Checked = cacheController.UserSettings.ShowLastDownloaded; // Load Language Setting try { switch (cacheController.UserSettings.Language) { case "de-DE": resourceManager = new ResourceManager("Ripper.Languages.german", Assembly.GetExecutingAssembly()); languageSelector.SelectedIndex = 0; pictureBox2.Image = Languages.english.de; break; case "fr-FR": resourceManager = new ResourceManager("Ripper.Languages.french", Assembly.GetExecutingAssembly()); languageSelector.SelectedIndex = 1; pictureBox2.Image = Languages.english.fr; break; case "en-EN": resourceManager = new ResourceManager("Ripper.Languages.english", Assembly.GetExecutingAssembly()); languageSelector.SelectedIndex = 2; pictureBox2.Image = Languages.english.us; break; /*case "zh-CN": resourceManager = new ResourceManager("Ripper.Languages.chinese-cn", Assembly.GetExecutingAssembly()); languageSelector.SelectedIndex = 3; pictureBox2.Image = Languages.english.cn; break;*/ default: resourceManager = new ResourceManager("Ripper.Languages.english", Assembly.GetExecutingAssembly()); languageSelector.SelectedIndex = 2; pictureBox2.Image = Languages.english.us; break; } AdjustCulture(); } catch (Exception) { languageSelector.SelectedIndex = 2; pictureBox2.Image = Languages.english.us; } } /// <summary> /// Adjusts the culture. /// </summary> private void AdjustCulture() { this.groupBox1.Text = this.resourceManager.GetString("downloadOptions", this.culture); this.label2.Text = this.resourceManager.GetString("lblDownloadFolder", this.culture); this.button4.Text = this.resourceManager.GetString("btnBrowse", this.culture); this.checkBox1.Text = this.resourceManager.GetString("chbSubdirectories", this.culture); this.checkBox8.Text = this.resourceManager.GetString("chbAutoTKButton", this.culture); this.showTrayPopups.Text = this.resourceManager.GetString("chbShowPopUps", this.culture); this.checkBox5.Text = this.resourceManager.GetString("chbAlwaysOnTop", this.culture); this.checkBox9.Text = this.resourceManager.GetString("chbShowDCPopUps", this.culture); this.mDownInSepFolderChk.Text = this.resourceManager.GetString("chbSubThreadRip", this.culture); this.saveHistoryChk.Text = this.resourceManager.GetString("chbSaveHistory", this.culture); this.label6.Text = this.resourceManager.GetString("lblThreadLimit", this.culture); this.label1.Text = this.resourceManager.GetString("lblminImageCount", this.culture); this.groupBox3.Text = this.resourceManager.GetString("gbMainOptions", this.culture); this.checkBox11.Text = this.resourceManager.GetString("ShowLastDownloaded", this.culture); this.checkBox10.Text = this.resourceManager.GetString("clipboardWatch"); } /// <summary> /// Set Language Strings /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void LanguageSelectorSelectedIndexChanged(object sender, EventArgs e) { switch (this.languageSelector.SelectedIndex) { case 0: this.pictureBox2.Image = Languages.english.de; break; case 1: this.pictureBox2.Image = Languages.english.fr; break; case 2: this.pictureBox2.Image = Languages.english.us; break; case 3: this.pictureBox2.Image = Languages.english.cn; break; } } /// <summary> /// Open Browse Download Folder Dialog /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private void Button4Click(object sender, EventArgs e) { var cacheController = CacheController.Instance(); this.FBD.ShowDialog(this); if (this.FBD.SelectedPath.Length <= 1) { return; } this.textBox2.Text = this.FBD.SelectedPath; SettingsHelper.SaveSetting("Download Folder", this.textBox2.Text); cacheController.UserSettings.DownloadFolder = this.textBox2.Text; } /// <summary> /// Close Dialog and Save Changes /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OkButtonClick(object sender, EventArgs e) { string mbThreadNum = resourceManager.GetString("mbThreadNum"), mbThreadbetw = resourceManager.GetString("mbThreadbetw"), mbNum = resourceManager.GetString("mbNum"); if (!Utility.IsNumeric(numericUDThreads.Text)) { MessageBox.Show(this, mbThreadNum); return; } if (!Utility.IsNumeric(numericUDThanks.Text)) { MessageBox.Show(this, mbNum); return; } if (Convert.ToInt32(numericUDThreads.Text) > 20 || Convert.ToInt32(numericUDThreads.Text) < 1) { MessageBox.Show(this, mbThreadbetw); return; } ThreadManager.GetInstance().SetThreadThreshHold(Convert.ToInt32(numericUDThreads.Text)); SettingsHelper.SaveSetting("Thread Limit", numericUDThreads.Text); SettingsHelper.SaveSetting("minImageCountThanks", numericUDThanks.Text); SettingsHelper.SaveSetting("SubDirs", checkBox1.Checked.ToString()); SettingsHelper.SaveSetting("Auto TK Button", checkBox8.Checked.ToString()); SettingsHelper.SaveSetting("clipBoardWatch", checkBox10.Checked.ToString()); SettingsHelper.SaveSetting("Show Popups", showTrayPopups.Checked.ToString()); SettingsHelper.SaveSetting("Always OnTop", checkBox5.Checked.ToString()); SettingsHelper.SaveSetting("DownInSepFolder", mDownInSepFolderChk.Checked.ToString()); SettingsHelper.SaveSetting("SaveRippedPosts", saveHistoryChk.Checked.ToString()); SettingsHelper.SaveSetting("Show Downloads Complete PopUp", checkBox9.Checked.ToString()); SettingsHelper.SaveSetting("ShowLastDownloaded", checkBox11.Checked.ToString()); switch (languageSelector.SelectedIndex) { case 0: SettingsHelper.SaveSetting("UserLanguage", "de-DE"); break; case 1: SettingsHelper.SaveSetting("UserLanguage", "fr-FR"); break; case 2: SettingsHelper.SaveSetting("UserLanguage", "en-EN"); break; /*case 3: SettingsHelper.SaveSetting("UserLanguage", "zh-CN"); break;*/ } Close(); } /// <summary> /// Checks the box8 checked changed. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void CheckBox8CheckedChanged(object sender, EventArgs e) { this.numericUDThanks.Enabled = this.checkBox8.Checked; } /// <summary> /// Checks the box1 checked changed. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void CheckBox1CheckedChanged(object sender, EventArgs e) { if (checkBox1.Checked) { mDownInSepFolderChk.Enabled = true; } else { mDownInSepFolderChk.Enabled = false; mDownInSepFolderChk.Checked = false; } } /// <summary> /// Check if Input is a Number between 1-20 /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void NumericUdThreadsValueChanged(object sender, EventArgs e) { if (Convert.ToInt32(numericUDThreads.Text) <= 20 && Convert.ToInt32(numericUDThreads.Text) >= 1) { return; } MessageBox.Show(this, this.resourceManager.GetString("mbThreadbetw")); this.numericUDThreads.Text = "3"; } } }
// This file was generated by CSLA Object Generator - CslaGenFork v4.5 // // Filename: CircList // ObjectType: CircList // CSLAType: ReadOnlyCollection using System; using System.Data; using System.Data.SqlClient; using Csla; using Csla.Data; using DocStore.Business.Util; using UsingLibrary; namespace DocStore.Business.Circulations { /// <summary> /// Collection of circulations of documents and folders (read only list).<br/> /// This is a generated <see cref="CircList"/> business object. /// This class is a root collection. /// </summary> /// <remarks> /// The items of the collection are <see cref="CircInfo"/> objects. /// </remarks> [Serializable] #if WINFORMS public partial class CircList : MyReadOnlyBindingListBase<CircList, CircInfo>, IHaveInterface, IHaveGenericInterface<CircList> #else public partial class CircList : MyReadOnlyListBase<CircList, CircInfo>, IHaveInterface, IHaveGenericInterface<CircList> #endif { #region Collection Business Methods /// <summary> /// Determines whether a <see cref="CircInfo"/> item is in the collection. /// </summary> /// <param name="circID">The CircID of the item to search for.</param> /// <returns><c>true</c> if the CircInfo is a collection item; otherwise, <c>false</c>.</returns> public bool Contains(int circID) { foreach (var circInfo in this) { if (circInfo.CircID == circID) { return true; } } return false; } #endregion #region Factory Methods /// <summary> /// Factory method. Loads a <see cref="CircList"/> collection, based on given parameters. /// </summary> /// <param name="docID">The DocID parameter of the CircList to fetch.</param> /// <param name="folderID">The FolderID parameter of the CircList to fetch.</param> /// <returns>A reference to the fetched <see cref="CircList"/> collection.</returns> public static CircList GetCircList(int? docID, int? folderID) { return DataPortal.Fetch<CircList>(new CriteriaGetByObject(docID, folderID)); } /// <summary> /// Factory method. Asynchronously loads a <see cref="CircList"/> collection, based on given parameters. /// </summary> /// <param name="docID">The DocID parameter of the CircList to fetch.</param> /// <param name="folderID">The FolderID parameter of the CircList to fetch.</param> /// <param name="callback">The completion callback method.</param> public static void GetCircList(int? docID, int? folderID, EventHandler<DataPortalResult<CircList>> callback) { DataPortal.BeginFetch<CircList>(new CriteriaGetByObject(docID, folderID), callback); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="CircList"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public CircList() { // Use factory methods and do not use direct creation. var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; AllowNew = false; AllowEdit = false; AllowRemove = false; RaiseListChangedEvents = rlce; } #endregion #region Nested Criteria /// <summary> /// CriteriaGetByObject criteria. /// </summary> [Serializable] protected class CriteriaGetByObject : CriteriaBase<CriteriaGetByObject> { /// <summary> /// Maintains metadata about <see cref="DocID"/> property. /// </summary> public static readonly PropertyInfo<int?> DocIDProperty = RegisterProperty<int?>(p => p.DocID); /// <summary> /// Gets or sets the Doc ID. /// </summary> /// <value>The Doc ID.</value> public int? DocID { get { return ReadProperty(DocIDProperty); } set { LoadProperty(DocIDProperty, value); } } /// <summary> /// Maintains metadata about <see cref="FolderID"/> property. /// </summary> public static readonly PropertyInfo<int?> FolderIDProperty = RegisterProperty<int?>(p => p.FolderID); /// <summary> /// Gets or sets the Folder ID. /// </summary> /// <value>The Folder ID.</value> public int? FolderID { get { return ReadProperty(FolderIDProperty); } set { LoadProperty(FolderIDProperty, value); } } /// <summary> /// Initializes a new instance of the <see cref="CriteriaGetByObject"/> class. /// </summary> /// <remarks> A parameterless constructor is required by the MobileFormatter.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public CriteriaGetByObject() { } /// <summary> /// Initializes a new instance of the <see cref="CriteriaGetByObject"/> class. /// </summary> /// <param name="docID">The DocID.</param> /// <param name="folderID">The FolderID.</param> public CriteriaGetByObject(int? docID, int? folderID) { DocID = docID; FolderID = folderID; } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.</returns> public override bool Equals(object obj) { if (obj is CriteriaGetByObject) { var c = (CriteriaGetByObject) obj; if (!DocID.Equals(c.DocID)) return false; if (!FolderID.Equals(c.FolderID)) return false; return true; } return false; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns>An hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns> public override int GetHashCode() { return string.Concat("CriteriaGetByObject", DocID.ToString(), FolderID.ToString()).GetHashCode(); } } #endregion #region Data Access /// <summary> /// Loads a <see cref="CircList"/> collection from the database, based on given criteria. /// </summary> /// <param name="crit">The fetch criteria.</param> protected void DataPortal_Fetch(CriteriaGetByObject crit) { using (var ctx = ConnectionManager<SqlConnection>.GetManager(Database.DocStoreConnection, false)) { using (var cmd = new SqlCommand("GetCircList", ctx.Connection)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@DocID", crit.DocID == null ? (object)DBNull.Value : crit.DocID.Value).DbType = DbType.Int32; cmd.Parameters.AddWithValue("@FolderID", crit.FolderID == null ? (object)DBNull.Value : crit.FolderID.Value).DbType = DbType.Int32; var args = new DataPortalHookArgs(cmd, crit); OnFetchPre(args); LoadCollection(cmd); OnFetchPost(args); } } } private void LoadCollection(SqlCommand cmd) { using (var dr = new SafeDataReader(cmd.ExecuteReader())) { Fetch(dr); } } /// <summary> /// Loads all <see cref="CircList"/> collection items from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { IsReadOnly = false; var rlce = RaiseListChangedEvents; RaiseListChangedEvents = false; while (dr.Read()) { Add(CircInfo.GetCircInfo(dr)); } RaiseListChangedEvents = rlce; IsReadOnly = true; } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); #endregion } }
#region [ license and copyright boilerplate ] /* MiscCorLib.Collections.Generic ConvertStructCollection.cs Copyright (c) 2016 Jim Kropa (https://github.com/jimkropa) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion namespace MiscCorLib.Collections.Generic { using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using JetBrains.Annotations; /// <summary> /// A set of static extension methods for converting generic /// collections of <see cref="ValueType"/> (a.k.a. "struct" values) /// into string arrays and delimited strings, /// optionally removing duplicate entries. /// </summary> /// <remarks> /// <para> /// For reverse effect, use static extension /// methods in <see cref="ConvertStrings"/> /// and <see cref="ConvertDelimitedString"/>. /// </para> /// </remarks> [CLSCompliant(true)] public static class ConvertStructCollection { /// <summary> /// A value to use when translating between collections of strings /// and generic collections of <see cref="ValueType"/>, /// indicating to preserve duplicate values /// in the resulting collection by default. /// </summary> public const bool DefaultRemoveDuplicates = false; #region [ Overloads of ToStringArray Extension Method ] /// <summary> /// Converts a generic collection of <see cref="ValueType"/> /// to a one-dimensional array of <see cref="string"/>, /// by calling the <see cref="ValueType.ToString"/> /// method on each item in the source collection, /// and optionally removing any duplicates. /// </summary> /// <param name="collection"> /// A generic collection of <see cref="ValueType"/> items. /// </param> /// <param name="removeDuplicates"> /// Whether to remove duplicate items in the array returned. /// Parameter is optional, default value is <c>false</c>. /// </param> /// <typeparam name="T"> /// The generic type of <paramref name="collection"/>, /// derived from <see cref="ValueType"/>. /// </typeparam> /// <returns> /// An array of strings with null or empty values omitted, /// and duplicates omitted unless the /// <paramref name="removeDuplicates"/> /// value is <c>true</c>. /// </returns> public static string[] ToStringArray<T>( this IEnumerable<T> collection, bool removeDuplicates = DefaultRemoveDuplicates) where T : struct { return collection.ToStringArray(null, removeDuplicates); } /// <summary> /// Converts a generic collection of <see cref="ValueType"/> /// to a one-dimensional array of <see cref="string"/>, /// by calling the <paramref name="toStringMethod"/> /// delegate on each item in the source collection, /// and optionally removing any duplicates. /// </summary> /// <param name="collection"> /// A generic collection of <see cref="ValueType"/> items. /// </param> /// <param name="toStringMethod"> /// A delegate function which accepts a <typeparamref name="T"/> /// value and returns a string. Pass this parameter if a custom /// format string is needed. If not specified, uses the default /// <see cref="ValueType.ToString"/> method. /// </param> /// <param name="removeDuplicates"> /// Whether to remove duplicate items in the array returned. /// Parameter is optional, default value is <c>false</c>. /// </param> /// <typeparam name="T"> /// The generic type of <paramref name="collection"/>, /// derived from <see cref="ValueType"/>. /// </typeparam> /// <returns> /// An array of strings created by the <paramref name="toStringMethod"/>, /// with null or empty values omitted, and duplicates omitted unless /// the <paramref name="removeDuplicates"/> value is <c>true</c>. /// </returns> public static string[] ToStringArray<T>( this IEnumerable<T> collection, Func<T, string> toStringMethod, bool removeDuplicates = DefaultRemoveDuplicates) where T : struct { if (collection == null) { return new string[0]; } ICollection<string> list = new List<string>(); // ReSharper disable once LoopCanBePartlyConvertedToQuery foreach (T item in collection) { string str = toStringMethod == null ? item.ToString() : toStringMethod(item); if (string.IsNullOrWhiteSpace(str)) { continue; } // The base List<string> class uses "Ordinal" comparison by default, // so applying the Linq method is not necessary: if (removeDuplicates && list.Contains(str)) // !list.Contains(str, StringComparer.Ordinal) { continue; } list.Add(str); } // T must be a non-nullable type // for List.ToArray() to work. //// return list.ToArray<string>(); // So convert the old-fashioned way instead: // Create an array the right size... string[] ary = new string[list.Count]; // ...and copy all of the values into it. list.CopyTo(ary, 0); return ary; } #endregion #region [ Overloads of ToDelimitedString Extension Method ] /// <summary> /// Converts a generic collection of <see cref="ValueType"/> /// to a comma-delimited <see cref="string"/>, /// by calling the <see cref="ValueType.ToString()"/> /// method on each item in the source collection, /// and optionally removing any duplicates. /// </summary> /// <param name="collection"> /// A generic collection of <see cref="ValueType"/> items. /// </param> /// <param name="removeDuplicates"> /// Whether to remove duplicate items in the array returned. /// Parameter is optional, default value is <c>false</c>. /// </param> /// <typeparam name="T"> /// The generic type of <paramref name="collection"/>, /// derived from <see cref="ValueType"/>. /// </typeparam> /// <returns> /// A comma-delimited string. /// </returns> public static string ToDelimitedString<T>( this IEnumerable<T> collection, bool removeDuplicates = DefaultRemoveDuplicates) where T : struct { return collection.ToDelimitedString( ConvertDelimitedString.DefaultSeparator, removeDuplicates); } /// <summary> /// Converts a generic collection of <see cref="ValueType"/> /// to a comma-delimited <see cref="string"/>, /// by calling the <paramref name="toStringMethod"/> /// delegate on each item in the source collection, /// and optionally removing any duplicates. /// </summary> /// <param name="collection"> /// A generic collection of <see cref="ValueType"/> items. /// </param> /// <param name="toStringMethod"> /// A delegate function which accepts a <typeparamref name="T"/> /// value and returns a string. Pass this parameter if a custom /// format string is needed. If not specified, uses the default /// <see cref="ValueType.ToString"/> method. /// </param> /// <param name="removeDuplicates"> /// Whether to remove duplicate items in the array returned. /// Parameter is optional, default value is <c>false</c>. /// </param> /// <typeparam name="T"> /// The generic type of <paramref name="collection"/>, /// derived from <see cref="ValueType"/>. /// </typeparam> /// <returns> /// A comma-delimited string. /// </returns> public static string ToDelimitedString<T>( this IEnumerable<T> collection, Func<T, string> toStringMethod, bool removeDuplicates = DefaultRemoveDuplicates) where T : struct { return collection.ToDelimitedString( toStringMethod, ConvertDelimitedString.DefaultSeparator, removeDuplicates); } /// <summary> /// Converts a generic collection of <see cref="ValueType"/> /// to a <see cref="string"/> delimited by the value /// of the <paramref name="separator"/> parameter, /// by calling the <see cref="ValueType.ToString()"/> /// method on each item in the source collection, /// and removing any duplicates. /// </summary> /// <param name="collection"> /// A generic collection of <see cref="ValueType"/> items. /// </param> /// <param name="separator"> /// A string delimiter to use instead of a comma. /// </param> /// <param name="removeDuplicates"> /// Whether to remove duplicate items in the array returned. /// Parameter is optional, default value is <c>false</c>. /// </param> /// <typeparam name="T"> /// The generic type of <paramref name="collection"/>, /// derived from <see cref="ValueType"/>. /// </typeparam> /// <returns> /// A <paramref name="separator"/>-delimited string. /// </returns> public static string ToDelimitedString<T>( this IEnumerable<T> collection, [NotNull] string separator, bool removeDuplicates = DefaultRemoveDuplicates) where T : struct { Contract.Requires<ArgumentException>(!ConvertStrings.IsNullOrWhiteSpace(separator)); return collection.ToDelimitedString( null, separator, removeDuplicates); } /// <summary> /// Converts a generic collection of <see cref="ValueType"/> /// to a <see cref="string"/> delimited by the value /// of the <paramref name="separator"/> parameter, /// by calling the <paramref name="toStringMethod"/> /// delegate on each item in the source collection, /// and optionally removing any duplicates. /// </summary> /// <param name="collection"> /// A generic collection of <see cref="ValueType"/> items. /// </param> /// <param name="toStringMethod"> /// A delegate function which accepts a <typeparamref name="T"/> /// value and returns a string. Pass this parameter if a custom /// format string is needed. If not specified, uses the default /// <see cref="ValueType.ToString"/> method. /// </param> /// <param name="separator"> /// A string delimiter to use instead of a comma. /// </param> /// <param name="removeDuplicates"> /// Whether to remove duplicate items in the array returned. /// Parameter is optional, default value is <c>false</c>. /// </param> /// <typeparam name="T"> /// The generic type of <paramref name="collection"/>, /// derived from <see cref="ValueType"/>. /// </typeparam> /// <returns> /// A <paramref name="separator"/>-delimited string. /// </returns> public static string ToDelimitedString<T>( this IEnumerable<T> collection, Func<T, string> toStringMethod, [NotNull] string separator, bool removeDuplicates = DefaultRemoveDuplicates) where T : struct { Contract.Requires<ArgumentException>(!ConvertStrings.IsNullOrWhiteSpace(separator)); return string.Join( separator, collection.ToStringArray(toStringMethod, removeDuplicates)); } #endregion } }
namespace JsonToEnum.Export { public enum PlatformErrorCodes { None = 0, Success = 1, TransportException = 2, UnhandledException = 3, NotImplemented = 4, SystemDisabled = 5, FailedToLoadAvailableLocalesConfiguration = 6, ParameterParseFailure = 7, ParameterInvalidRange = 8, BadRequest = 9, AuthenticationInvalid = 10, DataNotFound = 11, InsufficientPrivileges = 12, Duplicate = 13, UnknownSqlResult = 14, ValidationError = 15, ValidationMissingFieldError = 16, ValidationInvalidInputError = 17, InvalidParameters = 18, ParameterNotFound = 19, UnhandledHttpException = 20, NotFound = 21, WebAuthModuleAsyncFailed = 22, InvalidReturnValue = 23, UserBanned = 24, InvalidPostBody = 25, MissingPostBody = 26, ExternalServiceTimeout = 27, ValidationLengthError = 28, ValidationRangeError = 29, JsonDeserializationError = 30, ThrottleLimitExceeded = 31, ValidationTagError = 32, ValidationProfanityError = 33, ValidationUrlFormatError = 34, ThrottleLimitExceededMinutes = 35, ThrottleLimitExceededMomentarily = 36, ThrottleLimitExceededSeconds = 37, ExternalServiceUnknown = 38, ValidationWordLengthError = 39, ValidationInvisibleUnicode = 40, ValidationBadNames = 41, ExternalServiceFailed = 42, ServiceRetired = 43, UnknownSqlException = 44, UnsupportedLocale = 45, InvalidPageNumber = 46, MaximumPageSizeExceeded = 47, ServiceUnsupported = 48, ValidationMaximumUnicodeCombiningCharacters = 49, ValidationMaximumSequentialCarriageReturns = 50, PerEndpointRequestThrottleExceeded = 51, AuthContextCacheAssertion = 52, ObsoleteCredentialType = 89, UnableToUnPairMobileApp = 90, UnableToPairMobileApp = 91, CannotUseMobileAuthWithNonMobileProvider = 92, MissingDeviceCookie = 93, FacebookTokenExpired = 94, AuthTicketRequired = 95, CookieContextRequired = 96, UnknownAuthenticationError = 97, BungieNetAccountCreationRequired = 98, WebAuthRequired = 99, ContentUnknownSqlResult = 100, ContentNeedUniquePath = 101, ContentSqlException = 102, ContentNotFound = 103, ContentSuccessWithTagAddFail = 104, ContentSearchMissingParameters = 105, ContentInvalidId = 106, ContentPhysicalFileDeletionError = 107, ContentPhysicalFileCreationError = 108, ContentPerforceSubmissionError = 109, ContentPerforceInitializationError = 110, ContentDeploymentPackageNotReadyError = 111, ContentUploadFailed = 112, ContentTooManyResults = 113, ContentInvalidState = 115, ContentNavigationParentNotFound = 116, ContentNavigationParentUpdateError = 117, DeploymentPackageNotEditable = 118, ContentValidationError = 119, ContentPropertiesValidationError = 120, ContentTypeNotFound = 121, DeploymentPackageNotFound = 122, ContentSearchInvalidParameters = 123, ContentItemPropertyAggregationError = 124, DeploymentPackageFileNotFound = 125, ContentPerforceFileHistoryNotFound = 126, ContentAssetZipCreationFailure = 127, ContentAssetZipCreationBusy = 128, ContentProjectNotFound = 129, ContentFolderNotFound = 130, ContentPackagesInconsistent = 131, ContentPackagesInvalidState = 132, ContentPackagesInconsistentType = 133, ContentCannotDeletePackage = 134, ContentLockedForChanges = 135, ContentFileUploadFailed = 136, ContentNotReviewed = 137, ContentPermissionDenied = 138, ContentInvalidExternalUrl = 139, ContentExternalFileCannotBeImportedLocally = 140, ContentTagSaveFailure = 141, ContentPerforceUnmatchedFileError = 142, ContentPerforceChangelistResultNotFound = 143, ContentPerforceChangelistFileItemsNotFound = 144, ContentPerforceInvalidRevisionError = 145, ContentUnloadedSaveResult = 146, ContentPropertyInvalidNumber = 147, ContentPropertyInvalidUrl = 148, ContentPropertyInvalidDate = 149, ContentPropertyInvalidSet = 150, ContentPropertyCannotDeserialize = 151, ContentRegexValidationFailOnProperty = 152, ContentMaxLengthFailOnProperty = 153, ContentPropertyUnexpectedDeserializationError = 154, ContentPropertyRequired = 155, ContentCannotCreateFile = 156, ContentInvalidMigrationFile = 157, ContentMigrationAlteringProcessedItem = 158, ContentPropertyDefinitionNotFound = 159, ContentReviewDataChanged = 160, ContentRollbackRevisionNotInPackage = 161, ContentItemNotBasedOnLatestRevision = 162, ContentUnauthorized = 163, ContentCannotCreateDeploymentPackage = 164, ContentUserNotFound = 165, ContentLocalePermissionDenied = 166, ContentInvalidLinkToInternalEnvironment = 167, ContentInvalidBlacklistedContent = 168, ContentMacroMalformedNoContentId = 169, ContentMacroMalformedNoTemplateType = 170, ContentIllegalBNetMembershipId = 171, ContentLocaleDidNotMatchExpected = 172, ContentBabelCallFailed = 173, ContentEnglishPostLiveForbidden = 174, ContentLocaleEditPermissionDenied = 175, UserNonUniqueName = 200, UserManualLinkingStepRequired = 201, UserCreateUnknownSqlResult = 202, UserCreateUnknownSqlException = 203, UserMalformedMembershipId = 204, UserCannotFindRequestedUser = 205, UserCannotLoadAccountCredentialLinkInfo = 206, UserInvalidMobileAppType = 207, UserMissingMobilePairingInfo = 208, UserCannotGenerateMobileKeyWhileUsingMobileCredential = 209, UserGenerateMobileKeyExistingSlotCollision = 210, UserDisplayNameMissingOrInvalid = 211, UserCannotLoadAccountProfileData = 212, UserCannotSaveUserProfileData = 213, UserEmailMissingOrInvalid = 214, UserTermsOfUseRequired = 215, UserCannotCreateNewAccountWhileLoggedIn = 216, UserCannotResolveCentralAccount = 217, UserInvalidAvatar = 218, UserMissingCreatedUserResult = 219, UserCannotChangeUniqueNameYet = 220, UserCannotChangeDisplayNameYet = 221, UserCannotChangeEmail = 222, UserUniqueNameMustStartWithLetter = 223, UserNoLinkedAccountsSupportFriendListings = 224, UserAcknowledgmentTableFull = 225, UserCreationDestinyMembershipRequired = 226, UserFriendsTokenNeedsRefresh = 227, MessagingUnknownError = 300, MessagingSelfError = 301, MessagingSendThrottle = 302, MessagingNoBody = 303, MessagingTooManyUsers = 304, MessagingCanNotLeaveConversation = 305, MessagingUnableToSend = 306, MessagingDeletedUserForbidden = 307, MessagingCannotDeleteExternalConversation = 308, MessagingGroupChatDisabled = 309, MessagingMustIncludeSelfInPrivateMessage = 310, MessagingSenderIsBanned = 311, AddSurveyAnswersUnknownSqlException = 400, ForumBodyCannotBeEmpty = 500, ForumSubjectCannotBeEmptyOnTopicPost = 501, ForumCannotLocateParentPost = 502, ForumThreadLockedForReplies = 503, ForumUnknownSqlResultDuringCreatePost = 504, ForumUnknownTagCreationError = 505, ForumUnknownSqlResultDuringTagItem = 506, ForumUnknownExceptionCreatePost = 507, ForumQuestionMustBeTopicPost = 508, ForumExceptionDuringTagSearch = 509, ForumExceptionDuringTopicRetrieval = 510, ForumAliasedTagError = 511, ForumCannotLocateThread = 512, ForumUnknownExceptionEditPost = 513, ForumCannotLocatePost = 514, ForumUnknownExceptionGetOrCreateTags = 515, ForumEditPermissionDenied = 516, ForumUnknownSqlResultDuringTagIdRetrieval = 517, ForumCannotGetRating = 518, ForumUnknownExceptionGetRating = 519, ForumRatingsAccessError = 520, ForumRelatedPostAccessError = 521, ForumLatestReplyAccessError = 522, ForumUserStatusAccessError = 523, ForumAuthorAccessError = 524, ForumGroupAccessError = 525, ForumUrlExpectedButMissing = 526, ForumRepliesCannotBeEmpty = 527, ForumRepliesCannotBeInDifferentGroups = 528, ForumSubTopicCannotBeCreatedAtThisThreadLevel = 529, ForumCannotCreateContentTopic = 530, ForumTopicDoesNotExist = 531, ForumContentCommentsNotAllowed = 532, ForumUnknownSqlResultDuringEditPost = 533, ForumUnknownSqlResultDuringGetPost = 534, ForumPostValidationBadUrl = 535, ForumBodyTooLong = 536, ForumSubjectTooLong = 537, ForumAnnouncementNotAllowed = 538, ForumCannotShareOwnPost = 539, ForumEditNoOp = 540, ForumUnknownDatabaseErrorDuringGetPost = 541, ForumExceeedMaximumRowLimit = 542, ForumCannotSharePrivatePost = 543, ForumCannotCrossPostBetweenGroups = 544, ForumIncompatibleCategories = 555, ForumCannotUseTheseCategoriesOnNonTopicPost = 556, ForumCanOnlyDeleteTopics = 557, ForumDeleteSqlException = 558, ForumDeleteSqlUnknownResult = 559, ForumTooManyTags = 560, ForumCanOnlyRateTopics = 561, ForumBannedPostsCannotBeEdited = 562, ForumThreadRootIsBanned = 563, ForumCannotUseOfficialTagCategoryAsTag = 564, ForumAnswerCannotBeMadeOnCreatePost = 565, ForumAnswerCannotBeMadeOnEditPost = 566, ForumAnswerPostIdIsNotADirectReplyOfQuestion = 567, ForumAnswerTopicIdIsNotAQuestion = 568, ForumUnknownExceptionDuringMarkAnswer = 569, ForumUnknownSqlResultDuringMarkAnswer = 570, ForumCannotRateYourOwnPosts = 571, ForumPollsMustBeTheFirstPostInTopic = 572, ForumInvalidPollInput = 573, ForumGroupAdminEditNonMember = 574, ForumCannotEditModeratorEditedPost = 575, ForumRequiresDestinyMembership = 576, ForumUnexpectedError = 577, ForumAgeLock = 578, ForumMaxPages = 579, ForumMaxPagesOldestFirst = 580, ForumCannotApplyForumIdWithoutTags = 581, ForumCannotApplyForumIdToNonTopics = 582, ForumCannotDownvoteCommunityCreations = 583, ForumTopicsMustHaveOfficialCategory = 584, ForumRecruitmentTopicMalformed = 585, ForumRecruitmentTopicNotFound = 586, ForumRecruitmentTopicNoSlotsRemaining = 587, ForumRecruitmentTopicKickBan = 588, ForumRecruitmentTopicRequirementsNotMet = 589, ForumRecruitmentTopicNoPlayers = 590, ForumRecruitmentApproveFailMessageBan = 591, ForumRecruitmentGlobalBan = 592, ForumUserBannedFromThisTopic = 593, ForumRecruitmentFireteamMembersOnly = 594, GroupMembershipApplicationAlreadyResolved = 601, GroupMembershipAlreadyApplied = 602, GroupMembershipInsufficientPrivileges = 603, GroupIdNotReturnedFromCreation = 604, GroupSearchInvalidParameters = 605, GroupMembershipPendingApplicationNotFound = 606, GroupInvalidId = 607, GroupInvalidMembershipId = 608, GroupInvalidMembershipType = 609, GroupMissingTags = 610, GroupMembershipNotFound = 611, GroupInvalidRating = 612, GroupUserFollowingAccessError = 613, GroupUserMembershipAccessError = 614, GroupCreatorAccessError = 615, GroupAdminAccessError = 616, GroupPrivatePostNotViewable = 617, GroupMembershipNotLoggedIn = 618, GroupNotDeleted = 619, GroupUnknownErrorUndeletingGroup = 620, GroupDeleted = 621, GroupNotFound = 622, GroupMemberBanned = 623, GroupMembershipClosed = 624, GroupPrivatePostOverrideError = 625, GroupNameTaken = 626, GroupDeletionGracePeriodExpired = 627, GroupCannotCheckBanStatus = 628, GroupMaximumMembershipCountReached = 629, NoDestinyAccountForClanPlatform = 630, AlreadyRequestingMembershipForClanPlatform = 631, AlreadyClanMemberOnPlatform = 632, GroupJoinedCannotSetClanName = 633, GroupLeftCannotClearClanName = 634, GroupRelationshipRequestPending = 635, GroupRelationshipRequestBlocked = 636, GroupRelationshipRequestNotFound = 637, GroupRelationshipBlockNotFound = 638, GroupRelationshipNotFound = 639, GroupAlreadyAllied = 641, GroupAlreadyMember = 642, GroupRelationshipAlreadyExists = 643, InvalidGroupTypesForRelationshipRequest = 644, GroupAtMaximumAlliances = 646, GroupCannotSetClanOnlySettings = 647, ClanCannotSetTwoDefaultPostTypes = 648, GroupMemberInvalidMemberType = 649, GroupInvalidPlatformType = 650, GroupMemberInvalidSort = 651, GroupInvalidResolveState = 652, ClanAlreadyEnabledForPlatform = 653, ClanNotEnabledForPlatform = 654, ClanEnabledButCouldNotJoinNoAccount = 655, ClanEnabledButCouldNotJoinAlreadyMember = 656, ClanCannotJoinNoCredential = 657, NoClanMembershipForPlatform = 658, GroupToGroupFollowLimitReached = 659, ChildGroupAlreadyInAlliance = 660, OwnerGroupAlreadyInAlliance = 661, AllianceOwnerCannotJoinAlliance = 662, GroupNotInAlliance = 663, ChildGroupCannotInviteToAlliance = 664, GroupToGroupAlreadyFollowed = 665, GroupToGroupNotFollowing = 666, ClanMaximumMembershipReached = 667, ClanNameNotValid = 668, ClanNameNotValidError = 669, AllianceOwnerNotDefined = 670, AllianceChildNotDefined = 671, ClanNameIllegalCharacters = 672, ClanTagIllegalCharacters = 673, ClanRequiresInvitation = 674, ClanMembershipClosed = 675, ClanInviteAlreadyMember = 676, GroupInviteAlreadyMember = 677, GroupJoinApprovalRequired = 678, ClanTagRequired = 679, GroupNameCannotStartOrEndWithWhiteSpace = 680, ClanCallsignCannotStartOrEndWithWhiteSpace = 681, ClanMigrationFailed = 682, ClanNotEnabledAlreadyMemberOfAnotherClan = 683, GroupModerationNotPermittedOnNonMembers = 684, ClanCreationInWorldServerFailed = 685, ClanNotFound = 686, ClanMembershipLevelDoesNotPermitThatAction = 687, ClanMemberNotFound = 688, ClanMissingMembershipApprovers = 689, ClanInWrongStateForRequestedAction = 690, ClanNameAlreadyUsed = 691, ClanTooFewMembers = 692, ActivitiesUnknownException = 701, ActivitiesParameterNull = 702, ActivityCountsDiabled = 703, ActivitySearchInvalidParameters = 704, ActivityPermissionDenied = 705, ShareAlreadyShared = 706, ActivityLoggingDisabled = 707, ItemAlreadyFollowed = 801, ItemNotFollowed = 802, CannotFollowSelf = 803, GroupFollowLimitExceeded = 804, TagFollowLimitExceeded = 805, UserFollowLimitExceeded = 806, FollowUnsupportedEntityType = 807, NoValidTagsInList = 900, BelowMinimumSuggestionLength = 901, CannotGetSuggestionsOnMultipleTagsSimultaneously = 902, NotAValidPartialTag = 903, TagSuggestionsUnknownSqlResult = 904, TagsUnableToLoadPopularTagsFromDatabase = 905, TagInvalid = 906, TagNotFound = 907, SingleTagExpected = 908, TagsExceededMaximumPerItem = 909, IgnoreInvalidParameters = 1, IgnoreSqlException = 1001, IgnoreErrorRetrievingGroupPermissions = 1002, IgnoreErrorInsufficientPermission = 1003, IgnoreErrorRetrievingItem = 1004, IgnoreCannotIgnoreSelf = 1005, IgnoreIllegalType = 1006, IgnoreNotFound = 1007, IgnoreUserGloballyIgnored = 1008, IgnoreUserIgnored = 1009, NotificationSettingInvalid = 1100, PsnApiExpiredAccessToken = 1204, PSNExForbidden = 1205, PSNExSystemDisabled = 1218, PsnApiErrorCodeUnknown = 1223, PsnApiErrorWebException = 1224, PsnApiBadRequest = 1225, PsnApiAccessTokenRequired = 1226, PsnApiInvalidAccessToken = 1227, PsnApiBannedUser = 1229, PsnApiAccountUpgradeRequired = 1230, PsnApiServiceTemporarilyUnavailable = 1231, PsnApiServerBusy = 1232, PsnApiUnderMaintenance = 1233, PsnApiProfileUserNotFound = 1234, PsnApiProfilePrivacyRestriction = 1235, PsnApiProfileUnderMaintenance = 1236, PsnApiAccountAttributeMissing = 1237, XblExSystemDisabled = 1300, XblExUnknownError = 1301, XblApiErrorWebException = 1302, XblStsTokenInvalid = 1303, XblStsMissingToken = 1304, XblStsExpiredToken = 1305, XblAccessToTheSandboxDenied = 1306, XblMsaResponseMissing = 1307, XblMsaAccessTokenExpired = 1308, XblMsaInvalidRequest = 1309, XblMsaFriendsRequireSignIn = 1310, XblUserActionRequired = 1311, XblParentalControls = 1312, XblDeveloperAccount = 1313, XblUserTokenExpired = 1314, XblUserTokenInvalid = 1315, XblOffline = 1316, XblUnknownErrorCode = 1317, XblMsaInvalidGrant = 1318, ReportNotYetResolved = 1400, ReportOverturnDoesNotChangeDecision = 1401, ReportNotFound = 1402, ReportAlreadyReported = 1403, ReportInvalidResolution = 1404, ReportNotAssignedToYou = 1405, LegacyGameStatsSystemDisabled = 1500, LegacyGameStatsUnknownError = 1501, LegacyGameStatsMalformedSneakerNetCode = 1502, DestinyAccountAcquisitionFailure = 1600, DestinyAccountNotFound = 1601, DestinyBuildStatsDatabaseError = 1602, DestinyCharacterStatsDatabaseError = 1603, DestinyPvPStatsDatabaseError = 1604, DestinyPvEStatsDatabaseError = 1605, DestinyGrimoireStatsDatabaseError = 1606, DestinyStatsParameterMembershipTypeParseError = 1607, DestinyStatsParameterMembershipIdParseError = 1608, DestinyStatsParameterRangeParseError = 1609, DestinyStringItemHashNotFound = 1610, DestinyStringSetNotFound = 1611, DestinyContentLookupNotFoundForKey = 1612, DestinyContentItemNotFound = 1613, DestinyContentSectionNotFound = 1614, DestinyContentPropertyNotFound = 1615, DestinyContentConfigNotFound = 1616, DestinyContentPropertyBucketValueNotFound = 1617, DestinyUnexpectedError = 1618, DestinyInvalidAction = 1619, DestinyCharacterNotFound = 1620, DestinyInvalidFlag = 1621, DestinyInvalidRequest = 1622, DestinyItemNotFound = 1623, DestinyInvalidCustomizationChoices = 1624, DestinyVendorItemNotFound = 1625, DestinyInternalError = 1626, DestinyVendorNotFound = 1627, DestinyRecentActivitiesDatabaseError = 1628, DestinyItemBucketNotFound = 1629, DestinyInvalidMembershipType = 1630, DestinyVersionIncompatibility = 1631, DestinyItemAlreadyInInventory = 1632, DestinyBucketNotFound = 1633, DestinyCharacterNotInTower = 1634, DestinyCharacterNotLoggedIn = 1635, DestinyDefinitionsNotLoaded = 1636, DestinyInventoryFull = 1637, DestinyItemFailedLevelCheck = 1638, DestinyItemFailedUnlockCheck = 1639, DestinyItemUnequippable = 1640, DestinyItemUniqueEquipRestricted = 1641, DestinyNoRoomInDestination = 1642, DestinyServiceFailure = 1643, DestinyServiceRetired = 1644, DestinyTransferFailed = 1645, DestinyTransferNotFoundForSourceBucket = 1646, DestinyUnexpectedResultInVendorTransferCheck = 1647, DestinyUniquenessViolation = 1648, DestinyErrorDeserializationFailure = 1649, DestinyValidAccountTicketRequired = 1650, DestinyShardRelayClientTimeout = 1651, DestinyShardRelayProxyTimeout = 1652, DestinyPGCRNotFound = 1653, DestinyAccountMustBeOffline = 1654, DestinyCanOnlyEquipInGame = 1655, DestinyCannotPerformActionOnEquippedItem = 1656, DestinyQuestAlreadyCompleted = 1657, DestinyQuestAlreadyTracked = 1658, DestinyTrackableQuestsFull = 1659, DestinyItemNotTransferrable = 1660, DestinyVendorPurchaseNotAllowed = 1661, DestinyContentVersionMismatch = 1662, DestinyItemActionForbidden = 1663, DestinyRefundInvalid = 1664, DestinyPrivacyRestriction = 1665, DestinyActionInsufficientPrivileges = 1666, DestinyInvalidClaimException = 1667, DestinyLegacyPlatformRestricted = 1668, DestinyLegacyPlatformInUse = 1669, DestinyLegacyPlatformInaccessible = 1670, FbInvalidRequest = 1800, FbRedirectMismatch = 1801, FbAccessDenied = 1802, FbUnsupportedResponseType = 1803, FbInvalidScope = 1804, FbUnsupportedGrantType = 1805, FbInvalidGrant = 1806, InvitationExpired = 1900, InvitationUnknownType = 1901, InvitationInvalidResponseStatus = 1902, InvitationInvalidType = 1903, InvitationAlreadyPending = 1904, InvitationInsufficientPermission = 1905, InvitationInvalidCode = 1906, InvitationInvalidTargetState = 1907, InvitationCannotBeReactivated = 1908, InvitationNoRecipients = 1910, InvitationGroupCannotSendToSelf = 1911, InvitationTooManyRecipients = 1912, InvitationInvalid = 1913, InvitationNotFound = 1914, TokenInvalid = 2, TokenBadFormat = 2001, TokenAlreadyClaimed = 2002, TokenAlreadyClaimedSelf = 2003, TokenThrottling = 2004, TokenUnknownRedemptionFailure = 2005, TokenPurchaseClaimFailedAfterTokenClaimed = 2006, TokenUserAlreadyOwnsOffer = 2007, TokenInvalidOfferKey = 2008, TokenEmailNotValidated = 2009, TokenProvisioningBadVendorOrOffer = 2010, TokenPurchaseHistoryUnknownError = 2011, TokenThrottleStateUnknownError = 2012, TokenUserAgeNotVerified = 2013, TokenExceededOfferMaximum = 2014, TokenNoAvailableUnlocks = 2015, TokenMarketplaceInvalidPlatform = 2016, TokenNoMarketplaceCodesFound = 2017, TokenOfferNotAvailableForRedemption = 2018, TokenUnlockPartialFailure = 2019, TokenMarketplaceInvalidRegion = 2020, TokenOfferExpired = 2021, RAFExceededMaximumReferrals = 2022, RAFDuplicateBond = 2023, RAFNoValidVeteranDestinyMembershipsFound = 2024, RAFNotAValidVeteranUser = 2025, RAFCodeAlreadyClaimedOrNotFound = 2026, RAFMismatchedDestinyMembershipType = 2027, RAFUnableToAccessPurchaseHistory = 2028, RAFUnableToCreateBond = 2029, RAFUnableToFindBond = 2030, RAFUnableToRemoveBond = 2031, RAFCannotBondToSelf = 2032, RAFInvalidPlatform = 2033, RAFGenerateThrottled = 2034, RAFUnableToCreateBondVersionMismatch = 2035, RAFUnableToRemoveBondVersionMismatch = 2036, RAFRedeemThrottled = 2037, NoAvailableDiscountCode = 2038, DiscountAlreadyClaimed = 2039, DiscountClaimFailure = 2040, DiscountConfigurationFailure = 2041, DiscountGenerationFailure = 2042, DiscountAlreadyExists = 2043, ApiExceededMaxKeys = 2100, ApiInvalidOrExpiredKey = 2101, ApiKeyMissingFromRequest = 2102, ApplicationDisabled = 2103, ApplicationExceededMax = 2104, ApplicationDisallowedByScope = 2105, AuthorizationCodeInvalid = 2106, OriginHeaderDoesNotMatchKey = 2107, AccessNotPermittedByApplicationScope = 2108, ApplicationNameIsTaken = 2109, RefreshTokenNotYetValid = 2110, AccessTokenHasExpired = 2111, ApplicationTokenFormatNotValid = 2112, ApplicationNotConfiguredForBungieAuth = 2113, ApplicationNotConfiguredForOAuth = 2114, OAuthAccessTokenExpired = 2115, PartnershipInvalidType = 2200, PartnershipValidationError = 2201, PartnershipValidationTimeout = 2202, PartnershipAccessFailure = 2203, PartnershipAccountInvalid = 2204, PartnershipGetAccountInfoFailure = 2205, PartnershipDisabled = 2206, PartnershipAlreadyExists = 2207, TwitchNotLinked = 2208, TwitchAccountNotFound = 2209, TwitchCouldNotLoadDestinyInfo = 2210, CommunityStreamingUnavailable = 2300 } }
# CS_ARCH_ARM, CS_MODE_THUMB, None 0x12,0xea,0x01,0x00 = ands.w r0, r2, r1 0x0a,0x40 = ands r2, r1 0x0a,0x40 = ands r2, r1 0x10,0xea,0x01,0x00 = ands.w r0, r0, r1 0x11,0xea,0x03,0x03 = ands.w r3, r1, r3 0x01,0xea,0x00,0x00 = and.w r0, r1, r0 // 0x0f,0x40 = ands r7, r1 // 0x0f,0x40 = ands r7, r1 0x11,0xea,0x08,0x08 = ands.w r8, r1, r8 0x18,0xea,0x01,0x08 = ands.w r8, r8, r1 0x18,0xea,0x00,0x00 = ands.w r0, r8, r0 0x11,0xea,0x08,0x01 = ands.w r1, r1, r8 0x12,0xea,0x41,0x02 = ands.w r2, r2, r1, lsl #1 0x11,0xea,0x50,0x00 = ands.w r0, r1, r0, lsr #1 0x08,0xbf = it eq // 0x02,0xea,0x01,0x00 = andeq.w r0, r2, r1 0x08,0xbf = it eq // 0x0b,0x40 = andeq r3, r1 0x08,0xbf = it eq // 0x0b,0x40 = andeq r3, r1 0x08,0xbf = it eq // 0x00,0xea,0x01,0x00 = andeq.w r0, r0, r1 0x08,0xbf = it eq // 0x01,0xea,0x02,0x02 = andeq.w r2, r1, r2 0x08,0xbf = it eq // 0x11,0xea,0x00,0x00 = andseq.w r0, r1, r0 0x08,0xbf = it eq // 0x0f,0x40 = andeq r7, r1 0x08,0xbf = it eq // 0x0f,0x40 = andeq r7, r1 0x08,0xbf = it eq // 0x01,0xea,0x08,0x08 = andeq.w r8, r1, r8 0x08,0xbf = it eq // 0x08,0xea,0x01,0x08 = andeq.w r8, r8, r1 0x08,0xbf = it eq // 0x08,0xea,0x04,0x04 = andeq.w r4, r8, r4 0x08,0xbf = it eq // 0x04,0xea,0x08,0x04 = andeq.w r4, r4, r8 0x08,0xbf = it eq // 0x00,0xea,0x41,0x00 = andeq.w r0, r0, r1, lsl #1 0x08,0xbf = it eq // 0x01,0xea,0x55,0x05 = andeq.w r5, r1, r5, lsr #1 0x92,0xea,0x01,0x00 = eors.w r0, r2, r1 0x4d,0x40 = eors r5, r1 0x4d,0x40 = eors r5, r1 0x90,0xea,0x01,0x00 = eors.w r0, r0, r1 0x91,0xea,0x02,0x02 = eors.w r2, r1, r2 0x81,0xea,0x01,0x01 = eor.w r1, r1, r1 // 0x4f,0x40 = eors r7, r1 // 0x4f,0x40 = eors r7, r1 0x91,0xea,0x08,0x08 = eors.w r8, r1, r8 0x98,0xea,0x01,0x08 = eors.w r8, r8, r1 0x98,0xea,0x06,0x06 = eors.w r6, r8, r6 0x90,0xea,0x08,0x00 = eors.w r0, r0, r8 0x92,0xea,0x41,0x02 = eors.w r2, r2, r1, lsl #1 0x91,0xea,0x50,0x00 = eors.w r0, r1, r0, lsr #1 0x08,0xbf = it eq // 0x82,0xea,0x01,0x03 = eoreq.w r3, r2, r1 0x08,0xbf = it eq // 0x48,0x40 = eoreq r0, r1 0x08,0xbf = it eq // 0x4a,0x40 = eoreq r2, r1 0x08,0xbf = it eq // 0x83,0xea,0x01,0x03 = eoreq.w r3, r3, r1 0x08,0xbf = it eq // 0x81,0xea,0x00,0x00 = eoreq.w r0, r1, r0 0x08,0xbf = it eq // 0x91,0xea,0x01,0x01 = eorseq.w r1, r1, r1 0x08,0xbf = it eq // 0x4f,0x40 = eoreq r7, r1 0x08,0xbf = it eq // 0x4f,0x40 = eoreq r7, r1 0x08,0xbf = it eq // 0x81,0xea,0x08,0x08 = eoreq.w r8, r1, r8 0x08,0xbf = it eq // 0x88,0xea,0x01,0x08 = eoreq.w r8, r8, r1 0x08,0xbf = it eq // 0x88,0xea,0x00,0x00 = eoreq.w r0, r8, r0 0x08,0xbf = it eq // 0x83,0xea,0x08,0x03 = eoreq.w r3, r3, r8 0x08,0xbf = it eq // 0x84,0xea,0x41,0x04 = eoreq.w r4, r4, r1, lsl #1 0x08,0xbf = it eq // 0x81,0xea,0x50,0x00 = eoreq.w r0, r1, r0, lsr #1 0x12,0xfa,0x01,0xf0 = lsls.w r0, r2, r1 // 0x8a,0x40 = lsls r2, r1 0x11,0xfa,0x02,0xf2 = lsls.w r2, r1, r2 0x10,0xfa,0x01,0xf0 = lsls.w r0, r0, r1 // 0x11,0xfa,0x04,0xf4 = lsls.w r4, r1, r4 0x01,0xfa,0x04,0xf4 = lsl.w r4, r1, r4 // 0x8f,0x40 = lsls r7, r1 0x11,0xfa,0x08,0xf8 = lsls.w r8, r1, r8 0x18,0xfa,0x01,0xf8 = lsls.w r8, r8, r1 0x18,0xfa,0x03,0xf3 = lsls.w r3, r8, r3 0x15,0xfa,0x08,0xf5 = lsls.w r5, r5, r8 0x08,0xbf = it eq // 0x02,0xfa,0x01,0xf0 = lsleq.w r0, r2, r1 0x08,0xbf = it eq // 0x8a,0x40 = lsleq r2, r1 0x08,0xbf = it eq // 0x01,0xfa,0x02,0xf2 = lsleq.w r2, r1, r2 0x08,0xbf = it eq // 0x00,0xfa,0x01,0xf0 = lsleq.w r0, r0, r1 0x08,0xbf = it eq // 0x01,0xfa,0x03,0xf3 = lsleq.w r3, r1, r3 0x08,0xbf = it eq // 0x11,0xfa,0x04,0xf4 = lslseq.w r4, r1, r4 0x08,0xbf = it eq // 0x8f,0x40 = lsleq r7, r1 0x08,0xbf = it eq // 0x01,0xfa,0x08,0xf8 = lsleq.w r8, r1, r8 0x08,0xbf = it eq // 0x08,0xfa,0x01,0xf8 = lsleq.w r8, r8, r1 0x08,0xbf = it eq // 0x08,0xfa,0x00,0xf0 = lsleq.w r0, r8, r0 0x08,0xbf = it eq // 0x03,0xfa,0x08,0xf3 = lsleq.w r3, r3, r8 0x32,0xfa,0x01,0xf6 = lsrs.w r6, r2, r1 0xca,0x40 = lsrs r2, r1 0x31,0xfa,0x02,0xf2 = lsrs.w r2, r1, r2 0x32,0xfa,0x01,0xf2 = lsrs.w r2, r2, r1 0x31,0xfa,0x03,0xf3 = lsrs.w r3, r1, r3 0x21,0xfa,0x04,0xf4 = lsr.w r4, r1, r4 // 0xcf,0x40 = lsrs r7, r1 0x31,0xfa,0x08,0xf8 = lsrs.w r8, r1, r8 0x38,0xfa,0x01,0xf8 = lsrs.w r8, r8, r1 0x38,0xfa,0x02,0xf2 = lsrs.w r2, r8, r2 0x35,0xfa,0x08,0xf5 = lsrs.w r5, r5, r8 0x08,0xbf = it eq // 0x22,0xfa,0x01,0xf6 = lsreq.w r6, r2, r1 0x08,0xbf = it eq // 0xcf,0x40 = lsreq r7, r1 0x08,0xbf = it eq // 0x21,0xfa,0x07,0xf7 = lsreq.w r7, r1, r7 0x08,0xbf = it eq // 0x27,0xfa,0x01,0xf7 = lsreq.w r7, r7, r1 0x08,0xbf = it eq // 0x21,0xfa,0x02,0xf2 = lsreq.w r2, r1, r2 0x08,0xbf = it eq // 0x31,0xfa,0x00,0xf0 = lsrseq.w r0, r1, r0 0x08,0xbf = it eq // 0xcf,0x40 = lsreq r7, r1 0x08,0xbf = it eq // 0x21,0xfa,0x08,0xf8 = lsreq.w r8, r1, r8 0x08,0xbf = it eq // 0x28,0xfa,0x01,0xf8 = lsreq.w r8, r8, r1 0x08,0xbf = it eq // 0x28,0xfa,0x01,0xf1 = lsreq.w r1, r8, r1 0x08,0xbf = it eq // 0x24,0xfa,0x08,0xf4 = lsreq.w r4, r4, r8 0x56,0xfa,0x05,0xf7 = asrs.w r7, r6, r5 0x08,0x41 = asrs r0, r1 0x51,0xfa,0x00,0xf0 = asrs.w r0, r1, r0 0x53,0xfa,0x01,0xf3 = asrs.w r3, r3, r1 0x51,0xfa,0x01,0xf1 = asrs.w r1, r1, r1 0x41,0xfa,0x00,0xf0 = asr.w r0, r1, r0 // 0x0f,0x41 = asrs r7, r1 0x51,0xfa,0x08,0xf8 = asrs.w r8, r1, r8 0x58,0xfa,0x01,0xf8 = asrs.w r8, r8, r1 0x58,0xfa,0x05,0xf5 = asrs.w r5, r8, r5 0x55,0xfa,0x08,0xf5 = asrs.w r5, r5, r8 0x08,0xbf = it eq // 0x42,0xfa,0x01,0xf0 = asreq.w r0, r2, r1 0x08,0xbf = it eq // 0x0a,0x41 = asreq r2, r1 0x08,0xbf = it eq // 0x42,0xfa,0x01,0xf1 = asreq.w r1, r2, r1 0x08,0xbf = it eq // 0x44,0xfa,0x01,0xf4 = asreq.w r4, r4, r1 0x08,0xbf = it eq // 0x41,0xfa,0x06,0xf6 = asreq.w r6, r1, r6 0x08,0xbf = it eq // 0x51,0xfa,0x03,0xf3 = asrseq.w r3, r1, r3 0x08,0xbf = it eq // 0x0f,0x41 = asreq r7, r1 0x08,0xbf = it eq // 0x41,0xfa,0x08,0xf8 = asreq.w r8, r1, r8 0x08,0xbf = it eq // 0x48,0xfa,0x01,0xf8 = asreq.w r8, r8, r1 0x08,0xbf = it eq // 0x48,0xfa,0x01,0xf1 = asreq.w r1, r8, r1 0x08,0xbf = it eq // 0x43,0xfa,0x08,0xf3 = asreq.w r3, r3, r8 0x52,0xeb,0x01,0x05 = adcs.w r5, r2, r1 0x4d,0x41 = adcs r5, r1 // 0x4b,0x41 = adcs r3, r1 0x52,0xeb,0x01,0x02 = adcs.w r2, r2, r1 // 0x51,0xeb,0x03,0x03 = adcs.w r3, r1, r3 // 0x41,0xeb,0x00,0x00 = adc.w r0, r1, r0 // 0x4f,0x41 = adcs r7, r1 // 0x4f,0x41 = adcs r7, r1 0x51,0xeb,0x08,0x08 = adcs.w r8, r1, r8 0x58,0xeb,0x01,0x08 = adcs.w r8, r8, r1 0x58,0xeb,0x05,0x05 = adcs.w r5, r8, r5 0x52,0xeb,0x08,0x02 = adcs.w r2, r2, r8 0x53,0xeb,0x41,0x03 = adcs.w r3, r3, r1, lsl #1 0x51,0xeb,0x54,0x04 = adcs.w r4, r1, r4, lsr #1 0x08,0xbf = it eq // 0x42,0xeb,0x03,0x01 = adceq.w r1, r2, r3 0x08,0xbf = it eq // 0x49,0x41 = adceq r1, r1 0x08,0xbf = it eq // 0x4b,0x41 = adceq r3, r1 0x08,0xbf = it eq // 0x43,0xeb,0x01,0x03 = adceq.w r3, r3, r1 0x08,0xbf = it eq // 0x41,0xeb,0x00,0x00 = adceq.w r0, r1, r0 0x08,0xbf = it eq // 0x51,0xeb,0x03,0x03 = adcseq.w r3, r1, r3 0x08,0xbf = it eq // 0x4f,0x41 = adceq r7, r1 0x08,0xbf = it eq // 0x4f,0x41 = adceq r7, r1 0x08,0xbf = it eq // 0x41,0xeb,0x08,0x08 = adceq.w r8, r1, r8 0x08,0xbf = it eq // 0x48,0xeb,0x01,0x08 = adceq.w r8, r8, r1 0x08,0xbf = it eq // 0x48,0xeb,0x03,0x03 = adceq.w r3, r8, r3 0x08,0xbf = it eq // 0x41,0xeb,0x08,0x01 = adceq.w r1, r1, r8 0x08,0xbf = it eq // 0x42,0xeb,0x41,0x02 = adceq.w r2, r2, r1, lsl #1 0x08,0xbf = it eq // 0x41,0xeb,0x51,0x01 = adceq.w r1, r1, r1, lsr #1 0x72,0xeb,0x01,0x03 = sbcs.w r3, r2, r1 0x8c,0x41 = sbcs r4, r1 0x74,0xeb,0x01,0x01 = sbcs.w r1, r4, r1 0x74,0xeb,0x01,0x04 = sbcs.w r4, r4, r1 // 0x71,0xeb,0x02,0x02 = sbcs.w r2, r1, r2 // 0x61,0xeb,0x00,0x00 = sbc.w r0, r1, r0 // 0x8f,0x41 = sbcs r7, r1 0x71,0xeb,0x08,0x08 = sbcs.w r8, r1, r8 0x78,0xeb,0x01,0x08 = sbcs.w r8, r8, r1 0x78,0xeb,0x04,0x04 = sbcs.w r4, r8, r4 0x73,0xeb,0x08,0x03 = sbcs.w r3, r3, r8 0x72,0xeb,0x41,0x02 = sbcs.w r2, r2, r1, lsl #1 0x71,0xeb,0x55,0x05 = sbcs.w r5, r1, r5, lsr #1 0x08,0xbf = it eq // 0x62,0xeb,0x01,0x05 = sbceq.w r5, r2, r1 0x08,0xbf = it eq // 0x8d,0x41 = sbceq r5, r1 0x08,0xbf = it eq // 0x65,0xeb,0x01,0x01 = sbceq.w r1, r5, r1 0x08,0xbf = it eq // 0x65,0xeb,0x01,0x05 = sbceq.w r5, r5, r1 0x08,0xbf = it eq // 0x61,0xeb,0x00,0x00 = sbceq.w r0, r1, r0 0x08,0xbf = it eq // 0x71,0xeb,0x02,0x02 = sbcseq.w r2, r1, r2 0x08,0xbf = it eq // 0x8f,0x41 = sbceq r7, r1 0x08,0xbf = it eq // 0x61,0xeb,0x08,0x08 = sbceq.w r8, r1, r8 0x08,0xbf = it eq // 0x68,0xeb,0x01,0x08 = sbceq.w r8, r8, r1 0x08,0xbf = it eq // 0x68,0xeb,0x07,0x07 = sbceq.w r7, r8, r7 0x08,0xbf = it eq // 0x67,0xeb,0x08,0x07 = sbceq.w r7, r7, r8 0x08,0xbf = it eq // 0x62,0xeb,0x41,0x02 = sbceq.w r2, r2, r1, lsl #1 0x08,0xbf = it eq // 0x61,0xeb,0x55,0x05 = sbceq.w r5, r1, r5, lsr #1 0x72,0xfa,0x01,0xf3 = rors.w r3, r2, r1 0xc8,0x41 = rors r0, r1 0x70,0xfa,0x01,0xf1 = rors.w r1, r0, r1 0x72,0xfa,0x01,0xf2 = rors.w r2, r2, r1 0x71,0xfa,0x02,0xf2 = rors.w r2, r1, r2 0x61,0xfa,0x05,0xf5 = ror.w r5, r1, r5 // 0xcf,0x41 = rors r7, r1 0x71,0xfa,0x08,0xf8 = rors.w r8, r1, r8 0x78,0xfa,0x01,0xf8 = rors.w r8, r8, r1 0x78,0xfa,0x06,0xf6 = rors.w r6, r8, r6 0x76,0xfa,0x08,0xf6 = rors.w r6, r6, r8 0x08,0xbf = it eq // 0x62,0xfa,0x01,0xf4 = roreq.w r4, r2, r1 0x08,0xbf = it eq // 0xcc,0x41 = roreq r4, r1 0x08,0xbf = it eq // 0x64,0xfa,0x01,0xf1 = roreq.w r1, r4, r1 0x08,0xbf = it eq // 0x64,0xfa,0x01,0xf4 = roreq.w r4, r4, r1 0x08,0xbf = it eq // 0x61,0xfa,0x00,0xf0 = roreq.w r0, r1, r0 0x08,0xbf = it eq // 0x71,0xfa,0x00,0xf0 = rorseq.w r0, r1, r0 0x08,0xbf = it eq // 0xcf,0x41 = roreq r7, r1 0x08,0xbf = it eq // 0x61,0xfa,0x08,0xf8 = roreq.w r8, r1, r8 0x08,0xbf = it eq // 0x68,0xfa,0x01,0xf8 = roreq.w r8, r8, r1 0x08,0xbf = it eq // 0x68,0xfa,0x03,0xf3 = roreq.w r3, r8, r3 0x08,0xbf = it eq // 0x61,0xfa,0x08,0xf1 = roreq.w r1, r1, r8 0x52,0xea,0x01,0x07 = orrs.w r7, r2, r1 0x0a,0x43 = orrs r2, r1 0x0b,0x43 = orrs r3, r1 0x54,0xea,0x01,0x04 = orrs.w r4, r4, r1 0x51,0xea,0x05,0x05 = orrs.w r5, r1, r5 0x41,0xea,0x02,0x02 = orr.w r2, r1, r2 // 0x0f,0x43 = orrs r7, r1 // 0x0f,0x43 = orrs r7, r1 0x51,0xea,0x08,0x08 = orrs.w r8, r1, r8 0x58,0xea,0x01,0x08 = orrs.w r8, r8, r1 0x58,0xea,0x01,0x01 = orrs.w r1, r8, r1 0x50,0xea,0x08,0x00 = orrs.w r0, r0, r8 0x51,0xea,0x41,0x01 = orrs.w r1, r1, r1, lsl #1 0x51,0xea,0x50,0x00 = orrs.w r0, r1, r0, lsr #1 0x08,0xbf = it eq // 0x42,0xea,0x01,0x00 = orreq.w r0, r2, r1 0x08,0xbf = it eq // 0x0d,0x43 = orreq r5, r1 0x08,0xbf = it eq // 0x0d,0x43 = orreq r5, r1 0x08,0xbf = it eq // 0x42,0xea,0x01,0x02 = orreq.w r2, r2, r1 0x08,0xbf = it eq // 0x41,0xea,0x03,0x03 = orreq.w r3, r1, r3 0x08,0xbf = it eq // 0x51,0xea,0x04,0x04 = orrseq.w r4, r1, r4 0x08,0xbf = it eq // 0x0f,0x43 = orreq r7, r1 0x08,0xbf = it eq // 0x0f,0x43 = orreq r7, r1 0x08,0xbf = it eq // 0x41,0xea,0x08,0x08 = orreq.w r8, r1, r8 0x08,0xbf = it eq // 0x48,0xea,0x01,0x08 = orreq.w r8, r8, r1 0x08,0xbf = it eq // 0x48,0xea,0x00,0x00 = orreq.w r0, r8, r0 0x08,0xbf = it eq // 0x40,0xea,0x08,0x00 = orreq.w r0, r0, r8 0x08,0xbf = it eq // 0x42,0xea,0x41,0x02 = orreq.w r2, r2, r1, lsl #1 0x08,0xbf = it eq // 0x41,0xea,0x52,0x02 = orreq.w r2, r1, r2, lsr #1 0x32,0xea,0x01,0x03 = bics.w r3, r2, r1 0x8a,0x43 = bics r2, r1 0x32,0xea,0x01,0x01 = bics.w r1, r2, r1 0x32,0xea,0x01,0x02 = bics.w r2, r2, r1 0x31,0xea,0x00,0x00 = bics.w r0, r1, r0 0x21,0xea,0x00,0x00 = bic.w r0, r1, r0 // 0x8f,0x43 = bics r7, r1 0x31,0xea,0x08,0x08 = bics.w r8, r1, r8 0x38,0xea,0x01,0x08 = bics.w r8, r8, r1 0x38,0xea,0x07,0x07 = bics.w r7, r8, r7 0x35,0xea,0x08,0x05 = bics.w r5, r5, r8 0x33,0xea,0x41,0x03 = bics.w r3, r3, r1, lsl #1 0x31,0xea,0x54,0x04 = bics.w r4, r1, r4, lsr #1 0x08,0xbf = it eq // 0x22,0xea,0x01,0x00 = biceq.w r0, r2, r1 0x08,0xbf = it eq // 0x8d,0x43 = biceq r5, r1 0x08,0xbf = it eq // 0x25,0xea,0x01,0x01 = biceq.w r1, r5, r1 0x08,0xbf = it eq // 0x24,0xea,0x01,0x04 = biceq.w r4, r4, r1 0x08,0xbf = it eq // 0x21,0xea,0x02,0x02 = biceq.w r2, r1, r2 0x08,0xbf = it eq // 0x31,0xea,0x05,0x05 = bicseq.w r5, r1, r5 0x08,0xbf = it eq // 0x8f,0x43 = biceq r7, r1 0x08,0xbf = it eq // 0x21,0xea,0x08,0x08 = biceq.w r8, r1, r8 0x08,0xbf = it eq // 0x28,0xea,0x01,0x08 = biceq.w r8, r8, r1 0x08,0xbf = it eq // 0x28,0xea,0x00,0x00 = biceq.w r0, r8, r0 0x08,0xbf = it eq // 0x22,0xea,0x08,0x02 = biceq.w r2, r2, r8 0x08,0xbf = it eq // 0x24,0xea,0x41,0x04 = biceq.w r4, r4, r1, lsl #1 0x08,0xbf = it eq // 0x21,0xea,0x55,0x05 = biceq.w r5, r1, r5, lsr #1
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Runtime.ExceptionServices; using System.Security; using System.Security.Authentication; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; namespace System.Net.Security { // SecureChannel - a wrapper on SSPI based functionality. // Provides an additional abstraction layer over SSPI for SslStream. internal class SecureChannel { // When reading a frame from the wire first read this many bytes for the header. internal const int ReadHeaderSize = 5; private SafeFreeCredentials _credentialsHandle; private SafeDeleteContext _securityContext; private readonly string _destination; private readonly string _hostName; private readonly bool _serverMode; private readonly bool _remoteCertRequired; private readonly SslProtocols _sslProtocols; private readonly EncryptionPolicy _encryptionPolicy; private SslConnectionInfo _connectionInfo; private X509Certificate _serverCertificate; private X509Certificate _selectedClientCertificate; private bool _isRemoteCertificateAvailable; private X509CertificateCollection _clientCertificates; private LocalCertSelectionCallback _certSelectionDelegate; // These are the MAX encrypt buffer output sizes, not the actual sizes. private int _headerSize = 5; //ATTN must be set to at least 5 by default private int _trailerSize = 16; private int _maxDataSize = 16354; private bool _checkCertRevocation; private bool _checkCertName; private bool _refreshCredentialNeeded; private readonly Oid _serverAuthOid = new Oid("1.3.6.1.5.5.7.3.1", "1.3.6.1.5.5.7.3.1"); private readonly Oid _clientAuthOid = new Oid("1.3.6.1.5.5.7.3.2", "1.3.6.1.5.5.7.3.2"); internal SecureChannel(string hostname, bool serverMode, SslProtocols sslProtocols, X509Certificate serverCertificate, X509CertificateCollection clientCertificates, bool remoteCertRequired, bool checkCertName, bool checkCertRevocationStatus, EncryptionPolicy encryptionPolicy, LocalCertSelectionCallback certSelectionDelegate) { if (NetEventSource.IsEnabled) { NetEventSource.Enter(this, hostname, clientCertificates); NetEventSource.Log.SecureChannelCtor(this, hostname, clientCertificates, encryptionPolicy); } SslStreamPal.VerifyPackageInfo(); _destination = hostname; if (hostname == null) { NetEventSource.Fail(this, "hostname == null"); } _hostName = hostname; _serverMode = serverMode; _sslProtocols = sslProtocols; _serverCertificate = serverCertificate; _clientCertificates = clientCertificates; _remoteCertRequired = remoteCertRequired; _securityContext = null; _checkCertRevocation = checkCertRevocationStatus; _checkCertName = checkCertName; _certSelectionDelegate = certSelectionDelegate; _refreshCredentialNeeded = true; _encryptionPolicy = encryptionPolicy; if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } // // SecureChannel properties // // LocalServerCertificate - local certificate for server mode channel // LocalClientCertificate - selected certificated used in the client channel mode otherwise null // IsRemoteCertificateAvailable - true if the remote side has provided a certificate // HeaderSize - Header & trailer sizes used in the TLS stream // TrailerSize - // internal X509Certificate LocalServerCertificate { get { return _serverCertificate; } } internal X509Certificate LocalClientCertificate { get { return _selectedClientCertificate; } } internal bool IsRemoteCertificateAvailable { get { return _isRemoteCertificateAvailable; } } internal ChannelBinding GetChannelBinding(ChannelBindingKind kind) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, kind); ChannelBinding result = null; if (_securityContext != null) { result = SslStreamPal.QueryContextChannelBinding(_securityContext, kind); } if (NetEventSource.IsEnabled) NetEventSource.Exit(this, result); return result; } internal bool CheckCertRevocationStatus { get { return _checkCertRevocation; } } internal int HeaderSize { get { return _headerSize; } } internal int MaxDataSize { get { return _maxDataSize; } } internal SslConnectionInfo ConnectionInfo { get { return _connectionInfo; } } internal bool IsValidContext { get { return !(_securityContext == null || _securityContext.IsInvalid); } } internal bool IsServer { get { return _serverMode; } } internal bool RemoteCertRequired { get { return _remoteCertRequired; } } internal void SetRefreshCredentialNeeded() { _refreshCredentialNeeded = true; } internal void Close() { if (_securityContext != null) { _securityContext.Dispose(); } if (_credentialsHandle != null) { _credentialsHandle.Dispose(); } } // // SECURITY: we open a private key container on behalf of the caller // and we require the caller to have permission associated with that operation. // private X509Certificate2 EnsurePrivateKey(X509Certificate certificate) { if (certificate == null) { return null; } if (NetEventSource.IsEnabled) NetEventSource.Log.LocatingPrivateKey(certificate, this); try { string certHash = null; // Protecting from X509Certificate2 derived classes. X509Certificate2 certEx = MakeEx(certificate); certHash = certEx.Thumbprint; if (certEx != null) { if (certEx.HasPrivateKey) { if (NetEventSource.IsEnabled) NetEventSource.Log.CertIsType2(this); return certEx; } if ((object)certificate != (object)certEx) { certEx.Dispose(); } } X509Certificate2Collection collectionEx; // ELSE Try the MY user and machine stores for private key check. // For server side mode MY machine store takes priority. X509Store store = CertificateValidationPal.EnsureStoreOpened(_serverMode); if (store != null) { collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false); if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey) { if (NetEventSource.IsEnabled) NetEventSource.Log.FoundCertInStore(_serverMode, this); return collectionEx[0]; } } store = CertificateValidationPal.EnsureStoreOpened(!_serverMode); if (store != null) { collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false); if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey) { if (NetEventSource.IsEnabled) NetEventSource.Log.FoundCertInStore(_serverMode, this); return collectionEx[0]; } } } catch (CryptographicException) { } if (NetEventSource.IsEnabled) NetEventSource.Log.NotFoundCertInStore(this); return null; } private static X509Certificate2 MakeEx(X509Certificate certificate) { Debug.Assert(certificate != null, "certificate != null"); if (certificate.GetType() == typeof(X509Certificate2)) { return (X509Certificate2)certificate; } X509Certificate2 certificateEx = null; try { if (certificate.Handle != IntPtr.Zero) { certificateEx = new X509Certificate2(certificate.Handle); } } catch (SecurityException) { } catch (CryptographicException) { } return certificateEx; } // // Get certificate_authorities list, according to RFC 5246, Section 7.4.4. // Used only by client SSL code, never returns null. // private string[] GetRequestCertificateAuthorities() { string[] issuers = Array.Empty<string>(); if (IsValidContext) { issuers = CertificateValidationPal.GetRequestCertificateAuthorities(_securityContext); } return issuers; } /*++ AcquireCredentials - Attempts to find Client Credential Information, that can be sent to the server. In our case, this is only Client Certificates, that we have Credential Info. How it works: case 0: Cert Selection delegate is present Always use its result as the client cert answer. Try to use cached credential handle whenever feasible. Do not use cached anonymous creds if the delegate has returned null and the collection is not empty (allow responding with the cert later). case 1: Certs collection is empty Always use the same statically acquired anonymous SSL Credential case 2: Before our Connection with the Server If we have a cached credential handle keyed by first X509Certificate **content** in the passed collection, then we use that cached credential and hoping to restart a session. Otherwise create a new anonymous (allow responding with the cert later). case 3: After our Connection with the Server (i.e. during handshake or re-handshake) The server has requested that we send it a Certificate then we Enumerate a list of server sent Issuers trying to match against our list of Certificates, the first match is sent to the server. Once we got a cert we again try to match cached credential handle if possible. This will not restart a session but helps minimizing the number of handles we create. In the case of an error getting a Certificate or checking its private Key we fall back to the behavior of having no certs, case 1. Returns: True if cached creds were used, false otherwise. --*/ private bool AcquireClientCredentials(ref byte[] thumbPrint) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); // Acquire possible Client Certificate information and set it on the handle. X509Certificate clientCertificate = null; // This is a candidate that can come from the user callback or be guessed when targeting a session restart. var filteredCerts = new List<X509Certificate>(); // This is an intermediate client certs collection that try to use if no selectedCert is available yet. string[] issuers = null; // This is a list of issuers sent by the server, only valid is we do know what the server cert is. bool sessionRestartAttempt = false; // If true and no cached creds we will use anonymous creds. if (_certSelectionDelegate != null) { issuers = GetRequestCertificateAuthorities(); if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Calling CertificateSelectionCallback"); X509Certificate2 remoteCert = null; try { X509Certificate2Collection dummyCollection; remoteCert = CertificateValidationPal.GetRemoteCertificate(_securityContext, out dummyCollection); if (_clientCertificates == null) { _clientCertificates = new X509CertificateCollection(); } clientCertificate = _certSelectionDelegate(_hostName, _clientCertificates, remoteCert, issuers); } finally { if (remoteCert != null) { remoteCert.Dispose(); } } if (clientCertificate != null) { if (_credentialsHandle == null) { sessionRestartAttempt = true; } filteredCerts.Add(clientCertificate); if (NetEventSource.IsEnabled) NetEventSource.Log.CertificateFromDelegate(this); } else { if (_clientCertificates == null || _clientCertificates.Count == 0) { if (NetEventSource.IsEnabled) NetEventSource.Log.NoDelegateNoClientCert(this); sessionRestartAttempt = true; } else { if (NetEventSource.IsEnabled) NetEventSource.Log.NoDelegateButClientCert(this); } } } else if (_credentialsHandle == null && _clientCertificates != null && _clientCertificates.Count > 0) { // This is where we attempt to restart a session by picking the FIRST cert from the collection. // Otherwise it is either server sending a client cert request or the session is renegotiated. clientCertificate = _clientCertificates[0]; sessionRestartAttempt = true; if (clientCertificate != null) { filteredCerts.Add(clientCertificate); } if (NetEventSource.IsEnabled) NetEventSource.Log.AttemptingRestartUsingCert(clientCertificate, this); } else if (_clientCertificates != null && _clientCertificates.Count > 0) { // // This should be a server request for the client cert sent over currently anonymous sessions. // issuers = GetRequestCertificateAuthorities(); if (NetEventSource.IsEnabled) { if (issuers == null || issuers.Length == 0) { NetEventSource.Log.NoIssuersTryAllCerts(this); } else { NetEventSource.Log.LookForMatchingCerts(issuers.Length, this); } } for (int i = 0; i < _clientCertificates.Count; ++i) { // // Make sure we add only if the cert matches one of the issuers. // If no issuers were sent and then try all client certs starting with the first one. // if (issuers != null && issuers.Length != 0) { X509Certificate2 certificateEx = null; X509Chain chain = null; try { certificateEx = MakeEx(_clientCertificates[i]); if (certificateEx == null) { continue; } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Root cert: {certificateEx}"); chain = new X509Chain(); chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; chain.ChainPolicy.VerificationFlags = X509VerificationFlags.IgnoreInvalidName; chain.Build(certificateEx); bool found = false; // // We ignore any errors happened with chain. // if (chain.ChainElements.Count > 0) { for (int ii = 0; ii < chain.ChainElements.Count; ++ii) { string issuer = chain.ChainElements[ii].Certificate.Issuer; found = Array.IndexOf(issuers, issuer) != -1; if (found) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Matched {issuer}"); break; } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"No match: {issuer}"); } } if (!found) { continue; } } finally { if (chain != null) { chain.Dispose(); } if (certificateEx != null && (object)certificateEx != (object)_clientCertificates[i]) { certificateEx.Dispose(); } } } if (NetEventSource.IsEnabled) NetEventSource.Log.SelectedCert(_clientCertificates[i], this); filteredCerts.Add(_clientCertificates[i]); } } bool cachedCred = false; // This is a return result from this method. X509Certificate2 selectedCert = null; // This is a final selected cert (ensured that it does have private key with it). clientCertificate = null; if (NetEventSource.IsEnabled) { NetEventSource.Log.CertsAfterFiltering(filteredCerts.Count, this); if (filteredCerts.Count != 0) { NetEventSource.Log.FindingMatchingCerts(this); } } // // ATTN: When the client cert was returned by the user callback OR it was guessed AND it has no private key, // THEN anonymous (no client cert) credential will be used. // // SECURITY: Accessing X509 cert Credential is disabled for semitrust. // We no longer need to demand for unmanaged code permissions. // EnsurePrivateKey should do the right demand for us. for (int i = 0; i < filteredCerts.Count; ++i) { clientCertificate = filteredCerts[i]; if ((selectedCert = EnsurePrivateKey(clientCertificate)) != null) { break; } clientCertificate = null; selectedCert = null; } if ((object)clientCertificate != (object)selectedCert && !clientCertificate.Equals(selectedCert)) { NetEventSource.Fail(this, "'selectedCert' does not match 'clientCertificate'."); } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Selected cert = {selectedCert}"); try { // Try to locate cached creds first. // // SECURITY: selectedCert ref if not null is a safe object that does not depend on possible **user** inherited X509Certificate type. // byte[] guessedThumbPrint = selectedCert == null ? null : selectedCert.GetCertHash(); SafeFreeCredentials cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, _sslProtocols, _serverMode, _encryptionPolicy); // We can probably do some optimization here. If the selectedCert is returned by the delegate // we can always go ahead and use the certificate to create our credential // (instead of going anonymous as we do here). if (sessionRestartAttempt && cachedCredentialHandle == null && selectedCert != null && SslStreamPal.StartMutualAuthAsAnonymous) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Reset to anonymous session."); // IIS does not renegotiate a restarted session if client cert is needed. // So we don't want to reuse **anonymous** cached credential for a new SSL connection if the client has passed some certificate. // The following block happens if client did specify a certificate but no cached creds were found in the cache. // Since we don't restart a session the server side can still challenge for a client cert. if ((object)clientCertificate != (object)selectedCert) { selectedCert.Dispose(); } guessedThumbPrint = null; selectedCert = null; clientCertificate = null; } if (cachedCredentialHandle != null) { if (NetEventSource.IsEnabled) NetEventSource.Log.UsingCachedCredential(this); _credentialsHandle = cachedCredentialHandle; _selectedClientCertificate = clientCertificate; cachedCred = true; } else { _credentialsHandle = SslStreamPal.AcquireCredentialsHandle(selectedCert, _sslProtocols, _encryptionPolicy, _serverMode); thumbPrint = guessedThumbPrint; // Delay until here in case something above threw. _selectedClientCertificate = clientCertificate; } } finally { // An extra cert could have been created, dispose it now. if (selectedCert != null && (object)clientCertificate != (object)selectedCert) { selectedCert.Dispose(); } } if (NetEventSource.IsEnabled) NetEventSource.Exit(this, cachedCred, _credentialsHandle); return cachedCred; } // // Acquire Server Side Certificate information and set it on the class. // private bool AcquireServerCredentials(ref byte[] thumbPrint) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); X509Certificate localCertificate = null; bool cachedCred = false; if (_certSelectionDelegate != null) { X509CertificateCollection tempCollection = new X509CertificateCollection(); tempCollection.Add(_serverCertificate); localCertificate = _certSelectionDelegate(string.Empty, tempCollection, null, Array.Empty<string>()); if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Use delegate selected Cert"); } else { localCertificate = _serverCertificate; } if (localCertificate == null) { throw new NotSupportedException(SR.net_ssl_io_no_server_cert); } // SECURITY: Accessing X509 cert Credential is disabled for semitrust. // We no longer need to demand for unmanaged code permissions. // EnsurePrivateKey should do the right demand for us. X509Certificate2 selectedCert = EnsurePrivateKey(localCertificate); if (selectedCert == null) { throw new NotSupportedException(SR.net_ssl_io_no_server_cert); } if (!localCertificate.Equals(selectedCert)) { NetEventSource.Fail(this, "'selectedCert' does not match 'localCertificate'."); } // // Note selectedCert is a safe ref possibly cloned from the user passed Cert object // byte[] guessedThumbPrint = selectedCert.GetCertHash(); try { SafeFreeCredentials cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, _sslProtocols, _serverMode, _encryptionPolicy); if (cachedCredentialHandle != null) { _credentialsHandle = cachedCredentialHandle; _serverCertificate = localCertificate; cachedCred = true; } else { _credentialsHandle = SslStreamPal.AcquireCredentialsHandle(selectedCert, _sslProtocols, _encryptionPolicy, _serverMode); thumbPrint = guessedThumbPrint; _serverCertificate = localCertificate; } } finally { // An extra cert could have been created, dispose it now. if ((object)localCertificate != (object)selectedCert) { selectedCert.Dispose(); } } if (NetEventSource.IsEnabled) NetEventSource.Exit(this, cachedCred, _credentialsHandle); return cachedCred; } // internal ProtocolToken NextMessage(byte[] incoming, int offset, int count) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); byte[] nextmsg = null; SecurityStatusPal status = GenerateToken(incoming, offset, count, ref nextmsg); if (!_serverMode && status.ErrorCode == SecurityStatusPalErrorCode.CredentialsNeeded) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "NextMessage() returned SecurityStatusPal.CredentialsNeeded"); SetRefreshCredentialNeeded(); status = GenerateToken(incoming, offset, count, ref nextmsg); } ProtocolToken token = new ProtocolToken(nextmsg, status); if (NetEventSource.IsEnabled) NetEventSource.Exit(this, token); return token; } /*++ GenerateToken - Called after each successive state in the Client - Server handshake. This function generates a set of bytes that will be sent next to the server. The server responds, each response, is pass then into this function, again, and the cycle repeats until successful connection, or failure. Input: input - bytes from the wire output - ref to byte [], what we will send to the server in response Return: status - error information --*/ private SecurityStatusPal GenerateToken(byte[] input, int offset, int count, ref byte[] output) { #if TRACE_VERBOSE if (NetEventSource.IsEnabled) NetEventSource.Enter(this, $"_refreshCredentialNeeded = {_refreshCredentialNeeded}"); #endif if (offset < 0 || offset > (input == null ? 0 : input.Length)) { NetEventSource.Fail(this, "Argument 'offset' out of range."); throw new ArgumentOutOfRangeException(nameof(offset)); } if (count < 0 || count > (input == null ? 0 : input.Length - offset)) { NetEventSource.Fail(this, "Argument 'count' out of range."); throw new ArgumentOutOfRangeException(nameof(count)); } SecurityBuffer incomingSecurity = null; SecurityBuffer[] incomingSecurityBuffers = null; if (input != null) { incomingSecurity = new SecurityBuffer(input, offset, count, SecurityBufferType.SECBUFFER_TOKEN); incomingSecurityBuffers = new SecurityBuffer[] { incomingSecurity, new SecurityBuffer(null, 0, 0, SecurityBufferType.SECBUFFER_EMPTY) }; } SecurityBuffer outgoingSecurity = new SecurityBuffer(null, SecurityBufferType.SECBUFFER_TOKEN); SecurityStatusPal status = default(SecurityStatusPal); bool cachedCreds = false; byte[] thumbPrint = null; // // Looping through ASC or ISC with potentially cached credential that could have been // already disposed from a different thread before ISC or ASC dir increment a cred ref count. // try { do { thumbPrint = null; if (_refreshCredentialNeeded) { cachedCreds = _serverMode ? AcquireServerCredentials(ref thumbPrint) : AcquireClientCredentials(ref thumbPrint); } if (_serverMode) { status = SslStreamPal.AcceptSecurityContext( ref _credentialsHandle, ref _securityContext, incomingSecurity, outgoingSecurity, _remoteCertRequired); } else { if (incomingSecurity == null) { status = SslStreamPal.InitializeSecurityContext( ref _credentialsHandle, ref _securityContext, _destination, incomingSecurity, outgoingSecurity); } else { status = SslStreamPal.InitializeSecurityContext( _credentialsHandle, ref _securityContext, _destination, incomingSecurityBuffers, outgoingSecurity); } } } while (cachedCreds && _credentialsHandle == null); } finally { if (_refreshCredentialNeeded) { _refreshCredentialNeeded = false; // // Assuming the ISC or ASC has referenced the credential, // we want to call dispose so to decrement the effective ref count. // if (_credentialsHandle != null) { _credentialsHandle.Dispose(); } // // This call may bump up the credential reference count further. // Note that thumbPrint is retrieved from a safe cert object that was possible cloned from the user passed cert. // if (!cachedCreds && _securityContext != null && !_securityContext.IsInvalid && _credentialsHandle != null && !_credentialsHandle.IsInvalid) { SslSessionsCache.CacheCredential(_credentialsHandle, thumbPrint, _sslProtocols, _serverMode, _encryptionPolicy); } } } output = outgoingSecurity.token; return status; } /*++ ProcessHandshakeSuccess - Called on successful completion of Handshake - used to set header/trailer sizes for encryption use Fills in the information about established protocol --*/ internal void ProcessHandshakeSuccess() { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); StreamSizes streamSizes; SslStreamPal.QueryContextStreamSizes(_securityContext, out streamSizes); if (streamSizes != null) { try { _headerSize = streamSizes.Header; _trailerSize = streamSizes.Trailer; _maxDataSize = checked(streamSizes.MaximumMessage - (_headerSize + _trailerSize)); Debug.Assert(_maxDataSize > 0, "_maxDataSize > 0"); } catch (Exception e) when (!ExceptionCheck.IsFatal(e)) { NetEventSource.Fail(this, "StreamSizes out of range."); throw; } } SslStreamPal.QueryContextConnectionInfo(_securityContext, out _connectionInfo); if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } /*++ Encrypt - Encrypts our bytes before we send them over the wire PERF: make more efficient, this does an extra copy when the offset is non-zero. Input: buffer - bytes for sending offset - size - output - Encrypted bytes --*/ internal SecurityStatusPal Encrypt(byte[] buffer, int offset, int size, ref byte[] output, out int resultSize) { if (NetEventSource.IsEnabled) { NetEventSource.Enter(this, buffer, offset, size); NetEventSource.DumpBuffer(this, buffer, 0, Math.Min(buffer.Length, 128)); } byte[] writeBuffer = output; try { if (offset < 0 || offset > (buffer == null ? 0 : buffer.Length)) { throw new ArgumentOutOfRangeException(nameof(offset)); } if (size < 0 || size > (buffer == null ? 0 : buffer.Length - offset)) { throw new ArgumentOutOfRangeException(nameof(size)); } resultSize = 0; } catch (Exception e) when (!ExceptionCheck.IsFatal(e)) { NetEventSource.Fail(this, "Arguments out of range."); throw; } SecurityStatusPal secStatus = SslStreamPal.EncryptMessage( _securityContext, buffer, offset, size, _headerSize, _trailerSize, ref writeBuffer, out resultSize); if (secStatus.ErrorCode != SecurityStatusPalErrorCode.OK) { if (NetEventSource.IsEnabled) NetEventSource.Exit(this, $"ERROR {secStatus}"); } else { output = writeBuffer; if (NetEventSource.IsEnabled) NetEventSource.Exit(this, $"OK data size:{resultSize}"); } return secStatus; } internal SecurityStatusPal Decrypt(byte[] payload, ref int offset, ref int count) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, payload, offset, count); if (offset < 0 || offset > (payload == null ? 0 : payload.Length)) { NetEventSource.Fail(this, "Argument 'offset' out of range."); throw new ArgumentOutOfRangeException(nameof(offset)); } if (count < 0 || count > (payload == null ? 0 : payload.Length - offset)) { NetEventSource.Fail(this, "Argument 'count' out of range."); throw new ArgumentOutOfRangeException(nameof(count)); } SecurityStatusPal secStatus = SslStreamPal.DecryptMessage(_securityContext, payload, ref offset, ref count); return secStatus; } /*++ VerifyRemoteCertificate - Validates the content of a Remote Certificate checkCRL if true, checks the certificate revocation list for validity. checkCertName, if true checks the CN field of the certificate --*/ //This method validates a remote certificate. //SECURITY: The scenario is allowed in semitrust StorePermission is asserted for Chain.Build // A user callback has unique signature so it is safe to call it under permission assert. // internal bool VerifyRemoteCertificate(RemoteCertValidationCallback remoteCertValidationCallback, ref ProtocolToken alertToken) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); SslPolicyErrors sslPolicyErrors = SslPolicyErrors.None; // We don't catch exceptions in this method, so it's safe for "accepted" be initialized with true. bool success = false; X509Chain chain = null; X509Certificate2 remoteCertificateEx = null; try { X509Certificate2Collection remoteCertificateStore; remoteCertificateEx = CertificateValidationPal.GetRemoteCertificate(_securityContext, out remoteCertificateStore); _isRemoteCertificateAvailable = remoteCertificateEx != null; if (remoteCertificateEx == null) { if (NetEventSource.IsEnabled) NetEventSource.Exit(this, "(no remote cert)", !_remoteCertRequired); sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNotAvailable; } else { chain = new X509Chain(); chain.ChainPolicy.RevocationMode = _checkCertRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck; chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot; // Authenticate the remote party: (e.g. when operating in server mode, authenticate the client). chain.ChainPolicy.ApplicationPolicy.Add(_serverMode ? _clientAuthOid : _serverAuthOid); if (remoteCertificateStore != null) { chain.ChainPolicy.ExtraStore.AddRange(remoteCertificateStore); } sslPolicyErrors |= CertificateValidationPal.VerifyCertificateProperties( _securityContext, chain, remoteCertificateEx, _checkCertName, _serverMode, _hostName); } if (remoteCertValidationCallback != null) { success = remoteCertValidationCallback(_hostName, remoteCertificateEx, chain, sslPolicyErrors); } else { if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateNotAvailable && !_remoteCertRequired) { success = true; } else { success = (sslPolicyErrors == SslPolicyErrors.None); } } if (NetEventSource.IsEnabled) { LogCertificateValidation(remoteCertValidationCallback, sslPolicyErrors, success, chain); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"Cert validation, remote cert = {remoteCertificateEx}"); } if (!success) { alertToken = CreateFatalHandshakeAlertToken(sslPolicyErrors, chain); } } finally { // At least on Win2k server the chain is found to have dependencies on the original cert context. // So it should be closed first. if (chain != null) { chain.Dispose(); } if (remoteCertificateEx != null) { remoteCertificateEx.Dispose(); } } if (NetEventSource.IsEnabled) NetEventSource.Exit(this, success); return success; } public ProtocolToken CreateFatalHandshakeAlertToken(SslPolicyErrors sslPolicyErrors, X509Chain chain) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); TlsAlertMessage alertMessage; switch (sslPolicyErrors) { case SslPolicyErrors.RemoteCertificateChainErrors: alertMessage = GetAlertMessageFromChain(chain); break; case SslPolicyErrors.RemoteCertificateNameMismatch: alertMessage = TlsAlertMessage.BadCertificate; break; case SslPolicyErrors.RemoteCertificateNotAvailable: default: alertMessage = TlsAlertMessage.CertificateUnknown; break; } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"alertMessage:{alertMessage}"); SecurityStatusPal status; status = SslStreamPal.ApplyAlertToken(ref _credentialsHandle, _securityContext, TlsAlertType.Fatal, alertMessage); if (status.ErrorCode != SecurityStatusPalErrorCode.OK) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"ApplyAlertToken() returned {status.ErrorCode}"); if (status.Exception != null) { ExceptionDispatchInfo.Throw(status.Exception); } return null; } ProtocolToken token = GenerateAlertToken(); if (NetEventSource.IsEnabled) NetEventSource.Exit(this, token); return token; } public ProtocolToken CreateShutdownToken() { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); SecurityStatusPal status; status = SslStreamPal.ApplyShutdownToken(ref _credentialsHandle, _securityContext); if (status.ErrorCode != SecurityStatusPalErrorCode.OK) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"ApplyAlertToken() returned {status.ErrorCode}"); if (status.Exception != null) { ExceptionDispatchInfo.Throw(status.Exception); } return null; } ProtocolToken token = GenerateAlertToken(); if (NetEventSource.IsEnabled) NetEventSource.Exit(this, token); return token; } private ProtocolToken GenerateAlertToken() { byte[] nextmsg = null; SecurityStatusPal status; status = GenerateToken(null, 0, 0, ref nextmsg); ProtocolToken token = new ProtocolToken(nextmsg, status); return token; } private static TlsAlertMessage GetAlertMessageFromChain(X509Chain chain) { foreach (X509ChainStatus chainStatus in chain.ChainStatus) { if (chainStatus.Status == X509ChainStatusFlags.NoError) { continue; } if ((chainStatus.Status & (X509ChainStatusFlags.UntrustedRoot | X509ChainStatusFlags.PartialChain | X509ChainStatusFlags.Cyclic)) != 0) { return TlsAlertMessage.UnknownCA; } if ((chainStatus.Status & (X509ChainStatusFlags.Revoked | X509ChainStatusFlags.OfflineRevocation )) != 0) { return TlsAlertMessage.CertificateRevoked; } if ((chainStatus.Status & (X509ChainStatusFlags.CtlNotTimeValid | X509ChainStatusFlags.NotTimeNested | X509ChainStatusFlags.NotTimeValid)) != 0) { return TlsAlertMessage.CertificateExpired; } if ((chainStatus.Status & X509ChainStatusFlags.CtlNotValidForUsage) != 0) { return TlsAlertMessage.UnsupportedCert; } if ((chainStatus.Status & (X509ChainStatusFlags.CtlNotSignatureValid | X509ChainStatusFlags.InvalidExtension | X509ChainStatusFlags.NotSignatureValid | X509ChainStatusFlags.InvalidPolicyConstraints) | X509ChainStatusFlags.NoIssuanceChainPolicy | X509ChainStatusFlags.NotValidForUsage) != 0) { return TlsAlertMessage.BadCertificate; } // All other errors: return TlsAlertMessage.CertificateUnknown; } Debug.Fail("GetAlertMessageFromChain was called but none of the chain elements had errors."); return TlsAlertMessage.BadCertificate; } private void LogCertificateValidation(RemoteCertValidationCallback remoteCertValidationCallback, SslPolicyErrors sslPolicyErrors, bool success, X509Chain chain) { if (!NetEventSource.IsEnabled) return; if (sslPolicyErrors != SslPolicyErrors.None) { NetEventSource.Log.RemoteCertificateError(this, SR.net_log_remote_cert_has_errors); if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) != 0) { NetEventSource.Log.RemoteCertificateError(this, SR.net_log_remote_cert_not_available); } if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0) { NetEventSource.Log.RemoteCertificateError(this, SR.net_log_remote_cert_name_mismatch); } if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0) { string chainStatusString = "ChainStatus: "; foreach (X509ChainStatus chainStatus in chain.ChainStatus) { chainStatusString += "\t" + chainStatus.StatusInformation; } NetEventSource.Log.RemoteCertificateError(this, chainStatusString); } } if (success) { if (remoteCertValidationCallback != null) { NetEventSource.Log.RemoteCertDeclaredValid(this); } else { NetEventSource.Log.RemoteCertHasNoErrors(this); } } else { if (remoteCertValidationCallback != null) { NetEventSource.Log.RemoteCertUserDeclaredInvalid(this); } } } } // ProtocolToken - used to process and handle the return codes from the SSPI wrapper internal class ProtocolToken { internal SecurityStatusPal Status; internal byte[] Payload; internal int Size; internal bool Failed { get { return ((Status.ErrorCode != SecurityStatusPalErrorCode.OK) && (Status.ErrorCode != SecurityStatusPalErrorCode.ContinueNeeded)); } } internal bool Done { get { return (Status.ErrorCode == SecurityStatusPalErrorCode.OK); } } internal bool Renegotiate { get { return (Status.ErrorCode == SecurityStatusPalErrorCode.Renegotiate); } } internal bool CloseConnection { get { return (Status.ErrorCode == SecurityStatusPalErrorCode.ContextExpired); } } internal ProtocolToken(byte[] data, SecurityStatusPal status) { Status = status; Payload = data; Size = data != null ? data.Length : 0; } internal Exception GetException() { // If it's not done, then there's got to be an error, even if it's // a Handshake message up, and we only have a Warning message. return this.Done ? null : SslStreamPal.GetException(Status); } #if TRACE_VERBOSE public override string ToString() { return "Status=" + Status.ToString() + ", data size=" + Size; } #endif } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.IO; using CultureInfo = System.Globalization.CultureInfo; namespace System.Xml.Linq { /// <summary> /// Represents a class that allows elements to be streamed /// on input and output. /// </summary> public class XStreamingElement { internal XName name; internal object content; /// <summary> /// Creates a <see cref="XStreamingElement"/> node with a given name /// </summary> /// <param name="name">The name to assign to the new <see cref="XStreamingElement"/> node</param> public XStreamingElement(XName name) { if (name == null) throw new ArgumentNullException("name"); this.name = name; } /// <summary> /// Creates a <see cref="XStreamingElement"/> node with a given name and content /// </summary> /// <param name="name">The name to assign to the new <see cref="XStreamingElement"/> node</param> /// <param name="content">The content to assign to the new <see cref="XStreamingElement"/> node</param> public XStreamingElement(XName name, object content) : this(name) { this.content = content is List<object> ? new object[] { content } : content; } /// <summary> /// Creates a <see cref="XStreamingElement"/> node with a given name and content /// </summary> /// <param name="name">The name to assign to the new <see cref="XStreamingElement"/> node</param> /// <param name="content">An array containing content to assign to the new <see cref="XStreamingElement"/> node</param> public XStreamingElement(XName name, params object[] content) : this(name) { this.content = content; } /// <summary> /// Gets or sets the name of this streaming element. /// </summary> public XName Name { get { return name; } set { if (value == null) throw new ArgumentNullException("value"); name = value; } } /// <summary> /// Add content to an <see cref="XStreamingElement"/> /// </summary> /// <param name="content">Object containg content to add</param> public void Add(object content) { if (content != null) { List<object> list = this.content as List<object>; if (list == null) { list = new List<object>(); if (this.content != null) list.Add(this.content); this.content = list; } list.Add(content); } } /// <summary> /// Add content to an <see cref="XStreamingElement"/> /// </summary> /// <param name="content">array of objects containg content to add</param> public void Add(params object[] content) { Add((object)content); } /// <summary> /// Save the contents of an <see cref="XStreamingElement"/> to a <see cref="Stream"/> /// with formatting. /// </summary> /// <param name="stream"><see cref="Stream"/> to write to </param> public void Save(Stream stream) { Save(stream, SaveOptions.None); } /// <summary> /// Save the contents of an <see cref="XStreamingElement"/> to a <see cref="Stream"/>, /// optionally formatting. /// </summary> /// <param name="stream"><see cref="Stream"/> to write to </param> /// <param name="options"> /// If SaveOptions.DisableFormatting is enabled the output is not indented. /// If SaveOptions.OmitDuplicateNamespaces is enabled duplicate namespace declarations will be removed. /// </param> public void Save(Stream stream, SaveOptions options) { XmlWriterSettings ws = XNode.GetXmlWriterSettings(options); using (XmlWriter w = XmlWriter.Create(stream, ws)) { Save(w); } } /// <summary> /// Save the contents of an <see cref="XStreamingElement"/> to a text writer /// with formatting. /// </summary> /// <param name="textWriter"><see cref="TextWriter"/> to write to </param> public void Save(TextWriter textWriter) { Save(textWriter, SaveOptions.None); } /// <summary> /// Save the contents of an <see cref="XStreamingElement"/> to a text writer /// optionally formatting. /// </summary> /// <param name="textWriter"><see cref="TextWriter"/> to write to </param> /// <param name="options"> /// If SaveOptions.DisableFormatting is enabled the output is not indented. /// If SaveOptions.OmitDuplicateNamespaces is enabled duplicate namespace declarations will be removed. /// </param> public void Save(TextWriter textWriter, SaveOptions options) { XmlWriterSettings ws = XNode.GetXmlWriterSettings(options); using (XmlWriter w = XmlWriter.Create(textWriter, ws)) { Save(w); } } /// <summary> /// Save the contents of an <see cref="XStreamingElement"/> to an XML writer, not preserving whitepace /// </summary> /// <param name="writer"><see cref="XmlWriter"/> to write to </param> public void Save(XmlWriter writer) { if (writer == null) throw new ArgumentNullException("writer"); writer.WriteStartDocument(); WriteTo(writer); writer.WriteEndDocument(); } /// <summary> /// Get the XML content of an <see cref="XStreamingElement"/> as a /// formatted string. /// </summary> /// <returns>The XML text as a formatted string</returns> public override string ToString() { return GetXmlString(SaveOptions.None); } /// <summary> /// Gets the XML content of this streaming element as a string. /// </summary> /// <param name="options"> /// If SaveOptions.DisableFormatting is enabled the content is not indented. /// If SaveOptions.OmitDuplicateNamespaces is enabled duplicate namespace declarations will be removed. /// </param> /// <returns>An XML string</returns> public string ToString(SaveOptions options) { return GetXmlString(options); } /// <summary> /// Write this <see cref="XStreamingElement"/> to an <see cref="XmlWriter"/> /// </summary> /// <param name="writer"></param> public void WriteTo(XmlWriter writer) { if (writer == null) throw new ArgumentNullException("writer"); new StreamingElementWriter(writer).WriteStreamingElement(this); } string GetXmlString(SaveOptions o) { using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture)) { XmlWriterSettings ws = new XmlWriterSettings(); ws.OmitXmlDeclaration = true; if ((o & SaveOptions.DisableFormatting) == 0) ws.Indent = true; if ((o & SaveOptions.OmitDuplicateNamespaces) != 0) ws.NamespaceHandling |= NamespaceHandling.OmitDuplicates; using (XmlWriter w = XmlWriter.Create(sw, ws)) { WriteTo(w); } return sw.ToString(); } } } }
using System; using System.Collections.Generic; using System.Text; using System.Runtime.Serialization; using System.Collections; using Procurios.Public; namespace SPD.CommonObjects { /// <summary> /// differences between male and female /// </summary> [DataContract(Name = "Sex")] public enum Sex { /// <summary> /// {35A90EBF-F421-44A3-BE3A-47C72AFE47FE} /// </summary> [EnumMember] male, /// <summary> /// {35A90EBF-F421-44A3-BE3A-47C72AFE47FE} /// </summary> [EnumMember] female } /// <summary> /// Defines if an operation has hield pp or ps /// </summary> [DataContract(Name = "PPPS")] public enum PPPS { /// <summary> /// /// </summary> [EnumMember] notDefined = 0, /// <summary> /// /// </summary> [EnumMember] pp = 1, /// <summary> /// /// </summary> [EnumMember] ps = 2, } /// <summary> /// Defines if the healing of an Operation is ok or not ok /// This is not pp and ps /// </summary> [DataContract(Name = "Result")] public enum Result { /// <summary> /// /// </summary> [EnumMember] notDefined = 0, /// <summary> /// /// </summary> [EnumMember] ok = 1, /// <summary> /// /// </summary> [EnumMember] nok = 2 } /// <summary> /// /// </summary> [DataContract] public enum ActionKind { /// <summary> /// /// </summary> [EnumMember] control = 1, /// <summary> /// /// </summary> [EnumMember] operation = 2 } /// <summary> /// /// </summary> [DataContract] public enum ResidentOfAsmara { /// <summary> /// /// </summary> [EnumMember] undefined = 0, /// <summary> /// /// </summary> [EnumMember] yes = 1, /// <summary> /// /// </summary> [EnumMember] no = 2 } /// <summary> /// /// </summary> [DataContract] public enum Ambulant { /// <summary> /// /// </summary> [EnumMember] ambulant = 1, /// <summary> /// /// </summary> [EnumMember] notAmbulant = 2 } /// <summary> /// /// </summary> [DataContract] public enum Finished { /// <summary> /// /// </summary> [EnumMember] finished = 1, /// <summary> /// /// </summary> [EnumMember] notFinished = 2, /// <summary> /// /// </summary> [EnumMember] undefined = 0 } /// <summary> /// /// </summary> [DataContract] public enum Linz { /// <summary> /// /// </summary> [EnumMember] undefined = 0, /// <summary> /// /// </summary> [EnumMember] notPlanned = 1, /// <summary> /// /// </summary> [EnumMember] planned = 2, /// <summary> /// /// </summary> [EnumMember] running = 3, /// <summary> /// /// </summary> [EnumMember] finished = 4 } /// <summary> /// /// </summary> [DataContract] public enum Organ { /// <summary> /// /// </summary> [EnumMember] undefined = 0, /// <summary> /// /// </summary> [EnumMember] testicle = 1, //Hoden /// <summary> /// /// </summary> [EnumMember] renal = 2, //Nieren /// <summary> /// /// </summary> [EnumMember] penis = 3 } /// <summary> /// /// </summary> [DataContract] public class PatientData { private long id = -1; private string firstName; private string surName; private DateTime dateOfBirth; private Sex sex; private string phone; private int weight = -1; private string address; private ResidentOfAsmara residentOfAsmara = ResidentOfAsmara.undefined; private Ambulant ambulant = Ambulant.notAmbulant; private Finished finished = Finished.undefined; private Linz linz = Linz.undefined; private DateTime? waitListStartDate = null; /// <summary> /// Initializes a new instance of the <see cref="PatientData"/> class. /// </summary> public PatientData() { } /// <summary> /// Initializes a new instance of the <see cref="PatientData"/> class. /// </summary> /// <param name="id">The id.</param> /// <param name="firstname">The firstname.</param> /// <param name="surname">The surname.</param> /// <param name="dateOfBirth">The date of birth.</param> /// <param name="sex">The sex.</param> /// <param name="phone">The phone.</param> /// <param name="weight">The weight.</param> /// <param name="address">The address.</param> /// <param name="residentOfAsmara">The resident of asmara.</param> /// <param name="ambulant">The ambulant.</param> /// <param name="finished">The finished.</param> /// <param name="linz">The linz.</param> /// <param name="waitListStartDate">The wait List Start Date.</param> public PatientData(long id, string firstname, string surname, DateTime dateOfBirth, Sex sex, /*string city, string street,*/ string phone, int weight, string address, ResidentOfAsmara residentOfAsmara, Ambulant ambulant, Finished finished, Linz linz, DateTime? waitListStartDate) { this.id = id; this.firstName = firstname; this.surName = surname; this.dateOfBirth = dateOfBirth; this.sex = sex; this.phone = phone; this.weight = weight; this.address = address; this.residentOfAsmara = residentOfAsmara; this.ambulant = ambulant; this.finished = finished; this.Linz = linz; this.waitListStartDate = waitListStartDate; } /// <summary> /// Gets or sets the id. /// </summary> /// <value>The id.</value> [DataMember] public long Id { get { return id; } set { this.id = value; } } /// <summary> /// Gets or sets the first name. /// </summary> /// <value>The first name.</value> [DataMember] public string FirstName { get { return firstName; } set { firstName = value; } } /// <summary> /// Gets or sets the name of the sur. /// </summary> /// <value>The name of the sur.</value> [DataMember] public string SurName { get { return surName; } set { surName = value; } } /// <summary> /// Gets or sets the date of birth. /// </summary> /// <value>The date of birth.</value> [DataMember] public DateTime DateOfBirth { get { return dateOfBirth; } set { dateOfBirth = value; } } /// <summary> /// Gets or sets the sex. /// </summary> /// <value>The sex.</value> [DataMember] public Sex Sex { get { return sex; } set { sex = value; } } /// <summary> /// Gets or sets the phone. /// </summary> /// <value>The phone.</value> [DataMember] public string Phone { get { return phone; } set { phone = value; } } /// <summary> /// Gets or sets the weight. /// </summary> /// <value>The weight.</value> [DataMember] public int Weight { get { return weight; } set { weight = value; } } /// <summary> /// Gets or sets the address. /// </summary> /// <value>The address.</value> [DataMember] public string Address { get { return address; } set { address = value; } } /// <summary> /// Gets or sets the residentOfAsmara. /// </summary> /// <value>The address.</value> [DataMember] public ResidentOfAsmara ResidentOfAsmara { get { return residentOfAsmara; } set { residentOfAsmara = value; } } /// <summary> /// Gets or sets the ambulant. /// </summary> /// <value>The address.</value> [DataMember] public Ambulant Ambulant { get { return ambulant; } set { ambulant = value; } } /// <summary> /// Gets or sets the finished. /// </summary> /// <value>The address.</value> [DataMember] public Finished Finished { get { return finished; } set { finished = value; } } /// <summary> /// Gets or sets the finished. /// </summary> /// <value>The address.</value> [DataMember] public Linz Linz { get { return linz; } set { linz = value; } } /// <summary> /// Gets or Sets Wait List Start Time /// </summary> /// <value>The Date.</value> [DataMember] public DateTime? WaitListStartDate { get { return waitListStartDate; } set { waitListStartDate = value; } } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override string ToString() { return id.ToString() + " " + firstName + " " + surName + " " + dateOfBirth.ToShortDateString() + " " + sex.ToString() + " " + //city + " " + street; address + " " + weight + "kg "; } /// <summary> /// Toes the line breaked string. /// </summary> /// <returns></returns> public string ToLineBreakedString() { StringBuilder sb = new StringBuilder(); sb.Append("ID: ").Append(this.id).Append(Environment.NewLine); sb.Append("Fist Name: ").Append(this.firstName).Append(Environment.NewLine); sb.Append("Sur Name: ").Append(this.surName).Append(Environment.NewLine); sb.Append("Address: ").Append(this.address).Append(Environment.NewLine); sb.Append("Date Of Birth: ").Append(this.dateOfBirth).Append(Environment.NewLine); sb.Append("Phone: ").Append(this.phone).Append(Environment.NewLine); sb.Append("Sex: ").Append(this.sex).Append(Environment.NewLine); sb.Append("Weight: ").Append(this.weight).Append(Environment.NewLine); sb.Append("Ambuland: ").Append(this.ambulant).Append(Environment.NewLine); sb.Append("Finished: ").Append(this.finished).Append(Environment.NewLine); sb.Append("Linz: ").Append(this.linz).Append(Environment.NewLine); sb.Append("Resident Of Asmara: ").Append(this.residentOfAsmara); return sb.ToString(); } /// <summary> /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>. /// </summary> /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param> /// <returns> /// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false. /// </returns> /// <exception cref="T:System.NullReferenceException">The <paramref name="obj"/> parameter is null.</exception> public override bool Equals(object obj) { PatientData pd = obj as PatientData; if (pd == null) return false; return pd.Id == this.id; } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { return base.GetHashCode(); } } /// <summary> /// /// </summary> [DataContract] public class VisitData { private long visitId = -1; private string cause; private string localis; private string extradiagnosis; private string procedure; private string extratherapy; private long patientid; private DateTime visitDate; private string anesthesiology; private string ultrasound; private string blooddiagnostic; private string todo; private string radiodiagnostics; /// <summary> /// Initializes a new instance of the <see cref="VisitData"/> class. /// </summary> public VisitData() { } /// <summary> /// Initializes a new instance of the <see cref="VisitData"/> class. /// </summary> /// <param name="visitId">The visit id.</param> /// <param name="cause">The cause.</param> /// <param name="localis">The localis.</param> /// <param name="extradiagnosis">The extradiagnosis.</param> /// <param name="procedure">The procedure.</param> /// <param name="extratherapy">The extratherapy.</param> /// <param name="patientid">The patientid.</param> /// <param name="visitDate">The visit date.</param> /// <param name="anesthesiology">The anesthesiology.</param> /// <param name="ultrasound">The ultrasound.</param> /// <param name="blooddiagnostic">The blooddiagnostic.</param> /// <param name="todo">The todo.</param> /// <param name="radiodiagnostics">The radiodiagnostics.</param> public VisitData(long visitId, string cause, string localis, string extradiagnosis, string procedure, string extratherapy, long patientid, DateTime visitDate, string anesthesiology, string ultrasound, string blooddiagnostic, string todo, string radiodiagnostics) { this.visitId = visitId; this.cause = cause; this.localis = localis; this.extradiagnosis = extradiagnosis; this.procedure = procedure; this.extratherapy = extratherapy; this.patientid = patientid; this.visitDate = visitDate; this.anesthesiology = anesthesiology; this.ultrasound = ultrasound; this.blooddiagnostic = blooddiagnostic; this.todo = todo; this.radiodiagnostics = radiodiagnostics; } /// <summary> /// Gets or sets the id. /// </summary> /// <value>The id.</value> [DataMember] public long Id { get { return visitId; } set { this.visitId = value; } } /// <summary> /// Gets or sets the cause. /// </summary> /// <value>The cause.</value> [DataMember] public string Cause { get { return cause; } set { cause = value; } } /// <summary> /// Gets or sets the localis. /// </summary> /// <value>The localis.</value> [DataMember] public string Localis { get { return localis; } set { localis = value; } } /// <summary> /// Gets or sets the extra diagnosis. /// </summary> /// <value>The extra diagnosis.</value> [DataMember] public string ExtraDiagnosis { get { return extradiagnosis; } set { extradiagnosis = value; } } /// <summary> /// Gets or sets the procedure. /// </summary> /// <value>The procedure.</value> [DataMember] public string Procedure { get { return procedure; } set { procedure = value; } } /// <summary> /// Gets or sets the extra therapy. /// </summary> /// <value>The extra therapy.</value> [DataMember] public string ExtraTherapy { get { return extratherapy; } set { extratherapy = value; } } /// <summary> /// Gets or sets the patient id. /// </summary> /// <value>The patient id.</value> [DataMember] public long PatientId { get { return patientid; } set { patientid = value; } } /// <summary> /// Gets or sets the visit date. /// </summary> /// <value>The visit date.</value> [DataMember] public DateTime VisitDate { get { return visitDate; } set { visitDate = value; } } /// <summary> /// Gets or sets the anesthesiology. /// </summary> /// <value>The anesthesiology.</value> [DataMember] public string Anesthesiology { get { return anesthesiology; } set { anesthesiology = value; } } /// <summary> /// Gets or sets the ultrasound. /// </summary> /// <value>The ultrasound.</value> [DataMember] public string Ultrasound { get { return ultrasound; } set { ultrasound = value; } } /// <summary> /// Gets or sets the blooddiagnostic. /// </summary> /// <value>The blooddiagnostic.</value> [DataMember] public string Blooddiagnostic { get { return blooddiagnostic; } set { blooddiagnostic = value; } } /// <summary> /// Gets or sets the todo. /// </summary> /// <value>The todo.</value> [DataMember] public string Todo { get { return this.todo; } set { this.todo = value; } } /// <summary> /// Gets or sets the radiodiagnostics. /// </summary> /// <value>The radiodiagnostics.</value> [DataMember] public string Radiodiagnostics { get { return this.radiodiagnostics; } set { this.radiodiagnostics = value; } } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override string ToString() { return this.visitId.ToString(); } /// <summary> /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>. /// </summary> /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param> /// <returns> /// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false. /// </returns> /// <exception cref="T:System.NullReferenceException">The <paramref name="obj"/> parameter is null.</exception> public override bool Equals(object obj) { VisitData vd = obj as VisitData; if (vd == null) return false; return vd.Id == this.visitId; } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { return base.GetHashCode(); } } /// <summary> /// Operation Data /// </summary> [DataContract] public class OperationData { private long operationId = -1; private DateTime date; private string team; private string process; private string diagnoses; private string performed; private long patientId; private string additionalinformation; private string medication; private long intdiagnoses; private PPPS ppps = PPPS.notDefined; private Result result = Result.notDefined; private long kathDays = - 1; private Organ organ = Organ.undefined; private string opResult; /// <summary> /// Initializes a new instance of the <see cref="OperationData"/> class. /// </summary> public OperationData() { } /// <summary> /// Initializes a new instance of the <see cref="OperationData"/> class. /// </summary> /// <param name="operationId">The operation id.</param> /// <param name="date">The date.</param> /// <param name="team">The team.</param> /// <param name="process">The process.</param> /// <param name="diagnoses">The diagnoses.</param> /// <param name="performed">The performed.</param> /// <param name="patientId">The patient id.</param> /// <param name="additionalinformation">The additionalinformation.</param> /// <param name="medication">The medication.</param> /// <param name="intdiagnoses">The intdiagnoses.</param> /// <param name="ppps">The PPPS.</param> /// <param name="result">The result.</param> /// <param name="kathDays">Kathetar Days.</param> /// <param name="organ">Organ.</param> /// <param name="opResult">opResult.</param> public OperationData(long operationId, DateTime date, string team, string process, string diagnoses, string performed, long patientId, string additionalinformation, string medication, long intdiagnoses, PPPS ppps, Result result, long kathDays, Organ organ, string opResult) { this.operationId = operationId; this.date = date; this.team = team; this.process = process; this.diagnoses = diagnoses; this.performed = performed; this.patientId = patientId; this.additionalinformation = additionalinformation; this.medication = medication; this.intdiagnoses = intdiagnoses; this.ppps = ppps; this.result = result; this.kathDays = kathDays; this.organ = organ; this.opResult = opResult; } /// <summary> /// Gets or sets the operation id. /// </summary> /// <value>The operation id.</value> [DataMember] public long OperationId { get { return this.operationId; } set { this.operationId = value; } } /// <summary> /// Gets or sets the date. /// </summary> /// <value>The date.</value> [DataMember] public DateTime Date { get { return this.date; } set { this.date = value; } } /// <summary> /// Gets or sets the team. /// </summary> /// <value>The team.</value> [DataMember] public string Team { get { return this.team; } set { this.team = value; } } /// <summary> /// Gets or sets the process. /// </summary> /// <value>The process.</value> [DataMember] public string Process { get { return this.process; } set { this.process = value; } } /// <summary> /// Gets or sets the diagnoses. /// </summary> /// <value>The diagnoses.</value> [DataMember] public string Diagnoses { get { return this.diagnoses; } set { this.diagnoses = value; } } /// <summary> /// Gets or sets the performed. /// </summary> /// <value>The performed.</value> [DataMember] public string Performed { get { return this.performed; } set { this.performed = value; } } /// <summary> /// Gets or sets the patient id. /// </summary> /// <value>The patient id.</value> [DataMember] public long PatientId { get { return this.patientId; } set { this.patientId = value; } } /// <summary> /// Gets or sets the additionalinformation. /// </summary> /// <value>The additionalinformation.</value> [DataMember] public string Additionalinformation { get { return this.additionalinformation; } set { this.additionalinformation = value; } } /// <summary> /// Gets or sets the medication. /// </summary> /// <value>The medication.</value> [DataMember] public string Medication { get { return this.medication; } set { this.medication = value; } } /// <summary> /// Gets or sets the int diagnoses. /// </summary> /// <value>The int diagnoses.</value> [DataMember] public long IntDiagnoses { get { return this.intdiagnoses; } set { this.intdiagnoses = value; } } /// <summary> /// Gets or sets the PPPS. /// </summary> /// <value>The PPPS.</value> [DataMember] public PPPS Ppps { get { return this.ppps; } set { this.ppps = value; } } /// <summary> /// Gets or sets the result. /// </summary> /// <value>The result.</value> [DataMember] public Result Result { get { return this.result; } set { this.result = value; } } /// <summary> /// Gets or sets the katheder days. /// </summary> /// <value>The katheder days.</value> [DataMember] public long KathDays { get { return this.kathDays; } set { this.kathDays = value; } } /// <summary> /// Gets or sets the organ. /// </summary> /// <value>The organ.</value> [DataMember] public Organ Organ { get { return this.organ; } set { this.organ = value; } } /// <summary> /// Gets or sets the op result. /// </summary> /// <value>The op result.</value> [DataMember] public string OpResult { get { return this.opResult; } set { this.opResult = value; } } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override string ToString() { return this.operationId.ToString(); } /// <summary> /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>. /// </summary> /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param> /// <returns> /// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false. /// </returns> /// <exception cref="T:System.NullReferenceException">The <paramref name="obj"/> parameter is null.</exception> public override bool Equals(object obj) { OperationData od = obj as OperationData; if (od == null) return false; return od.OperationId == this.operationId; } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { return base.GetHashCode(); } } /// <summary> /// /// </summary> [DataContract] public class ImageData { private long photoID; private long patientID; private string link; private string kommentar; /// <summary> /// Initializes a new instance of the <see cref="ImageData"/> class. /// </summary> public ImageData() { } /// <summary> /// Initializes a new instance of the <see cref="ImageData"/> class. /// </summary> /// <param name="photoID">The photo ID.</param> /// <param name="patientID">The patient ID.</param> /// <param name="link">The link.</param> /// <param name="kommentar">The kommentar.</param> public ImageData(long photoID, long patientID, string link, string kommentar) { this.photoID = photoID; this.patientID = patientID; this.link = link; this.kommentar = kommentar; } /// <summary> /// Gets or sets the photo ID. /// </summary> /// <value>The photo ID.</value> [DataMember] public long PhotoID { get { return photoID; } set { this.photoID = value; } } /// <summary> /// Gets or sets the patient ID. /// </summary> /// <value>The patient ID.</value> [DataMember] public long PatientID { get { return patientID; } set { patientID = value; } } /// <summary> /// Gets or sets the link. /// </summary> /// <value>The link.</value> [DataMember] public string Link { get { return link; } set { link = value; } } /// <summary> /// Gets or sets the kommentar. /// </summary> /// <value>The kommentar.</value> [DataMember] public string Kommentar { get { return kommentar; } set { kommentar = value; } } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override string ToString() { return "ID:" + this.photoID.ToString() + " PID: " + this.patientID.ToString() + " Link: " + this.link + " Kommentar: " + this.kommentar; } /// <summary> /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>. /// </summary> /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param> /// <returns> /// true if the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>; otherwise, false. /// </returns> /// <exception cref="T:System.NullReferenceException">The <paramref name="obj"/> parameter is null.</exception> public override bool Equals(object obj) { ImageData id = obj as ImageData; if (id == null) return false; return id.PhotoID == this.photoID; } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { return base.GetHashCode(); } } /// <summary> /// Defines the next action for a patient e.g a patient has to have a control checkup 1/2009 /// </summary> [DataContract] public class NextActionData { private long nextActionID = -1; private long patientID; private ActionKind actionKind; private long actionYear; private long actionhalfYear; private string todo; /// <summary> /// Initializes a new instance of the <see cref="NextActionData"/> class. /// </summary> public NextActionData() { } /// <summary> /// Initializes a new instance of the <see cref="NextActionData"/> class. /// </summary> /// <param name="nextActionID">The next action ID.</param> /// <param name="patientID">The patient ID.</param> /// <param name="actionKind">Kind of the action.</param> /// <param name="actionYear">The action year.</param> /// <param name="actionhalfYear">The actionhalf year.</param> /// <param name="todo">ToDo.</param> public NextActionData(long nextActionID, long patientID, ActionKind actionKind, long actionYear, long actionhalfYear, string todo) { this.nextActionID = nextActionID; this.patientID = patientID; this.actionKind = actionKind; this.actionYear = actionYear; this.actionhalfYear = actionhalfYear; this.todo = todo; } /// <summary> /// Gets or sets the next action ID. /// </summary> /// <value>The next action ID.</value> [DataMember] public long NextActionID { get { return this.nextActionID; } set { this.nextActionID = value; } } /// <summary> /// Gets or sets the patient ID. /// </summary> /// <value>The patient ID.</value> [DataMember] public long PatientID { get { return this.patientID; } set { this.patientID = value; } } /// <summary> /// Gets or sets the kind of the action. /// </summary> /// <value>The kind of the action.</value> [DataMember] public ActionKind ActionKind { get { return this.actionKind; } set { this.actionKind = value; } } /// <summary> /// Gets or sets the action year. /// </summary> /// <value>The action year.</value> [DataMember] public long ActionYear { get { return this.actionYear; } set { this.actionYear = value; } } /// <summary> /// Gets or sets the actionhalf year. /// </summary> /// <value>The actionhalf year.</value> [DataMember] public long ActionhalfYear { get { return this.actionhalfYear; } set { this.actionhalfYear = value; } } /// <summary> /// Gets or sets the actionhalf year. /// </summary> /// <value>The actionhalf year.</value> [DataMember] public string Todo { get { return this.todo; } set { this.todo = value; } } /// <summary> /// Overrides the ToString() Method /// </summary> /// <returns></returns> public override string ToString() { return this.actionhalfYear.ToString() + "/" + this.actionYear.ToString() + " " + this.actionKind.ToString(); } } /// <summary> /// /// </summary> [DataContract] public class PatientDiagnoseGroupData { private long diagnoseGroupDataID; private long patientID; /// <summary> /// Constructor /// </summary> public PatientDiagnoseGroupData() { } /// <summary> /// Constructor /// </summary> /// <param name="patientID">patient Id</param> /// <param name="diagnoseGroupDataID"> Diagnose Group Id </param> public PatientDiagnoseGroupData(long patientID, long diagnoseGroupDataID) { this.patientID = patientID; this.diagnoseGroupDataID = diagnoseGroupDataID; } /// <summary> /// Gets or sets the diagnose group data ID. /// </summary> /// <value>The diagnose group data ID.</value> [DataMember] public long DiagnoseGroupDataID { get { return this.diagnoseGroupDataID; } set { this.diagnoseGroupDataID = value; } } /// <summary> /// Gets or sets the patient ID. /// </summary> /// <value>The patient ID.</value> [DataMember] public long PatientID { get { return this.patientID; } set { this.patientID = value; } } } /// <summary> /// /// </summary> [DataContract] public class DiagnoseGroupData { private long diagnoseGroupDataID; private string shortName; private string longName; /// <summary> /// Gets or sets the diagnose group data ID. /// </summary> /// <value>The diagnose group data ID.</value> [DataMember] public long DiagnoseGroupDataID { get { return this.diagnoseGroupDataID; } set { this.diagnoseGroupDataID = value; } } /// <summary> /// Gets or sets the short name. /// </summary> /// <value>The short name.</value> [DataMember] public string ShortName { get { return this.shortName; } set { this.shortName = value; } } /// <summary> /// Gets or sets the long name. /// </summary> /// <value>The long name.</value> [DataMember] public string LongName { get { return this.longName; } set { this.longName = value; } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> /// <exception cref="T:System.NullReferenceException"> /// The <paramref name="obj"/> parameter is null. /// </exception> public override bool Equals(object obj) { DiagnoseGroupData dgd = obj as DiagnoseGroupData; if (dgd == null) return false; return dgd.diagnoseGroupDataID == this.diagnoseGroupDataID; } /// <summary> /// Overrides the ToString() Method /// </summary> /// <returns></returns> public override string ToString() { return this.ShortName; //return // this.diagnoseGroupDataID.ToString() + "" + // this.shortName + " " + // this.longName; } /// <summary> /// Returns a hash code for this instance. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. /// </returns> public override int GetHashCode() { int prime = 31; int result = 1; result = prime * result + (int)diagnoseGroupDataID; result = prime * result + ((shortName == null) ? 0 : shortName.GetHashCode()); result = prime * result + ((longName == null) ? 0 : longName.GetHashCode()); return result; } } }
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using Scriban.Helpers; using Scriban.Runtime; using Scriban.Syntax; namespace Scriban.Parsing { public partial class Parser { private void ParseScribanStatement(string identifier, ScriptStatement parent, bool parseEndOfStatementAfterEnd, ref ScriptStatement statement, ref bool hasEnd, ref bool nextStatement) { var startToken = Current; switch (identifier) { case "end": hasEnd = true; statement = ParseEndStatement(parseEndOfStatementAfterEnd); break; case "wrap": CheckNotInCase(parent, startToken); statement = ParseWrapStatement(); break; case "if": CheckNotInCase(parent, startToken); statement = ParseIfStatement(false, null); break; case "case": CheckNotInCase(parent, startToken); statement = ParseCaseStatement(); break; case "when": var whenStatement = ParseWhenStatement(); var whenParent = parent as ScriptConditionStatement; if (parent is ScriptWhenStatement) { ((ScriptWhenStatement)whenParent).Next = whenStatement; } else if (parent is ScriptCaseStatement) { statement = whenStatement; } else { nextStatement = false; // unit test: TODO LogError(startToken, "A `when` condition must be preceded by another `when`/`else`/`case` condition"); } hasEnd = true; break; case "else": var nextCondition = ParseElseStatement(false); var parentCondition = parent as ScriptConditionStatement; if (parent is ScriptIfStatement || parent is ScriptWhenStatement) { if (parent is ScriptIfStatement) { ((ScriptIfStatement)parentCondition).Else = nextCondition; } else { ((ScriptWhenStatement)parentCondition).Next = nextCondition; } } else if (parent is ScriptForStatement forStatement) { forStatement.Else = (ScriptElseStatement)nextCondition; } else { nextStatement = false; // unit test: 201-if-else-error3.txt LogError(startToken, "A else condition must be preceded by another if/else/when condition or a for loop."); } hasEnd = true; break; case "for": CheckNotInCase(parent, startToken); if (PeekToken().Type == TokenType.Dot) { statement = ParseExpressionStatement(); } else { statement = ParseForStatement<ScriptForStatement>(); } break; case "tablerow": if (_isScientific) goto default; CheckNotInCase(parent, startToken); if (PeekToken().Type == TokenType.Dot) { statement = ParseExpressionStatement(); } else { statement = ParseForStatement<ScriptTableRowStatement>(); } break; case "with": CheckNotInCase(parent, startToken); statement = ParseWithStatement(); break; case "import": CheckNotInCase(parent, startToken); statement = ParseImportStatement(); break; case "readonly": CheckNotInCase(parent, startToken); statement = ParseReadOnlyStatement(); break; case "while": CheckNotInCase(parent, startToken); if (PeekToken().Type == TokenType.Dot) { statement = ParseExpressionStatement(); } else { statement = ParseWhileStatement(); } break; case "break": CheckNotInCase(parent, startToken); var breakStatement = Open<ScriptBreakStatement>(); statement = breakStatement; ExpectAndParseKeywordTo(breakStatement.BreakKeyword); // Parse break ExpectEndOfStatement(); Close(statement); // This has to be done at execution time, because of the wrap statement //if (!IsInLoop()) //{ // LogError(statement, "Unexpected statement outside of a loop"); //} break; case "continue": CheckNotInCase(parent, startToken); var continueStatement = Open<ScriptContinueStatement>(); statement = continueStatement; ExpectAndParseKeywordTo(continueStatement.ContinueKeyword); // Parse continue keyword ExpectEndOfStatement(); Close(statement); // This has to be done at execution time, because of the wrap statement //if (!IsInLoop()) //{ // LogError(statement, "Unexpected statement outside of a loop"); //} break; case "func": CheckNotInCase(parent, startToken); statement = ParseFunctionStatement(false); break; case "ret": CheckNotInCase(parent, startToken); statement = ParseReturnStatement(); break; case "capture": CheckNotInCase(parent, startToken); statement = ParseCaptureStatement(); break; default: CheckNotInCase(parent, startToken); // Otherwise it is an expression statement statement = ParseExpressionStatement(); break; } } private ScriptEndStatement ParseEndStatement(bool parseEndOfStatementAfterEnd) { var endStatement = Open<ScriptEndStatement>(); ExpectAndParseKeywordTo(endStatement.EndKeyword); if (parseEndOfStatementAfterEnd) { ExpectEndOfStatement(); } return Close(endStatement); } private ScriptFunction ParseFunctionStatement(bool isAnonymous) { var scriptFunction = Open<ScriptFunction>(); var previousExpressionLevel = _expressionLevel; try { // Reset expression level when parsing _expressionLevel = 0; if (isAnonymous) { scriptFunction.NameOrDoToken = ExpectAndParseKeywordTo(ScriptKeyword.Do()); } else { scriptFunction.FuncToken = ExpectAndParseKeywordTo(ScriptKeyword.Func()); scriptFunction.NameOrDoToken = ExpectAndParseVariable(scriptFunction); } // If we have parenthesis, this is a function with explicit parameters if (Current.Type == TokenType.OpenParen) { scriptFunction.OpenParen = ParseToken(TokenType.OpenParen); var parameters = new ScriptList<ScriptParameter>(); bool hasTripleDot = false; bool hasOptionals = false; bool isFirst = true; while (true) { // Parse any required comma (before each new non-first argument) // Or closing parent (and we exit the loop) if (Current.Type == TokenType.CloseParen) { scriptFunction.CloseParen = ParseToken(TokenType.CloseParen); scriptFunction.Span.End = scriptFunction.CloseParen.Span.End; break; } if (!isFirst) { if (Current.Type == TokenType.Comma) { PushTokenToTrivia(); NextToken(); FlushTriviasToLastTerminal(); } else { LogError(Current, "Expecting a comma to separate arguments in a function call."); } } isFirst = false; // Else we expect an expression if (IsStartOfExpression()) { var parameter = Open<ScriptParameter>(); var arg = ExpectAndParseVariable(scriptFunction); if (!(arg is ScriptVariableGlobal)) { LogError(arg.Span, "Expecting only a simple name parameter for a function"); } parameter.Name = arg; if (Current.Type == TokenType.Equal) { if (hasTripleDot) { LogError(arg.Span, "Cannot declare an optional parameter after a variable parameter (`...`)."); } hasOptionals = true; parameter.EqualOrTripleDotToken = ScriptToken.Equal(); ExpectAndParseTokenTo(parameter.EqualOrTripleDotToken, TokenType.Equal); parameter.Span.End = parameter.EqualOrTripleDotToken.Span.End; var defaultValue = ExpectAndParseExpression(parameter); if (defaultValue is ScriptLiteral literal) { parameter.DefaultValue = literal; parameter.Span.End = literal.Span.End; } else { LogError(arg.Span, "Expecting only a literal for an optional parameter value."); } } else if (Current.Type == TokenType.TripleDot) { if (hasTripleDot) { LogError(arg.Span, "Cannot declare multiple variable parameters."); } hasTripleDot = true; hasOptionals = true; parameter.EqualOrTripleDotToken = ScriptToken.TripleDot(); ExpectAndParseTokenTo(parameter.EqualOrTripleDotToken, TokenType.TripleDot); parameter.Span.End = parameter.EqualOrTripleDotToken.Span.End; } else if (hasOptionals) { LogError(arg.Span, "Cannot declare a normal parameter after an optional parameter."); } parameters.Add(parameter); scriptFunction.Span.End = parameter.Span.End; } else { LogError(Current, "Expecting an expression for argument function calls instead of this token."); break; } } if (scriptFunction.CloseParen == null) { LogError(Current, "Expecting a closing parenthesis for a function call."); } // Setup parameters once they have been all parsed scriptFunction.Parameters = parameters; } ExpectEndOfStatement(); // If the function is anonymous we don't expect an EOS after the `end` scriptFunction.Body = ParseBlockStatement(scriptFunction, !isAnonymous); } finally { _expressionLevel = previousExpressionLevel; } return Close(scriptFunction); } private ScriptImportStatement ParseImportStatement() { var importStatement = Open<ScriptImportStatement>(); ExpectAndParseKeywordTo(importStatement.ImportKeyword); // Parse import keyword importStatement.Expression = ExpectAndParseExpression(importStatement); ExpectEndOfStatement(); return Close(importStatement); } private ScriptReadOnlyStatement ParseReadOnlyStatement() { var readOnlyStatement = Open<ScriptReadOnlyStatement>(); ExpectAndParseKeywordTo(readOnlyStatement.ReadOnlyKeyword); // Parse readonly keyword readOnlyStatement.Variable = ExpectAndParseVariable(readOnlyStatement); ExpectEndOfStatement(); return Close(readOnlyStatement); } private ScriptReturnStatement ParseReturnStatement() { var ret = Open<ScriptReturnStatement>(); ExpectAndParseKeywordTo(ret.RetKeyword); // Parse ret keyword if (IsStartOfExpression()) { ret.Expression = ParseExpression(ret); } ExpectEndOfStatement(); return Close(ret); } private ScriptWhileStatement ParseWhileStatement() { var whileStatement = Open<ScriptWhileStatement>(); ExpectAndParseKeywordTo(whileStatement.WhileKeyword); // Parse while keyword // Parse the condition // unit test: 220-while-error1.txt whileStatement.Condition = ExpectAndParseExpression(whileStatement, allowAssignment: false); if (ExpectEndOfStatement()) { whileStatement.Body = ParseBlockStatement(whileStatement); } return Close(whileStatement); } private ScriptWithStatement ParseWithStatement() { var withStatement = Open<ScriptWithStatement>(); ExpectAndParseKeywordTo(withStatement.WithKeyword); // // Parse with keyword withStatement.Name = ExpectAndParseExpression(withStatement); if (ExpectEndOfStatement()) { withStatement.Body = ParseBlockStatement(withStatement); } return Close(withStatement); } private ScriptWrapStatement ParseWrapStatement() { var wrapStatement = Open<ScriptWrapStatement>(); ExpectAndParseKeywordTo(wrapStatement.WrapKeyword); // Parse wrap keyword wrapStatement.Target = ExpectAndParseExpression(wrapStatement); if (ExpectEndOfStatement()) { wrapStatement.Body = ParseBlockStatement(wrapStatement); } return Close(wrapStatement); } private void FixRawStatementAfterFrontMatter(ScriptPage page) { // In case of parsing a front matter, we don't want to include any \r\n after the end of the front-matter // So we manipulate back the syntax tree for the expected raw statement (if any), otherwise we can early // exit. var rawStatement = page.Body.Statements.FirstOrDefault() as ScriptRawStatement; if (rawStatement == null) { return; } rawStatement.Text = rawStatement.Text.TrimStart(); } private static bool IsScribanKeyword(string text) { switch (text) { case "if": case "else": case "end": case "for": case "case": case "when": case "while": case "break": case "continue": case "func": case "import": case "readonly": case "with": case "capture": case "ret": case "wrap": case "do": return true; } return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using System.Globalization; using Xunit; namespace System.Text.Tests { public static partial class RuneTests { [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsWindows8xOrLater))] // the localization tables used by our test data only exist on Win8+ [PlatformSpecific(TestPlatforms.Windows)] [InlineData('0', '0', '0', "en-US")] [InlineData('a', 'A', 'a', "en-US")] [InlineData('i', 'I', 'i', "en-US")] [InlineData('i', '\u0130', 'i', "tr-TR")] [InlineData('z', 'Z', 'z', "en-US")] [InlineData('A', 'A', 'a', "en-US")] [InlineData('I', 'I', 'i', "en-US")] [InlineData('I', 'I', '\u0131', "tr-TR")] [InlineData('Z', 'Z', 'z', "en-US")] [InlineData('\u00DF', '\u00DF', '\u00DF', "de-DE")] // U+00DF LATIN SMALL LETTER SHARP S -- n.b. ToUpper doesn't create the majuscule form [InlineData('\u0130', '\u0130', 'i', "tr-TR")] // U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE [InlineData('\u0131', 'I', '\u0131', "tr-TR")] // U+0131 LATIN SMALL LETTER DOTLESS I [InlineData('\u1E9E', '\u1E9E', '\u00DF', "de-DE")] // U+1E9E LATIN CAPITAL LETTER SHARP S [InlineData(0x10400, 0x10400, 0x10428, "en-US")] // U+10400 DESERET CAPITAL LETTER LONG I [InlineData(0x10428, 0x10400, 0x10428, "en-US")] // U+10428 DESERET SMALL LETTER LONG I public static void Casing_CultureAware(int original, int upper, int lower, string culture) { var rune = new Rune(original); var cultureInfo = CultureInfo.GetCultureInfo(culture); Assert.Equal(new Rune(upper), Rune.ToUpper(rune, cultureInfo)); Assert.Equal(new Rune(lower), Rune.ToLower(rune, cultureInfo)); } // Invariant ToUpper / ToLower doesn't modify Turkish I or majuscule Eszett [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsWindows8xOrLater))] // the localization tables used by our test data only exist on Win8+ [PlatformSpecific(TestPlatforms.Windows)] [InlineData('0', '0', '0')] [InlineData('a', 'A', 'a')] [InlineData('i', 'I', 'i')] [InlineData('z', 'Z', 'z')] [InlineData('A', 'A', 'a')] [InlineData('I', 'I', 'i')] [InlineData('Z', 'Z', 'z')] [InlineData('\u00DF', '\u00DF', '\u00DF')] // U+00DF LATIN SMALL LETTER SHARP S [InlineData('\u0130', '\u0130', '\u0130')] // U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE [InlineData('\u0131', '\u0131', '\u0131')] // U+0131 LATIN SMALL LETTER DOTLESS I [InlineData('\u1E9E', '\u1E9E', '\u1E9E')] // U+1E9E LATIN CAPITAL LETTER SHARP S [InlineData(0x10400, 0x10400, 0x10428)] // U+10400 DESERET CAPITAL LETTER LONG I [InlineData(0x10428, 0x10400, 0x10428)] // U+10428 DESERET SMALL LETTER LONG I public static void Casing_Invariant(int original, int upper, int lower) { var rune = new Rune(original); Assert.Equal(new Rune(upper), Rune.ToUpperInvariant(rune)); Assert.Equal(new Rune(lower), Rune.ToLowerInvariant(rune)); } [Theory] [MemberData(nameof(GeneralTestData_BmpCodePoints_NoSurrogates))] public static void Ctor_Cast_Char_Valid(GeneralTestData testData) { Rune rune = new Rune(checked((char)testData.ScalarValue)); Rune runeFromCast = (Rune)(char)testData.ScalarValue; Assert.Equal(rune, runeFromCast); Assert.Equal(testData.ScalarValue, rune.Value); Assert.Equal(testData.IsAscii, rune.IsAscii); Assert.Equal(testData.IsBmp, rune.IsBmp); Assert.Equal(testData.Plane, rune.Plane); } [Theory] [MemberData(nameof(BmpCodePoints_SurrogatesOnly))] public static void Ctor_Cast_Char_Invalid_Throws(char ch) { Assert.Throws<ArgumentOutOfRangeException>(nameof(ch), () => new Rune(ch)); Assert.Throws<ArgumentOutOfRangeException>(nameof(ch), () => (Rune)ch); } [Theory] [MemberData(nameof(GeneralTestData_BmpCodePoints_NoSurrogates))] [MemberData(nameof(GeneralTestData_SupplementaryCodePoints_ValidOnly))] public static void Ctor_Cast_Int32_Valid(GeneralTestData testData) { Rune rune = new Rune((int)testData.ScalarValue); Rune runeFromCast = (Rune)(int)testData.ScalarValue; Assert.Equal(rune, runeFromCast); Assert.Equal(testData.ScalarValue, rune.Value); Assert.Equal(testData.IsAscii, rune.IsAscii); Assert.Equal(testData.IsBmp, rune.IsBmp); Assert.Equal(testData.Plane, rune.Plane); } [Theory] [MemberData(nameof(BmpCodePoints_SurrogatesOnly))] [MemberData(nameof(SupplementaryCodePoints_InvalidOnly))] public static void Ctor_Cast_Int32_Invalid_Throws(int value) { Assert.Throws<ArgumentOutOfRangeException>(nameof(value), () => new Rune(value)); Assert.Throws<ArgumentOutOfRangeException>(nameof(value), () => (Rune)value); } [Theory] [MemberData(nameof(GeneralTestData_BmpCodePoints_NoSurrogates))] [MemberData(nameof(GeneralTestData_SupplementaryCodePoints_ValidOnly))] public static void Ctor_Cast_UInt32_Valid(GeneralTestData testData) { Rune rune = new Rune((uint)testData.ScalarValue); Rune runeFromCast = (Rune)(uint)testData.ScalarValue; Assert.Equal(rune, runeFromCast); Assert.Equal(testData.ScalarValue, rune.Value); Assert.Equal(testData.IsAscii, rune.IsAscii); Assert.Equal(testData.IsBmp, rune.IsBmp); Assert.Equal(testData.Plane, rune.Plane); } [Theory] [MemberData(nameof(BmpCodePoints_SurrogatesOnly))] [MemberData(nameof(SupplementaryCodePoints_InvalidOnly))] public static void Ctor_Cast_UInt32_Invalid_Throws(int value) { Assert.Throws<ArgumentOutOfRangeException>(nameof(value), () => new Rune((uint)value)); Assert.Throws<ArgumentOutOfRangeException>(nameof(value), () => (Rune)(uint)value); } [Theory] [MemberData(nameof(SurrogatePairTestData_ValidOnly))] public static void Ctor_SurrogatePair_Valid(char highSurrogate, char lowSurrogate, int expectedValue) { Assert.Equal(expectedValue, new Rune(highSurrogate, lowSurrogate).Value); } [Theory] [MemberData(nameof(SurrogatePairTestData_InvalidOnly))] public static void Ctor_SurrogatePair_Valid(char highSurrogate, char lowSurrogate) { string expectedParamName = !char.IsHighSurrogate(highSurrogate) ? nameof(highSurrogate) : nameof(lowSurrogate); Assert.Throws<ArgumentOutOfRangeException>(expectedParamName, () => new Rune(highSurrogate, lowSurrogate)); } [Theory] [InlineData('A', 'a', -1)] [InlineData('A', 'A', 0)] [InlineData('a', 'A', 1)] [InlineData(0x10000, 0x10000, 0)] [InlineData('\uFFFD', 0x10000, -1)] [InlineData(0x10FFFF, 0x10000, 1)] public static void CompareTo_And_ComparisonOperators(int first, int other, int expectedSign) { Rune a = new Rune(first); Rune b = new Rune(other); Assert.Equal(expectedSign, Math.Sign(a.CompareTo(b))); Assert.Equal(expectedSign < 0, a < b); Assert.Equal(expectedSign <= 0, a <= b); Assert.Equal(expectedSign > 0, a > b); Assert.Equal(expectedSign >= 0, a >= b); } [Theory] [InlineData(new char[0], OperationStatus.NeedMoreData, 0xFFFD, 0)] // empty buffer [InlineData(new char[] { '\u1234' }, OperationStatus.Done, 0x1234, 1)] // BMP char [InlineData(new char[] { '\u1234', '\ud800' }, OperationStatus.Done, 0x1234, 1)] // BMP char [InlineData(new char[] { '\ud83d', '\ude32' }, OperationStatus.Done, 0x1F632, 2)] // supplementary value (U+1F632 ASTONISHED FACE) [InlineData(new char[] { '\udc00' }, OperationStatus.InvalidData, 0xFFFD, 1)] // standalone low surrogate [InlineData(new char[] { '\udc00', '\udc00' }, OperationStatus.InvalidData, 0xFFFD, 1)] // standalone low surrogate [InlineData(new char[] { '\udc00', '\udc00' }, OperationStatus.InvalidData, 0xFFFD, 1)] // standalone low surrogate [InlineData(new char[] { '\ud800' }, OperationStatus.NeedMoreData, 0xFFFD, 1)] // high surrogate at end of buffer [InlineData(new char[] { '\ud800', '\ud800' }, OperationStatus.InvalidData, 0xFFFD, 1)] // standalone high surrogate [InlineData(new char[] { '\ud800', '\u1234' }, OperationStatus.InvalidData, 0xFFFD, 1)] // standalone high surrogate public static void DecodeFromUtf16(char[] data, OperationStatus expectedOperationStatus, int expectedRuneValue, int expectedCharsConsumed) { Assert.Equal(expectedOperationStatus, Rune.DecodeFromUtf16(data, out Rune actualRune, out int actualCharsConsumed)); Assert.Equal(expectedRuneValue, actualRune.Value); Assert.Equal(expectedCharsConsumed, actualCharsConsumed); } [Theory] [InlineData(new char[0], OperationStatus.NeedMoreData, 0xFFFD, 0)] // empty buffer [InlineData(new char[] { '\u1234', '\u5678' }, OperationStatus.Done, 0x5678, 1)] // BMP char [InlineData(new char[] { '\udc00', '\ud800' }, OperationStatus.NeedMoreData, 0xFFFD, 1)] // high surrogate at end of buffer [InlineData(new char[] { '\ud83d', '\ude32' }, OperationStatus.Done, 0x1F632, 2)] // supplementary value (U+1F632 ASTONISHED FACE) [InlineData(new char[] { '\u1234', '\udc00' }, OperationStatus.InvalidData, 0xFFFD, 1)] // standalone low surrogate [InlineData(new char[] { '\udc00' }, OperationStatus.InvalidData, 0xFFFD, 1)] // standalone low surrogate public static void DecodeLastFromUtf16(char[] data, OperationStatus expectedOperationStatus, int expectedRuneValue, int expectedCharsConsumed) { Assert.Equal(expectedOperationStatus, Rune.DecodeLastFromUtf16(data, out Rune actualRune, out int actualCharsConsumed)); Assert.Equal(expectedRuneValue, actualRune.Value); Assert.Equal(expectedCharsConsumed, actualCharsConsumed); } [Theory] [InlineData(new byte[0], OperationStatus.NeedMoreData, 0xFFFD, 0)] // empty buffer [InlineData(new byte[] { 0x30 }, OperationStatus.Done, 0x0030, 1)] // ASCII byte [InlineData(new byte[] { 0x30, 0x40, 0x50 }, OperationStatus.Done, 0x0030, 1)] // ASCII byte [InlineData(new byte[] { 0x80 }, OperationStatus.InvalidData, 0xFFFD, 1)] // standalone continuation byte [InlineData(new byte[] { 0x80, 0x80, 0x80 }, OperationStatus.InvalidData, 0xFFFD, 1)] // standalone continuation byte [InlineData(new byte[] { 0xC1 }, OperationStatus.InvalidData, 0xFFFD, 1)] // C1 is never a valid UTF-8 byte [InlineData(new byte[] { 0xF5 }, OperationStatus.InvalidData, 0xFFFD, 1)] // F5 is never a valid UTF-8 byte [InlineData(new byte[] { 0xC2 }, OperationStatus.NeedMoreData, 0xFFFD, 1)] // C2 is a valid byte; expecting it to be followed by a continuation byte [InlineData(new byte[] { 0xED }, OperationStatus.NeedMoreData, 0xFFFD, 1)] // ED is a valid byte; expecting it to be followed by a continuation byte [InlineData(new byte[] { 0xF4 }, OperationStatus.NeedMoreData, 0xFFFD, 1)] // F4 is a valid byte; expecting it to be followed by a continuation byte [InlineData(new byte[] { 0xC2, 0xC2 }, OperationStatus.InvalidData, 0xFFFD, 1)] // C2 not followed by continuation byte [InlineData(new byte[] { 0xC3, 0x90 }, OperationStatus.Done, 0x00D0, 2)] // [ C3 90 ] is U+00D0 LATIN CAPITAL LETTER ETH [InlineData(new byte[] { 0xC1, 0xBF }, OperationStatus.InvalidData, 0xFFFD, 1)] // [ C1 BF ] is overlong 2-byte sequence, all overlong sequences have maximal invalid subsequence length 1 [InlineData(new byte[] { 0xE0, 0x9F }, OperationStatus.InvalidData, 0xFFFD, 1)] // [ E0 9F ] is overlong 3-byte sequence, all overlong sequences have maximal invalid subsequence length 1 [InlineData(new byte[] { 0xE0, 0xA0 }, OperationStatus.NeedMoreData, 0xFFFD, 2)] // [ E0 A0 ] is valid 2-byte start of 3-byte sequence [InlineData(new byte[] { 0xED, 0x9F }, OperationStatus.NeedMoreData, 0xFFFD, 2)] // [ ED 9F ] is valid 2-byte start of 3-byte sequence [InlineData(new byte[] { 0xED, 0xBF }, OperationStatus.InvalidData, 0xFFFD, 1)] // [ ED BF ] would place us in UTF-16 surrogate range, all surrogate sequences have maximal invalid subsequence length 1 [InlineData(new byte[] { 0xEE, 0x80 }, OperationStatus.NeedMoreData, 0xFFFD, 2)] // [ EE 80 ] is valid 2-byte start of 3-byte sequence [InlineData(new byte[] { 0xF0, 0x8F }, OperationStatus.InvalidData, 0xFFFD, 1)] // [ F0 8F ] is overlong 4-byte sequence, all overlong sequences have maximal invalid subsequence length 1 [InlineData(new byte[] { 0xF0, 0x90 }, OperationStatus.NeedMoreData, 0xFFFD, 2)] // [ F0 90 ] is valid 2-byte start of 4-byte sequence [InlineData(new byte[] { 0xF4, 0x90 }, OperationStatus.InvalidData, 0xFFFD, 1)] // [ F4 90 ] would place us beyond U+10FFFF, all such sequences have maximal invalid subsequence length 1 [InlineData(new byte[] { 0xE2, 0x88, 0xB4 }, OperationStatus.Done, 0x2234, 3)] // [ E2 88 B4 ] is U+2234 THEREFORE [InlineData(new byte[] { 0xE2, 0x88, 0xC0 }, OperationStatus.InvalidData, 0xFFFD, 2)] // [ E2 88 ] followed by non-continuation byte, maximal invalid subsequence length 2 [InlineData(new byte[] { 0xF0, 0x9F, 0x98 }, OperationStatus.NeedMoreData, 0xFFFD, 3)] // [ F0 9F 98 ] is valid 3-byte start of 4-byte sequence [InlineData(new byte[] { 0xF0, 0x9F, 0x98, 0x20 }, OperationStatus.InvalidData, 0xFFFD, 3)] // [ F0 9F 98 ] followed by non-continuation byte, maximal invalid subsequence length 3 [InlineData(new byte[] { 0xF0, 0x9F, 0x98, 0xB2 }, OperationStatus.Done, 0x1F632, 4)] // [ F0 9F 98 B2 ] is U+1F632 ASTONISHED FACE public static void DecodeFromUtf8(byte[] data, OperationStatus expectedOperationStatus, int expectedRuneValue, int expectedBytesConsumed) { Assert.Equal(expectedOperationStatus, Rune.DecodeFromUtf8(data, out Rune actualRune, out int actualBytesConsumed)); Assert.Equal(expectedRuneValue, actualRune.Value); Assert.Equal(expectedBytesConsumed, actualBytesConsumed); } [Theory] [InlineData(new byte[0], OperationStatus.NeedMoreData, 0xFFFD, 0)] // empty buffer [InlineData(new byte[] { 0x30 }, OperationStatus.Done, 0x0030, 1)] // ASCII byte [InlineData(new byte[] { 0x30, 0x40, 0x50 }, OperationStatus.Done, 0x0050, 1)] // ASCII byte [InlineData(new byte[] { 0x80 }, OperationStatus.InvalidData, 0xFFFD, 1)] // standalone continuation byte [InlineData(new byte[] { 0x80, 0x80, 0x80 }, OperationStatus.InvalidData, 0xFFFD, 1)] // standalone continuation byte [InlineData(new byte[] { 0x80, 0x80, 0x80, 0x80 }, OperationStatus.InvalidData, 0xFFFD, 1)] // standalone continuation byte [InlineData(new byte[] { 0x80, 0x80, 0x80, 0xC2 }, OperationStatus.NeedMoreData, 0xFFFD, 1)] // [ C2 ] at end of buffer, valid 1-byte start of 2-byte sequence [InlineData(new byte[] { 0xC1 }, OperationStatus.InvalidData, 0xFFFD, 1)] // [ C1 ] is never a valid byte [InlineData(new byte[] { 0x80, 0xE2, 0x88, 0xB4 }, OperationStatus.Done, 0x2234, 3)] // [ E2 88 B4 ] is U+2234 THEREFORE [InlineData(new byte[] { 0xF0, 0x9F, 0x98, 0xB2 }, OperationStatus.Done, 0x1F632, 4)] // [ F0 9F 98 B2 ] is U+1F632 ASTONISHED FACE [InlineData(new byte[] { 0xE2, 0x88, 0xB4, 0xB2 }, OperationStatus.InvalidData, 0xFFFD, 1)] // [ B2 ] is standalone continuation byte [InlineData(new byte[] { 0x80, 0x62, 0x80, 0x80 }, OperationStatus.InvalidData, 0xFFFD, 1)] // [ 80 ] is standalone continuation byte [InlineData(new byte[] { 0xF0, 0x9F, 0x98, }, OperationStatus.NeedMoreData, 0xFFFD, 3)] // [ F0 9F 98 ] is valid 3-byte start of 4-byte sequence public static void DecodeLastFromUtf8(byte[] data, OperationStatus expectedOperationStatus, int expectedRuneValue, int expectedBytesConsumed) { Assert.Equal(expectedOperationStatus, Rune.DecodeLastFromUtf8(data, out Rune actualRune, out int actualBytesConsumed)); Assert.Equal(expectedRuneValue, actualRune.Value); Assert.Equal(expectedBytesConsumed, actualBytesConsumed); } [Theory] [InlineData(0, 0, true)] [InlineData(0x10FFFF, 0x10FFFF, true)] [InlineData(0xFFFD, 0xFFFD, true)] [InlineData(0xFFFD, 0xFFFF, false)] [InlineData('a', 'a', true)] [InlineData('a', 'A', false)] [InlineData('a', 'b', false)] public static void Equals_OperatorEqual_OperatorNotEqual(int first, int other, bool expected) { Rune a = new Rune(first); Rune b = new Rune(other); Assert.Equal(expected, Object.Equals(a, b)); Assert.Equal(expected, a.Equals(b)); Assert.Equal(expected, a.Equals((object)b)); Assert.Equal(expected, a == b); Assert.NotEqual(expected, a != b); } [Theory] [InlineData(0)] [InlineData('a')] [InlineData('\uFFFD')] [InlineData(0x10FFFF)] public static void GetHashCodeTests(int scalarValue) { Assert.Equal(scalarValue, new Rune(scalarValue).GetHashCode()); } [Theory] [InlineData("a", 0, (int)'a')] [InlineData("ab", 1, (int)'b')] [InlineData("x\U0001F46Ey", 3, (int)'y')] [InlineData("x\U0001F46Ey", 1, 0x1F46E)] // U+1F46E POLICE OFFICER public static void GetRuneAt_TryGetRuneAt_Utf16_Success(string inputString, int index, int expectedScalarValue) { // GetRuneAt Assert.Equal(expectedScalarValue, Rune.GetRuneAt(inputString, index).Value); // TryGetRuneAt Assert.True(Rune.TryGetRuneAt(inputString, index, out Rune rune)); Assert.Equal(expectedScalarValue, rune.Value); } // Our unit test runner doesn't deal well with malformed literal strings, so // we smuggle it as a char[] and turn it into a string within the test itself. [Theory] [InlineData(new char[] { 'x', '\uD83D', '\uDC6E', 'y' }, 2)] // attempt to index into the middle of a UTF-16 surrogate pair [InlineData(new char[] { 'x', '\uD800', 'y' }, 1)] // high surrogate not followed by low surrogate [InlineData(new char[] { 'x', '\uDFFF', '\uDFFF' }, 1)] // attempt to start at a low surrogate [InlineData(new char[] { 'x', '\uD800' }, 1)] // end of string reached before could complete surrogate pair public static void GetRuneAt_TryGetRuneAt_Utf16_InvalidData(char[] inputCharArray, int index) { string inputString = new string(inputCharArray); // GetRuneAt Assert.Throws<ArgumentException>("index", () => Rune.GetRuneAt(inputString, index)); // TryGetRuneAt Assert.False(Rune.TryGetRuneAt(inputString, index, out Rune rune)); Assert.Equal(0, rune.Value); } [Fact] public static void GetRuneAt_TryGetRuneAt_Utf16_BadArgs() { // null input Assert.Throws<ArgumentNullException>("input", () => Rune.GetRuneAt(null, 0)); // negative index specified Assert.Throws<ArgumentOutOfRangeException>("index", () => Rune.GetRuneAt("hello", -1)); // index goes past end of string Assert.Throws<ArgumentOutOfRangeException>("index", () => Rune.GetRuneAt(string.Empty, 0)); } [Theory] [MemberData(nameof(UnicodeInfoTestData_Latin1AndSelectOthers))] public static void GetNumericValue(UnicodeInfoTestData testData) { Assert.Equal(testData.NumericValue, Rune.GetNumericValue(testData.ScalarValue)); } [Theory] [MemberData(nameof(UnicodeInfoTestData_Latin1AndSelectOthers))] public static void GetUnicodeCategory(UnicodeInfoTestData testData) { Assert.Equal(testData.UnicodeCategory, Rune.GetUnicodeCategory(testData.ScalarValue)); } [Theory] [MemberData(nameof(UnicodeInfoTestData_Latin1AndSelectOthers))] public static void IsControl(UnicodeInfoTestData testData) { Assert.Equal(testData.IsControl, Rune.IsControl(testData.ScalarValue)); } [Theory] [MemberData(nameof(UnicodeInfoTestData_Latin1AndSelectOthers))] public static void IsDigit(UnicodeInfoTestData testData) { Assert.Equal(testData.IsDigit, Rune.IsDigit(testData.ScalarValue)); } [Theory] [MemberData(nameof(UnicodeInfoTestData_Latin1AndSelectOthers))] public static void IsLetter(UnicodeInfoTestData testData) { Assert.Equal(testData.IsLetter, Rune.IsLetter(testData.ScalarValue)); } [Theory] [MemberData(nameof(UnicodeInfoTestData_Latin1AndSelectOthers))] public static void IsLetterOrDigit(UnicodeInfoTestData testData) { Assert.Equal(testData.IsLetterOrDigit, Rune.IsLetterOrDigit(testData.ScalarValue)); } [Theory] [MemberData(nameof(UnicodeInfoTestData_Latin1AndSelectOthers))] public static void IsLower(UnicodeInfoTestData testData) { Assert.Equal(testData.IsLower, Rune.IsLower(testData.ScalarValue)); } [Theory] [MemberData(nameof(UnicodeInfoTestData_Latin1AndSelectOthers))] public static void IsNumber(UnicodeInfoTestData testData) { Assert.Equal(testData.IsNumber, Rune.IsNumber(testData.ScalarValue)); } [Theory] [MemberData(nameof(UnicodeInfoTestData_Latin1AndSelectOthers))] public static void IsPunctuation(UnicodeInfoTestData testData) { Assert.Equal(testData.IsPunctuation, Rune.IsPunctuation(testData.ScalarValue)); } [Theory] [MemberData(nameof(UnicodeInfoTestData_Latin1AndSelectOthers))] public static void IsSeparator(UnicodeInfoTestData testData) { Assert.Equal(testData.IsSeparator, Rune.IsSeparator(testData.ScalarValue)); } [Theory] [MemberData(nameof(UnicodeInfoTestData_Latin1AndSelectOthers))] public static void IsSymbol(UnicodeInfoTestData testData) { Assert.Equal(testData.IsSymbol, Rune.IsSymbol(testData.ScalarValue)); } [Theory] [MemberData(nameof(UnicodeInfoTestData_Latin1AndSelectOthers))] public static void IsUpper(UnicodeInfoTestData testData) { Assert.Equal(testData.IsUpper, Rune.IsUpper(testData.ScalarValue)); } [Theory] [MemberData(nameof(IsValidTestData))] public static void IsValid(int scalarValue, bool expectedIsValid) { Assert.Equal(expectedIsValid, Rune.IsValid(scalarValue)); Assert.Equal(expectedIsValid, Rune.IsValid((uint)scalarValue)); } [Theory] [MemberData(nameof(UnicodeInfoTestData_Latin1AndSelectOthers))] public static void IsWhiteSpace(UnicodeInfoTestData testData) { Assert.Equal(testData.IsWhiteSpace, Rune.IsWhiteSpace(testData.ScalarValue)); } [Theory] [InlineData(0, 0)] [InlineData(0x80, 0x80)] [InlineData(0x80, 0x100)] [InlineData(0x100, 0x80)] public static void Operators_And_CompareTo(uint scalarValueLeft, uint scalarValueRight) { Rune left = new Rune(scalarValueLeft); Rune right = new Rune(scalarValueRight); Assert.Equal(scalarValueLeft == scalarValueRight, left == right); Assert.Equal(scalarValueLeft != scalarValueRight, left != right); Assert.Equal(scalarValueLeft < scalarValueRight, left < right); Assert.Equal(scalarValueLeft <= scalarValueRight, left <= right); Assert.Equal(scalarValueLeft > scalarValueRight, left > right); Assert.Equal(scalarValueLeft >= scalarValueRight, left >= right); Assert.Equal(scalarValueLeft.CompareTo(scalarValueRight), left.CompareTo(right)); } [Fact] public static void ReplacementChar() { Assert.Equal(0xFFFD, Rune.ReplacementChar.Value); } [Theory] [MemberData(nameof(GeneralTestData_BmpCodePoints_NoSurrogates))] public static void TryCreate_Char_Valid(GeneralTestData testData) { Assert.True(Rune.TryCreate((char)testData.ScalarValue, out Rune result)); Assert.Equal(testData.ScalarValue, result.Value); } [Theory] [MemberData(nameof(BmpCodePoints_SurrogatesOnly))] public static void TryCreate_Char_Invalid(int scalarValue) { Assert.False(Rune.TryCreate((char)scalarValue, out Rune result)); Assert.Equal(0, result.Value); } [Theory] [MemberData(nameof(SurrogatePairTestData_InvalidOnly))] public static void TryCreate_SurrogateChars_Invalid(char highSurrogate, char lowSurrogate) { Assert.False(Rune.TryCreate(highSurrogate, lowSurrogate, out Rune result)); Assert.Equal(0, result.Value); } [Theory] [MemberData(nameof(SurrogatePairTestData_ValidOnly))] public static void TryCreate_SurrogateChars_Valid(char highSurrogate, char lowSurrogate, int expectedValue) { Assert.True(Rune.TryCreate(highSurrogate, lowSurrogate, out Rune result)); Assert.Equal(expectedValue, result.Value); } [Theory] [MemberData(nameof(GeneralTestData_BmpCodePoints_NoSurrogates))] [MemberData(nameof(GeneralTestData_SupplementaryCodePoints_ValidOnly))] public static void TryCreate_Int32_Valid(GeneralTestData testData) { Assert.True(Rune.TryCreate((int)testData.ScalarValue, out Rune result)); Assert.Equal(testData.ScalarValue, result.Value); } [Theory] [MemberData(nameof(BmpCodePoints_SurrogatesOnly))] [MemberData(nameof(SupplementaryCodePoints_InvalidOnly))] public static void TryCreate_Int32_Invalid(int scalarValue) { Assert.False(Rune.TryCreate((int)scalarValue, out Rune result)); Assert.Equal(0, result.Value); } [Theory] [MemberData(nameof(GeneralTestData_BmpCodePoints_NoSurrogates))] [MemberData(nameof(GeneralTestData_SupplementaryCodePoints_ValidOnly))] public static void TryCreate_UInt32_Valid(GeneralTestData testData) { Assert.True(Rune.TryCreate((uint)testData.ScalarValue, out Rune result)); Assert.Equal(testData.ScalarValue, result.Value); } [Theory] [MemberData(nameof(BmpCodePoints_SurrogatesOnly))] [MemberData(nameof(SupplementaryCodePoints_InvalidOnly))] public static void TryCreate_UInt32_Invalid(int scalarValue) { Assert.False(Rune.TryCreate((uint)scalarValue, out Rune result)); Assert.Equal(0, result.Value); } [Theory] [MemberData(nameof(GeneralTestData_BmpCodePoints_NoSurrogates))] [MemberData(nameof(GeneralTestData_SupplementaryCodePoints_ValidOnly))] public static void ToStringTests(GeneralTestData testData) { Assert.Equal(new string(testData.Utf16Sequence), new Rune(testData.ScalarValue).ToString()); } [Theory] [MemberData(nameof(GeneralTestData_BmpCodePoints_NoSurrogates))] [MemberData(nameof(GeneralTestData_SupplementaryCodePoints_ValidOnly))] public static void TryEncodeToUtf16(GeneralTestData testData) { Rune rune = new Rune(testData.ScalarValue); Assert.Equal(testData.Utf16Sequence.Length, rune.Utf16SequenceLength); // First, try with a buffer that's too short Span<char> utf16Buffer = stackalloc char[rune.Utf16SequenceLength - 1]; bool success = rune.TryEncodeToUtf16(utf16Buffer, out int charsWritten); Assert.False(success); Assert.Equal(0, charsWritten); Assert.Throws<ArgumentException>("destination", () => rune.EncodeToUtf16(new char[rune.Utf16SequenceLength - 1])); // Then, try with a buffer that's appropriately sized utf16Buffer = stackalloc char[rune.Utf16SequenceLength]; success = rune.TryEncodeToUtf16(utf16Buffer, out charsWritten); Assert.True(success); Assert.Equal(testData.Utf16Sequence.Length, charsWritten); Assert.True(utf16Buffer.SequenceEqual(testData.Utf16Sequence)); utf16Buffer.Clear(); Assert.Equal(testData.Utf16Sequence.Length, rune.EncodeToUtf16(utf16Buffer)); Assert.True(utf16Buffer.SequenceEqual(testData.Utf16Sequence)); // Finally, try with a buffer that's too long (should succeed) utf16Buffer = stackalloc char[rune.Utf16SequenceLength + 1]; success = rune.TryEncodeToUtf16(utf16Buffer, out charsWritten); Assert.True(success); Assert.Equal(testData.Utf16Sequence.Length, charsWritten); Assert.True(utf16Buffer.Slice(0, testData.Utf16Sequence.Length).SequenceEqual(testData.Utf16Sequence)); utf16Buffer.Clear(); Assert.Equal(testData.Utf16Sequence.Length, rune.EncodeToUtf16(utf16Buffer)); Assert.True(utf16Buffer.Slice(0, testData.Utf16Sequence.Length).SequenceEqual(testData.Utf16Sequence)); } [Theory] [MemberData(nameof(GeneralTestData_BmpCodePoints_NoSurrogates))] [MemberData(nameof(GeneralTestData_SupplementaryCodePoints_ValidOnly))] public static void TryEncodeToUtf8(GeneralTestData testData) { Rune rune = new Rune(testData.ScalarValue); Assert.Equal(testData.Utf8Sequence.Length, actual: rune.Utf8SequenceLength); // First, try with a buffer that's too short Span<byte> utf8Buffer = stackalloc byte[rune.Utf8SequenceLength - 1]; bool success = rune.TryEncodeToUtf8(utf8Buffer, out int bytesWritten); Assert.False(success); Assert.Equal(0, bytesWritten); Assert.Throws<ArgumentException>("destination", () => rune.EncodeToUtf8(new byte[rune.Utf8SequenceLength - 1])); // Then, try with a buffer that's appropriately sized utf8Buffer = stackalloc byte[rune.Utf8SequenceLength]; success = rune.TryEncodeToUtf8(utf8Buffer, out bytesWritten); Assert.True(success); Assert.Equal(testData.Utf8Sequence.Length, bytesWritten); Assert.True(utf8Buffer.SequenceEqual(testData.Utf8Sequence)); utf8Buffer.Clear(); Assert.Equal(testData.Utf8Sequence.Length, rune.EncodeToUtf8(utf8Buffer)); Assert.True(utf8Buffer.SequenceEqual(testData.Utf8Sequence)); // Finally, try with a buffer that's too long (should succeed) utf8Buffer = stackalloc byte[rune.Utf8SequenceLength + 1]; success = rune.TryEncodeToUtf8(utf8Buffer, out bytesWritten); Assert.True(success); Assert.Equal(testData.Utf8Sequence.Length, bytesWritten); Assert.True(utf8Buffer.Slice(0, testData.Utf8Sequence.Length).SequenceEqual(testData.Utf8Sequence)); utf8Buffer.Clear(); Assert.Equal(testData.Utf8Sequence.Length, rune.EncodeToUtf8(utf8Buffer)); Assert.True(utf8Buffer.Slice(0, testData.Utf8Sequence.Length).SequenceEqual(testData.Utf8Sequence)); } } }
/* * 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.Linq; using System.Text; using System.Threading.Tasks; using OpenSim.Framework; using log4net; using System.Reflection; using System.Threading; using System.Net; using OpenMetaverse.StructuredData; using OpenSim.Framework.Servers.HttpServer; using System.IO; namespace OpenSim.Region.Framework.Scenes { /// <summary> /// Manages communications, monitoring, and events from regions surrounding this one /// /// "Surrounding" doesnt necessarily mean touching. We want to have information about regions /// that are potentially very distant, but that clients may want to be able to see into from /// their present location. This is done by managing a maximum draw distance and using that /// to query neighboring regions. /// </summary> public class SurroundingRegionManager { private static readonly ILog _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// The maximum draw distance we support for allowing child connections to our surrounding regions /// </summary> private const int MAX_DRAW_DISTANCE = 512; /// <summary> /// The number of seconds between sending heartbeats from this region to all neighbors /// </summary> private const int NEIGHBOR_PING_FREQUENCY_SECS = 300; /// <summary> /// The number of seconds that a region has to ping us before we consider it timed out /// </summary> private const int NEIGHBOR_PING_TIMEOUT_SECS = 900; /// <summary> /// In very rare cases, two neighbor regions may start/register at the exact same time, and the initial /// region query will be misssing the neighbors. After a random number of seconds between the min and max /// in this range, a new reconciliation query will be performed adding region(s) to our list that may have /// been missing during the initial startup /// </summary> private readonly Tuple<int, int> NEIGHBOR_RECONCILIATION_TIME_RANGE_SECS = new Tuple<int, int>(300, 600); /// <summary> /// The type of message we're sending or receiving /// </summary> private enum MessageType { Heartbeat, Up, Down } /// <summary> /// The URL we use to send a heartbeat to our neighbors /// </summary> private const string HEARTBEAT_HANDLER_URL = "/region2/heartbeat"; /// <summary> /// The URL we use to send an up notice to our neighbors /// </summary> private const string UP_HANDLER_URL = "/region2/regionup"; /// <summary> /// The URL we use to send a down notice to our neighbors /// </summary> private const string DOWN_HANDLER_URL = "/region2/regiondown"; /// <summary> /// The timeout in ms for calls to our neighbor regions /// </summary> private const int NEIGHBOR_HANDLER_TIMEOUT = 5000; /// <summary> /// The scene we're managing regions for /// </summary> private Scene _scene; /// <summary> /// The shared key used for region/region auth /// </summary> private string _gridSendKey; /// <summary> /// A dict of regions keyed by their handles of neighbors that we know and are reasonably sure are up /// </summary> private Dictionary<ulong, KnownNeighborRegion> _knownNeighbors = new Dictionary<ulong, KnownNeighborRegion>(); /// <summary> /// Timer used to manage up/down checks for regions /// </summary> private Timer _regionHeartbeatTimer; /// <summary> /// The time in ticks that we initial queried the database for our neighbors /// </summary> private ulong _timeNeighborsInitiallyQueried; /// <summary> /// The number of seconds after which we should reconcile neighbor regions /// </summary> private ulong _reconcileAfterSecs; /// <summary> /// Regions that were not available when we sent our 'up' message. These regions should not be reconciled /// We will bring them up if we receieve a ping later /// </summary> private HashSet<ulong> _doaRegions = new HashSet<ulong>(); /// <summary> /// Delegate for monitoring state changes /// </summary> /// <param name="neighbor">The neighbor that changed</param> /// <param name="changeType">Type of change that happened</param> public delegate void NeighborStateChange(SimpleRegionInfo neighbor, NeighborStateChangeType changeType); /// <summary> /// Event that is fired whenever there is a state change /// </summary> public event NeighborStateChange OnNeighborStateChange; public SurroundingRegionManager(Scene myRegion, string gridSendKey) { _scene = myRegion; _gridSendKey = gridSendKey; _reconcileAfterSecs = (ulong)Util.RandomClass.Next(NEIGHBOR_RECONCILIATION_TIME_RANGE_SECS.Item1, NEIGHBOR_RECONCILIATION_TIME_RANGE_SECS.Item2); _regionHeartbeatTimer = new Timer(this.DoRegionHeartbeat, null, NEIGHBOR_PING_FREQUENCY_SECS * 1000, NEIGHBOR_PING_FREQUENCY_SECS * 1000); //register HTTP comms _scene.CommsManager.HttpServer.AddStreamHandler(new BinaryStreamHandler("POST", HEARTBEAT_HANDLER_URL, OnHeartbeatReceived)); _scene.CommsManager.HttpServer.AddStreamHandler(new BinaryStreamHandler("POST", UP_HANDLER_URL, OnNeighborRegionUp)); _scene.CommsManager.HttpServer.AddStreamHandler(new BinaryStreamHandler("POST", DOWN_HANDLER_URL, OnNeighborRegionDown)); } private string OnHeartbeatReceived(Stream request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { if (CheckAuthorization(httpRequest, httpResponse)) { return UnpackMessageAndCallHandler(request, httpResponse, this.HandleNeighborPing); } else { return "Unauthorized"; } } private string OnNeighborRegionUp(Stream request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { if (CheckAuthorization(httpRequest, httpResponse)) { return UnpackMessageAndCallHandler(request, httpResponse, this.HandleNeighborUp); } else { return "Unauthorized"; } } private string OnNeighborRegionDown(Stream request, string path, string param, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { if (CheckAuthorization(httpRequest, httpResponse)) { return UnpackMessageAndCallHandler(request, httpResponse, this.HandleNeighborDown); } else { return "Unauthorized"; } } private bool CheckAuthorization(OSHttpRequest httpRequest, OSHttpResponse httpResponse) { if (Util.CheckHttpAuthorization(_gridSendKey, httpRequest.Headers)) { return true; } else { httpResponse.StatusCode = 401; return false; } } /// <summary> /// Unpacks the message sent from a neighboring region and calls the given handler /// </summary> /// <param name="request"></param> /// <param name="httpResponse"></param> /// <param name="handler"></param> /// <returns></returns> private string UnpackMessageAndCallHandler(Stream request, OSHttpResponse httpResponse, Action<SimpleRegionInfo> handler) { try { byte[] binaryLLSD; using (MemoryStream ms = new MemoryStream()) { request.CopyTo(ms); binaryLLSD = ms.ToArray(); } OSDMap regionInfoPackage = (OSDMap)OSDParser.DeserializeLLSDBinary(binaryLLSD); RegionInfo regionInfo = new RegionInfo(); regionInfo.UnpackRegionInfoData(regionInfoPackage); handler(regionInfo); httpResponse.StatusCode = 200; return "OK"; } catch (Exception e) { httpResponse.StatusCode = 500; return "OnHeartbeatReceived: Error: " + e.ToString(); } } /// <summary> /// Sends the region up notification to our known neighbors /// </summary> public void SendRegionUpToNeighbors() { List<KnownNeighborRegion> neighborSnap = GetNeighborsSnapshot(); SendMessageTo(neighborSnap, UP_HANDLER_URL, MessageType.Up); } /// <summary> /// Sends the region down notification to our known neighbors /// </summary> public void SendRegionDownToNeighbors() { List<KnownNeighborRegion> neighborSnap = GetNeighborsSnapshot(); SendMessageTo(neighborSnap, DOWN_HANDLER_URL, MessageType.Down); } private void DoRegionHeartbeat(object state) { //do we need to reconcile? if (_timeNeighborsInitiallyQueried != 0 && Util.GetLongTickCount() - _timeNeighborsInitiallyQueried >= _reconcileAfterSecs * 1000) { _timeNeighborsInitiallyQueried = 0; ReconcileNeighborsFromStorage().Wait(); } List<KnownNeighborRegion> neighborSnap = GetNeighborsSnapshot(); //send our heartbeat to everyone else SendMessageTo(neighborSnap, HEARTBEAT_HANDLER_URL, MessageType.Heartbeat); //now prune regions that we haven't seen a heartbeat from List<KnownNeighborRegion> toPrune = new List<KnownNeighborRegion>(); lock (_knownNeighbors) { foreach (var kvp in _knownNeighbors) { if (Util.GetLongTickCount() - kvp.Value.LastPingReceivedOn > NEIGHBOR_PING_TIMEOUT_SECS * 1000) { toPrune.Add(kvp.Value); } } foreach (var neighbor in toPrune) { _knownNeighbors.Remove(neighbor.RegionInfo.RegionHandle); } } foreach (var neighbor in toPrune) { TriggerNeighborStateChange(neighbor.RegionInfo, NeighborStateChangeType.NeighborDown); } } /// <summary> /// Locks and copies the neighbors list into a new list /// </summary> /// <returns></returns> public List<KnownNeighborRegion> GetNeighborsSnapshot() { List<KnownNeighborRegion> neighborSnap; lock (_knownNeighbors) { neighborSnap = new List<KnownNeighborRegion>(_knownNeighbors.Count); neighborSnap.AddRange(_knownNeighbors.Values); } return neighborSnap; } private void SendMessageTo(List<KnownNeighborRegion> neighborSnap, string url, MessageType messageType) { try { List<Task> waitingResults = new List<Task>(); OSDMap regionInfo = _scene.RegionInfo.PackRegionInfoData(); byte[] serializedRegionInfo = OSDParser.SerializeLLSDBinary(regionInfo); foreach (var neighbor in neighborSnap) { var req = (HttpWebRequest)HttpWebRequest.Create(neighbor.RegionInfo.InsecurePublicHTTPServerURI + url); req.Headers["authorization"] = Util.GenerateHttpAuthorization(_gridSendKey); req.Timeout = NEIGHBOR_HANDLER_TIMEOUT; req.ReadWriteTimeout = NEIGHBOR_HANDLER_TIMEOUT; req.Method = "POST"; waitingResults.Add(this.DoRegionAsyncCall(req, neighbor, messageType, serializedRegionInfo)); } Task.WaitAll(waitingResults.ToArray()); } catch (AggregateException e) //we're catching exceptions in the call, so we really should never see this { for (int j = 0; j < e.InnerExceptions.Count; j++) { _log.ErrorFormat("[REGIONMANAGER]: Error thrown from async call: {0}", e); } } catch (Exception e) { _log.ErrorFormat("[REGIONMANAGER]: Error thrown while sending heartbeat: {0}", e); } } private async Task<bool> DoRegionAsyncCall(HttpWebRequest req, KnownNeighborRegion neighbor, MessageType type, byte[] body) { try { using (System.IO.Stream reqStream = await req.GetRequestStreamAsync()) { await reqStream.WriteAsync(body, 0, body.Length); } } catch (Exception e) { _log.ErrorFormat("[REGIONMANAGER]: Could not post request for {0} to region {1} at {2}: {3}", type, neighbor.RegionInfo.RegionHandle, Util.RegionHandleToLocationString(neighbor.RegionInfo.RegionHandle), e.Message); KillNeighborOnUpMessageFailure(neighbor, type); return false; } try { using (WebResponse response = await req.GetResponseAsync(NEIGHBOR_HANDLER_TIMEOUT)) { //we dont do anything with the response } } catch (Exception e) { _log.ErrorFormat("[REGIONMANAGER]: Unable to read response to {0} for region {1} at {2}: {3}", type, neighbor.RegionInfo.RegionHandle, Util.RegionHandleToLocationString(neighbor.RegionInfo.RegionHandle), e.Message); KillNeighborOnUpMessageFailure(neighbor, type); return false; } return true; } private void KillNeighborOnUpMessageFailure(KnownNeighborRegion neighbor, MessageType type) { //if this is an "up" message, consider the region crashed and remove it from neighbors if (type == MessageType.Up) { lock (_knownNeighbors) { _knownNeighbors.Remove(neighbor.RegionInfo.RegionHandle); _doaRegions.Add(neighbor.RegionInfo.RegionHandle); } } } /// <summary> /// Begins a series of async calls to refresh neighbor regions from storage. This should be /// called only when we're first coming on line /// </summary> /// <remarks> /// Will throw exceptions if the list can not be loaded /// </remarks> public async Task RefreshNeighborsFromStorage() { Task<List<SimpleRegionInfo>> neighborsTask = _scene.CommsManager.GridService.RequestNeighbors2Async( _scene.RegionInfo.RegionLocX, _scene.RegionInfo.RegionLocY, MAX_DRAW_DISTANCE); await neighborsTask; Dictionary<ulong, KnownNeighborRegion> knownNeighbors = new Dictionary<ulong, KnownNeighborRegion>(); foreach (var neighbor in neighborsTask.Result) { var region = new KnownNeighborRegion { LastPingReceivedOn = Util.GetLongTickCount(), RegionInfo = neighbor }; knownNeighbors.Add(region.RegionInfo.RegionHandle, region); } //atomic swapout _knownNeighbors = knownNeighbors; _timeNeighborsInitiallyQueried = Util.GetLongTickCount(); return; } /// <summary> /// Begins a series of async calls to reconcile our neighbor regions against storage. This function is called /// once after startup to ensure that we should have a true list of all regions /// </summary> /// <remarks> /// Will throw exceptions if the list can not be loaded /// </remarks> private async Task ReconcileNeighborsFromStorage() { Task<List<SimpleRegionInfo>> neighborsTask = _scene.CommsManager.GridService.RequestNeighbors2Async( _scene.RegionInfo.RegionLocX, _scene.RegionInfo.RegionLocY, MAX_DRAW_DISTANCE); List<SimpleRegionInfo> newRegions = await neighborsTask; List<SimpleRegionInfo> regionsNowUp = new List<SimpleRegionInfo>(); lock (_knownNeighbors) { //add any regions we don't know about foreach (var region in newRegions) { if (!_knownNeighbors.ContainsKey(region.RegionHandle) && !_doaRegions.Contains(region.RegionHandle)) { _knownNeighbors.Add(region.RegionHandle, new KnownNeighborRegion { RegionInfo = region, LastPingReceivedOn = Util.GetLongTickCount() }); regionsNowUp.Add(region); } } _doaRegions.Clear(); } foreach (var region in regionsNowUp) { TriggerNeighborStateChange(region, NeighborStateChangeType.NeighborUp); } } /// <summary> /// Signal that a neighbor has come up /// </summary> /// <param name="region">The region information</param> private void HandleNeighborUp(SimpleRegionInfo region) { var newNeighbor = new KnownNeighborRegion { LastPingReceivedOn = Util.GetLongTickCount(), RegionInfo = region }; lock (_knownNeighbors) { _knownNeighbors[region.RegionHandle] = newNeighbor; } TriggerNeighborStateChange(region, NeighborStateChangeType.NeighborUp); } /// <summary> /// Signal that a neighbor has gone down /// </summary> /// <param name="region"></param> private void HandleNeighborDown(SimpleRegionInfo region) { lock (_knownNeighbors) { _knownNeighbors.Remove(region.RegionHandle); } TriggerNeighborStateChange(region, NeighborStateChangeType.NeighborDown); } /// <summary> /// Signal that we've received a ping from a neighbor /// </summary> /// <param name="region"></param> private void HandleNeighborPing(SimpleRegionInfo region) { bool newNeighbor = false; KnownNeighborRegion neighbor; lock (_knownNeighbors) { if (_knownNeighbors.TryGetValue(region.RegionHandle, out neighbor)) { neighbor.LastPingReceivedOn = Util.GetLongTickCount(); } else { newNeighbor = true; neighbor = new KnownNeighborRegion { LastPingReceivedOn = Util.GetLongTickCount(), RegionInfo = region }; _knownNeighbors.Add(neighbor.RegionInfo.RegionHandle, neighbor); } } if (newNeighbor) { TriggerNeighborStateChange(region, NeighborStateChangeType.NeighborUp); } TriggerNeighborStateChange(region, NeighborStateChangeType.NeighborPing); } /// <summary> /// Triggers the state change event /// </summary> /// <param name="neighbor"></param> /// <param name="neighborStateChangeType"></param> private void TriggerNeighborStateChange(SimpleRegionInfo neighbor, NeighborStateChangeType neighborStateChangeType) { if (neighborStateChangeType != NeighborStateChangeType.NeighborPing) { _log.InfoFormat("[REGIONMANAGER]: Neighbor region {0} at {1} state change {2}", neighbor.RegionHandle, Util.RegionHandleToLocationString(neighbor.RegionHandle), neighborStateChangeType); } var stateChangeHandler = this.OnNeighborStateChange; if (stateChangeHandler != null) { stateChangeHandler(neighbor, neighborStateChangeType); } } /// <summary> /// Returns a neighbor we know about at x,y or null if there is no known neighbor there /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public SimpleRegionInfo GetKnownNeighborAt(uint x, uint y) { lock (_knownNeighbors) { KnownNeighborRegion foundRegion; if (_knownNeighbors.TryGetValue(Util.RegionHandleFromLocation(x, y), out foundRegion)) { return foundRegion.RegionInfo; } else { return null; } } } /// <summary> /// Returns whether or not we know about a neighbor at the given coordinates /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <returns></returns> public bool HasKnownNeighborAt(uint x, uint y) { return GetKnownNeighborAt(x, y) != null; } /// <summary> /// Returns a neighbor we know about by its handle or null if there is no known neighbor there /// </summary> /// <param name="handle">The region handle</param> /// <returns></returns> public SimpleRegionInfo GetKnownNeighborByHandle(ulong handle) { lock (_knownNeighbors) { KnownNeighborRegion foundRegion; if (_knownNeighbors.TryGetValue(handle, out foundRegion)) { return foundRegion.RegionInfo; } else { return null; } } } private SimpleRegionInfo FindKnownNeighbor(uint x, uint y) { foreach (var region in _knownNeighbors.Values) { if ((region.RegionInfo.RegionLocX == x) && (region.RegionInfo.RegionLocY == y)) return region.RegionInfo; } return null; } // Called with _knownNeighbors already locked. // Returns true if anything added to visibleNeighbors private void AddVisibleRegion(SimpleRegionInfo[,] visibleNeighbors, bool[,] inspected, uint x, uint y, uint xmin, uint xmax, uint ymin, uint ymax) { if ((x < xmin) || (x > xmax) || (y < ymin) || (y > ymax)) return; // off the grid, nothing to do // visibleNeighbors[] and inspected[] arrays use 0-based coordinates. uint xmap = x - xmin; uint ymap = y - ymin; if (inspected[xmap, ymap]) return; // already did this one inspected[xmap, ymap] = true; SimpleRegionInfo neighbor = FindKnownNeighbor(x, y); if (neighbor == null) return; // region not present visibleNeighbors[xmap, ymap] = neighbor; AddVisibleNeighbors(visibleNeighbors, inspected, x, y, xmin, xmax, ymin, ymax); } // Called with _knownNeighbors already locked. // Returns true if anything added to visibleNeighbors private void AddVisibleNeighbors(SimpleRegionInfo[,] visibleNeighbors, bool[,] inspected, uint x, uint y, uint xmin, uint xmax, uint ymin, uint ymax) { // Visibility rules are view must pass through at least one horizontal or vertical neighbor. AddVisibleRegion(visibleNeighbors, inspected, x, y - 1, xmin, xmax, ymin, ymax); AddVisibleRegion(visibleNeighbors, inspected, x, y + 1, xmin, xmax, ymin, ymax); AddVisibleRegion(visibleNeighbors, inspected, x - 1, y, xmin, xmax, ymin, ymax); AddVisibleRegion(visibleNeighbors, inspected, x + 1, y, xmin, xmax, ymin, ymax); } /// <summary> /// Returns a list of neighbors we are aware of that are within the given client draw distance from any /// of our edges /// </summary> /// <param name="drawDistance">DD in meters</param> /// <returns>List of known neighbors</returns> public List<SimpleRegionInfo> GetKnownNeighborsWithinClientDD(uint drawDistance, uint maxRange) { drawDistance = Math.Max(drawDistance, 64); drawDistance = Math.Min(drawDistance, MAX_DRAW_DISTANCE); uint xmin, xmax, ymin, ymax; var regionInfo = _scene.RegionInfo; Util.GetDrawDistanceBasedRegionRectangle(drawDistance, maxRange, regionInfo.RegionLocX, regionInfo.RegionLocY, out xmin, out xmax, out ymin, out ymax); uint gridsize = xmax - xmin + 1; uint center = (xmax - xmin) / 2; List<SimpleRegionInfo> neighbors = new List<SimpleRegionInfo>(); // visibleNeighbors[] and inspected[] arrays use 0-based coordinates. SimpleRegionInfo[,] visibleNeighbors = new SimpleRegionInfo[gridsize, gridsize]; lock (_knownNeighbors) { foreach (KnownNeighborRegion neighbor in _knownNeighbors.Values) { if (Util.IsWithinDDRectangle(neighbor.RegionInfo.RegionLocX, neighbor.RegionInfo.RegionLocY, xmin, xmax, ymin, ymax)) { //region within bounds neighbors.Add(neighbor.RegionInfo); } } // Apply per-presence region visibility filter bool[,] inspected = new bool[gridsize, gridsize]; // context for recursive call // The starting/center point in the visibility grid is always included. visibleNeighbors[center, center] = new SimpleRegionInfo(regionInfo); inspected[center, center] = true; // Recursively path-find all visible neighbors. AddVisibleNeighbors(visibleNeighbors, inspected, regionInfo.RegionLocX, regionInfo.RegionLocY, xmin, xmax, ymin, ymax); } // Now replace the full list of neighbors with the regions in the filtered visible array. neighbors.Clear(); foreach (var region in visibleNeighbors) if ((region != null) && (region.RegionHandle != regionInfo.RegionHandle)) // got one and it's not this one neighbors.Add(region); return neighbors; } /// <summary> /// Returns the number of regions that we know about surrounding this region within MAX_DRAW_DISTANCE /// </summary> /// <returns></returns> public int GetKnownNeighborCount() { lock (_knownNeighbors) { return _knownNeighbors.Count; } } } }
// 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-3-1.cs - Beta1 Layout Test - RDawson // // Tests layout of classes using 1-deep nesting in // the same assembly and module // // 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; A a = new A(); mi_RetCode = a.Test(); if(mi_RetCode == 100) Console.WriteLine("Pass"); else Console.WriteLine("FAIL"); return mi_RetCode; } } struct A{ //@csharp - C# will not allow family or famorassem accessibility on value class members public int Test(){ int mi_RetCode = 100; ///////////////////////////////// // Test nested class access if(Test_Nested(ClsPubInst) != 100) mi_RetCode = 0; if(Test_Nested(ClsPrivInst) != 100) mi_RetCode = 0; if(Test_Nested(ClsAsmInst) != 100) mi_RetCode = 0; // to get rid of compiler warning // warning CS0414: The private field 'A.ClsPrivStat' is assigned but its value is never used A.ClsPubStat.ToString(); A.ClsPrivStat.ToString(); return mi_RetCode; } public int Test_Nested(Cls Nested_Cls){ int mi_RetCode = 100; ///////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// // ACCESS NESTED FIELDS/MEMBERS ///////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// ///////////////////////////////// // Test instance field access Nested_Cls.NestFldPubInst = 100; if(Nested_Cls.NestFldPubInst != 100) mi_RetCode = 0; Nested_Cls.NestFldAsmInst = 100; if(Nested_Cls.NestFldAsmInst != 100) mi_RetCode = 0; ///////////////////////////////// // Test static field access Cls.NestFldPubStat = 100; if(Cls.NestFldPubStat != 100) mi_RetCode = 0; Cls.NestFldAsmStat = 100; if(Cls.NestFldAsmStat != 100) mi_RetCode = 0; ///////////////////////////////// // Test instance method access if(Nested_Cls.NestMethPubInst() != 100) mi_RetCode = 0; if(Nested_Cls.NestMethAsmInst() != 100) mi_RetCode = 0; ///////////////////////////////// // Test static method access if(Cls.NestMethPubStat() != 100) mi_RetCode = 0; if(Cls.NestMethAsmStat() != 100) mi_RetCode = 0; //////////////////////////////////////////// // Test access from within the nested class if(Nested_Cls.Test() != 100) mi_RetCode = 0; return mi_RetCode; } ////////////////////////////// // Instance Fields public int FldPubInst; private int FldPrivInst; internal int FldAsmInst; //Translates to "assembly" ////////////////////////////// // Static Fields public static int FldPubStat; private static int FldPrivStat; internal static int FldAsmStat; //assembly ////////////////////////////////////// // Instance fields for nested classes public Cls ClsPubInst; private Cls ClsPrivInst; internal Cls ClsAsmInst; ///////////////////////////////////// // Static fields of nested classes public static Cls ClsPubStat = new Cls(); 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; } internal int MethAsmInst(){ Console.WriteLine("A::MethAsmInst()"); return 100; } ////////////////////////////// // Static Methods public static int MethPubStat(){ Console.WriteLine("A::MethPubStat()"); return 100; } private static int MethPrivStat(){ Console.WriteLine("A::MethPrivStat()"); return 100; } internal static int MethAsmStat(){ Console.WriteLine("A::MethAsmStat()"); return 100; } public struct 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; FldAsmStat = 100; if(FldAsmStat != 100) mi_RetCode = 0; ///////////////////////////////// // Test static method access if(MethPubStat() != 100) mi_RetCode = 0; if(MethAsmStat() != 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; private int NestFldPrivInst; internal int NestFldAsmInst; //Translates to "assembly" ////////////////////////////// // Static Fields public static int NestFldPubStat; private static int NestFldPrivStat; internal static int NestFldAsmStat; //assembly ////////////////////////////// // Instance NestMethods public int NestMethPubInst(){ Console.WriteLine("A::NestMethPubInst()"); return 100; } private int NestMethPrivInst(){ Console.WriteLine("A::NestMethPrivInst()"); return 100; } internal int NestMethAsmInst(){ Console.WriteLine("A::NestMethAsmInst()"); return 100; } ////////////////////////////// // Static NestMethods public static int NestMethPubStat(){ Console.WriteLine("A::NestMethPubStat()"); return 100; } private static int NestMethPrivStat(){ Console.WriteLine("A::NestMethPrivStat()"); return 100; } internal static int NestMethAsmStat(){ Console.WriteLine("A::NestMethAsmStat()"); 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.Diagnostics; using System; using Microsoft.Win32; using System.Net; using System.IO; using System.Reflection; using System.Collections; using System.ComponentModel; using System.Globalization; using System.Security; using System.Security.Permissions; namespace System.ComponentModel.Design { /// <summary> /// <para> /// Provides design-time support for licensing. /// </para> /// </summary> public class DesigntimeLicenseContext : LicenseContext { internal Hashtable savedLicenseKeys = new Hashtable(); /// <summary> /// <para> /// Gets or sets the license usage mode. /// </para> /// </summary> public override LicenseUsageMode UsageMode => LicenseUsageMode.Designtime; /// <summary> /// <para> /// Gets a saved license key. /// </para> /// </summary> public override string GetSavedLicenseKey(Type type, Assembly resourceAssembly) { return null; } /// <summary> /// <para> /// Sets a saved license key. /// </para> /// </summary> public override void SetSavedLicenseKey(Type type, string key) { savedLicenseKeys[type.AssemblyQualifiedName] = key; } } internal class RuntimeLicenseContext : LicenseContext { private static TraceSwitch s_runtimeLicenseContextSwitch = new TraceSwitch("RuntimeLicenseContextTrace", "RuntimeLicenseContext tracing"); private const int ReadBlock = 400; internal Hashtable savedLicenseKeys; /// <summary> /// This method takes a file URL and converts it to a local path. The trick here is that /// if there is a '#' in the path, everything after this is treated as a fragment. So /// we need to append the fragment to the end of the path. /// </summary> private string GetLocalPath(string fileName) { System.Diagnostics.Debug.Assert(fileName != null && fileName.Length > 0, "Cannot get local path, fileName is not valid"); Uri uri = new Uri(fileName); return uri.LocalPath + uri.Fragment; } public override string GetSavedLicenseKey(Type type, Assembly resourceAssembly) { if (savedLicenseKeys == null || savedLicenseKeys[type.AssemblyQualifiedName] == null) { Debug.WriteLineIf(s_runtimeLicenseContextSwitch.TraceVerbose, "savedLicenseKey is null or doesnt contain our type"); if (savedLicenseKeys == null) { savedLicenseKeys = new Hashtable(); } if (resourceAssembly == null) { resourceAssembly = Assembly.GetEntryAssembly(); } if (resourceAssembly == null) { Debug.WriteLineIf(s_runtimeLicenseContextSwitch.TraceVerbose, "resourceAssembly is null"); // If Assembly.EntryAssembly returns null, then we will // try everything! // foreach (Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) { // Though, I could not repro this, we seem to be hitting an AssemblyBuilder // when walking through all the assemblies in the current app domain. This throws an // exception on Assembly.CodeBase and we bail out. Catching exceptions here is not a // bad thing. if (asm.IsDynamic) continue; // file://fullpath/foo.exe // string fileName; fileName = GetLocalPath(asm.EscapedCodeBase); fileName = new FileInfo(fileName).Name; Stream s = asm.GetManifestResourceStream(fileName + ".licenses"); if (s == null) { //Since the casing may be different depending on how the assembly was loaded, //we'll do a case insensitive lookup for this manifest resource stream... s = CaseInsensitiveManifestResourceStreamLookup(asm, fileName + ".licenses"); } if (s != null) { DesigntimeLicenseContextSerializer.Deserialize(s, fileName.ToUpper(CultureInfo.InvariantCulture), this); break; } } } else if (!resourceAssembly.IsDynamic) { // EscapedCodeBase won't be supported by emitted assemblies anyway Debug.WriteLineIf(s_runtimeLicenseContextSwitch.TraceVerbose, "resourceAssembly is not null"); string fileName; fileName = GetLocalPath(resourceAssembly.EscapedCodeBase); fileName = Path.GetFileName(fileName); // we don't want to use FileInfo here... it requests FileIOPermission that we // might now have... see VSWhidbey 527758 string licResourceName = fileName + ".licenses"; // first try the filename Stream s = resourceAssembly.GetManifestResourceStream(licResourceName); if (s == null) { string resolvedName = null; CompareInfo comparer = CultureInfo.InvariantCulture.CompareInfo; string shortAssemblyName = resourceAssembly.GetName().Name; // if the assembly has been renamed, we try our best to find a good match in the available resources // by looking at the assembly name (which doesn't change even after a file rename) + ".exe.licenses" or + ".dll.licenses" foreach (String existingName in resourceAssembly.GetManifestResourceNames()) { if (comparer.Compare(existingName, licResourceName, CompareOptions.IgnoreCase) == 0 || comparer.Compare(existingName, shortAssemblyName + ".exe.licenses", CompareOptions.IgnoreCase) == 0 || comparer.Compare(existingName, shortAssemblyName + ".dll.licenses", CompareOptions.IgnoreCase) == 0) { resolvedName = existingName; break; } } if (resolvedName != null) { s = resourceAssembly.GetManifestResourceStream(resolvedName); } } if (s != null) { DesigntimeLicenseContextSerializer.Deserialize(s, fileName.ToUpper(CultureInfo.InvariantCulture), this); } } } Debug.WriteLineIf(s_runtimeLicenseContextSwitch.TraceVerbose, $"returning : {(string)savedLicenseKeys[type.AssemblyQualifiedName]}"); return (string)savedLicenseKeys[type.AssemblyQualifiedName]; } /** * Looks up a .licenses file in the assembly manifest using * case-insensitive lookup rules. We do this because the name * we are attempting to locate could have different casing * depending on how the assembly was loaded. **/ private Stream CaseInsensitiveManifestResourceStreamLookup(Assembly satellite, string name) { CompareInfo comparer = CultureInfo.InvariantCulture.CompareInfo; //loop through the resource names in the assembly // we try to handle the case where the assembly file name has been renamed // by trying to guess the original file name based on the assembly name... string assemblyShortName = satellite.GetName().Name; foreach (string existingName in satellite.GetManifestResourceNames()) { if (comparer.Compare(existingName, name, CompareOptions.IgnoreCase) == 0 || comparer.Compare(existingName, assemblyShortName + ".exe.licenses") == 0 || comparer.Compare(existingName, assemblyShortName + ".dll.licenses") == 0) { name = existingName; break; } } //finally, attempt to return our stream based on the //case insensitive match we found // return satellite.GetManifestResourceStream(name); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Linq; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServices.CSharp.Debugging; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Debugging { public partial class ProximityExpressionsGetterTests { private SyntaxTree GetTree() { return SyntaxFactory.ParseSyntaxTree(Resources.ProximityExpressionsGetterTestFile); } private SyntaxTree GetTreeFromCode(string code) { return SyntaxFactory.ParseSyntaxTree(code); } public void GenerateBaseline() { Console.WriteLine(typeof(FactAttribute)); var text = Resources.ProximityExpressionsGetterTestFile; using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(text)) { var languageDebugInfo = new CSharpLanguageDebugInfoService(); var hostdoc = workspace.Documents.First(); var snapshot = hostdoc.TextBuffer.CurrentSnapshot; var document = workspace.CurrentSolution.GetDocument(hostdoc.Id); var builder = new StringBuilder(); var statements = document.GetSyntaxRootAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None).DescendantTokens().Select(t => t.GetAncestor<StatementSyntax>()).Distinct().WhereNotNull(); // Try to get proximity expressions at every token position and the start of every // line. var index = 0; foreach (var statement in statements) { builder.AppendLine("[WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)]"); builder.AppendLine("public void TestAtStartOfStatement_" + index + "()"); builder.AppendLine("{"); var token = statement.GetFirstToken(); var line = snapshot.GetLineFromPosition(token.SpanStart); builder.AppendLine(" //// Line " + (line.LineNumber + 1)); builder.AppendLine(); if (line.LineNumber > 0) { builder.AppendLine(" //// " + snapshot.GetLineFromLineNumber(line.LineNumber - 1).GetText()); } builder.AppendLine(" //// " + line.GetText()); var charIndex = token.SpanStart - line.Start; builder.AppendLine(" //// " + new string(' ', charIndex) + "^"); builder.AppendLine(" var tree = GetTree(\"ProximityExpressionsGetterTestFile.cs\");"); builder.AppendLine(" var terms = CSharpProximityExpressionsService.Do(tree, " + token.SpanStart + ");"); var proximityExpressionsGetter = new CSharpProximityExpressionsService(); var terms = proximityExpressionsGetter.GetProximityExpressionsAsync(document, token.SpanStart, CancellationToken.None).Result; if (terms == null) { builder.AppendLine(" Assert.Null(terms);"); } else { builder.AppendLine(" Assert.NotNull(terms);"); var termsString = terms.Select(t => "\"" + t + "\"").Join(", "); builder.AppendLine(" AssertEx.Equal(new[] { " + termsString + " }, terms);"); } builder.AppendLine("}"); builder.AppendLine(); index++; } var str = builder.ToString(); Console.WriteLine(str); } } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void TestWithinStatement_1() { var tree = GetTreeFromCode(@"using System; using System.Collections.Generic; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { var xx = true; var yy = new List<bool>(); yy.Add(xx?true:false); } } }"); var terms = CSharpProximityExpressionsService.Do(tree, 245); Assert.NotNull(terms); AssertEx.Equal(new[] { "yy", "xx" }, terms); } private void TestProximityExpressionGetter( string markup, Action<CSharpProximityExpressionsService, Document, int> continuation) { using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromLines(markup)) { var testDocument = workspace.Documents.Single(); var caretPosition = testDocument.CursorPosition.Value; var snapshot = testDocument.TextBuffer.CurrentSnapshot; var languageDebugInfo = new CSharpLanguageDebugInfoService(); var document = workspace.CurrentSolution.GetDocument(testDocument.Id); var proximityExpressionsGetter = new CSharpProximityExpressionsService(); continuation(proximityExpressionsGetter, document, caretPosition); } } private void TestTryDo(string input, params string[] expectedTerms) { TestProximityExpressionGetter(input, (getter, document, position) => { var actualTerms = getter.GetProximityExpressionsAsync(document, position, CancellationToken.None).Result; Assert.Equal(expectedTerms.Length == 0, actualTerms == null); if (expectedTerms.Length > 0) { AssertEx.Equal(expectedTerms, actualTerms); } }); } private void TestIsValid(string input, string expression, bool expectedValid) { TestProximityExpressionGetter(input, (getter, semanticSnapshot, position) => { var actualValid = getter.IsValidAsync(semanticSnapshot, position, expression, CancellationToken.None).Result; Assert.Equal(expectedValid, actualValid); }); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void TestTryDo1() { TestTryDo("class Class { void Method() { string local;$$ } }", "local", "this"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void TestNoParentToken() { TestTryDo("$$"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void TestIsValid1() { TestIsValid("class Class { void Method() { string local;$$ } }", "local", true); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void TestIsValidWithDiagnostics() { // local doesn't exist in this context TestIsValid("class Class { void Method() { string local; } $$}", "local", false); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void TestIsValidReferencingLocalBeforeDeclaration() { TestIsValid("class Class { void Method() { $$int i; int j; } }", "j", false); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void TestIsValidReferencingUndefinedVariable() { TestIsValid("class Class { void Method() { $$int i; int j; } }", "k", false); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void TestIsValidNoTypeSymbol() { TestIsValid("namespace Namespace$$ { }", "foo", false); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void TestIsValidLocalAfterPosition() { TestIsValid("class Class { void Method() { $$ int i; string local; } }", "local", false); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void TestThis() { TestTryDo(@" class Class { public Class() : this(true) { base.ToString(); this.ToString()$$; } }", "this"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void TestArrayCreationExpression() { TestTryDo(@" class Class { void Method() { int[] i = new int[] { 3 }$$; } }", "i", "this"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void TestPostfixUnaryExpressionSyntax() { TestTryDo(@" class Class { void Method() { int i = 3; i++$$; } }", "i", "this"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void TestLabeledStatement() { TestTryDo(@" class Class { void Method() { label: int i = 3; label2$$: i++; } }", "i", "this"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void TestThrowStatement() { TestTryDo(@" class Class { static void Method() { e = new Exception(); thr$$ow e; } }", "e"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void TestDoStatement() { TestTryDo(@" class Class { static void Method() { do$$ { } while (true); } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void TestLockStatement() { TestTryDo(@" class Class { static void Method() { lock(typeof(Cl$$ass)) { }; } }"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void TestWhileStatement() { TestTryDo(@" class Class { static void Method() { while(DateTime.Now <$$ DateTime.Now) { }; } }", "DateTime", "DateTime.Now"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void TestForStatementWithDeclarators() { TestTryDo(@" class Class { static void Method() { for(int i = 0; i < 10; i$$++) { } } }", "i"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void TestForStatementWithInitializers() { TestTryDo(@" class Class { static void Method() { int i = 0; for(i = 1; i < 10; i$$++) { } } }", "i"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void TestUsingStatement() { TestTryDo(@" class Class { void Method() { using (FileStream fs = new FileStream($$)) { } } }", "this"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] [WorkItem(538879)] public void TestValueInPropertySetter() { TestTryDo(@" class Class { string Name { get { return """"; } set { $$ } } }", "this", "value"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void TestValueInEventAdd() { TestTryDo(@" class Class { event Action Event { add { $$ } set { } } }", "this", "value"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void TestValueInEventRemove() { TestTryDo(@" class Class { event Action Event { add { } remove { $$ } } }", "this", "value"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] [WorkItem(538880)] public void TestValueInIndexerSetter() { TestTryDo(@" class Class { string this[int index] { get { return """"; } set { $$ } } }", "index", "this", "value"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] [WorkItem(538881)] public void TestCatchBlock() { TestTryDo(@" class Class { void Method() { try { } catch(Exception ex) { int $$ } } }", "ex", "this"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] [WorkItem(538881)] public void TestCatchBlockEmpty_OpenBrace() { TestTryDo(@" class Class { void Method() { try { } catch(Exception ex) { $$ } } }", "ex", "this"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void TestCatchBlockEmpty_CloseBrace() { TestTryDo(@" class Class { void Method() { try { } catch(Exception ex) { } $$ } }", "this"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] [WorkItem(538874)] public void TestObjectCreation() { TestTryDo(@" class Class { void Method() { $$Foo(new Bar(a).Baz); } }", "a", "new Bar(a).Baz", "Foo", "this"); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] [WorkItem(538874)] public void Test2() { TestIsValid(@" class D { private static int x; } class Class { void Method() { $$Foo(D.x); } }", "D.x", false); } [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] [WorkItem(538890)] public void TestArrayCreation() { TestTryDo(@" class Class { int a; void Method() { $$new int[] { a }; } }", "this"); } [WorkItem(751141)] [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void Bug751141() { TestTryDo(@" class Program { double m_double = 1.1; static void Main(string[] args) { new Program().M(); } void M() { int local_int = (int)m_double; $$System.Diagnostics.Debugger.Break(); } } ", "System.Diagnostics.Debugger", "local_int", "m_double", "(int)m_double", "this"); } [WorkItem(775161)] [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void ForLoopExpressionsInFirstStatementOfLoop1() { TestTryDo(@"class Program { static void Main(string[] args) { for(int i = 0; i < 5; i++) { $$var x = 8; } } }", "i", "x"); } [WorkItem(775161)] [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void ForLoopExpressionsInFirstStatementOfLoop2() { TestTryDo(@"class Program { static void Main(string[] args) { int i = 0, j = 0, k = 0, m = 0, n = 0; for(i = 0; j < 5; k++) { $$m = 8; n = 7; } } }", "m", "i", "j", "k"); } [WorkItem(775161)] [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void ForLoopExpressionsInFirstStatementOfLoop3() { TestTryDo(@"class Program { static void Main(string[] args) { int i = 0, j = 0, k = 0, m = 0; for(i = 0; j < 5; k++) { var m = 8; $$var n = 7; } } }", "m", "n"); } [WorkItem(775161)] [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void ForLoopExpressionsInFirstStatementOfLoop4() { TestTryDo(@"class Program { static void Main(string[] args) { int i = 0, j = 0, k = 0, m = 0; for(i = 0; j < 5; k++) $$m = 8; } }", "m", "i", "j", "k"); } [WorkItem(775161)] [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void ForEachLoopExpressionsInFirstStatementOfLoop1() { TestTryDo(@"class Program { static void Main(string[] args) { foreach (var x in new int[] { 1, 2, 3 }) { $$var z = 0; } } }", "x", "z"); } [WorkItem(775161)] [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void ForEachLoopExpressionsInFirstStatementOfLoop2() { TestTryDo(@"class Program { static void Main(string[] args) { foreach (var x in new int[] { 1, 2, 3 }) $$var z = 0; } }", "x", "z"); } [WorkItem(775161)] [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void ExpressionsAfterForLoop1() { TestTryDo(@"class Program { static void Main(string[] args) { int a = 0, b = 0, c = 0, d = 0; for (a = 5; b < 1; b++) { c = 8; d = 9; // included } $$var z = 0; } }", "a", "b", "d", "z"); } [WorkItem(775161)] [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void ExpressionsAfterForLoop2() { TestTryDo(@"class Program { static void Main(string[] args) { int a = 0, b = 0, c = 0; for (a = 5; b < 1; b++) { c = 8; int d = 9; // not included } $$var z = 0; } }", "a", "b", "z"); } [WorkItem(775161)] [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void ExpressionsAfterForEachLoop() { TestTryDo(@"class Program { static void Main(string[] args) { int a = 0, b = 0, c = 0, d = 0; foreach (var q in new int[] {1, 2, 3}) { c = 8; d = 9; // included } $$var z = 0; } }", "q", "d", "z"); } [WorkItem(775161)] [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void ExpressionsAfterNestedForLoop() { TestTryDo(@"class Program { static void Main(string[] args) { int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0; for (a = 5; b < 1; b++) { c = 8; d = 9; for (a = 7; b < 9; b--) { e = 8; f = 10; // included } } $$var z = 0; } }", "a", "b", "f", "z"); } [WorkItem(775161)] [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void ExpressionsAfterCheckedStatement() { TestTryDo(@"class Program { static void Main(string[] args) { int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0; checked { a = 7; b = 0; // included } $$var z = 0; } }", "b", "z"); } [WorkItem(775161)] [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void ExpressionsAfterUncheckedStatement() { TestTryDo(@"class Program { static void Main(string[] args) { int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0; unchecked { a = 7; b = 0; // included } $$var z = 0; } }", "b", "z"); } [WorkItem(775161)] [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void ExpressionsAfterIfStatement() { TestTryDo(@"class Program { static void Main(string[] args) { int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0; if (a == 0) { c = 8; d = 9; // included } $$var z = 0; } }", "a", "d", "z"); } [WorkItem(775161)] [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void ExpressionsAfterIfStatementWithElse() { TestTryDo(@"class Program { static void Main(string[] args) { int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0; if (a == 0) { c = 8; d = 9; // included } else { e = 1; f = 2; // included } $$var z = 0; } }", "a", "d", "f", "z"); } [WorkItem(775161)] [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void ExpressionsAfterLockStatement() { TestTryDo(@"class Program { static void Main(string[] args) { int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0; lock (new object()) { a = 2; b = 3; // included } $$var z = 0; } }", "b", "z"); } [WorkItem(775161)] [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void ExpressionsAfterSwitchStatement() { TestTryDo(@"class Program { static void Main(string[] args) { int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0; switch(a) { case 1: b = 7; c = 8; // included break; case 2: d = 9; e = 10; // included break; default: f = 1; g = 2; // included break; } $$var z = 0; } }", "a", "c", "e", "g", "z"); } [WorkItem(775161)] [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void ExpressionsAfterTryStatement() { TestTryDo(@"class Program { static void Main(string[] args) { int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0; try { a = 2; b = 3; // included } catch (System.DivideByZeroException) { c = 2; d = 5; // included } catch (System.EntryPointNotFoundException) { e = 8; f = 9; // included } $$var z = 0; } }", "b", "d", "f", "z"); } [WorkItem(775161)] [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void ExpressionsAfterTryStatementWithFinally() { TestTryDo(@"class Program { static void Main(string[] args) { int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0; try { a = 2; b = 3; } catch (System.DivideByZeroException) { c = 2; d = 5; } catch (System.EntryPointNotFoundException) { e = 8; f = 9; } finally { g = 2; // included } $$var z = 0; } }", "g", "z"); } [WorkItem(775161)] [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void ExpressionsAfterUsingStatement() { TestTryDo(@"class Program { static void Main(string[] args) { int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0; using (null as System.IDisposable) { a = 4; b = 8; // Included } $$var z = 0; } }", "b", "z"); } [WorkItem(775161)] [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void ExpressionsAfterWhileStatement() { TestTryDo(@"class Program { static void Main(string[] args) { int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0; while (a < 5) { a++; b = 8; // Included } $$var z = 0; } }", "a", "b", "z"); } [WorkItem(778215)] [WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingProximityExpressions)] public void ExpressionsInParenthesizedExpressions() { TestTryDo(@"class Program { static void Main(string[] args) { int i = 0, j = 0, k = 0, m = 0; int flags = 7; if((flags & i) == k) { $$ m = 8; } } }", "m", "flags", "i", "k"); } } }
#if NETSTANDARD2_1 using System; using System.Buffers; using System.IO.Pipelines; using System.Text; using System.Threading; using System.Threading.Tasks; using Lime.Protocol.Serialization; using Lime.Protocol.Server; namespace Lime.Protocol.Network { /// <summary> /// Manages <see cref="ITransport"/> buffers using the <see cref="System.IO.Pipelines.Pipe"/> class. /// </summary> public sealed class EnvelopePipe : IStartable, IStoppable, IDisposable { public const int DEFAULT_PAUSE_WRITER_THRESHOLD = 8192 * 1024; private readonly Func<Memory<byte>, CancellationToken, ValueTask<int>> _receiveFunc; private readonly Func<ReadOnlyMemory<byte>, CancellationToken, ValueTask> _sendFunc; private readonly IEnvelopeSerializer _envelopeSerializer; private readonly ITraceWriter _traceWriter; private readonly int _pauseWriterThreshold; private readonly Pipe _receivePipe; private readonly Pipe _sendPipe; private readonly CancellationTokenSource _pipeCts; private readonly SemaphoreSlim _semaphore; private Task _receiveTask; private Task _sendTask; /// <summary> /// Creates a new instance of <see cref="EnvelopePipe"/>. /// </summary> /// <param name="receiveFunc">The function that will be invoked by the receive task, which passes a memory to be filled by the underlying connection.</param> /// <param name="sendFunc">The function that will be invoked by the send task, container the buffer that should be written to the underlying connection.</param> /// <param name="envelopeSerializer">The envelope serializer</param> /// <param name="traceWriter">The trace writer</param> /// <param name="pauseWriterThreshold">The number of unconsumed bytes in the receive pipe to pause the read task.</param> /// <param name="memoryPool">The memory pool instance to be used by the pipes</param> public EnvelopePipe( Func<Memory<byte>, CancellationToken, ValueTask<int>> receiveFunc, Func<ReadOnlyMemory<byte>, CancellationToken, ValueTask> sendFunc, IEnvelopeSerializer envelopeSerializer, ITraceWriter traceWriter = null, int pauseWriterThreshold = -1, MemoryPool<byte> memoryPool = null) { _receiveFunc = receiveFunc ?? throw new ArgumentNullException(nameof(receiveFunc)); _sendFunc = sendFunc ?? throw new ArgumentNullException(nameof(sendFunc)); _envelopeSerializer = envelopeSerializer ?? throw new ArgumentNullException(nameof(envelopeSerializer)); _traceWriter = traceWriter; _pauseWriterThreshold = pauseWriterThreshold > 0 ? pauseWriterThreshold : -1; var pipeOptions = new PipeOptions( pool: memoryPool ?? MemoryPool<byte>.Shared, pauseWriterThreshold: _pauseWriterThreshold); _receivePipe = new Pipe(pipeOptions); _sendPipe = new Pipe(pipeOptions); _pipeCts = new CancellationTokenSource(); _semaphore = new SemaphoreSlim(1); } /// <summary> /// Starts the pipe producer / consumer tasks. /// </summary> public async Task StartAsync(CancellationToken cancellationToken) { await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); try { if (_receiveTask != null || _sendTask != null) { throw new InvalidOperationException("The pipe is already started"); } _receiveTask = ReceiveAndWriteToPipeAsync(_receiveFunc, _receivePipe.Writer, _pipeCts.Token); _sendTask = ReadPipeAndSendAsync(_sendFunc, _sendPipe.Reader, _pipeCts.Token); } finally { _semaphore.Release(); } } /// <summary> /// Stops the pipe producer / consumer tasks and awaits they to end. /// </summary> public async Task StopAsync(CancellationToken cancellationToken) { await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); try { if (_receiveTask == null && _sendTask == null) { throw new InvalidOperationException("The pipe is not started"); } _pipeCts.Cancel(); if (_receiveTask != null) await _receiveTask; if (_sendTask != null) await _sendTask; } finally { _semaphore.Release(); } } /// <summary> /// Writes a envelope into the send pipe. /// </summary> public async Task SendAsync(Envelope envelope, CancellationToken cancellationToken) { if (envelope == null) throw new ArgumentNullException(nameof(envelope)); if (_sendTask == null) throw new InvalidOperationException($"The send task was not initialized. Call {nameof(StartAsync)} first."); if (_sendTask.IsCompleted) throw new InvalidOperationException("Send task is completed"); var envelopeJson = _envelopeSerializer.Serialize(envelope); await TraceAsync(envelopeJson, DataOperation.Send).ConfigureAwait(false); // Gets memory from the pipe to write the encoded string. // .NET string are UTF16 and the length to UTF8 is usually larger. // We can use Encoding.UTF8.GetBytes instead to get the precise length but here this is just a hint and the impact is irrelevant, // so we can avoid the overhead. var memory = _sendPipe.Writer.GetMemory(envelopeJson.Length); var length = Encoding.UTF8.GetBytes(envelopeJson, memory.Span); if (_pauseWriterThreshold > 0 && length >= _pauseWriterThreshold) { throw new InvalidOperationException("Serialized envelope size is larger than pauseWriterThreshold and cannot be sent"); } // Signals the pipe that the data is ready. _sendPipe.Writer.Advance(length); var flushResult = await _sendPipe.Writer.FlushAsync(cancellationToken).ConfigureAwait(false); if (flushResult.IsCompleted || flushResult.IsCanceled) { throw new InvalidOperationException("Send pipe is completed"); } } /// <summary> /// Receives an envelope from the receive pipe. /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> /// <exception cref="InvalidOperationException"></exception> public async Task<Envelope> ReceiveAsync(CancellationToken cancellationToken) { if (_receiveTask == null) throw new InvalidOperationException($"The receive task was not initialized. Call {nameof(StartAsync)} first."); if (_receiveTask.IsCompleted) throw new InvalidOperationException("The receive task is completed"); Envelope envelope = null; while (envelope == null && !cancellationToken.IsCancellationRequested) { var readResult = await _receivePipe.Reader.ReadAsync(cancellationToken).ConfigureAwait(false); var buffer = readResult.Buffer; if (readResult.IsCompleted || buffer.IsEmpty) { // The receiveTask is completing, no need to throw an exception. break; } var consumed = buffer.Start; if (JsonBuffer.TryExtractJsonFromBuffer(buffer, out var json)) { var envelopeJson = Encoding.UTF8.GetString(json.ToArray()); await TraceAsync(envelopeJson, DataOperation.Receive).ConfigureAwait(false); envelope = _envelopeSerializer.Deserialize(envelopeJson); consumed = json.End; } if (envelope != null) { // An envelope was found and the buffer may contain another one _receivePipe.Reader.AdvanceTo(consumed); } else { // No envelope found after examining the whole buffer, more data is needed _receivePipe.Reader.AdvanceTo(consumed, buffer.End); } } return envelope; } public void Dispose() { _pipeCts.Dispose(); } private Task TraceAsync(string data, DataOperation operation) { if (_traceWriter == null || !_traceWriter.IsEnabled) return Task.CompletedTask; return _traceWriter.TraceAsync(data, operation); } /// <summary> /// Receives data from the provided function using the memory retrieve from the pipe writer. /// </summary> private static async Task ReceiveAndWriteToPipeAsync( Func<Memory<byte>, CancellationToken, ValueTask<int>> receiveFunc, PipeWriter writer, CancellationToken cancellationToken) { Exception exception = null; try { while (!cancellationToken.IsCancellationRequested) { var memory = writer.GetMemory(); var read = await receiveFunc(memory, cancellationToken).ConfigureAwait(false); if (read == 0) break; writer.Advance(read); var flushResult = await writer.FlushAsync(cancellationToken).ConfigureAwait(false); if (flushResult.IsCompleted || flushResult.IsCanceled) break; } } catch (Exception ex) { exception = ex; } finally { await writer.CompleteAsync(exception).ConfigureAwait(false); } } /// <summary> /// Read data from the provided pipe and send it using the function. /// </summary> private static async Task ReadPipeAndSendAsync( Func<ReadOnlyMemory<byte>, CancellationToken, ValueTask> sendFunc, PipeReader reader, CancellationToken cancellationToken) { Exception exception = null; try { while (!cancellationToken.IsCancellationRequested) { var result = await reader.ReadAsync(cancellationToken).ConfigureAwait(false); var buffer = result.Buffer; if (result.IsCompleted || buffer.IsEmpty) break; foreach (var memory in buffer) { await sendFunc(memory, cancellationToken); } reader.AdvanceTo(buffer.End); } } catch (Exception ex) { exception = ex; } finally { await reader.CompleteAsync(exception).ConfigureAwait(false); } } } } #endif
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Globalization; using System.Net; using System.Net.Sockets; using System.Text; using log4net.Layout; using log4net.Core; using log4net.Util; namespace log4net.Appender { /// <summary> /// Sends logging events as connectionless UDP datagrams to a remote host or a /// multicast group using an <see cref="UdpClient" />. /// </summary> /// <remarks> /// <para> /// UDP guarantees neither that messages arrive, nor that they arrive in the correct order. /// </para> /// <para> /// To view the logging results, a custom application can be developed that listens for logging /// events. /// </para> /// <para> /// When decoding events send via this appender remember to use the same encoding /// to decode the events as was used to send the events. See the <see cref="Encoding"/> /// property to specify the encoding to use. /// </para> /// </remarks> /// <example> /// This example shows how to log receive logging events that are sent /// on IP address 244.0.0.1 and port 8080 to the console. The event is /// encoded in the packet as a unicode string and it is decoded as such. /// <code lang="C#"> /// IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); /// UdpClient udpClient; /// byte[] buffer; /// string loggingEvent; /// /// try /// { /// udpClient = new UdpClient(8080); /// /// while(true) /// { /// buffer = udpClient.Receive(ref remoteEndPoint); /// loggingEvent = System.Text.Encoding.Unicode.GetString(buffer); /// Console.WriteLine(loggingEvent); /// } /// } /// catch(Exception e) /// { /// Console.WriteLine(e.ToString()); /// } /// </code> /// <code lang="Visual Basic"> /// Dim remoteEndPoint as IPEndPoint /// Dim udpClient as UdpClient /// Dim buffer as Byte() /// Dim loggingEvent as String /// /// Try /// remoteEndPoint = new IPEndPoint(IPAddress.Any, 0) /// udpClient = new UdpClient(8080) /// /// While True /// buffer = udpClient.Receive(ByRef remoteEndPoint) /// loggingEvent = System.Text.Encoding.Unicode.GetString(buffer) /// Console.WriteLine(loggingEvent) /// Wend /// Catch e As Exception /// Console.WriteLine(e.ToString()) /// End Try /// </code> /// <para> /// An example configuration section to log information using this appender to the /// IP 224.0.0.1 on port 8080: /// </para> /// <code lang="XML" escaped="true"> /// <appender name="UdpAppender" type="log4net.Appender.UdpAppender"> /// <remoteAddress value="224.0.0.1" /> /// <remotePort value="8080" /> /// <layout type="log4net.Layout.PatternLayout" value="%-5level %logger [%ndc] - %message%newline" /> /// </appender> /// </code> /// </example> /// <author>Gert Driesen</author> /// <author>Nicko Cadell</author> public class UdpAppender : AppenderSkeleton { #region Public Instance Constructors /// <summary> /// Initializes a new instance of the <see cref="UdpAppender" /> class. /// </summary> /// <remarks> /// The default constructor initializes all fields to their default values. /// </remarks> public UdpAppender() { } #endregion Public Instance Constructors #region Public Instance Properties /// <summary> /// Gets or sets the IP address of the remote host or multicast group to which /// the underlying <see cref="UdpClient" /> should sent the logging event. /// </summary> /// <value> /// The IP address of the remote host or multicast group to which the logging event /// will be sent. /// </value> /// <remarks> /// <para> /// Multicast addresses are identified by IP class <b>D</b> addresses (in the range 224.0.0.0 to /// 239.255.255.255). Multicast packets can pass across different networks through routers, so /// it is possible to use multicasts in an Internet scenario as long as your network provider /// supports multicasting. /// </para> /// <para> /// Hosts that want to receive particular multicast messages must register their interest by joining /// the multicast group. Multicast messages are not sent to networks where no host has joined /// the multicast group. Class <b>D</b> IP addresses are used for multicast groups, to differentiate /// them from normal host addresses, allowing nodes to easily detect if a message is of interest. /// </para> /// <para> /// Static multicast addresses that are needed globally are assigned by IANA. A few examples are listed in the table below: /// </para> /// <para> /// <list type="table"> /// <listheader> /// <term>IP Address</term> /// <description>Description</description> /// </listheader> /// <item> /// <term>224.0.0.1</term> /// <description> /// <para> /// Sends a message to all system on the subnet. /// </para> /// </description> /// </item> /// <item> /// <term>224.0.0.2</term> /// <description> /// <para> /// Sends a message to all routers on the subnet. /// </para> /// </description> /// </item> /// <item> /// <term>224.0.0.12</term> /// <description> /// <para> /// The DHCP server answers messages on the IP address 224.0.0.12, but only on a subnet. /// </para> /// </description> /// </item> /// </list> /// </para> /// <para> /// A complete list of actually reserved multicast addresses and their owners in the ranges /// defined by RFC 3171 can be found at the <A href="http://www.iana.org/assignments/multicast-addresses">IANA web site</A>. /// </para> /// <para> /// The address range 239.0.0.0 to 239.255.255.255 is reserved for administrative scope-relative /// addresses. These addresses can be reused with other local groups. Routers are typically /// configured with filters to prevent multicast traffic in this range from flowing outside /// of the local network. /// </para> /// </remarks> public IPAddress RemoteAddress { get { return m_remoteAddress; } set { m_remoteAddress = value; } } /// <summary> /// Gets or sets the TCP port number of the remote host or multicast group to which /// the underlying <see cref="UdpClient" /> should sent the logging event. /// </summary> /// <value> /// An integer value in the range <see cref="IPEndPoint.MinPort" /> to <see cref="IPEndPoint.MaxPort" /> /// indicating the TCP port number of the remote host or multicast group to which the logging event /// will be sent. /// </value> /// <remarks> /// The underlying <see cref="UdpClient" /> will send messages to this TCP port number /// on the remote host or multicast group. /// </remarks> /// <exception cref="ArgumentOutOfRangeException">The value specified is less than <see cref="IPEndPoint.MinPort" /> or greater than <see cref="IPEndPoint.MaxPort" />.</exception> public int RemotePort { get { return m_remotePort; } set { if (value < IPEndPoint.MinPort || value > IPEndPoint.MaxPort) { #if !NETMF throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("value", (object)value, "The value specified is less than " + IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + " or greater than " + IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); #else throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("value", (object)value, "The value specified is less than " + IPEndPoint.MinPort.ToString() + " or greater than " + IPEndPoint.MaxPort.ToString() + "."); #endif } else { m_remotePort = value; } } } /// <summary> /// Gets or sets the TCP port number from which the underlying <see cref="UdpClient" /> will communicate. /// </summary> /// <value> /// An integer value in the range <see cref="IPEndPoint.MinPort" /> to <see cref="IPEndPoint.MaxPort" /> /// indicating the TCP port number from which the underlying <see cref="UdpClient" /> will communicate. /// </value> /// <remarks> /// <para> /// The underlying <see cref="UdpClient" /> will bind to this port for sending messages. /// </para> /// <para> /// Setting the value to 0 (the default) will cause the udp client not to bind to /// a local port. /// </para> /// </remarks> /// <exception cref="ArgumentOutOfRangeException">The value specified is less than <see cref="IPEndPoint.MinPort" /> or greater than <see cref="IPEndPoint.MaxPort" />.</exception> public int LocalPort { get { return m_localPort; } set { if (value != 0 && (value < IPEndPoint.MinPort || value > IPEndPoint.MaxPort)) { #if !NETMF throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("value", (object)value, "The value specified is less than " + IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + " or greater than " + IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); #else throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("value", (object)value, "The value specified is less than " + IPEndPoint.MinPort.ToString() + " or greater than " + IPEndPoint.MaxPort.ToString() + "."); #endif } else { m_localPort = value; } } } /// <summary> /// Gets or sets <see cref="Encoding"/> used to write the packets. /// </summary> /// <value> /// The <see cref="Encoding"/> used to write the packets. /// </value> /// <remarks> /// <para> /// The <see cref="Encoding"/> used to write the packets. /// </para> /// </remarks> public Encoding Encoding { get { return m_encoding; } set { m_encoding = value; } } #endregion Public Instance Properties #region Protected Instance Properties /// <summary> /// Gets or sets the underlying <see cref="UdpClient" />. /// </summary> /// <value> /// The underlying <see cref="UdpClient" />. /// </value> /// <remarks> /// <see cref="UdpAppender" /> creates a <see cref="UdpClient" /> to send logging events /// over a network. Classes deriving from <see cref="UdpAppender" /> can use this /// property to get or set this <see cref="UdpClient" />. Use the underlying <see cref="UdpClient" /> /// returned from <see cref="Client" /> if you require access beyond that which /// <see cref="UdpAppender" /> provides. /// </remarks> protected UdpClient Client { get { return this.m_client; } set { this.m_client = value; } } /// <summary> /// Gets or sets the cached remote endpoint to which the logging events should be sent. /// </summary> /// <value> /// The cached remote endpoint to which the logging events will be sent. /// </value> /// <remarks> /// The <see cref="ActivateOptions" /> method will initialize the remote endpoint /// with the values of the <see cref="RemoteAddress" /> and <see cref="RemotePort"/> /// properties. /// </remarks> protected IPEndPoint RemoteEndPoint { get { return this.m_remoteEndPoint; } set { this.m_remoteEndPoint = value; } } #endregion Protected Instance Properties #region Implementation of IOptionHandler /// <summary> /// Initialize the appender based on the options set. /// </summary> /// <remarks> /// <para> /// This is part of the <see cref="IOptionHandler"/> delayed object /// activation scheme. The <see cref="ActivateOptions"/> method must /// be called on this object after the configuration properties have /// been set. Until <see cref="ActivateOptions"/> is called this /// object is in an undefined state and must not be used. /// </para> /// <para> /// If any of the configuration properties are modified then /// <see cref="ActivateOptions"/> must be called again. /// </para> /// <para> /// The appender will be ignored if no <see cref="RemoteAddress" /> was specified or /// an invalid remote or local TCP port number was specified. /// </para> /// </remarks> /// <exception cref="ArgumentNullException">The required property <see cref="RemoteAddress" /> was not specified.</exception> /// <exception cref="ArgumentOutOfRangeException">The TCP port number assigned to <see cref="LocalPort" /> or <see cref="RemotePort" /> is less than <see cref="IPEndPoint.MinPort" /> or greater than <see cref="IPEndPoint.MaxPort" />.</exception> public override void ActivateOptions() { base.ActivateOptions(); if (this.RemoteAddress == null) { throw new ArgumentNullException("The required property 'Address' was not specified."); } else if (this.RemotePort < IPEndPoint.MinPort || this.RemotePort > IPEndPoint.MaxPort) { #if !NETMF throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("this.RemotePort", (object)this.RemotePort, "The RemotePort is less than " + IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + " or greater than " + IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); #else throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("this.RemotePort", (object)this.RemotePort, "The RemotePort is less than " + IPEndPoint.MinPort.ToString() + " or greater than " + IPEndPoint.MaxPort.ToString() + "."); #endif } else if (this.LocalPort != 0 && (this.LocalPort < IPEndPoint.MinPort || this.LocalPort > IPEndPoint.MaxPort)) { #if !NETMF throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("this.LocalPort", (object)this.LocalPort, "The LocalPort is less than " + IPEndPoint.MinPort.ToString(NumberFormatInfo.InvariantInfo) + " or greater than " + IPEndPoint.MaxPort.ToString(NumberFormatInfo.InvariantInfo) + "."); #else throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("this.LocalPort", (object)this.LocalPort, "The LocalPort is less than " + IPEndPoint.MinPort.ToString() + " or greater than " + IPEndPoint.MaxPort.ToString() + "."); #endif } else { this.RemoteEndPoint = new IPEndPoint(this.RemoteAddress, this.RemotePort); this.InitializeClientConnection(); } } #endregion #region Override implementation of AppenderSkeleton /// <summary> /// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(LoggingEvent)"/> method. /// </summary> /// <param name="loggingEvent">The event to log.</param> /// <remarks> /// <para> /// Sends the event using an UDP datagram. /// </para> /// <para> /// Exceptions are passed to the <see cref="AppenderSkeleton.ErrorHandler"/>. /// </para> /// </remarks> protected override void Append(LoggingEvent loggingEvent) { try { #if !NETMF Byte [] buffer = m_encoding.GetBytes(RenderLoggingEvent(loggingEvent).ToCharArray()); #else string s = RenderLoggingEvent(loggingEvent); Byte[] buffer = m_encoding.GetBytes(s); #endif this.Client.Send(buffer, buffer.Length, this.RemoteEndPoint); } catch (Exception ex) { ErrorHandler.Error( "Unable to send logging event to remote host " + this.RemoteAddress.ToString() + " on port " + this.RemotePort + ".", ex, ErrorCode.WriteFailure); } } /// <summary> /// This appender requires a <see cref="Layout"/> to be set. /// </summary> /// <value><c>true</c></value> /// <remarks> /// <para> /// This appender requires a <see cref="Layout"/> to be set. /// </para> /// </remarks> override protected bool RequiresLayout { get { return true; } } /// <summary> /// Closes the UDP connection and releases all resources associated with /// this <see cref="UdpAppender" /> instance. /// </summary> /// <remarks> /// <para> /// Disables the underlying <see cref="UdpClient" /> and releases all managed /// and unmanaged resources associated with the <see cref="UdpAppender" />. /// </para> /// </remarks> override protected void OnClose() { base.OnClose(); if (this.Client != null) { this.Client.Close(); this.Client = null; } } #endregion Override implementation of AppenderSkeleton #region Protected Instance Methods /// <summary> /// Initializes the underlying <see cref="UdpClient" /> connection. /// </summary> /// <remarks> /// <para> /// The underlying <see cref="UdpClient"/> is initialized and binds to the /// port number from which you intend to communicate. /// </para> /// <para> /// Exceptions are passed to the <see cref="AppenderSkeleton.ErrorHandler"/>. /// </para> /// </remarks> protected virtual void InitializeClientConnection() { try { if (this.LocalPort == 0) { #if NETCF || NET_1_0 || SSCLI_1_0 || CLI_1_0 || NETMF this.Client = new UdpClient(); #else this.Client = new UdpClient(RemoteAddress.AddressFamily); #endif } else { #if NETCF || NET_1_0 || SSCLI_1_0 || CLI_1_0 || NETMF this.Client = new UdpClient(this.LocalPort); #else this.Client = new UdpClient(this.LocalPort, RemoteAddress.AddressFamily); #endif } } catch (Exception ex) { ErrorHandler.Error( "Could not initialize the UdpClient connection on port " + #if !NETMF this.LocalPort.ToString(NumberFormatInfo.InvariantInfo) + ".", #else this.LocalPort.ToString() + ".", #endif ex, ErrorCode.GenericFailure); this.Client = null; } } #endregion Protected Instance Methods #region Private Instance Fields /// <summary> /// The IP address of the remote host or multicast group to which /// the logging event will be sent. /// </summary> private IPAddress m_remoteAddress; /// <summary> /// The TCP port number of the remote host or multicast group to /// which the logging event will be sent. /// </summary> private int m_remotePort; /// <summary> /// The cached remote endpoint to which the logging events will be sent. /// </summary> private IPEndPoint m_remoteEndPoint; /// <summary> /// The TCP port number from which the <see cref="UdpClient" /> will communicate. /// </summary> private int m_localPort; /// <summary> /// The <see cref="UdpClient" /> instance that will be used for sending the /// logging events. /// \todo Needs re-instatement with a real network connection /// </summary> private UdpClient m_client; /// <summary> /// The encoding to use for the packet. /// </summary> #if !NETMF private Encoding m_encoding = Encoding.Default; #else private Encoding m_encoding = Encoding.UTF8; #endif #endregion Private Instance Fields } }
// // DiffieHellmanManaged.cs: Implements the Diffie-Hellman key agreement algorithm // // Author: // Pieter Philippaerts (Pieter@mentalis.org) // // (C) 2003 The Mentalis.org Team (http://www.mentalis.org/) // // References: // - PKCS#3 [http://www.rsasecurity.com/rsalabs/pkcs/pkcs-3/] // // // 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; using Mono.Math; namespace Mono.Security.Cryptography { /// <summary> /// Implements the Diffie-Hellman algorithm. /// </summary> public sealed class DiffieHellmanManaged : DiffieHellman { /// <summary> /// Initializes a new <see cref="DiffieHellmanManaged"/> instance. /// </summary> /// <remarks>The default length of the shared secret is 1024 bits.</remarks> public DiffieHellmanManaged() : this(1024, 160, DHKeyGeneration.Static) {} /// <summary> /// Initializes a new <see cref="DiffieHellmanManaged"/> instance. /// </summary> /// <param name="bitLength">The length, in bits, of the public P parameter.</param> /// <param name="l">The length, in bits, of the secret value X. This parameter can be set to 0 to use the default size.</param> /// <param name="method">One of the <see cref="DHKeyGeneration"/> values.</param> /// <remarks>The larger the bit length, the more secure the algorithm is. The default is 1024 bits. The minimum bit length is 128 bits.<br/>The size of the private value will be one fourth of the bit length specified.</remarks> /// <exception cref="ArgumentException">The specified bit length is invalid.</exception> public DiffieHellmanManaged(int bitLength, int l, DHKeyGeneration method) { if (bitLength < 256 || l < 0) throw new ArgumentException(); BigInteger p, g; GenerateKey (bitLength, method, out p, out g); Initialize(p, g, null, l, false); } /// <summary> /// Initializes a new <see cref="DiffieHellmanManaged"/> instance. /// </summary> /// <param name="p">The P parameter of the Diffie-Hellman algorithm. This is a public parameter.</param> /// <param name="g">The G parameter of the Diffie-Hellman algorithm. This is a public parameter.</param> /// <param name="x">The X parameter of the Diffie-Hellman algorithm. This is a private parameter. If this parameters is a null reference (<b>Nothing</b> in Visual Basic), a secret value of the default size will be generated.</param> /// <exception cref="ArgumentNullException"><paramref name="p"/> or <paramref name="g"/> is a null reference (<b>Nothing</b> in Visual Basic).</exception> /// <exception cref="CryptographicException"><paramref name="p"/> or <paramref name="g"/> is invalid.</exception> public DiffieHellmanManaged(byte[] p, byte[] g, byte[] x) { if (p == null || g == null) throw new ArgumentNullException(); if (x == null) Initialize(new BigInteger(p), new BigInteger(g), null, 0, true); else Initialize(new BigInteger(p), new BigInteger(g), new BigInteger(x), 0, true); } /// <summary> /// Initializes a new <see cref="DiffieHellmanManaged"/> instance. /// </summary> /// <param name="p">The P parameter of the Diffie-Hellman algorithm.</param> /// <param name="g">The G parameter of the Diffie-Hellman algorithm.</param> /// <param name="l">The length, in bits, of the private value. If 0 is specified, the default value will be used.</param> /// <exception cref="ArgumentNullException"><paramref name="p"/> or <paramref name="g"/> is a null reference (<b>Nothing</b> in Visual Basic).</exception> /// <exception cref="ArgumentException"><paramref name="l"/> is invalid.</exception> /// <exception cref="CryptographicException"><paramref name="p"/> or <paramref name="g"/> is invalid.</exception> public DiffieHellmanManaged(byte[] p, byte[] g, int l) { if (p == null || g == null) throw new ArgumentNullException(); if (l < 0) throw new ArgumentException(); Initialize(new BigInteger(p), new BigInteger(g), null, l, true); } // initializes the private variables (throws CryptographicException) private void Initialize(BigInteger p, BigInteger g, BigInteger x, int secretLen, bool checkInput) { if (checkInput) { if (!p.IsProbablePrime() || g <= 0 || g >= p || (x != null && (x <= 0 || x > p - 2))) throw new CryptographicException(); } // default is to generate a number as large as the prime this // is usually overkill, but it's the most secure thing we can // do if the user doesn't specify a desired secret length ... if (secretLen == 0) secretLen = p.BitCount(); m_P = p; m_G = g; if (x == null) { BigInteger pm1 = m_P - 1; for(m_X = BigInteger.GenerateRandom(secretLen); m_X >= pm1 || m_X == 0; m_X = BigInteger.GenerateRandom(secretLen)) {} } else { m_X = x; } } /// <summary> /// Creates the key exchange data. /// </summary> /// <returns>The key exchange data to be sent to the intended recipient.</returns> public override byte[] CreateKeyExchange() { BigInteger y = m_G.ModPow(m_X, m_P); byte[] ret = y.GetBytes(); y.Clear(); return ret; } /// <summary> /// Extracts secret information from the key exchange data. /// </summary> /// <param name="keyEx">The key exchange data within which the shared key is hidden.</param> /// <returns>The shared key derived from the key exchange data.</returns> public override byte[] DecryptKeyExchange(byte[] keyEx) { BigInteger pvr = new BigInteger(keyEx); BigInteger z = pvr.ModPow(m_X, m_P); byte[] ret = z.GetBytes(); z.Clear(); return ret; } /// <summary> /// Gets the name of the key exchange algorithm. /// </summary> /// <value>The name of the key exchange algorithm.</value> public override string KeyExchangeAlgorithm { get { return "1.2.840.113549.1.3"; // PKCS#3 OID } } /// <summary> /// Gets the name of the signature algorithm. /// </summary> /// <value>The name of the signature algorithm.</value> public override string SignatureAlgorithm { get { return null; } } // clear keys protected override void Dispose(bool disposing) { if (!m_Disposed) { if (m_P != null) m_P.Clear(); if (m_G != null) m_G.Clear(); if (m_X != null) m_X.Clear(); } m_Disposed = true; } /// <summary> /// Exports the <see cref="DHParameters"/>. /// </summary> /// <param name="includePrivateParameters"><b>true</b> to include private parameters; otherwise, <b>false</b>.</param> /// <returns>The parameters for <see cref="DiffieHellman"/>.</returns> public override DHParameters ExportParameters(bool includePrivateParameters) { DHParameters ret = new DHParameters(); ret.P = m_P.GetBytes(); ret.G = m_G.GetBytes(); if (includePrivateParameters) { ret.X = m_X.GetBytes(); } return ret; } /// <summary> /// Imports the specified <see cref="DHParameters"/>. /// </summary> /// <param name="parameters">The parameters for <see cref="DiffieHellman"/>.</param> /// <exception cref="CryptographicException"><paramref name="P"/> or <paramref name="G"/> is a null reference (<b>Nothing</b> in Visual Basic) -or- <paramref name="P"/> is not a prime number.</exception> public override void ImportParameters(DHParameters parameters) { if (parameters.P == null) throw new CryptographicException("Missing P value."); if (parameters.G == null) throw new CryptographicException("Missing G value."); BigInteger p = new BigInteger(parameters.P), g = new BigInteger(parameters.G), x = null; if (parameters.X != null) { x = new BigInteger(parameters.X); } Initialize(p, g, x, 0, true); } ~DiffieHellmanManaged() { Dispose(false); } //TODO: implement DH key generation methods private void GenerateKey(int bitlen, DHKeyGeneration keygen, out BigInteger p, out BigInteger g) { if (keygen == DHKeyGeneration.Static) { if (bitlen == 768) p = new BigInteger(m_OAKLEY768); else if (bitlen == 1024) p = new BigInteger(m_OAKLEY1024); else if (bitlen == 1536) p = new BigInteger(m_OAKLEY1536); else throw new ArgumentException("Invalid bit size."); g = new BigInteger(22); // all OAKLEY keys use 22 as generator //} else if (keygen == DHKeyGeneration.SophieGermain) { // throw new NotSupportedException(); //TODO //} else if (keygen == DHKeyGeneration.DSA) { // 1. Let j = (p - 1)/q. // 2. Set h = any integer, where 1 < h < p - 1 // 3. Set g = h^j mod p // 4. If g = 1 go to step 2 // BigInteger j = (p - 1) / q; } else { // random p = BigInteger.GeneratePseudoPrime(bitlen); g = new BigInteger(3); // always use 3 as a generator } } private BigInteger m_P; private BigInteger m_G; private BigInteger m_X; private bool m_Disposed; private static byte[] m_OAKLEY768 = new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x3A, 0x36, 0x20, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; private static byte[] m_OAKLEY1024 = new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED, 0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6, 0x49, 0x28, 0x66, 0x51, 0xEC, 0xE6, 0x53, 0x81, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; private static byte[] m_OAKLEY1536 = new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED, 0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6, 0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, 0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05, 0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, 0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F, 0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, 0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB, 0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, 0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04, 0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x23, 0x73, 0x27, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; } }
// 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.IO; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.JsonPatch; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.ObjectPool; using Moq; using Newtonsoft.Json; using Xunit; namespace Microsoft.AspNetCore.Mvc.Formatters { public class NewtonsoftJsonPatchInputFormatterTest { private static readonly ObjectPoolProvider _objectPoolProvider = new DefaultObjectPoolProvider(); private static readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings(); [Fact] public async Task Constructor_BuffersRequestBody_ByDefault() { // Arrange var formatter = new NewtonsoftJsonPatchInputFormatter( GetLogger(), _serializerSettings, ArrayPool<char>.Shared, _objectPoolProvider, new MvcOptions(), new MvcNewtonsoftJsonOptions()); var content = "[{\"op\":\"add\",\"path\":\"Customer/Name\",\"value\":\"John\"}]"; var contentBytes = Encoding.UTF8.GetBytes(content); var httpContext = new DefaultHttpContext(); httpContext.Features.Set<IHttpResponseFeature>(new TestResponseFeature()); httpContext.Request.Body = new NonSeekableReadStream(contentBytes, allowSyncReads: false); httpContext.Request.ContentType = "application/json"; var formatterContext = CreateInputFormatterContext(typeof(JsonPatchDocument<Customer>), httpContext); // Act var result = await formatter.ReadAsync(formatterContext); // Assert Assert.False(result.HasError); var patchDocument = Assert.IsType<JsonPatchDocument<Customer>>(result.Model); Assert.Equal("add", patchDocument.Operations[0].op); Assert.Equal("Customer/Name", patchDocument.Operations[0].path); Assert.Equal("John", patchDocument.Operations[0].value); } [Fact] public async Task Constructor_SuppressInputFormatterBuffering_DoesNotBufferRequestBody() { // Arrange var mvcOptions = new MvcOptions() { SuppressInputFormatterBuffering = false, }; var formatter = new NewtonsoftJsonPatchInputFormatter( GetLogger(), _serializerSettings, ArrayPool<char>.Shared, _objectPoolProvider, mvcOptions, new MvcNewtonsoftJsonOptions()); var content = "[{\"op\":\"add\",\"path\":\"Customer/Name\",\"value\":\"John\"}]"; var contentBytes = Encoding.UTF8.GetBytes(content); var httpContext = new DefaultHttpContext(); httpContext.Features.Set<IHttpResponseFeature>(new TestResponseFeature()); httpContext.Request.Body = new NonSeekableReadStream(contentBytes); httpContext.Request.ContentType = "application/json"; var formatterContext = CreateInputFormatterContext(typeof(JsonPatchDocument<Customer>), httpContext); // Act // Mutate options after passing into the constructor to make sure that the value type is not store in the constructor mvcOptions.SuppressInputFormatterBuffering = true; var result = await formatter.ReadAsync(formatterContext); // Assert Assert.False(result.HasError); var patchDocument = Assert.IsType<JsonPatchDocument<Customer>>(result.Model); Assert.Equal("add", patchDocument.Operations[0].op); Assert.Equal("Customer/Name", patchDocument.Operations[0].path); Assert.Equal("John", patchDocument.Operations[0].value); Assert.False(httpContext.Request.Body.CanSeek); result = await formatter.ReadAsync(formatterContext); // Assert Assert.False(result.HasError); Assert.Null(result.Model); } [Fact] public async Task JsonPatchInputFormatter_ReadsOneOperation_Successfully() { // Arrange var formatter = CreateFormatter(); var content = "[{\"op\":\"add\",\"path\":\"Customer/Name\",\"value\":\"John\"}]"; var contentBytes = Encoding.UTF8.GetBytes(content); var httpContext = CreateHttpContext(contentBytes); var formatterContext = CreateInputFormatterContext(typeof(JsonPatchDocument<Customer>), httpContext); // Act var result = await formatter.ReadAsync(formatterContext); // Assert Assert.False(result.HasError); var patchDocument = Assert.IsType<JsonPatchDocument<Customer>>(result.Model); Assert.Equal("add", patchDocument.Operations[0].op); Assert.Equal("Customer/Name", patchDocument.Operations[0].path); Assert.Equal("John", patchDocument.Operations[0].value); } [Fact] public async Task JsonPatchInputFormatter_ReadsMultipleOperations_Successfully() { // Arrange var formatter = CreateFormatter(); var content = "[{\"op\": \"add\", \"path\" : \"Customer/Name\", \"value\":\"John\"}," + "{\"op\": \"remove\", \"path\" : \"Customer/Name\"}]"; var contentBytes = Encoding.UTF8.GetBytes(content); var httpContext = CreateHttpContext(contentBytes); var formatterContext = CreateInputFormatterContext(typeof(JsonPatchDocument<Customer>), httpContext); // Act var result = await formatter.ReadAsync(formatterContext); // Assert Assert.False(result.HasError); var patchDocument = Assert.IsType<JsonPatchDocument<Customer>>(result.Model); Assert.Equal("add", patchDocument.Operations[0].op); Assert.Equal("Customer/Name", patchDocument.Operations[0].path); Assert.Equal("John", patchDocument.Operations[0].value); Assert.Equal("remove", patchDocument.Operations[1].op); Assert.Equal("Customer/Name", patchDocument.Operations[1].path); } [Theory] [InlineData("application/json-patch+json", true)] [InlineData("application/json", false)] [InlineData("application/*", false)] [InlineData("*/*", false)] public void CanRead_ReturnsTrueOnlyForJsonPatchContentType(string requestContentType, bool expectedCanRead) { // Arrange var formatter = CreateFormatter(); var content = "[{\"op\": \"add\", \"path\" : \"Customer/Name\", \"value\":\"John\"}]"; var contentBytes = Encoding.UTF8.GetBytes(content); var httpContext = CreateHttpContext(contentBytes, contentType: requestContentType); var formatterContext = CreateInputFormatterContext(typeof(JsonPatchDocument<Customer>), httpContext); // Act var result = formatter.CanRead(formatterContext); // Assert Assert.Equal(expectedCanRead, result); } [Theory] [InlineData(typeof(Customer))] [InlineData(typeof(IJsonPatchDocument))] public void CanRead_ReturnsFalse_NonJsonPatchContentType(Type modelType) { // Arrange var formatter = CreateFormatter(); var content = "[{\"op\": \"add\", \"path\" : \"Customer/Name\", \"value\":\"John\"}]"; var contentBytes = Encoding.UTF8.GetBytes(content); var httpContext = CreateHttpContext(contentBytes, contentType: "application/json-patch+json"); var provider = new EmptyModelMetadataProvider(); var metadata = provider.GetMetadataForType(modelType); var formatterContext = CreateInputFormatterContext(modelType, httpContext); // Act var result = formatter.CanRead(formatterContext); // Assert Assert.False(result); } [Fact] public async Task JsonPatchInputFormatter_ReturnsModelStateErrors_InvalidModelType() { // Arrange var exceptionMessage = "Cannot deserialize the current JSON array (e.g. [1,2,3]) into type " + $"'{typeof(Customer).FullName}' because the type requires a JSON object "; // This test relies on 2.1 error message behavior var formatter = CreateFormatter(allowInputFormatterExceptionMessages: true); var content = "[{\"op\": \"add\", \"path\" : \"Customer/Name\", \"value\":\"John\"}]"; var contentBytes = Encoding.UTF8.GetBytes(content); var httpContext = CreateHttpContext(contentBytes, contentType: "application/json-patch+json"); var formatterContext = CreateInputFormatterContext(typeof(Customer), httpContext); // Act var result = await formatter.ReadAsync(formatterContext); // Assert Assert.True(result.HasError); Assert.Contains(exceptionMessage, formatterContext.ModelState[""].Errors[0].ErrorMessage); } private static ILogger GetLogger() { return NullLogger.Instance; } private NewtonsoftJsonPatchInputFormatter CreateFormatter(bool allowInputFormatterExceptionMessages = false) { return new NewtonsoftJsonPatchInputFormatter( NullLogger.Instance, _serializerSettings, ArrayPool<char>.Shared, _objectPoolProvider, new MvcOptions(), new MvcNewtonsoftJsonOptions() { AllowInputFormatterExceptionMessages = allowInputFormatterExceptionMessages, }); } private InputFormatterContext CreateInputFormatterContext(Type modelType, HttpContext httpContext) { var provider = new EmptyModelMetadataProvider(); var metadata = provider.GetMetadataForType(modelType); return new InputFormatterContext( httpContext, modelName: string.Empty, modelState: new ModelStateDictionary(), metadata: metadata, readerFactory: new TestHttpRequestStreamReaderFactory().CreateReader); } private static HttpContext CreateHttpContext( byte[] contentBytes, string contentType = "application/json-patch+json") { var request = new Mock<HttpRequest>(); var headers = new Mock<IHeaderDictionary>(); request.SetupGet(r => r.Headers).Returns(headers.Object); request.SetupGet(f => f.Body).Returns(new MemoryStream(contentBytes)); request.SetupGet(f => f.ContentType).Returns(contentType); var httpContext = new Mock<HttpContext>(); httpContext.SetupGet(c => c.Request).Returns(request.Object); httpContext.SetupGet(c => c.Request).Returns(request.Object); return httpContext.Object; } private class Customer { public string Name { get; set; } } private class TestResponseFeature : HttpResponseFeature { public override void OnCompleted(Func<object, Task> callback, object state) { // do not do anything } } } }
namespace Microsoft.PythonTools.Project.Web { partial class PythonWebLauncherOptions { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PythonWebLauncherOptions)); this._debugGroup = new System.Windows.Forms.GroupBox(); this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); this._environment = new System.Windows.Forms.TextBox(); this._searchPaths = new System.Windows.Forms.TextBox(); this._arguments = new System.Windows.Forms.TextBox(); this._interpArgs = new System.Windows.Forms.TextBox(); this._interpreterPath = new System.Windows.Forms.TextBox(); this._interpreterPathLabel = new System.Windows.Forms.Label(); this._interpArgsLabel = new System.Windows.Forms.Label(); this._argumentsLabel = new System.Windows.Forms.Label(); this._searchPathLabel = new System.Windows.Forms.Label(); this._portNumberLabel = new System.Windows.Forms.Label(); this._portNumber = new System.Windows.Forms.TextBox(); this._launchUrl = new System.Windows.Forms.TextBox(); this._launchUrlLabel = new System.Windows.Forms.Label(); this._environmentLabel = new System.Windows.Forms.Label(); this._toolTip = new System.Windows.Forms.ToolTip(this.components); this._debugServerTarget = new System.Windows.Forms.TextBox(); this._debugServerArguments = new System.Windows.Forms.TextBox(); this._debugServerEnvironment = new System.Windows.Forms.TextBox(); this._debugServerEnvironmentLabel = new System.Windows.Forms.Label(); this._debugServerArgumentsLabel = new System.Windows.Forms.Label(); this._debugServerTargetLabel = new System.Windows.Forms.Label(); this._debugServerTargetType = new System.Windows.Forms.ComboBox(); this._runServerTarget = new System.Windows.Forms.TextBox(); this._runServerArguments = new System.Windows.Forms.TextBox(); this._runServerEnvironment = new System.Windows.Forms.TextBox(); this._runServerEnvironmentLabel = new System.Windows.Forms.Label(); this._runServerArgumentsLabel = new System.Windows.Forms.Label(); this._runServerTargetLabel = new System.Windows.Forms.Label(); this._runServerTargetType = new System.Windows.Forms.ComboBox(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this._debugServerGroup = new System.Windows.Forms.GroupBox(); this.tableLayoutPanel4 = new System.Windows.Forms.TableLayoutPanel(); this._runServerGroup = new System.Windows.Forms.GroupBox(); this.tableLayoutPanel3 = new System.Windows.Forms.TableLayoutPanel(); this._debugGroup.SuspendLayout(); this.tableLayoutPanel2.SuspendLayout(); this.tableLayoutPanel1.SuspendLayout(); this._debugServerGroup.SuspendLayout(); this.tableLayoutPanel4.SuspendLayout(); this._runServerGroup.SuspendLayout(); this.tableLayoutPanel3.SuspendLayout(); this.SuspendLayout(); // // _debugGroup // resources.ApplyResources(this._debugGroup, "_debugGroup"); this._debugGroup.Controls.Add(this.tableLayoutPanel2); this._debugGroup.Name = "_debugGroup"; this._debugGroup.TabStop = false; // // tableLayoutPanel2 // resources.ApplyResources(this.tableLayoutPanel2, "tableLayoutPanel2"); this.tableLayoutPanel2.Controls.Add(this._environment, 1, 6); this.tableLayoutPanel2.Controls.Add(this._searchPaths, 1, 0); this.tableLayoutPanel2.Controls.Add(this._arguments, 1, 1); this.tableLayoutPanel2.Controls.Add(this._interpArgs, 1, 3); this.tableLayoutPanel2.Controls.Add(this._interpreterPath, 1, 2); this.tableLayoutPanel2.Controls.Add(this._interpArgsLabel, 0, 3); this.tableLayoutPanel2.Controls.Add(this._argumentsLabel, 0, 1); this.tableLayoutPanel2.Controls.Add(this._searchPathLabel, 0, 0); this.tableLayoutPanel2.Controls.Add(this._portNumberLabel, 0, 5); this.tableLayoutPanel2.Controls.Add(this._portNumber, 1, 5); this.tableLayoutPanel2.Controls.Add(this._launchUrl, 1, 4); this.tableLayoutPanel2.Controls.Add(this._launchUrlLabel, 0, 4); this.tableLayoutPanel2.Controls.Add(this._environmentLabel, 0, 6); this.tableLayoutPanel2.Controls.Add(this._interpreterPathLabel, 0, 2); this.tableLayoutPanel2.Name = "tableLayoutPanel2"; // // _environment // resources.ApplyResources(this._environment, "_environment"); this._environment.Name = "_environment"; this._toolTip.SetToolTip(this._environment, resources.GetString("_environment.ToolTip")); this._environment.TextChanged += new System.EventHandler(this.Setting_TextChanged); // // _searchPaths // resources.ApplyResources(this._searchPaths, "_searchPaths"); this._searchPaths.Name = "_searchPaths"; this._toolTip.SetToolTip(this._searchPaths, resources.GetString("_searchPaths.ToolTip")); this._searchPaths.TextChanged += new System.EventHandler(this.Setting_TextChanged); // // _arguments // resources.ApplyResources(this._arguments, "_arguments"); this._arguments.Name = "_arguments"; this._toolTip.SetToolTip(this._arguments, resources.GetString("_arguments.ToolTip")); this._arguments.TextChanged += new System.EventHandler(this.Setting_TextChanged); // // _interpArgs // resources.ApplyResources(this._interpArgs, "_interpArgs"); this._interpArgs.Name = "_interpArgs"; this._toolTip.SetToolTip(this._interpArgs, resources.GetString("_interpArgs.ToolTip")); this._interpArgs.TextChanged += new System.EventHandler(this.Setting_TextChanged); // // _interpreterPath // resources.ApplyResources(this._interpreterPath, "_interpreterPath"); this._interpreterPath.Name = "_interpreterPath"; this._toolTip.SetToolTip(this._interpreterPath, resources.GetString("_interpreterPath.ToolTip")); this._interpreterPath.TextChanged += new System.EventHandler(this.Setting_TextChanged); // // _interpreterPathLabel // resources.ApplyResources(this._interpreterPathLabel, "_interpreterPathLabel"); this._interpreterPathLabel.Name = "_interpreterPathLabel"; this._toolTip.SetToolTip(this._interpreterPathLabel, resources.GetString("_interpreterPathLabel.ToolTip")); // // _interpArgsLabel // resources.ApplyResources(this._interpArgsLabel, "_interpArgsLabel"); this._interpArgsLabel.Name = "_interpArgsLabel"; this._toolTip.SetToolTip(this._interpArgsLabel, resources.GetString("_interpArgsLabel.ToolTip")); // // _argumentsLabel // resources.ApplyResources(this._argumentsLabel, "_argumentsLabel"); this._argumentsLabel.Name = "_argumentsLabel"; this._toolTip.SetToolTip(this._argumentsLabel, resources.GetString("_argumentsLabel.ToolTip")); // // _searchPathLabel // resources.ApplyResources(this._searchPathLabel, "_searchPathLabel"); this._searchPathLabel.Name = "_searchPathLabel"; this._toolTip.SetToolTip(this._searchPathLabel, resources.GetString("_searchPathLabel.ToolTip")); // // _portNumberLabel // resources.ApplyResources(this._portNumberLabel, "_portNumberLabel"); this._portNumberLabel.Name = "_portNumberLabel"; this._toolTip.SetToolTip(this._portNumberLabel, resources.GetString("_portNumberLabel.ToolTip")); // // _portNumber // resources.ApplyResources(this._portNumber, "_portNumber"); this._portNumber.Name = "_portNumber"; this._toolTip.SetToolTip(this._portNumber, resources.GetString("_portNumber.ToolTip")); this._portNumber.TextChanged += new System.EventHandler(this.Setting_TextChanged); // // _launchUrl // resources.ApplyResources(this._launchUrl, "_launchUrl"); this._launchUrl.Name = "_launchUrl"; this._toolTip.SetToolTip(this._launchUrl, resources.GetString("_launchUrl.ToolTip")); this._launchUrl.TextChanged += new System.EventHandler(this.Setting_TextChanged); // // _launchUrlLabel // resources.ApplyResources(this._launchUrlLabel, "_launchUrlLabel"); this._launchUrlLabel.Name = "_launchUrlLabel"; this._toolTip.SetToolTip(this._launchUrlLabel, resources.GetString("_launchUrlLabel.ToolTip")); // // _environmentLabel // resources.ApplyResources(this._environmentLabel, "_environmentLabel"); this._environmentLabel.Name = "_environmentLabel"; this._toolTip.SetToolTip(this._environmentLabel, resources.GetString("_environmentLabel.ToolTip")); // // _debugServerTarget // resources.ApplyResources(this._debugServerTarget, "_debugServerTarget"); this._debugServerTarget.Name = "_debugServerTarget"; this._toolTip.SetToolTip(this._debugServerTarget, resources.GetString("_debugServerTarget.ToolTip")); this._debugServerTarget.TextChanged += new System.EventHandler(this.Setting_TextChanged); // // _debugServerArguments // resources.ApplyResources(this._debugServerArguments, "_debugServerArguments"); this.tableLayoutPanel4.SetColumnSpan(this._debugServerArguments, 2); this._debugServerArguments.Name = "_debugServerArguments"; this._toolTip.SetToolTip(this._debugServerArguments, resources.GetString("_debugServerArguments.ToolTip")); this._debugServerArguments.TextChanged += new System.EventHandler(this.Setting_TextChanged); // // _debugServerEnvironment // resources.ApplyResources(this._debugServerEnvironment, "_debugServerEnvironment"); this.tableLayoutPanel4.SetColumnSpan(this._debugServerEnvironment, 2); this._debugServerEnvironment.Name = "_debugServerEnvironment"; this._toolTip.SetToolTip(this._debugServerEnvironment, resources.GetString("_debugServerEnvironment.ToolTip")); this._debugServerEnvironment.TextChanged += new System.EventHandler(this.Setting_TextChanged); // // _debugServerEnvironmentLabel // resources.ApplyResources(this._debugServerEnvironmentLabel, "_debugServerEnvironmentLabel"); this._debugServerEnvironmentLabel.Name = "_debugServerEnvironmentLabel"; this._toolTip.SetToolTip(this._debugServerEnvironmentLabel, resources.GetString("_debugServerEnvironmentLabel.ToolTip")); // // _debugServerArgumentsLabel // resources.ApplyResources(this._debugServerArgumentsLabel, "_debugServerArgumentsLabel"); this._debugServerArgumentsLabel.Name = "_debugServerArgumentsLabel"; this._toolTip.SetToolTip(this._debugServerArgumentsLabel, resources.GetString("_debugServerArgumentsLabel.ToolTip")); // // _debugServerTargetLabel // resources.ApplyResources(this._debugServerTargetLabel, "_debugServerTargetLabel"); this._debugServerTargetLabel.Name = "_debugServerTargetLabel"; this._toolTip.SetToolTip(this._debugServerTargetLabel, resources.GetString("_debugServerTargetLabel.ToolTip")); // // _debugServerTargetType // resources.ApplyResources(this._debugServerTargetType, "_debugServerTargetType"); this._debugServerTargetType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this._debugServerTargetType.FormattingEnabled = true; this._debugServerTargetType.Items.AddRange(new object[] { resources.GetString("_debugServerTargetType.Items"), resources.GetString("_debugServerTargetType.Items1"), resources.GetString("_debugServerTargetType.Items2"), resources.GetString("_debugServerTargetType.Items3")}); this._debugServerTargetType.Name = "_debugServerTargetType"; this._toolTip.SetToolTip(this._debugServerTargetType, resources.GetString("_debugServerTargetType.ToolTip")); this._debugServerTargetType.SelectedValueChanged += new System.EventHandler(this.Setting_SelectedValueChanged); // // _runServerTarget // resources.ApplyResources(this._runServerTarget, "_runServerTarget"); this._runServerTarget.Name = "_runServerTarget"; this._toolTip.SetToolTip(this._runServerTarget, resources.GetString("_runServerTarget.ToolTip")); this._runServerTarget.TextChanged += new System.EventHandler(this.Setting_TextChanged); // // _runServerArguments // resources.ApplyResources(this._runServerArguments, "_runServerArguments"); this.tableLayoutPanel3.SetColumnSpan(this._runServerArguments, 2); this._runServerArguments.Name = "_runServerArguments"; this._toolTip.SetToolTip(this._runServerArguments, resources.GetString("_runServerArguments.ToolTip")); this._runServerArguments.TextChanged += new System.EventHandler(this.Setting_TextChanged); // // _runServerEnvironment // resources.ApplyResources(this._runServerEnvironment, "_runServerEnvironment"); this.tableLayoutPanel3.SetColumnSpan(this._runServerEnvironment, 2); this._runServerEnvironment.Name = "_runServerEnvironment"; this._toolTip.SetToolTip(this._runServerEnvironment, resources.GetString("_runServerEnvironment.ToolTip")); this._runServerEnvironment.TextChanged += new System.EventHandler(this.Setting_TextChanged); // // _runServerEnvironmentLabel // resources.ApplyResources(this._runServerEnvironmentLabel, "_runServerEnvironmentLabel"); this._runServerEnvironmentLabel.Name = "_runServerEnvironmentLabel"; this._toolTip.SetToolTip(this._runServerEnvironmentLabel, resources.GetString("_runServerEnvironmentLabel.ToolTip")); // // _runServerArgumentsLabel // resources.ApplyResources(this._runServerArgumentsLabel, "_runServerArgumentsLabel"); this._runServerArgumentsLabel.Name = "_runServerArgumentsLabel"; this._toolTip.SetToolTip(this._runServerArgumentsLabel, resources.GetString("_runServerArgumentsLabel.ToolTip")); // // _runServerTargetLabel // resources.ApplyResources(this._runServerTargetLabel, "_runServerTargetLabel"); this._runServerTargetLabel.Name = "_runServerTargetLabel"; this._toolTip.SetToolTip(this._runServerTargetLabel, resources.GetString("_runServerTargetLabel.ToolTip")); // // _runServerTargetType // resources.ApplyResources(this._runServerTargetType, "_runServerTargetType"); this._runServerTargetType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this._runServerTargetType.FormattingEnabled = true; this._runServerTargetType.Items.AddRange(new object[] { resources.GetString("_runServerTargetType.Items"), resources.GetString("_runServerTargetType.Items1"), resources.GetString("_runServerTargetType.Items2"), resources.GetString("_runServerTargetType.Items3")}); this._runServerTargetType.Name = "_runServerTargetType"; this._toolTip.SetToolTip(this._runServerTargetType, resources.GetString("_runServerTargetType.ToolTip")); this._runServerTargetType.SelectedValueChanged += new System.EventHandler(this.Setting_SelectedValueChanged); // // tableLayoutPanel1 // resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1"); this.tableLayoutPanel1.Controls.Add(this._debugServerGroup, 0, 2); this.tableLayoutPanel1.Controls.Add(this._runServerGroup, 0, 1); this.tableLayoutPanel1.Controls.Add(this._debugGroup, 0, 0); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; // // _debugServerGroup // resources.ApplyResources(this._debugServerGroup, "_debugServerGroup"); this._debugServerGroup.Controls.Add(this.tableLayoutPanel4); this._debugServerGroup.Name = "_debugServerGroup"; this._debugServerGroup.TabStop = false; // // tableLayoutPanel4 // resources.ApplyResources(this.tableLayoutPanel4, "tableLayoutPanel4"); this.tableLayoutPanel4.Controls.Add(this._debugServerTarget, 1, 0); this.tableLayoutPanel4.Controls.Add(this._debugServerArguments, 1, 1); this.tableLayoutPanel4.Controls.Add(this._debugServerEnvironment, 1, 2); this.tableLayoutPanel4.Controls.Add(this._debugServerEnvironmentLabel, 0, 2); this.tableLayoutPanel4.Controls.Add(this._debugServerArgumentsLabel, 0, 1); this.tableLayoutPanel4.Controls.Add(this._debugServerTargetLabel, 0, 0); this.tableLayoutPanel4.Controls.Add(this._debugServerTargetType, 2, 0); this.tableLayoutPanel4.Name = "tableLayoutPanel4"; // // _runServerGroup // resources.ApplyResources(this._runServerGroup, "_runServerGroup"); this._runServerGroup.Controls.Add(this.tableLayoutPanel3); this._runServerGroup.Name = "_runServerGroup"; this._runServerGroup.TabStop = false; // // tableLayoutPanel3 // resources.ApplyResources(this.tableLayoutPanel3, "tableLayoutPanel3"); this.tableLayoutPanel3.Controls.Add(this._runServerTarget, 1, 0); this.tableLayoutPanel3.Controls.Add(this._runServerArguments, 1, 1); this.tableLayoutPanel3.Controls.Add(this._runServerEnvironment, 1, 2); this.tableLayoutPanel3.Controls.Add(this._runServerEnvironmentLabel, 0, 2); this.tableLayoutPanel3.Controls.Add(this._runServerArgumentsLabel, 0, 1); this.tableLayoutPanel3.Controls.Add(this._runServerTargetLabel, 0, 0); this.tableLayoutPanel3.Controls.Add(this._runServerTargetType, 2, 0); this.tableLayoutPanel3.Name = "tableLayoutPanel3"; // // PythonWebLauncherOptions // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.tableLayoutPanel1); this.Name = "PythonWebLauncherOptions"; this._debugGroup.ResumeLayout(false); this._debugGroup.PerformLayout(); this.tableLayoutPanel2.ResumeLayout(false); this.tableLayoutPanel2.PerformLayout(); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); this._debugServerGroup.ResumeLayout(false); this._debugServerGroup.PerformLayout(); this.tableLayoutPanel4.ResumeLayout(false); this.tableLayoutPanel4.PerformLayout(); this._runServerGroup.ResumeLayout(false); this._runServerGroup.PerformLayout(); this.tableLayoutPanel3.ResumeLayout(false); this.tableLayoutPanel3.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.GroupBox _debugGroup; private System.Windows.Forms.TextBox _interpreterPath; private System.Windows.Forms.Label _interpreterPathLabel; private System.Windows.Forms.Label _interpArgsLabel; private System.Windows.Forms.TextBox _interpArgs; private System.Windows.Forms.TextBox _arguments; private System.Windows.Forms.Label _argumentsLabel; private System.Windows.Forms.TextBox _searchPaths; private System.Windows.Forms.Label _searchPathLabel; private System.Windows.Forms.ToolTip _toolTip; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.Label _portNumberLabel; private System.Windows.Forms.TextBox _portNumber; private System.Windows.Forms.TextBox _launchUrl; private System.Windows.Forms.Label _launchUrlLabel; private System.Windows.Forms.GroupBox _debugServerGroup; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel4; private System.Windows.Forms.TextBox _debugServerTarget; private System.Windows.Forms.TextBox _debugServerArguments; private System.Windows.Forms.TextBox _debugServerEnvironment; private System.Windows.Forms.Label _debugServerEnvironmentLabel; private System.Windows.Forms.Label _debugServerArgumentsLabel; private System.Windows.Forms.Label _debugServerTargetLabel; private System.Windows.Forms.ComboBox _debugServerTargetType; private System.Windows.Forms.GroupBox _runServerGroup; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel3; private System.Windows.Forms.TextBox _runServerTarget; private System.Windows.Forms.TextBox _runServerArguments; private System.Windows.Forms.TextBox _runServerEnvironment; private System.Windows.Forms.Label _runServerEnvironmentLabel; private System.Windows.Forms.Label _runServerArgumentsLabel; private System.Windows.Forms.Label _runServerTargetLabel; private System.Windows.Forms.ComboBox _runServerTargetType; private System.Windows.Forms.TextBox _environment; private System.Windows.Forms.Label _environmentLabel; } }
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; #if WCF_SUPPORTED using System.ServiceModel; using System.ServiceModel.Channels; #endif using System.Threading; #if SILVERLIGHT using System.Windows; using System.Windows.Threading; #endif using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Layouts; using NLog.LogReceiverService; /// <summary> /// Sends log messages to a NLog Receiver Service (using WCF or Web Services). /// </summary> /// <seealso href="http://nlog-project.org/wiki/LogReceiverService_target">Documentation on NLog Wiki</seealso> [Target("LogReceiverService")] public class LogReceiverWebServiceTarget : Target { private LogEventInfoBuffer buffer = new LogEventInfoBuffer(10000, false, 10000); private bool inCall; /// <summary> /// Initializes a new instance of the <see cref="LogReceiverWebServiceTarget"/> class. /// </summary> public LogReceiverWebServiceTarget() { this.Parameters = new List<MethodCallParameter>(); } /// <summary> /// Gets or sets the endpoint address. /// </summary> /// <value>The endpoint address.</value> /// <docgen category='Connection Options' order='10' /> [RequiredParameter] public virtual string EndpointAddress { get; set; } #if WCF_SUPPORTED /// <summary> /// Gets or sets the name of the endpoint configuration in WCF configuration file. /// </summary> /// <value>The name of the endpoint configuration.</value> /// <docgen category='Connection Options' order='10' /> public string EndpointConfigurationName { get; set; } /// <summary> /// Gets or sets a value indicating whether to use binary message encoding. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool UseBinaryEncoding { get; set; } #endif /// <summary> /// Gets or sets the client ID. /// </summary> /// <value>The client ID.</value> /// <docgen category='Payload Options' order='10' /> public Layout ClientId { get; set; } /// <summary> /// Gets the list of parameters. /// </summary> /// <value>The parameters.</value> /// <docgen category='Payload Options' order='10' /> [ArrayParameter(typeof(MethodCallParameter), "parameter")] public IList<MethodCallParameter> Parameters { get; private set; } /// <summary> /// Gets or sets a value indicating whether to include per-event properties in the payload sent to the server. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeEventProperties { get; set; } /// <summary> /// Called when log events are being sent (test hook). /// </summary> /// <param name="events">The events.</param> /// <param name="asyncContinuations">The async continuations.</param> /// <returns>True if events should be sent, false to stop processing them.</returns> protected internal virtual bool OnSend(NLogEvents events, IEnumerable<AsyncLogEventInfo> asyncContinuations) { return true; } /// <summary> /// Writes logging event to the log target. Must be overridden in inheriting /// classes. /// </summary> /// <param name="logEvent">Logging event to be written out.</param> protected override void Write(AsyncLogEventInfo logEvent) { this.Write(new[] { logEvent }); } /// <summary> /// Writes an array of logging events to the log target. By default it iterates on all /// events and passes them to "Append" method. Inheriting classes can use this method to /// optimize batch writes. /// </summary> /// <param name="logEvents">Logging events to be written out.</param> protected override void Write(AsyncLogEventInfo[] logEvents) { // if web service call is being processed, buffer new events and return // lock is being held here if (this.inCall) { foreach (var ev in logEvents) { this.buffer.Append(ev); } return; } var networkLogEvents = this.TranslateLogEvents(logEvents); this.Send(networkLogEvents, logEvents); } private static int GetStringOrdinal(NLogEvents context, Dictionary<string, int> stringTable, string value) { int stringIndex; if (!stringTable.TryGetValue(value, out stringIndex)) { stringIndex = context.Strings.Count; stringTable.Add(value, stringIndex); context.Strings.Add(value); } return stringIndex; } private NLogEvents TranslateLogEvents(AsyncLogEventInfo[] logEvents) { if (logEvents.Length == 0 && !LogManager.ThrowExceptions) { InternalLogger.Error("LogEvents array is empty, sending empty event..."); return new NLogEvents(); } string clientID = string.Empty; if (this.ClientId != null) { clientID = this.ClientId.Render(logEvents[0].LogEvent); } var networkLogEvents = new NLogEvents { ClientName = clientID, LayoutNames = new StringCollection(), Strings = new StringCollection(), BaseTimeUtc = logEvents[0].LogEvent.TimeStamp.ToUniversalTime().Ticks }; var stringTable = new Dictionary<string, int>(); for (int i = 0; i < this.Parameters.Count; ++i) { networkLogEvents.LayoutNames.Add(this.Parameters[i].Name); } if (this.IncludeEventProperties) { for (int i = 0; i < logEvents.Length; ++i) { var ev = logEvents[i].LogEvent; // add all event-level property names in 'LayoutNames' collection. foreach (var prop in ev.Properties) { string propName = prop.Key as string; if (propName != null) { if (!networkLogEvents.LayoutNames.Contains(propName)) { networkLogEvents.LayoutNames.Add(propName); } } } } } networkLogEvents.Events = new NLogEvent[logEvents.Length]; for (int i = 0; i < logEvents.Length; ++i) { networkLogEvents.Events[i] = this.TranslateEvent(logEvents[i].LogEvent, networkLogEvents, stringTable); } return networkLogEvents; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Client is disposed asynchronously.")] private void Send(NLogEvents events, IEnumerable<AsyncLogEventInfo> asyncContinuations) { if (!this.OnSend(events, asyncContinuations)) { return; } #if WCF_SUPPORTED var client = CreateWcfLogReceiverClient(); client.ProcessLogMessagesCompleted += (sender, e) => { // report error to the callers foreach (var ev in asyncContinuations) { ev.Continuation(e.Error); } // send any buffered events this.SendBufferedEvents(); }; this.inCall = true; #if SILVERLIGHT if (!Deployment.Current.Dispatcher.CheckAccess()) { Deployment.Current.Dispatcher.BeginInvoke(() => client.ProcessLogMessagesAsync(events)); } else { client.ProcessLogMessagesAsync(events); } #else client.ProcessLogMessagesAsync(events); #endif #else var client = new SoapLogReceiverClient(this.EndpointAddress); this.inCall = true; client.BeginProcessLogMessages( events, result => { Exception exception = null; try { client.EndProcessLogMessages(result); } catch (Exception ex) { if (ex.MustBeRethrown()) { throw; } exception = ex; } // report error to the callers foreach (var ev in asyncContinuations) { ev.Continuation(exception); } // send any buffered events this.SendBufferedEvents(); }, null); #endif } #if WCF_SUPPORTED /// <summary> /// Creating a new instance of WcfLogReceiverClient /// /// Inheritors can override this method and provide their own /// service configuration - binding and endpoint address /// </summary> /// <returns></returns> protected virtual WcfLogReceiverClient CreateWcfLogReceiverClient() { WcfLogReceiverClient client; if (string.IsNullOrEmpty(this.EndpointConfigurationName)) { // endpoint not specified - use BasicHttpBinding Binding binding; if (this.UseBinaryEncoding) { binding = new CustomBinding(new BinaryMessageEncodingBindingElement(), new HttpTransportBindingElement()); } else { binding = new BasicHttpBinding(); } client = new WcfLogReceiverClient(binding, new EndpointAddress(this.EndpointAddress)); } else { client = new WcfLogReceiverClient(this.EndpointConfigurationName, new EndpointAddress(this.EndpointAddress)); } client.ProcessLogMessagesCompleted += ClientOnProcessLogMessagesCompleted; return client; } private void ClientOnProcessLogMessagesCompleted(object sender, AsyncCompletedEventArgs asyncCompletedEventArgs) { var client = sender as WcfLogReceiverClient; if (client != null && client.State == CommunicationState.Opened) { client.Close(); } } #endif private void SendBufferedEvents() { lock (this.SyncRoot) { // clear inCall flag AsyncLogEventInfo[] bufferedEvents = this.buffer.GetEventsAndClear(); if (bufferedEvents.Length > 0) { var networkLogEvents = this.TranslateLogEvents(bufferedEvents); this.Send(networkLogEvents, bufferedEvents); } else { // nothing in the buffer, clear in-call flag this.inCall = false; } } } private NLogEvent TranslateEvent(LogEventInfo eventInfo, NLogEvents context, Dictionary<string, int> stringTable) { var nlogEvent = new NLogEvent(); nlogEvent.Id = eventInfo.SequenceID; nlogEvent.MessageOrdinal = GetStringOrdinal(context, stringTable, eventInfo.FormattedMessage); nlogEvent.LevelOrdinal = eventInfo.Level.Ordinal; nlogEvent.LoggerOrdinal = GetStringOrdinal(context, stringTable, eventInfo.LoggerName); nlogEvent.TimeDelta = eventInfo.TimeStamp.ToUniversalTime().Ticks - context.BaseTimeUtc; for (int i = 0; i < this.Parameters.Count; ++i) { var param = this.Parameters[i]; var value = param.Layout.Render(eventInfo); int stringIndex = GetStringOrdinal(context, stringTable, value); nlogEvent.ValueIndexes.Add(stringIndex); } // layout names beyond Parameters.Count are per-event property names. for (int i = this.Parameters.Count; i < context.LayoutNames.Count; ++i) { string value; object propertyValue; if (eventInfo.Properties.TryGetValue(context.LayoutNames[i], out propertyValue)) { value = Convert.ToString(propertyValue, CultureInfo.InvariantCulture); } else { value = string.Empty; } int stringIndex = GetStringOrdinal(context, stringTable, value); nlogEvent.ValueIndexes.Add(stringIndex); } return nlogEvent; } } }
/* * 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 log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System; using System.Collections; using System.Collections.Generic; using System.Reflection; namespace OpenSim.Region.CoreModules.Scripting.LSLHttp { /// <summary> /// Data describing an external URL set up by a script. /// </summary> public class UrlData { /// <summary> /// Scene object part hosting the script /// </summary> public UUID hostID; /// <summary> /// The item ID of the script that requested the URL. /// </summary> public UUID itemID; /// <summary> /// The script engine that runs the script. /// </summary> public IScriptModule engine; /// <summary> /// The generated URL. /// </summary> public string url; /// <summary> /// The random UUID component of the generated URL. /// </summary> public UUID urlcode; /// <summary> /// The external requests currently being processed or awaiting retrieval for this URL. /// </summary> public Dictionary<UUID, RequestData> requests; } public class RequestData { public UUID requestID; public Dictionary<string, string> headers; public string body; public int responseCode; public string responseBody; public string responseType = "text/plain"; //public ManualResetEvent ev; public bool requestDone; public int startTime; public string uri; } /// <summary> /// This module provides external URLs for in-world scripts. /// </summary> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "UrlModule")] public class UrlModule : ISharedRegionModule, IUrlModule { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Indexs the URL request metadata (which script requested it, outstanding requests, etc.) by the request ID /// randomly generated when a request is received for this URL. /// </summary> /// <remarks> /// Manipulation or retrieval from this dictionary must be locked on m_UrlMap to preserve consistency with /// m_UrlMap /// </remarks> private Dictionary<UUID, UrlData> m_RequestMap = new Dictionary<UUID, UrlData>(); /// <summary> /// Indexs the URL request metadata (which script requested it, outstanding requests, etc.) by the full URL /// </summary> private Dictionary<string, UrlData> m_UrlMap = new Dictionary<string, UrlData>(); private uint m_HttpsPort = 0; private IHttpServer m_HttpServer = null; private IHttpServer m_HttpsServer = null; public string ExternalHostNameForLSL { get; private set; } /// <summary> /// The default maximum number of urls /// </summary> public const int DefaultTotalUrls = 100; /// <summary> /// Maximum number of external urls that can be set up by this module. /// </summary> public int TotalUrls { get; set; } public Type ReplaceableInterface { get { return null; } } public string Name { get { return "UrlModule"; } } public void Initialise(IConfigSource config) { IConfig networkConfig = config.Configs["Network"]; if (networkConfig != null) { ExternalHostNameForLSL = config.Configs["Network"].GetString("ExternalHostNameForLSL", null); bool ssl_enabled = config.Configs["Network"].GetBoolean("https_listener", false); if (ssl_enabled) m_HttpsPort = (uint)config.Configs["Network"].GetInt("https_port", (int)m_HttpsPort); } if (ExternalHostNameForLSL == null) ExternalHostNameForLSL = System.Environment.MachineName; IConfig llFunctionsConfig = config.Configs["LL-Functions"]; if (llFunctionsConfig != null) TotalUrls = llFunctionsConfig.GetInt("max_external_urls_per_simulator", DefaultTotalUrls); else TotalUrls = DefaultTotalUrls; } public void PostInitialise() { } public void AddRegion(Scene scene) { if (m_HttpServer == null) { // There can only be one // m_HttpServer = MainServer.Instance; // // We can use the https if it is enabled if (m_HttpsPort > 0) { m_HttpsServer = MainServer.GetHttpServer(m_HttpsPort); } } scene.RegisterModuleInterface<IUrlModule>(this); scene.EventManager.OnScriptReset += OnScriptReset; } public void RegionLoaded(Scene scene) { IScriptModule[] scriptModules = scene.RequestModuleInterfaces<IScriptModule>(); foreach (IScriptModule scriptModule in scriptModules) { scriptModule.OnScriptRemoved += ScriptRemoved; scriptModule.OnObjectRemoved += ObjectRemoved; } } public void RemoveRegion(Scene scene) { } public void Close() { } public UUID RequestURL(IScriptModule engine, SceneObjectPart host, UUID itemID) { UUID urlcode = UUID.Random(); lock (m_UrlMap) { if (m_UrlMap.Count >= TotalUrls) { engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", "" }); return urlcode; } string url = "http://" + ExternalHostNameForLSL + ":" + m_HttpServer.Port.ToString() + "/lslhttp/" + urlcode.ToString() + "/"; UrlData urlData = new UrlData(); urlData.hostID = host.UUID; urlData.itemID = itemID; urlData.engine = engine; urlData.url = url; urlData.urlcode = urlcode; urlData.requests = new Dictionary<UUID, RequestData>(); m_UrlMap[url] = urlData; string uri = "/lslhttp/" + urlcode.ToString() + "/"; PollServiceEventArgs args = new PollServiceEventArgs(HttpRequestHandler, uri, HasEvents, GetEvents, NoEvents, urlcode, 25000); args.Type = PollServiceEventArgs.EventType.LslHttp; m_HttpServer.AddPollServiceHTTPHandler(uri, args); m_log.DebugFormat( "[URL MODULE]: Set up incoming request url {0} for {1} in {2} {3}", uri, itemID, host.Name, host.LocalId); engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_GRANTED", url }); } return urlcode; } public UUID RequestSecureURL(IScriptModule engine, SceneObjectPart host, UUID itemID) { UUID urlcode = UUID.Random(); if (m_HttpsServer == null) { engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", "" }); return urlcode; } lock (m_UrlMap) { if (m_UrlMap.Count >= TotalUrls) { engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_DENIED", "" }); return urlcode; } string url = "https://" + ExternalHostNameForLSL + ":" + m_HttpsServer.Port.ToString() + "/lslhttps/" + urlcode.ToString() + "/"; UrlData urlData = new UrlData(); urlData.hostID = host.UUID; urlData.itemID = itemID; urlData.engine = engine; urlData.url = url; urlData.urlcode = urlcode; urlData.requests = new Dictionary<UUID, RequestData>(); m_UrlMap[url] = urlData; string uri = "/lslhttps/" + urlcode.ToString() + "/"; PollServiceEventArgs args = new PollServiceEventArgs(HttpRequestHandler, uri, HasEvents, GetEvents, NoEvents, urlcode, 25000); args.Type = PollServiceEventArgs.EventType.LslHttp; m_HttpsServer.AddPollServiceHTTPHandler(uri, args); m_log.DebugFormat( "[URL MODULE]: Set up incoming secure request url {0} for {1} in {2} {3}", uri, itemID, host.Name, host.LocalId); engine.PostScriptEvent(itemID, "http_request", new Object[] { urlcode.ToString(), "URL_REQUEST_GRANTED", url }); } return urlcode; } public void ReleaseURL(string url) { lock (m_UrlMap) { UrlData data; if (!m_UrlMap.TryGetValue(url, out data)) { return; } foreach (UUID req in data.requests.Keys) m_RequestMap.Remove(req); m_log.DebugFormat( "[URL MODULE]: Releasing url {0} for {1} in {2}", url, data.itemID, data.hostID); RemoveUrl(data); m_UrlMap.Remove(url); } } public void HttpContentType(UUID request, string type) { lock (m_UrlMap) { if (m_RequestMap.ContainsKey(request)) { UrlData urlData = m_RequestMap[request]; urlData.requests[request].responseType = type; } else { m_log.Info("[HttpRequestHandler] There is no http-in request with id " + request.ToString()); } } } public void HttpResponse(UUID request, int status, string body) { lock (m_UrlMap) { if (m_RequestMap.ContainsKey(request)) { UrlData urlData = m_RequestMap[request]; string responseBody = body; if (urlData.requests[request].responseType.Equals("text/plain")) { string value; if (urlData.requests[request].headers.TryGetValue("user-agent", out value)) { if (value != null && value.IndexOf("MSIE") >= 0) { // wrap the html escaped response if the target client is IE // It ignores "text/plain" if the body is html responseBody = "<html>" + System.Web.HttpUtility.HtmlEncode(body) + "</html>"; } } } urlData.requests[request].responseCode = status; urlData.requests[request].responseBody = responseBody; //urlData.requests[request].ev.Set(); urlData.requests[request].requestDone = true; } else { m_log.Info("[HttpRequestHandler] There is no http-in request with id " + request.ToString()); } } } public string GetHttpHeader(UUID requestId, string header) { lock (m_UrlMap) { if (m_RequestMap.ContainsKey(requestId)) { UrlData urlData = m_RequestMap[requestId]; string value; if (urlData.requests[requestId].headers.TryGetValue(header, out value)) return value; } else { m_log.Warn("[HttpRequestHandler] There was no http-in request with id " + requestId); } } return String.Empty; } public int GetFreeUrls() { lock (m_UrlMap) return TotalUrls - m_UrlMap.Count; } public void ScriptRemoved(UUID itemID) { // m_log.DebugFormat("[URL MODULE]: Removing script {0}", itemID); lock (m_UrlMap) { List<string> removeURLs = new List<string>(); foreach (KeyValuePair<string, UrlData> url in m_UrlMap) { if (url.Value.itemID == itemID) { RemoveUrl(url.Value); removeURLs.Add(url.Key); foreach (UUID req in url.Value.requests.Keys) m_RequestMap.Remove(req); } } foreach (string urlname in removeURLs) m_UrlMap.Remove(urlname); } } public void ObjectRemoved(UUID objectID) { lock (m_UrlMap) { List<string> removeURLs = new List<string>(); foreach (KeyValuePair<string, UrlData> url in m_UrlMap) { if (url.Value.hostID == objectID) { RemoveUrl(url.Value); removeURLs.Add(url.Key); foreach (UUID req in url.Value.requests.Keys) m_RequestMap.Remove(req); } } foreach (string urlname in removeURLs) m_UrlMap.Remove(urlname); } } private void RemoveUrl(UrlData data) { m_HttpServer.RemoveHTTPHandler("", "/lslhttp/" + data.urlcode.ToString() + "/"); } private Hashtable NoEvents(UUID requestID, UUID sessionID) { Hashtable response = new Hashtable(); UrlData urlData; lock (m_UrlMap) { // We need to return a 404 here in case the request URL was removed at exactly the same time that a // request was made. In this case, the request thread can outrace llRemoveURL() and still be polling // for the request ID. if (!m_RequestMap.ContainsKey(requestID)) { response["int_response_code"] = 404; response["str_response_string"] = ""; response["keepalive"] = false; response["reusecontext"] = false; return response; } urlData = m_RequestMap[requestID]; if (System.Environment.TickCount - urlData.requests[requestID].startTime > 25000) { response["int_response_code"] = 500; response["str_response_string"] = "Script timeout"; response["content_type"] = "text/plain"; response["keepalive"] = false; response["reusecontext"] = false; //remove from map urlData.requests.Remove(requestID); m_RequestMap.Remove(requestID); return response; } } return response; } private bool HasEvents(UUID requestID, UUID sessionID) { lock (m_UrlMap) { // We return true here because an external URL request that happened at the same time as an llRemoveURL() // can still make it through to HttpRequestHandler(). That will return without setting up a request // when it detects that the URL has been removed. The poller, however, will continue to ask for // events for that request, so here we will signal that there are events and in GetEvents we will // return a 404. if (!m_RequestMap.ContainsKey(requestID)) { return true; } UrlData urlData = m_RequestMap[requestID]; if (!urlData.requests.ContainsKey(requestID)) { return true; } // Trigger return of timeout response. if (System.Environment.TickCount - urlData.requests[requestID].startTime > 25000) { return true; } return urlData.requests[requestID].requestDone; } } private Hashtable GetEvents(UUID requestID, UUID sessionID) { Hashtable response; lock (m_UrlMap) { UrlData url = null; RequestData requestData = null; if (!m_RequestMap.ContainsKey(requestID)) return NoEvents(requestID, sessionID); url = m_RequestMap[requestID]; requestData = url.requests[requestID]; if (!requestData.requestDone) return NoEvents(requestID, sessionID); response = new Hashtable(); if (System.Environment.TickCount - requestData.startTime > 25000) { response["int_response_code"] = 500; response["str_response_string"] = "Script timeout"; response["content_type"] = "text/plain"; response["keepalive"] = false; response["reusecontext"] = false; return response; } //put response response["int_response_code"] = requestData.responseCode; response["str_response_string"] = requestData.responseBody; response["content_type"] = requestData.responseType; // response["content_type"] = "text/plain"; response["keepalive"] = false; response["reusecontext"] = false; //remove from map url.requests.Remove(requestID); m_RequestMap.Remove(requestID); } return response; } public void HttpRequestHandler(UUID requestID, Hashtable request) { string uri = request["uri"].ToString(); bool is_ssl = uri.Contains("lslhttps"); try { Hashtable headers = (Hashtable)request["headers"]; // string uri_full = "http://" + m_ExternalHostNameForLSL + ":" + m_HttpServer.Port.ToString() + uri;// "/lslhttp/" + urlcode.ToString() + "/"; int pos1 = uri.IndexOf("/");// /lslhttp int pos2 = uri.IndexOf("/", pos1 + 1);// /lslhttp/ int pos3 = uri.IndexOf("/", pos2 + 1);// /lslhttp/<UUID>/ string uri_tmp = uri.Substring(0, pos3 + 1); //HTTP server code doesn't provide us with QueryStrings string pathInfo; string queryString; queryString = ""; pathInfo = uri.Substring(pos3); UrlData urlData = null; lock (m_UrlMap) { string url; if (is_ssl) url = "https://" + ExternalHostNameForLSL + ":" + m_HttpsServer.Port.ToString() + uri_tmp; else url = "http://" + ExternalHostNameForLSL + ":" + m_HttpServer.Port.ToString() + uri_tmp; // Avoid a race - the request URL may have been released via llRequestUrl() whilst this // request was being processed. if (!m_UrlMap.TryGetValue(url, out urlData)) return; //for llGetHttpHeader support we need to store original URI here //to make x-path-info / x-query-string / x-script-url / x-remote-ip headers //as per http://wiki.secondlife.com/wiki/LlGetHTTPHeader RequestData requestData = new RequestData(); requestData.requestID = requestID; requestData.requestDone = false; requestData.startTime = System.Environment.TickCount; requestData.uri = uri; if (requestData.headers == null) requestData.headers = new Dictionary<string, string>(); foreach (DictionaryEntry header in headers) { string key = (string)header.Key; string value = (string)header.Value; requestData.headers.Add(key, value); } foreach (DictionaryEntry de in request) { if (de.Key.ToString() == "querystringkeys") { System.String[] keys = (System.String[])de.Value; foreach (String key in keys) { if (request.ContainsKey(key)) { string val = (String)request[key]; queryString = queryString + key + "=" + val + "&"; } } if (queryString.Length > 1) queryString = queryString.Substring(0, queryString.Length - 1); } } //if this machine is behind DNAT/port forwarding, currently this is being //set to address of port forwarding router requestData.headers["x-remote-ip"] = requestData.headers["remote_addr"]; requestData.headers["x-path-info"] = pathInfo; requestData.headers["x-query-string"] = queryString; requestData.headers["x-script-url"] = urlData.url; urlData.requests.Add(requestID, requestData); m_RequestMap.Add(requestID, urlData); } urlData.engine.PostScriptEvent( urlData.itemID, "http_request", new Object[] { requestID.ToString(), request["http-method"].ToString(), request["body"].ToString() }); } catch (Exception we) { //Hashtable response = new Hashtable(); m_log.Warn("[HttpRequestHandler]: http-in request failed"); m_log.Warn(we.Message); m_log.Warn(we.StackTrace); } } private void OnScriptReset(uint localID, UUID itemID) { ScriptRemoved(itemID); } } }
using System.Linq; using System.Windows; using EV3RC.Hardware; using EV3RC.Services.MotorsConfiguration; using Lego.Ev3.Core; using MotorMode = EV3RC.Hardware.MotorMode; namespace EV3RC.UI.Motors { public class MotorsViewModel : BlockConnectedViewModel { private readonly IMotorsConfiguration _motorsConfiguration; private PortItem[] _ports = new[] { new PortItem { Name = Resources.MotorsView.Motors_NotSelected, Value = null }, new PortItem { Name = Resources.MotorsView.Motors_PortA, Value = OutputPort.A }, new PortItem { Name = Resources.MotorsView.Motors_PortB, Value = OutputPort.B }, new PortItem { Name = Resources.MotorsView.Motors_PortC, Value = OutputPort.C }, new PortItem { Name = Resources.MotorsView.Motors_PortD, Value = OutputPort.D } }; private PowerItem[] _powers = new[] { new PowerItem { Name = "100%", Value = 100 }, new PowerItem { Name = "90%", Value = 90 }, new PowerItem { Name = "80%", Value = 80 }, new PowerItem { Name = "70%", Value = 70 }, new PowerItem { Name = "60%", Value = 60 }, new PowerItem { Name = "50%", Value = 50 }, new PowerItem { Name = "40%", Value = 40 }, new PowerItem { Name = "30%", Value = 30 }, new PowerItem { Name = "20%", Value = 20 }, new PowerItem { Name = "10%", Value = 10} }; private MotorModeItem[] _modes = new[] { new MotorModeItem { Name = Resources.MotorsView.Motors_ModeForward, Value = MotorMode.Forward }, new MotorModeItem { Name = Resources.MotorsView.Motors_ModeForwardBackward, Value = MotorMode.ForwardBackward }, new MotorModeItem { Name = Resources.MotorsView.Motors_ModeToggle, Value = MotorMode.Toggle }, }; private TimeItem[] _times = new[] { new TimeItem { Name = "0:00:00.100", Value = 100 }, new TimeItem { Name = "0:00:00.150", Value = 150 }, new TimeItem { Name = "0:00:00.200", Value = 200 }, new TimeItem { Name = "0:00:00.250", Value = 250 }, new TimeItem { Name = "0:00:00.400", Value = 400 }, new TimeItem { Name = "0:00:00.500", Value = 500 }, new TimeItem { Name = "0:00:00.500", Value = 500 }, new TimeItem { Name = "0:00:00.800", Value = 800 }, new TimeItem { Name = "0:00:00.900", Value = 900 }, new TimeItem { Name = "0:00:01.000", Value = 1000 }, new TimeItem { Name = "0:00:01.500", Value = 1500 }, new TimeItem { Name = "0:00:02.000", Value = 2000 }, new TimeItem { Name = "0:00:03.000", Value = 3000 }, new TimeItem { Name = "0:00:04.000", Value = 4000 }, new TimeItem { Name = "0:00:05.000", Value = 5000 }, new TimeItem { Name = "0:00:06.000", Value = 6000 }, }; private PortItem _leftMotorPort; private bool _leftMotorReverse; private PortItem _rightMotorPort; private bool _rightMotorReverse; private PortItem _additionalMotor1Port; private PortItem _additionalMotor2Port; private bool _isAdditionalMotor1Enabled = false; private MotorModeItem _isAdditionalMotor1Mode; private PowerItem _isAdditionalMotor1Power; private TimeItem _isAdditionalMotor1Time; private TimeItem _isAdditionalMotor1Delay; private Visibility _isAdditionalMotor1DelayVisible; private bool _isAdditionalMotor2Enabled = false; private MotorModeItem _isAdditionalMotor2Mode; private PowerItem _isAdditionalMotor2Power; private TimeItem _isAdditionalMotor2Time; private TimeItem _isAdditionalMotor2Delay; private Visibility _isAdditionalMotor2DelayVisible; private bool _isAdditionalMotor1Reverse = false; private bool _isAdditionalMotor2Reverse = false; private PowerItem _basePower; private PowerItem _decelerationPower; private PowerItem _accelerationPower; public MotorsViewModel(IEV3Controller brick, IMotorsConfiguration motorsConfiguration) : base(brick) { _motorsConfiguration = motorsConfiguration; LoadSettings(); } public PortItem[] Ports { get { return _ports; } set { _ports = value; NotifyOfPropertyChange(() => Ports); } } public PowerItem[] Powers { get { return _powers; } set { _powers = value; NotifyOfPropertyChange(() => Powers); } } public MotorModeItem[] Modes { get { return _modes; } set { _modes = value; NotifyOfPropertyChange(() => Modes); } } public TimeItem[] Times { get { return _times; } set { _times = value; NotifyOfPropertyChange(() => Times); } } public PortItem LeftMotorPort { get { return _leftMotorPort; } set { _leftMotorPort = value; NotifyOfPropertyChange(() => LeftMotorPort); if (value?.Value != null) { if (RightMotorPort == value) RightMotorPort = Ports.First(); if (AdditionalMotor1Port == value) AdditionalMotor1Port = Ports.First(); if (AdditionalMotor2Port == value) AdditionalMotor2Port = Ports.First(); } SaveSettings(); } } public bool LeftMotorReverse { get { return _leftMotorReverse; } set { _leftMotorReverse = value; NotifyOfPropertyChange(() => LeftMotorReverse); SaveSettings(); } } public PortItem RightMotorPort { get { return _rightMotorPort; } set { _rightMotorPort = value; NotifyOfPropertyChange(() => RightMotorPort); if (value?.Value != null) { if (LeftMotorPort == value) LeftMotorPort = Ports.First(); if (AdditionalMotor1Port == value) AdditionalMotor1Port = Ports.First(); if (AdditionalMotor2Port == value) AdditionalMotor2Port = Ports.First(); } SaveSettings(); } } public bool RightMotorReverse { get { return _rightMotorReverse; } set { _rightMotorReverse = value; NotifyOfPropertyChange(() => RightMotorReverse); SaveSettings(); } } public PortItem AdditionalMotor1Port { get { return _additionalMotor1Port; } set { _additionalMotor1Port = value; NotifyOfPropertyChange(() => AdditionalMotor1Port); if (value?.Value != null) { if (LeftMotorPort == value) LeftMotorPort = Ports.First(); if (RightMotorPort == value) RightMotorPort = Ports.First(); if (AdditionalMotor2Port == value) AdditionalMotor2Port = Ports.First(); } SaveSettings(); } } public MotorModeItem AdditionalMotor1Mode { get { return _isAdditionalMotor1Mode; } set { _isAdditionalMotor1Mode = value; NotifyOfPropertyChange(() => AdditionalMotor1Mode); AdditionalMotor1DelayVisible = value.Value == MotorMode.ForwardBackward ? Visibility.Visible : Visibility.Collapsed; SaveSettings(); } } public PowerItem AdditionalMotor1Power { get { return _isAdditionalMotor1Power; } set { _isAdditionalMotor1Power = value; NotifyOfPropertyChange(() => AdditionalMotor1Power); SaveSettings(); } } public TimeItem AdditionalMotor1Time { get { return _isAdditionalMotor1Time; } set { _isAdditionalMotor1Time = value; NotifyOfPropertyChange(() => AdditionalMotor1Time); SaveSettings(); } } public TimeItem AdditionalMotor1Delay { get { return _isAdditionalMotor1Delay; } set { _isAdditionalMotor1Delay = value; NotifyOfPropertyChange(() => AdditionalMotor1Delay); SaveSettings(); } } public Visibility AdditionalMotor1DelayVisible { get { return _isAdditionalMotor1DelayVisible; } set { _isAdditionalMotor1DelayVisible = value; NotifyOfPropertyChange(() => AdditionalMotor1DelayVisible); } } public PortItem AdditionalMotor2Port { get { return _additionalMotor2Port; } set { _additionalMotor2Port = value; NotifyOfPropertyChange(() => AdditionalMotor2Port); if (value?.Value != null) { if (LeftMotorPort == value) LeftMotorPort = Ports.First(); if (RightMotorPort == value) RightMotorPort = Ports.First(); if (AdditionalMotor1Port == value) AdditionalMotor1Port = Ports.First(); } SaveSettings(); } } public MotorModeItem AdditionalMotor2Mode { get { return _isAdditionalMotor2Mode; } set { _isAdditionalMotor2Mode = value; NotifyOfPropertyChange(() => AdditionalMotor2Mode); AdditionalMotor2DelayVisible = value.Value == MotorMode.ForwardBackward ? Visibility.Visible : Visibility.Collapsed; SaveSettings(); } } public PowerItem AdditionalMotor2Power { get { return _isAdditionalMotor2Power; } set { _isAdditionalMotor2Power = value; NotifyOfPropertyChange(() => AdditionalMotor2Power); SaveSettings(); } } public TimeItem AdditionalMotor2Time { get { return _isAdditionalMotor2Time; } set { _isAdditionalMotor2Time = value; NotifyOfPropertyChange(() => AdditionalMotor2Time); SaveSettings(); } } public TimeItem AdditionalMotor2Delay { get { return _isAdditionalMotor2Delay; } set { _isAdditionalMotor2Delay = value; NotifyOfPropertyChange(() => AdditionalMotor2Delay); SaveSettings(); } } public Visibility AdditionalMotor2DelayVisible { get { return _isAdditionalMotor2DelayVisible; } set { _isAdditionalMotor2DelayVisible = value; NotifyOfPropertyChange(() => AdditionalMotor2DelayVisible); } } public PowerItem BasePower { get { return _basePower; } set { _basePower = value; NotifyOfPropertyChange(() => BasePower); SaveSettings(); } } public PowerItem DecelerationPower { get { return _decelerationPower; } set { _decelerationPower = value; NotifyOfPropertyChange(() => DecelerationPower); SaveSettings(); } } public PowerItem AccelerationPower { get { return _accelerationPower; } set { _accelerationPower = value; NotifyOfPropertyChange(() => AccelerationPower); SaveSettings(); } } public bool IsAdditionalMotor1Enabled { get { return _isAdditionalMotor1Enabled; } set { _isAdditionalMotor1Enabled = value; NotifyOfPropertyChange(() => IsAdditionalMotor1Enabled); SaveSettings(); } } public bool IsAdditionalMotor2Enabled { get { return _isAdditionalMotor2Enabled; } set { _isAdditionalMotor2Enabled = value; NotifyOfPropertyChange(() => IsAdditionalMotor2Enabled); SaveSettings(); } } public bool IsAdditionalMotor1Reverse { get { return _isAdditionalMotor1Reverse; } set { _isAdditionalMotor1Reverse = value; NotifyOfPropertyChange(() => _isAdditionalMotor1Reverse); SaveSettings(); } } public bool IsAdditionalMotor2Reverse { get { return _isAdditionalMotor2Reverse; } set { _isAdditionalMotor2Reverse = value; NotifyOfPropertyChange(() => IsAdditionalMotor2Reverse); SaveSettings(); } } private void LoadSettings() { var nullMotor = Ports.FirstOrDefault(p => !p.Value.HasValue); _leftMotorPort = Ports.FirstOrDefault(p => p.Value == _motorsConfiguration.LeftPort) ?? nullMotor; _leftMotorReverse = _motorsConfiguration.LeftPortReverse; _rightMotorPort = Ports.FirstOrDefault(p => p.Value == _motorsConfiguration.RightPort) ?? nullMotor; _rightMotorReverse = _motorsConfiguration.RightPortReverse; _isAdditionalMotor1Enabled = _motorsConfiguration.AdditionalMotor1Enabled; _additionalMotor1Port = Ports.FirstOrDefault(p => p.Value == _motorsConfiguration.AdditionalMotor1Port) ?? nullMotor; _isAdditionalMotor1Mode = Modes.FirstOrDefault(p => p.Value == _motorsConfiguration.AdditionalMotor1Mode) ?? Modes.First(); _isAdditionalMotor1Power = Powers.FirstOrDefault(p => p.Value == _motorsConfiguration.AdditionalMotor1Power); _isAdditionalMotor1Time = Times.FirstOrDefault(p => p.Value == _motorsConfiguration.AdditionalMotor1Time); _isAdditionalMotor1Delay = Times.FirstOrDefault(p => p.Value == _motorsConfiguration.AdditionalMotor1Delay); _isAdditionalMotor1DelayVisible = _isAdditionalMotor1Mode.Value == MotorMode.ForwardBackward ? Visibility.Visible : Visibility.Collapsed; _isAdditionalMotor1Reverse = _motorsConfiguration.AdditionalMotor1Reverse; _isAdditionalMotor2Enabled = _motorsConfiguration.AdditionalMotor2Enabled; _additionalMotor2Port = Ports.FirstOrDefault(p => p.Value == _motorsConfiguration.AdditionalMotor2Port) ?? nullMotor; _isAdditionalMotor2Mode = Modes.FirstOrDefault(p => p.Value == _motorsConfiguration.AdditionalMotor2Mode) ?? Modes.First(); _isAdditionalMotor2Power = Powers.FirstOrDefault(p => p.Value == _motorsConfiguration.AdditionalMotor2Power); _isAdditionalMotor2Time = Times.FirstOrDefault(p => p.Value == _motorsConfiguration.AdditionalMotor2Time); _isAdditionalMotor2Delay = Times.FirstOrDefault(p => p.Value == _motorsConfiguration.AdditionalMotor2Delay); _isAdditionalMotor2DelayVisible = _isAdditionalMotor2Mode.Value == MotorMode.ForwardBackward ? Visibility.Visible : Visibility.Collapsed; _isAdditionalMotor2Reverse = _motorsConfiguration.AdditionalMotor2Reverse; _basePower = Powers.FirstOrDefault(p => p.Value == _motorsConfiguration.BasePower); _accelerationPower = Powers.FirstOrDefault(p => p.Value == _motorsConfiguration.AccelerationPower); _decelerationPower = Powers.FirstOrDefault(p => p.Value == _motorsConfiguration.DecelerationPower); } private void SaveSettings() { _motorsConfiguration.Update(LeftMotorPort?.Value, LeftMotorReverse, RightMotorPort?.Value, RightMotorReverse, IsAdditionalMotor1Enabled, AdditionalMotor1Port?.Value, AdditionalMotor1Mode?.Value, AdditionalMotor1Power?.Value ?? 100, AdditionalMotor1Time?.Value ?? 1000, AdditionalMotor1Delay?.Value ?? 1000, IsAdditionalMotor1Reverse, IsAdditionalMotor2Enabled, AdditionalMotor2Port?.Value, AdditionalMotor2Mode?.Value, AdditionalMotor2Power?.Value ?? 100, AdditionalMotor2Time?.Value ?? 1000, AdditionalMotor2Delay?.Value ?? 1000, IsAdditionalMotor2Reverse, BasePower?.Value ?? 50, AccelerationPower?.Value ?? 100, DecelerationPower?.Value ?? 10); } } }
// 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.Xml; using System.Globalization; using System.Collections.Generic; using System.Xml.Serialization; namespace System.Runtime.Serialization { #if USE_REFEMIT || uapaot public class XmlReaderDelegator #else internal class XmlReaderDelegator #endif { protected XmlReader reader; protected XmlDictionaryReader dictionaryReader; protected bool isEndOfEmptyElement = false; public XmlReaderDelegator(XmlReader reader) { XmlObjectSerializer.CheckNull(reader, nameof(reader)); this.reader = reader; this.dictionaryReader = reader as XmlDictionaryReader; } internal XmlReader UnderlyingReader { get { return reader; } } internal ExtensionDataReader UnderlyingExtensionDataReader { get { return reader as ExtensionDataReader; } } internal int AttributeCount { get { return isEndOfEmptyElement ? 0 : reader.AttributeCount; } } internal string GetAttribute(string name) { return isEndOfEmptyElement ? null : reader.GetAttribute(name); } internal string GetAttribute(string name, string namespaceUri) { return isEndOfEmptyElement ? null : reader.GetAttribute(name, namespaceUri); } internal string GetAttribute(int i) { if (isEndOfEmptyElement) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(i), SR.Format(SR.XmlElementAttributes))); return reader.GetAttribute(i); } internal bool IsEmptyElement { get { return false; } } internal bool IsNamespaceURI(string ns) { if (dictionaryReader == null) return ns == reader.NamespaceURI; else return dictionaryReader.IsNamespaceUri(ns); } internal bool IsLocalName(string localName) { if (dictionaryReader == null) return localName == reader.LocalName; else return dictionaryReader.IsLocalName(localName); } internal bool IsNamespaceUri(XmlDictionaryString ns) { if (dictionaryReader == null) return ns.Value == reader.NamespaceURI; else return dictionaryReader.IsNamespaceUri(ns); } internal bool IsLocalName(XmlDictionaryString localName) { if (dictionaryReader == null) return localName.Value == reader.LocalName; else return dictionaryReader.IsLocalName(localName); } internal int IndexOfLocalName(XmlDictionaryString[] localNames, XmlDictionaryString ns) { if (dictionaryReader != null) return dictionaryReader.IndexOfLocalName(localNames, ns); if (reader.NamespaceURI == ns.Value) { string localName = this.LocalName; for (int i = 0; i < localNames.Length; i++) { if (localName == localNames[i].Value) { return i; } } } return -1; } #if USE_REFEMIT public bool IsStartElement() #else internal bool IsStartElement() #endif { return !isEndOfEmptyElement && reader.IsStartElement(); } internal bool IsStartElement(string localname, string ns) { return !isEndOfEmptyElement && reader.IsStartElement(localname, ns); } #if USE_REFEMIT public bool IsStartElement(XmlDictionaryString localname, XmlDictionaryString ns) #else internal bool IsStartElement(XmlDictionaryString localname, XmlDictionaryString ns) #endif { if (dictionaryReader == null) return !isEndOfEmptyElement && reader.IsStartElement(localname.Value, ns.Value); else return !isEndOfEmptyElement && dictionaryReader.IsStartElement(localname, ns); } internal bool MoveToAttribute(string name) { return isEndOfEmptyElement ? false : reader.MoveToAttribute(name); } internal bool MoveToAttribute(string name, string ns) { return isEndOfEmptyElement ? false : reader.MoveToAttribute(name, ns); } internal void MoveToAttribute(int i) { if (isEndOfEmptyElement) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(i), SR.Format(SR.XmlElementAttributes))); reader.MoveToAttribute(i); } internal bool MoveToElement() { return isEndOfEmptyElement ? false : reader.MoveToElement(); } internal bool MoveToFirstAttribute() { return isEndOfEmptyElement ? false : reader.MoveToFirstAttribute(); } internal bool MoveToNextAttribute() { return isEndOfEmptyElement ? false : reader.MoveToNextAttribute(); } #if USE_REFEMIT public XmlNodeType NodeType #else internal XmlNodeType NodeType #endif { get { return isEndOfEmptyElement ? XmlNodeType.EndElement : reader.NodeType; } } internal bool Read() { //reader.MoveToFirstAttribute(); //if (NodeType == XmlNodeType.Attribute) reader.MoveToElement(); if (!reader.IsEmptyElement) return reader.Read(); if (isEndOfEmptyElement) { isEndOfEmptyElement = false; return reader.Read(); } isEndOfEmptyElement = true; return true; } internal XmlNodeType MoveToContent() { if (isEndOfEmptyElement) return XmlNodeType.EndElement; return reader.MoveToContent(); } internal bool ReadAttributeValue() { return isEndOfEmptyElement ? false : reader.ReadAttributeValue(); } #if USE_REFEMIT public void ReadEndElement() #else internal void ReadEndElement() #endif { if (isEndOfEmptyElement) Read(); else reader.ReadEndElement(); } private Exception CreateInvalidPrimitiveTypeException(Type type) { return new InvalidDataContractException(SR.Format( type.IsInterface ? SR.InterfaceTypeCannotBeCreated : SR.InvalidPrimitiveType_Serialization, DataContract.GetClrTypeFullName(type))); } public object ReadElementContentAsAnyType(Type valueType) { Read(); object o = ReadContentAsAnyType(valueType); ReadEndElement(); return o; } internal object ReadContentAsAnyType(Type valueType) { switch (Type.GetTypeCode(valueType)) { case TypeCode.Boolean: return ReadContentAsBoolean(); case TypeCode.Char: return ReadContentAsChar(); case TypeCode.Byte: return ReadContentAsUnsignedByte(); case TypeCode.Int16: return ReadContentAsShort(); case TypeCode.Int32: return ReadContentAsInt(); case TypeCode.Int64: return ReadContentAsLong(); case TypeCode.Single: return ReadContentAsSingle(); case TypeCode.Double: return ReadContentAsDouble(); case TypeCode.Decimal: return ReadContentAsDecimal(); case TypeCode.DateTime: return ReadContentAsDateTime(); case TypeCode.String: return ReadContentAsString(); case TypeCode.SByte: return ReadContentAsSignedByte(); case TypeCode.UInt16: return ReadContentAsUnsignedShort(); case TypeCode.UInt32: return ReadContentAsUnsignedInt(); case TypeCode.UInt64: return ReadContentAsUnsignedLong(); case TypeCode.Empty: case TypeCode.DBNull: case TypeCode.Object: default: if (valueType == Globals.TypeOfByteArray) return ReadContentAsBase64(); else if (valueType == Globals.TypeOfObject) return new object(); else if (valueType == Globals.TypeOfTimeSpan) return ReadContentAsTimeSpan(); else if (valueType == Globals.TypeOfGuid) return ReadContentAsGuid(); else if (valueType == Globals.TypeOfUri) return ReadContentAsUri(); else if (valueType == Globals.TypeOfXmlQualifiedName) return ReadContentAsQName(); break; } throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateInvalidPrimitiveTypeException(valueType)); } internal IDataNode ReadExtensionData(Type valueType) { switch (Type.GetTypeCode(valueType)) { case TypeCode.Boolean: return new DataNode<bool>(ReadContentAsBoolean()); case TypeCode.Char: return new DataNode<char>(ReadContentAsChar()); case TypeCode.Byte: return new DataNode<byte>(ReadContentAsUnsignedByte()); case TypeCode.Int16: return new DataNode<short>(ReadContentAsShort()); case TypeCode.Int32: return new DataNode<int>(ReadContentAsInt()); case TypeCode.Int64: return new DataNode<long>(ReadContentAsLong()); case TypeCode.Single: return new DataNode<float>(ReadContentAsSingle()); case TypeCode.Double: return new DataNode<double>(ReadContentAsDouble()); case TypeCode.Decimal: return new DataNode<decimal>(ReadContentAsDecimal()); case TypeCode.DateTime: return new DataNode<DateTime>(ReadContentAsDateTime()); case TypeCode.String: return new DataNode<string>(ReadContentAsString()); case TypeCode.SByte: return new DataNode<sbyte>(ReadContentAsSignedByte()); case TypeCode.UInt16: return new DataNode<ushort>(ReadContentAsUnsignedShort()); case TypeCode.UInt32: return new DataNode<uint>(ReadContentAsUnsignedInt()); case TypeCode.UInt64: return new DataNode<ulong>(ReadContentAsUnsignedLong()); case TypeCode.Empty: case TypeCode.DBNull: case TypeCode.Object: default: if (valueType == Globals.TypeOfByteArray) return new DataNode<byte[]>(ReadContentAsBase64()); else if (valueType == Globals.TypeOfObject) return new DataNode<object>(new object()); else if (valueType == Globals.TypeOfTimeSpan) return new DataNode<TimeSpan>(ReadContentAsTimeSpan()); else if (valueType == Globals.TypeOfGuid) return new DataNode<Guid>(ReadContentAsGuid()); else if (valueType == Globals.TypeOfUri) return new DataNode<Uri>(ReadContentAsUri()); else if (valueType == Globals.TypeOfXmlQualifiedName) return new DataNode<XmlQualifiedName>(ReadContentAsQName()); break; } throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateInvalidPrimitiveTypeException(valueType)); } private void ThrowConversionException(string value, string type) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(XmlObjectSerializer.TryAddLineInfo(this, SR.Format(SR.XmlInvalidConversion, value, type)))); } private void ThrowNotAtElement() { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.XmlStartElementExpected, "EndElement"))); } #if USE_REFEMIT public virtual char ReadElementContentAsChar() #else internal virtual char ReadElementContentAsChar() #endif { return ToChar(ReadElementContentAsInt()); } internal virtual char ReadContentAsChar() { return ToChar(ReadContentAsInt()); } private char ToChar(int value) { if (value < char.MinValue || value > char.MaxValue) { ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "Char"); } return (char)value; } #if USE_REFEMIT public string ReadElementContentAsString() #else internal string ReadElementContentAsString() #endif { if (isEndOfEmptyElement) ThrowNotAtElement(); return reader.ReadElementContentAsString(); } internal string ReadContentAsString() { return isEndOfEmptyElement ? string.Empty : reader.ReadContentAsString(); } #if USE_REFEMIT public bool ReadElementContentAsBoolean() #else internal bool ReadElementContentAsBoolean() #endif { if (isEndOfEmptyElement) ThrowNotAtElement(); return reader.ReadElementContentAsBoolean(); } internal bool ReadContentAsBoolean() { if (isEndOfEmptyElement) ThrowConversionException(string.Empty, "Boolean"); return reader.ReadContentAsBoolean(); } #if USE_REFEMIT public float ReadElementContentAsFloat() #else internal float ReadElementContentAsFloat() #endif { if (isEndOfEmptyElement) ThrowNotAtElement(); return reader.ReadElementContentAsFloat(); } internal float ReadContentAsSingle() { if (isEndOfEmptyElement) ThrowConversionException(string.Empty, "Float"); return reader.ReadContentAsFloat(); } #if USE_REFEMIT public double ReadElementContentAsDouble() #else internal double ReadElementContentAsDouble() #endif { if (isEndOfEmptyElement) ThrowNotAtElement(); return reader.ReadElementContentAsDouble(); } internal double ReadContentAsDouble() { if (isEndOfEmptyElement) ThrowConversionException(string.Empty, "Double"); return reader.ReadContentAsDouble(); } #if USE_REFEMIT public decimal ReadElementContentAsDecimal() #else internal decimal ReadElementContentAsDecimal() #endif { if (isEndOfEmptyElement) ThrowNotAtElement(); return reader.ReadElementContentAsDecimal(); } internal decimal ReadContentAsDecimal() { if (isEndOfEmptyElement) ThrowConversionException(string.Empty, "Decimal"); return reader.ReadContentAsDecimal(); } #if USE_REFEMIT public virtual byte[] ReadElementContentAsBase64() #else internal virtual byte[] ReadElementContentAsBase64() #endif { if (isEndOfEmptyElement) ThrowNotAtElement(); if (dictionaryReader == null) { return ReadContentAsBase64(reader.ReadElementContentAsString()); } else { return dictionaryReader.ReadElementContentAsBase64(); } } public virtual byte[] ReadContentAsBase64() { if (isEndOfEmptyElement) return Array.Empty<byte>(); if (dictionaryReader == null) { return ReadContentAsBase64(reader.ReadContentAsString()); } else { return dictionaryReader.ReadContentAsBase64(); } } internal byte[] ReadContentAsBase64(string str) { if (str == null) return null; str = str.Trim(); if (str.Length == 0) return Array.Empty<byte>(); try { return Convert.FromBase64String(str); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "byte[]", exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "byte[]", exception)); } } #if USE_REFEMIT public virtual DateTime ReadElementContentAsDateTime() #else internal virtual DateTime ReadElementContentAsDateTime() #endif { if (isEndOfEmptyElement) ThrowNotAtElement(); return XmlConvert.ToDateTime(reader.ReadElementContentAsString(), XmlDateTimeSerializationMode.RoundtripKind); } internal virtual DateTime ReadContentAsDateTime() { if (isEndOfEmptyElement) ThrowConversionException(string.Empty, "DateTime"); return reader.ReadContentAsDateTime(); } #if USE_REFEMIT public int ReadElementContentAsInt() #else internal int ReadElementContentAsInt() #endif { if (isEndOfEmptyElement) ThrowNotAtElement(); return reader.ReadElementContentAsInt(); } internal int ReadContentAsInt() { if (isEndOfEmptyElement) ThrowConversionException(string.Empty, "Int32"); return reader.ReadContentAsInt(); } #if USE_REFEMIT public long ReadElementContentAsLong() #else internal long ReadElementContentAsLong() #endif { if (isEndOfEmptyElement) ThrowNotAtElement(); return reader.ReadElementContentAsLong(); } internal long ReadContentAsLong() { if (isEndOfEmptyElement) ThrowConversionException(string.Empty, "Int64"); return reader.ReadContentAsLong(); } #if USE_REFEMIT public short ReadElementContentAsShort() #else internal short ReadElementContentAsShort() #endif { return ToShort(ReadElementContentAsInt()); } internal short ReadContentAsShort() { return ToShort(ReadContentAsInt()); } private short ToShort(int value) { if (value < short.MinValue || value > short.MaxValue) { ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "Int16"); } return (short)value; } #if USE_REFEMIT public byte ReadElementContentAsUnsignedByte() #else internal byte ReadElementContentAsUnsignedByte() #endif { return ToByte(ReadElementContentAsInt()); } internal byte ReadContentAsUnsignedByte() { return ToByte(ReadContentAsInt()); } private byte ToByte(int value) { if (value < byte.MinValue || value > byte.MaxValue) { ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "Byte"); } return (byte)value; } #if USE_REFEMIT [CLSCompliant(false)] public SByte ReadElementContentAsSignedByte() #else internal sbyte ReadElementContentAsSignedByte() #endif { return ToSByte(ReadElementContentAsInt()); } internal sbyte ReadContentAsSignedByte() { return ToSByte(ReadContentAsInt()); } private sbyte ToSByte(int value) { if (value < sbyte.MinValue || value > sbyte.MaxValue) { ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "SByte"); } return (sbyte)value; } #if USE_REFEMIT [CLSCompliant(false)] public UInt32 ReadElementContentAsUnsignedInt() #else internal uint ReadElementContentAsUnsignedInt() #endif { return ToUInt32(ReadElementContentAsLong()); } internal uint ReadContentAsUnsignedInt() { return ToUInt32(ReadContentAsLong()); } private uint ToUInt32(long value) { if (value < uint.MinValue || value > uint.MaxValue) { ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "UInt32"); } return (uint)value; } #if USE_REFEMIT [CLSCompliant(false)] public virtual UInt64 ReadElementContentAsUnsignedLong() #else internal virtual ulong ReadElementContentAsUnsignedLong() #endif { if (isEndOfEmptyElement) ThrowNotAtElement(); string str = reader.ReadElementContentAsString(); if (str == null || str.Length == 0) ThrowConversionException(string.Empty, "UInt64"); return XmlConverter.ToUInt64(str); } internal virtual ulong ReadContentAsUnsignedLong() { string str = reader.ReadContentAsString(); if (str == null || str.Length == 0) ThrowConversionException(string.Empty, "UInt64"); return XmlConverter.ToUInt64(str); } #if USE_REFEMIT [CLSCompliant(false)] public UInt16 ReadElementContentAsUnsignedShort() #else internal ushort ReadElementContentAsUnsignedShort() #endif { return ToUInt16(ReadElementContentAsInt()); } internal ushort ReadContentAsUnsignedShort() { return ToUInt16(ReadContentAsInt()); } private ushort ToUInt16(int value) { if (value < ushort.MinValue || value > ushort.MaxValue) { ThrowConversionException(value.ToString(NumberFormatInfo.CurrentInfo), "UInt16"); } return (ushort)value; } #if USE_REFEMIT public TimeSpan ReadElementContentAsTimeSpan() #else internal TimeSpan ReadElementContentAsTimeSpan() #endif { if (isEndOfEmptyElement) ThrowNotAtElement(); string str = reader.ReadElementContentAsString(); return XmlConverter.ToTimeSpan(str); } internal TimeSpan ReadContentAsTimeSpan() { string str = reader.ReadContentAsString(); return XmlConverter.ToTimeSpan(str); } #if USE_REFEMIT public Guid ReadElementContentAsGuid() #else internal Guid ReadElementContentAsGuid() #endif { if (isEndOfEmptyElement) ThrowNotAtElement(); string str = reader.ReadElementContentAsString(); try { return new Guid(str); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Guid", exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Guid", exception)); } catch (OverflowException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Guid", exception)); } } internal Guid ReadContentAsGuid() { string str = reader.ReadContentAsString(); try { return Guid.Parse(str); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Guid", exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Guid", exception)); } catch (OverflowException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Guid", exception)); } } #if USE_REFEMIT public Uri ReadElementContentAsUri() #else internal Uri ReadElementContentAsUri() #endif { if (isEndOfEmptyElement) ThrowNotAtElement(); string str = ReadElementContentAsString(); try { return new Uri(str, UriKind.RelativeOrAbsolute); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Uri", exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Uri", exception)); } } internal Uri ReadContentAsUri() { string str = ReadContentAsString(); try { return new Uri(str, UriKind.RelativeOrAbsolute); } catch (ArgumentException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Uri", exception)); } catch (FormatException exception) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateConversionException(str, "Uri", exception)); } } #if USE_REFEMIT public XmlQualifiedName ReadElementContentAsQName() #else internal XmlQualifiedName ReadElementContentAsQName() #endif { Read(); XmlQualifiedName obj = ReadContentAsQName(); ReadEndElement(); return obj; } internal virtual XmlQualifiedName ReadContentAsQName() { return ParseQualifiedName(ReadContentAsString()); } private XmlQualifiedName ParseQualifiedName(string str) { string name, ns, prefix; if (str == null || str.Length == 0) name = ns = string.Empty; else XmlObjectSerializerReadContext.ParseQualifiedName(str, this, out name, out ns, out prefix); return new XmlQualifiedName(name, ns); } private void CheckExpectedArrayLength(XmlObjectSerializerReadContext context, int arrayLength) { context.IncrementItemCount(arrayLength); } protected int GetArrayLengthQuota(XmlObjectSerializerReadContext context) { return Math.Min(context.RemainingItemCount, int.MaxValue); } private void CheckActualArrayLength(int expectedLength, int actualLength, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) { if (expectedLength != actualLength) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayExceededSizeAttribute, expectedLength, itemName.Value, itemNamespace.Value))); } #if USE_REFEMIT public bool TryReadBooleanArray(XmlObjectSerializerReadContext context, #else internal bool TryReadBooleanArray(XmlObjectSerializerReadContext context, #endif XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, out bool[] array) { if (dictionaryReader == null) { array = null; return false; } if (arrayLength != -1) { CheckExpectedArrayLength(context, arrayLength); array = new bool[arrayLength]; int read = 0, offset = 0; while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0) { offset += read; } CheckActualArrayLength(arrayLength, offset, itemName, itemNamespace); } else { array = BooleanArrayHelperWithDictionaryString.Instance.ReadArray( dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context)); context.IncrementItemCount(array.Length); } return true; } #if USE_REFEMIT public virtual bool TryReadDateTimeArray(XmlObjectSerializerReadContext context, #else internal virtual bool TryReadDateTimeArray(XmlObjectSerializerReadContext context, #endif XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, out DateTime[] array) { if (dictionaryReader == null) { array = null; return false; } if (arrayLength != -1) { CheckExpectedArrayLength(context, arrayLength); array = new DateTime[arrayLength]; int read = 0, offset = 0; while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0) { offset += read; } CheckActualArrayLength(arrayLength, offset, itemName, itemNamespace); } else { array = DateTimeArrayHelperWithDictionaryString.Instance.ReadArray( dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context)); context.IncrementItemCount(array.Length); } return true; } #if USE_REFEMIT public bool TryReadDecimalArray(XmlObjectSerializerReadContext context, #else internal bool TryReadDecimalArray(XmlObjectSerializerReadContext context, #endif XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, out decimal[] array) { if (dictionaryReader == null) { array = null; return false; } if (arrayLength != -1) { CheckExpectedArrayLength(context, arrayLength); array = new decimal[arrayLength]; int read = 0, offset = 0; while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0) { offset += read; } CheckActualArrayLength(arrayLength, offset, itemName, itemNamespace); } else { array = DecimalArrayHelperWithDictionaryString.Instance.ReadArray( dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context)); context.IncrementItemCount(array.Length); } return true; } #if USE_REFEMIT public bool TryReadInt32Array(XmlObjectSerializerReadContext context, #else internal bool TryReadInt32Array(XmlObjectSerializerReadContext context, #endif XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, out int[] array) { if (dictionaryReader == null) { array = null; return false; } if (arrayLength != -1) { CheckExpectedArrayLength(context, arrayLength); array = new int[arrayLength]; int read = 0, offset = 0; while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0) { offset += read; } CheckActualArrayLength(arrayLength, offset, itemName, itemNamespace); } else { array = Int32ArrayHelperWithDictionaryString.Instance.ReadArray( dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context)); context.IncrementItemCount(array.Length); } return true; } #if USE_REFEMIT public bool TryReadInt64Array(XmlObjectSerializerReadContext context, #else internal bool TryReadInt64Array(XmlObjectSerializerReadContext context, #endif XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, out long[] array) { if (dictionaryReader == null) { array = null; return false; } if (arrayLength != -1) { CheckExpectedArrayLength(context, arrayLength); array = new long[arrayLength]; int read = 0, offset = 0; while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0) { offset += read; } CheckActualArrayLength(arrayLength, offset, itemName, itemNamespace); } else { array = Int64ArrayHelperWithDictionaryString.Instance.ReadArray( dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context)); context.IncrementItemCount(array.Length); } return true; } #if USE_REFEMIT public bool TryReadSingleArray(XmlObjectSerializerReadContext context, #else internal bool TryReadSingleArray(XmlObjectSerializerReadContext context, #endif XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, out float[] array) { if (dictionaryReader == null) { array = null; return false; } if (arrayLength != -1) { CheckExpectedArrayLength(context, arrayLength); array = new float[arrayLength]; int read = 0, offset = 0; while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0) { offset += read; } CheckActualArrayLength(arrayLength, offset, itemName, itemNamespace); } else { array = SingleArrayHelperWithDictionaryString.Instance.ReadArray( dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context)); context.IncrementItemCount(array.Length); } return true; } #if USE_REFEMIT public bool TryReadDoubleArray(XmlObjectSerializerReadContext context, #else internal bool TryReadDoubleArray(XmlObjectSerializerReadContext context, #endif XmlDictionaryString itemName, XmlDictionaryString itemNamespace, int arrayLength, out double[] array) { if (dictionaryReader == null) { array = null; return false; } if (arrayLength != -1) { CheckExpectedArrayLength(context, arrayLength); array = new double[arrayLength]; int read = 0, offset = 0; while ((read = dictionaryReader.ReadArray(itemName, itemNamespace, array, offset, arrayLength - offset)) > 0) { offset += read; } CheckActualArrayLength(arrayLength, offset, itemName, itemNamespace); } else { array = DoubleArrayHelperWithDictionaryString.Instance.ReadArray( dictionaryReader, itemName, itemNamespace, GetArrayLengthQuota(context)); context.IncrementItemCount(array.Length); } return true; } internal IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope) { return (reader is IXmlNamespaceResolver) ? ((IXmlNamespaceResolver)reader).GetNamespacesInScope(scope) : null; } // IXmlLineInfo members internal bool HasLineInfo() { IXmlLineInfo iXmlLineInfo = reader as IXmlLineInfo; return (iXmlLineInfo == null) ? false : iXmlLineInfo.HasLineInfo(); } internal int LineNumber { get { IXmlLineInfo iXmlLineInfo = reader as IXmlLineInfo; return (iXmlLineInfo == null) ? 0 : iXmlLineInfo.LineNumber; } } internal int LinePosition { get { IXmlLineInfo iXmlLineInfo = reader as IXmlLineInfo; return (iXmlLineInfo == null) ? 0 : iXmlLineInfo.LinePosition; } } // IXmlTextParser members internal bool Normalized { get { XmlTextReader xmlTextReader = reader as XmlTextReader; if (xmlTextReader == null) { IXmlTextParser xmlTextParser = reader as IXmlTextParser; return (xmlTextParser == null) ? false : xmlTextParser.Normalized; } else return xmlTextReader.Normalization; } set { XmlTextReader xmlTextReader = reader as XmlTextReader; if (xmlTextReader == null) { IXmlTextParser xmlTextParser = reader as IXmlTextParser; if (xmlTextParser != null) xmlTextParser.Normalized = value; } else xmlTextReader.Normalization = value; } } internal WhitespaceHandling WhitespaceHandling { get { XmlTextReader xmlTextReader = reader as XmlTextReader; if (xmlTextReader == null) { IXmlTextParser xmlTextParser = reader as IXmlTextParser; return (xmlTextParser == null) ? WhitespaceHandling.None : xmlTextParser.WhitespaceHandling; } else return xmlTextReader.WhitespaceHandling; } set { XmlTextReader xmlTextReader = reader as XmlTextReader; if (xmlTextReader == null) { IXmlTextParser xmlTextParser = reader as IXmlTextParser; if (xmlTextParser != null) xmlTextParser.WhitespaceHandling = value; } else xmlTextReader.WhitespaceHandling = value; } } // delegating properties and methods internal string Name { get { return reader.Name; } } internal string LocalName { get { return reader.LocalName; } } internal string NamespaceURI { get { return reader.NamespaceURI; } } internal string Value { get { return reader.Value; } } internal Type ValueType { get { return reader.ValueType; } } internal int Depth { get { return reader.Depth; } } internal string LookupNamespace(string prefix) { return reader.LookupNamespace(prefix); } internal bool EOF { get { return reader.EOF; } } internal void Skip() { reader.Skip(); isEndOfEmptyElement = false; } } }
#if !IGNORE_VISTA using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Data; using MyMeta; using VistaDB; using VistaDB.DDA; using VistaDB.Provider; namespace MyMeta.Plugins { public class VistaDB4xPlugin : IMyMetaPlugin { #region IMyMetaPlugin Interface private IMyMetaPluginContext context; void IMyMetaPlugin.Initialize(IMyMetaPluginContext context) { this.context = context; } string IMyMetaPlugin.ProviderName { get { return @"VistaDB 3.x"; } } string IMyMetaPlugin.ProviderUniqueKey { get { return @"VISTADB3X"; } } string IMyMetaPlugin.ProviderAuthorInfo { get { return @"VistaDB 3.x MyMeta Plugin Written by Mike Griffin"; } } Uri IMyMetaPlugin.ProviderAuthorUri { get { return new Uri(@"http://www.mygenerationsoftware.com/"); } } bool IMyMetaPlugin.StripTrailingNulls { get { return false; } } bool IMyMetaPlugin.RequiredDatabaseName { get { return false; } } string IMyMetaPlugin.SampleConnectionString { get { return @"Data Source=C:\Program Files\VistaDB 3.0\Data\Northwind.vdb3;OpenMode=NonexclusiveReadOnly"; } } IDbConnection IMyMetaPlugin.NewConnection { get { if (IsIntialized) { //TODO: This is what we need to use: VistaDB.MetaHelper mh = new VistaDB.MetaHelper(); VistaDBConnection cn = new VistaDBConnection(this.context.ConnectionString); return cn as IDbConnection; } else return null; } } string IMyMetaPlugin.DefaultDatabase { get { return this.GetDatabaseName(); } } DataTable IMyMetaPlugin.Databases { get { DataTable metaData = new DataTable(); IVistaDBDatabase db = null; try { metaData = context.CreateDatabasesDataTable(); DataRow row = metaData.NewRow(); metaData.Rows.Add(row); db = DDA.OpenDatabase(this.GetFullDatabaseName(), VistaDBDatabaseOpenMode.NonexclusiveReadOnly, ""); row["CATALOG_NAME"] = GetDatabaseName(); row["DESCRIPTION"] = db.Description; } finally { if(db != null) db.Close(); } return metaData; } } DataTable IMyMetaPlugin.GetTables(string database) { DataTable metaData = new DataTable(); IVistaDBDatabase db = null; try { metaData = context.CreateTablesDataTable(); db = DDA.OpenDatabase(this.GetFullDatabaseName(), VistaDBDatabaseOpenMode.NonexclusiveReadOnly, ""); ArrayList tables = db.EnumTables(); foreach (string table in tables) { IVistaDBTableSchema tblStructure = db.TableSchema(table); DataRow row = metaData.NewRow(); metaData.Rows.Add(row); row["TABLE_NAME"] = tblStructure.Name; row["DESCRIPTION"] = tblStructure.Description; } } finally { if(db != null) db.Close(); } return metaData; } DataTable IMyMetaPlugin.GetViews(string database) { DataTable metaData = new DataTable(); //IVistaDBDatabase db = null; try { metaData = context.CreateViewsDataTable(); using (VistaDBConnection conn = new VistaDBConnection()) { conn.ConnectionString = context.ConnectionString; conn.Open(); using (VistaDBCommand cmd = new VistaDBCommand("SELECT * FROM GetViews()", conn)) { using (VistaDBDataAdapter da = new VistaDBDataAdapter(cmd)) { DataTable views = new DataTable(); da.Fill(views); foreach(DataRow vistaRow in views.Rows) { DataRow row = metaData.NewRow(); metaData.Rows.Add(row); row["TABLE_NAME"] = vistaRow["VIEW_NAME"]; row["DESCRIPTION"] = vistaRow["DESCRIPTION"]; row["VIEW_TEXT"] = vistaRow["VIEW_DEFINITION"]; row["IS_UPDATABLE"] = vistaRow["IS_UPDATABLE"]; } } } } } catch{} return metaData; } DataTable IMyMetaPlugin.GetProcedures(string database) { return new DataTable(); } DataTable IMyMetaPlugin.GetDomains(string database) { return new DataTable(); } DataTable IMyMetaPlugin.GetProcedureParameters(string database, string procedure) { return new DataTable(); } DataTable IMyMetaPlugin.GetProcedureResultColumns(string database, string procedure) { return new DataTable(); } DataTable IMyMetaPlugin.GetViewColumns(string database, string view) { DataTable metaData = new DataTable(); //IVistaDBDatabase db = null; try { metaData = context.CreateColumnsDataTable(); using (VistaDBConnection conn = new VistaDBConnection()) { conn.ConnectionString = context.ConnectionString; conn.Open(); string sql = "SELECT * FROM GetViewColumns('" + view + "')"; using (VistaDBCommand cmd = new VistaDBCommand(sql, conn)) { using (VistaDBDataAdapter da = new VistaDBDataAdapter(cmd)) { DataTable views = new DataTable(); da.Fill(views); foreach(DataRow vistaRow in views.Rows) { DataRow row = metaData.NewRow(); metaData.Rows.Add(row); int width = Convert.ToInt32(vistaRow["COLUMN_SIZE"]); int dec = 0; int length = 0; int octLength = width; bool timestamp = false; string type = vistaRow["DATA_TYPE_NAME"] as string; switch(type) { case "Char": case "NChar": case "NText": case "NVarchar": case "Text": case "Varchar": length = width; width = 0; dec = 0; break; case "Currency": case "Double": case "Decimal": case "Single": break; case "Timestamp": timestamp = true; break; default: width = 0; dec = 0; break; } string def = Convert.ToString(vistaRow["DEFAULT_VALUE"]); row["TABLE_NAME"] = view; row["COLUMN_NAME"] = vistaRow["COLUMN_NAME"]; row["ORDINAL_POSITION"] = vistaRow["COLUMN_ORDINAL"]; row["IS_NULLABLE"] = vistaRow["ALLOW_NULL"]; row["COLUMN_HASDEFAULT"] = def == string.Empty ? false : true; row["COLUMN_DEFAULT"] = def; row["IS_AUTO_KEY"] = vistaRow["IDENTITY_VALUE"]; row["AUTO_KEY_SEED"] = vistaRow["IDENTITY_SEED"]; row["AUTO_KEY_INCREMENT"] = vistaRow["IDENTITY_STEP"]; row["TYPE_NAME"] = type; row["NUMERIC_PRECISION"] = width; row["NUMERIC_SCALE"] = dec; row["CHARACTER_MAXIMUM_LENGTH"] = length; row["CHARACTER_OCTET_LENGTH"] = octLength; row["DESCRIPTION"] = vistaRow["COLUMN_DESCRIPTION"]; if (timestamp) { row["IS_COMPUTED"] = true; } } } } } } catch{} return metaData; } DataTable IMyMetaPlugin.GetTableColumns(string database, string table) { DataTable metaData = new DataTable(); IVistaDBDatabase db = null; try { metaData = context.CreateColumnsDataTable(); db = DDA.OpenDatabase(this.GetFullDatabaseName(), VistaDBDatabaseOpenMode.NonexclusiveReadOnly, ""); ArrayList tables = db.EnumTables(); IVistaDBTableSchema tblStructure = db.TableSchema(table); foreach (IVistaDBColumnAttributes c in tblStructure) { string colName = c.Name; string def = ""; if(tblStructure.Defaults.Contains(colName)) { def = tblStructure.Defaults[colName].Expression; } int width = c.MaxLength; //c.ColumnWidth; int dec = 0; //c.ColumnDecimals; int length = 0; int octLength = width; IVistaDBIdentityInformation identity = null; if(tblStructure.Identities.Contains(colName)) { identity = tblStructure.Identities[colName]; } string[] pks = null; if(tblStructure.Indexes.Contains("PrimaryKey")) { pks = tblStructure.Indexes["PrimaryKey"].KeyExpression.Split(';'); } else { foreach(IVistaDBIndexInformation pk in tblStructure.Indexes) { if(pk.Primary) { pks = pk.KeyExpression.Split(';'); break; } } } System.Collections.Hashtable pkCols = null; if(pks != null) { pkCols = new Hashtable(); foreach(string pkColName in pks) { pkCols[pkColName] = true; } } switch(c.Type) { case VistaDBType.Char: case VistaDBType.NChar: case VistaDBType.NText: case VistaDBType.NVarChar: case VistaDBType.Text: case VistaDBType.VarChar: length = width; width = 0; dec = 0; break; case VistaDBType.Money: case VistaDBType.Float: case VistaDBType.Decimal: case VistaDBType.Real: break; default: width = 0; dec = 0; break; } DataRow row = metaData.NewRow(); metaData.Rows.Add(row); row["TABLE_NAME"] = tblStructure.Name; row["COLUMN_NAME"] = c.Name; row["ORDINAL_POSITION"] = c.RowIndex; row["IS_NULLABLE"] = c.AllowNull; row["COLUMN_HASDEFAULT"] = def == string.Empty ? false : true; row["COLUMN_DEFAULT"] = def; row["IS_AUTO_KEY"] = identity == null ? false : true; row["AUTO_KEY_SEED"] = 1; row["AUTO_KEY_INCREMENT"] = identity == null ? 0 : Convert.ToInt32(identity.StepExpression); row["TYPE_NAME"] = c.Type.ToString(); row["NUMERIC_PRECISION"] = width; row["NUMERIC_SCALE"] = dec; row["CHARACTER_MAXIMUM_LENGTH"] = length; row["CHARACTER_OCTET_LENGTH"] = octLength; row["DESCRIPTION"] = c.Description; if (c.Type == VistaDBType.Timestamp) { row["IS_COMPUTED"] = true; } } } finally { if(db != null) db.Close(); } return metaData; } List<string> IMyMetaPlugin.GetPrimaryKeyColumns(string database, string table) { List<string> primaryKeys = new List<string>(); IVistaDBDatabase db = null; try { db = DDA.OpenDatabase(this.GetFullDatabaseName(), VistaDBDatabaseOpenMode.NonexclusiveReadOnly, ""); IVistaDBTableSchema tblStructure = db.TableSchema(table); string[] pks = null; if(tblStructure.Indexes.Contains("PrimaryKey")) { pks = tblStructure.Indexes["PrimaryKey"].KeyExpression.Split(';'); } else { foreach(IVistaDBIndexInformation pk in tblStructure.Indexes) { if(pk.Primary) { pks = pk.KeyExpression.Split(';'); break; } } } if(pks != null) { foreach(string pkColName in pks) { primaryKeys.Add(pkColName); } } } finally { if(db != null) db.Close(); } return primaryKeys; } List<string> IMyMetaPlugin.GetViewSubViews(string database, string view) { return new List<string>(); } List<string> IMyMetaPlugin.GetViewSubTables(string database, string view) { return new List<string>(); } DataTable IMyMetaPlugin.GetTableIndexes(string database, string table) { DataTable metaData = new DataTable(); IVistaDBDatabase db = null; try { metaData = context.CreateIndexesDataTable(); db = DDA.OpenDatabase(this.GetFullDatabaseName(), VistaDBDatabaseOpenMode.NonexclusiveReadOnly, ""); ArrayList tables = db.EnumTables(); IVistaDBTableSchema tblStructure = db.TableSchema(table); foreach (IVistaDBIndexInformation indexInfo in tblStructure.Indexes) { string[] pks = indexInfo.KeyExpression.Split(';'); int index = 0; foreach(string colName in pks) { DataRow row = metaData.NewRow(); metaData.Rows.Add(row); row["TABLE_CATALOG"] = GetDatabaseName(); row["TABLE_NAME"] = tblStructure.Name; row["INDEX_CATALOG"] = GetDatabaseName(); row["INDEX_NAME"] = indexInfo.Name; row["UNIQUE"] = indexInfo.Unique; row["COLLATION"] = indexInfo.KeyStructure[index++].Descending ? 2 : 1; row["COLUMN_NAME"] = colName; } } } finally { if(db != null) db.Close(); } return metaData; } DataTable IMyMetaPlugin.GetForeignKeys(string database, string tableName) { DataTable metaData = new DataTable(); IVistaDBDatabase db = null; try { metaData = context.CreateForeignKeysDataTable(); db = DDA.OpenDatabase(this.GetFullDatabaseName(), VistaDBDatabaseOpenMode.NonexclusiveReadOnly, ""); ArrayList tables = db.EnumTables(); foreach (string table in tables) { IVistaDBTableSchema tblStructure = db.TableSchema(table); foreach (IVistaDBRelationshipInformation relInfo in tblStructure.ForeignKeys) { if(relInfo.ForeignTable != tableName && relInfo.PrimaryTable != tableName) continue; string fCols = relInfo.ForeignKey; string pCols = String.Empty; string primaryTbl = relInfo.PrimaryTable; string pkName = ""; using (IVistaDBTableSchema pkTableStruct = db.TableSchema(primaryTbl)) { foreach (IVistaDBIndexInformation idxInfo in pkTableStruct.Indexes) { if (!idxInfo.Primary) continue; pkName = idxInfo.Name; pCols = idxInfo.KeyExpression; break; } } string [] fColumns = fCols.Split(';'); string [] pColumns = pCols.Split(';'); for(int i = 0; i < fColumns.GetLength(0); i++) { DataRow row = metaData.NewRow(); metaData.Rows.Add(row); row["PK_TABLE_CATALOG"] = GetDatabaseName(); row["PK_TABLE_SCHEMA"] = DBNull.Value; row["FK_TABLE_CATALOG"] = DBNull.Value; row["FK_TABLE_SCHEMA"] = DBNull.Value; row["FK_TABLE_NAME"] = tblStructure.Name; row["PK_TABLE_NAME"] = relInfo.PrimaryTable; row["ORDINAL"] = 0; row["FK_NAME"] = relInfo.Name; row["PK_NAME"] = pkName; row["PK_COLUMN_NAME"] = pColumns[i]; row["FK_COLUMN_NAME"] = fColumns[i]; row["UPDATE_RULE"] = relInfo.UpdateIntegrity; row["DELETE_RULE"] = relInfo.DeleteIntegrity; } } } } finally { if(db != null) db.Close(); } return metaData; } public object GetDatabaseSpecificMetaData(object myMetaObject, string key) { return null; } #endregion #region Internal Methods private IVistaDBDDA DDA = VistaDBEngine.Connections.OpenDDA(); private bool IsIntialized { get { return (context != null); } } public string GetDatabaseName() { VistaDBConnection cn = new VistaDBConnection(this.context.ConnectionString); string dbName = cn.DataSource; int index = dbName.LastIndexOfAny(new char[]{'\\'}); if (index >= 0) { dbName = dbName.Substring(index + 1); } return dbName; } public string GetFullDatabaseName() { VistaDBConnection cn = new VistaDBConnection(this.context.ConnectionString); return cn.DataSource; } #endregion } } #endif
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ /* * Do not modify this file. This file is generated from the codecommit-2015-04-13.normal.json service model. */ using System; using System.Collections.Generic; using Amazon.CodeCommit.Model; namespace Amazon.CodeCommit { /// <summary> /// Interface for accessing CodeCommit /// /// AWS CodeCommit /// <para> /// This is the <i>AWS CodeCommit API Reference</i>. This reference provides descriptions /// of the AWS CodeCommit API. /// </para> /// /// <para> /// You can use the AWS CodeCommit API to work with the following objects: /// </para> /// <ul> <li>Repositories</li> <li>Branches</li> <li>Commits</li> </ul> /// <para> /// For information about how to use AWS CodeCommit, see the <i>AWS CodeCommit User Guide</i>. /// </para> /// </summary> public partial interface IAmazonCodeCommit : IDisposable { #region BatchGetRepositories /// <summary> /// Gets information about one or more repositories. /// /// <note> /// <para> /// The description field for a repository accepts all HTML characters and all valid Unicode /// characters. Applications that do not HTML-encode the description and display it in /// a web page could expose users to potentially malicious code. Make sure that you HTML-encode /// the description field in any application that uses this API to display the repository /// description on a web page. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the BatchGetRepositories service method.</param> /// /// <returns>The response from the BatchGetRepositories service method, as returned by CodeCommit.</returns> /// <exception cref="Amazon.CodeCommit.Model.EncryptionIntegrityChecksFailedException"> /// An encryption integrity check failed. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyAccessDeniedException"> /// An encryption key could not be accessed. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyDisabledException"> /// The encryption key is disabled. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyNotFoundException"> /// No encryption key was found. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyUnavailableException"> /// The encryption key is not available. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.InvalidRepositoryNameException"> /// At least one specified repository name is not valid. /// /// <note>This exception only occurs when a specified repository name is not valid. Other /// exceptions occur when a required repository parameter is missing, or when a specified /// repository does not exist.</note> /// </exception> /// <exception cref="Amazon.CodeCommit.Model.MaximumRepositoryNamesExceededException"> /// The maximum number of allowed repository names was exceeded. Currently, this number /// is 25. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.RepositoryNamesRequiredException"> /// A repository names object is required but was not specified. /// </exception> BatchGetRepositoriesResponse BatchGetRepositories(BatchGetRepositoriesRequest request); /// <summary> /// Initiates the asynchronous execution of the BatchGetRepositories operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the BatchGetRepositories operation on AmazonCodeCommitClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndBatchGetRepositories /// operation.</returns> IAsyncResult BeginBatchGetRepositories(BatchGetRepositoriesRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the BatchGetRepositories operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginBatchGetRepositories.</param> /// /// <returns>Returns a BatchGetRepositoriesResult from CodeCommit.</returns> BatchGetRepositoriesResponse EndBatchGetRepositories(IAsyncResult asyncResult); #endregion #region CreateBranch /// <summary> /// Creates a new branch in a repository and points the branch to a commit. /// /// <note>Calling the create branch operation does not set a repository's default branch. /// To do this, call the update default branch operation.</note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateBranch service method.</param> /// /// <returns>The response from the CreateBranch service method, as returned by CodeCommit.</returns> /// <exception cref="Amazon.CodeCommit.Model.BranchNameExistsException"> /// The specified branch name already exists. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.BranchNameRequiredException"> /// A branch name is required but was not specified. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.CommitDoesNotExistException"> /// The specified commit does not exist or no commit was specified, and the specified /// repository has no default branch. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.CommitIdRequiredException"> /// A commit ID was not specified. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionIntegrityChecksFailedException"> /// An encryption integrity check failed. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyAccessDeniedException"> /// An encryption key could not be accessed. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyDisabledException"> /// The encryption key is disabled. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyNotFoundException"> /// No encryption key was found. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyUnavailableException"> /// The encryption key is not available. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.InvalidBranchNameException"> /// The specified branch name is not valid. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.InvalidCommitIdException"> /// The specified commit ID is not valid. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.InvalidRepositoryNameException"> /// At least one specified repository name is not valid. /// /// <note>This exception only occurs when a specified repository name is not valid. Other /// exceptions occur when a required repository parameter is missing, or when a specified /// repository does not exist.</note> /// </exception> /// <exception cref="Amazon.CodeCommit.Model.RepositoryDoesNotExistException"> /// The specified repository does not exist. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.RepositoryNameRequiredException"> /// A repository name is required but was not specified. /// </exception> CreateBranchResponse CreateBranch(CreateBranchRequest request); /// <summary> /// Initiates the asynchronous execution of the CreateBranch operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateBranch operation on AmazonCodeCommitClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateBranch /// operation.</returns> IAsyncResult BeginCreateBranch(CreateBranchRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the CreateBranch operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateBranch.</param> /// /// <returns>Returns a CreateBranchResult from CodeCommit.</returns> CreateBranchResponse EndCreateBranch(IAsyncResult asyncResult); #endregion #region CreateRepository /// <summary> /// Creates a new, empty repository. /// </summary> /// <param name="request">Container for the necessary parameters to execute the CreateRepository service method.</param> /// /// <returns>The response from the CreateRepository service method, as returned by CodeCommit.</returns> /// <exception cref="Amazon.CodeCommit.Model.EncryptionIntegrityChecksFailedException"> /// An encryption integrity check failed. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyAccessDeniedException"> /// An encryption key could not be accessed. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyDisabledException"> /// The encryption key is disabled. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyNotFoundException"> /// No encryption key was found. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyUnavailableException"> /// The encryption key is not available. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.InvalidRepositoryDescriptionException"> /// The specified repository description is not valid. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.InvalidRepositoryNameException"> /// At least one specified repository name is not valid. /// /// <note>This exception only occurs when a specified repository name is not valid. Other /// exceptions occur when a required repository parameter is missing, or when a specified /// repository does not exist.</note> /// </exception> /// <exception cref="Amazon.CodeCommit.Model.RepositoryLimitExceededException"> /// A repository resource limit was exceeded. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.RepositoryNameExistsException"> /// The specified repository name already exists. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.RepositoryNameRequiredException"> /// A repository name is required but was not specified. /// </exception> CreateRepositoryResponse CreateRepository(CreateRepositoryRequest request); /// <summary> /// Initiates the asynchronous execution of the CreateRepository operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the CreateRepository operation on AmazonCodeCommitClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndCreateRepository /// operation.</returns> IAsyncResult BeginCreateRepository(CreateRepositoryRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the CreateRepository operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginCreateRepository.</param> /// /// <returns>Returns a CreateRepositoryResult from CodeCommit.</returns> CreateRepositoryResponse EndCreateRepository(IAsyncResult asyncResult); #endregion #region DeleteRepository /// <summary> /// Deletes a repository. If a specified repository was already deleted, a null repository /// ID will be returned. /// /// <important>Deleting a repository also deletes all associated objects and metadata. /// After a repository is deleted, all future push calls to the deleted repository will /// fail.</important> /// </summary> /// <param name="request">Container for the necessary parameters to execute the DeleteRepository service method.</param> /// /// <returns>The response from the DeleteRepository service method, as returned by CodeCommit.</returns> /// <exception cref="Amazon.CodeCommit.Model.EncryptionIntegrityChecksFailedException"> /// An encryption integrity check failed. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyAccessDeniedException"> /// An encryption key could not be accessed. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyDisabledException"> /// The encryption key is disabled. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyNotFoundException"> /// No encryption key was found. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyUnavailableException"> /// The encryption key is not available. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.InvalidRepositoryNameException"> /// At least one specified repository name is not valid. /// /// <note>This exception only occurs when a specified repository name is not valid. Other /// exceptions occur when a required repository parameter is missing, or when a specified /// repository does not exist.</note> /// </exception> /// <exception cref="Amazon.CodeCommit.Model.RepositoryNameRequiredException"> /// A repository name is required but was not specified. /// </exception> DeleteRepositoryResponse DeleteRepository(DeleteRepositoryRequest request); /// <summary> /// Initiates the asynchronous execution of the DeleteRepository operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteRepository operation on AmazonCodeCommitClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndDeleteRepository /// operation.</returns> IAsyncResult BeginDeleteRepository(DeleteRepositoryRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the DeleteRepository operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginDeleteRepository.</param> /// /// <returns>Returns a DeleteRepositoryResult from CodeCommit.</returns> DeleteRepositoryResponse EndDeleteRepository(IAsyncResult asyncResult); #endregion #region GetBranch /// <summary> /// Retrieves information about a repository branch, including its name and the last commit /// ID. /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetBranch service method.</param> /// /// <returns>The response from the GetBranch service method, as returned by CodeCommit.</returns> /// <exception cref="Amazon.CodeCommit.Model.BranchDoesNotExistException"> /// The specified branch does not exist. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.BranchNameRequiredException"> /// A branch name is required but was not specified. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionIntegrityChecksFailedException"> /// An encryption integrity check failed. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyAccessDeniedException"> /// An encryption key could not be accessed. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyDisabledException"> /// The encryption key is disabled. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyNotFoundException"> /// No encryption key was found. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyUnavailableException"> /// The encryption key is not available. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.InvalidBranchNameException"> /// The specified branch name is not valid. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.InvalidRepositoryNameException"> /// At least one specified repository name is not valid. /// /// <note>This exception only occurs when a specified repository name is not valid. Other /// exceptions occur when a required repository parameter is missing, or when a specified /// repository does not exist.</note> /// </exception> /// <exception cref="Amazon.CodeCommit.Model.RepositoryDoesNotExistException"> /// The specified repository does not exist. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.RepositoryNameRequiredException"> /// A repository name is required but was not specified. /// </exception> GetBranchResponse GetBranch(GetBranchRequest request); /// <summary> /// Initiates the asynchronous execution of the GetBranch operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetBranch operation on AmazonCodeCommitClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetBranch /// operation.</returns> IAsyncResult BeginGetBranch(GetBranchRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the GetBranch operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetBranch.</param> /// /// <returns>Returns a GetBranchResult from CodeCommit.</returns> GetBranchResponse EndGetBranch(IAsyncResult asyncResult); #endregion #region GetRepository /// <summary> /// Gets information about a repository. /// /// <note> /// <para> /// The description field for a repository accepts all HTML characters and all valid Unicode /// characters. Applications that do not HTML-encode the description and display it in /// a web page could expose users to potentially malicious code. Make sure that you HTML-encode /// the description field in any application that uses this API to display the repository /// description on a web page. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the GetRepository service method.</param> /// /// <returns>The response from the GetRepository service method, as returned by CodeCommit.</returns> /// <exception cref="Amazon.CodeCommit.Model.EncryptionIntegrityChecksFailedException"> /// An encryption integrity check failed. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyAccessDeniedException"> /// An encryption key could not be accessed. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyDisabledException"> /// The encryption key is disabled. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyNotFoundException"> /// No encryption key was found. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyUnavailableException"> /// The encryption key is not available. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.InvalidRepositoryNameException"> /// At least one specified repository name is not valid. /// /// <note>This exception only occurs when a specified repository name is not valid. Other /// exceptions occur when a required repository parameter is missing, or when a specified /// repository does not exist.</note> /// </exception> /// <exception cref="Amazon.CodeCommit.Model.RepositoryDoesNotExistException"> /// The specified repository does not exist. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.RepositoryNameRequiredException"> /// A repository name is required but was not specified. /// </exception> GetRepositoryResponse GetRepository(GetRepositoryRequest request); /// <summary> /// Initiates the asynchronous execution of the GetRepository operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetRepository operation on AmazonCodeCommitClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndGetRepository /// operation.</returns> IAsyncResult BeginGetRepository(GetRepositoryRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the GetRepository operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginGetRepository.</param> /// /// <returns>Returns a GetRepositoryResult from CodeCommit.</returns> GetRepositoryResponse EndGetRepository(IAsyncResult asyncResult); #endregion #region ListBranches /// <summary> /// Gets information about one or more branches in a repository. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListBranches service method.</param> /// /// <returns>The response from the ListBranches service method, as returned by CodeCommit.</returns> /// <exception cref="Amazon.CodeCommit.Model.EncryptionIntegrityChecksFailedException"> /// An encryption integrity check failed. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyAccessDeniedException"> /// An encryption key could not be accessed. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyDisabledException"> /// The encryption key is disabled. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyNotFoundException"> /// No encryption key was found. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyUnavailableException"> /// The encryption key is not available. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.InvalidContinuationTokenException"> /// The specified continuation token is not valid. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.InvalidRepositoryNameException"> /// At least one specified repository name is not valid. /// /// <note>This exception only occurs when a specified repository name is not valid. Other /// exceptions occur when a required repository parameter is missing, or when a specified /// repository does not exist.</note> /// </exception> /// <exception cref="Amazon.CodeCommit.Model.RepositoryDoesNotExistException"> /// The specified repository does not exist. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.RepositoryNameRequiredException"> /// A repository name is required but was not specified. /// </exception> ListBranchesResponse ListBranches(ListBranchesRequest request); /// <summary> /// Initiates the asynchronous execution of the ListBranches operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListBranches operation on AmazonCodeCommitClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListBranches /// operation.</returns> IAsyncResult BeginListBranches(ListBranchesRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the ListBranches operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListBranches.</param> /// /// <returns>Returns a ListBranchesResult from CodeCommit.</returns> ListBranchesResponse EndListBranches(IAsyncResult asyncResult); #endregion #region ListRepositories /// <summary> /// Gets information about one or more repositories. /// </summary> /// <param name="request">Container for the necessary parameters to execute the ListRepositories service method.</param> /// /// <returns>The response from the ListRepositories service method, as returned by CodeCommit.</returns> /// <exception cref="Amazon.CodeCommit.Model.InvalidContinuationTokenException"> /// The specified continuation token is not valid. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.InvalidOrderException"> /// The specified sort order is not valid. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.InvalidSortByException"> /// The specified sort by value is not valid. /// </exception> ListRepositoriesResponse ListRepositories(ListRepositoriesRequest request); /// <summary> /// Initiates the asynchronous execution of the ListRepositories operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListRepositories operation on AmazonCodeCommitClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndListRepositories /// operation.</returns> IAsyncResult BeginListRepositories(ListRepositoriesRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the ListRepositories operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginListRepositories.</param> /// /// <returns>Returns a ListRepositoriesResult from CodeCommit.</returns> ListRepositoriesResponse EndListRepositories(IAsyncResult asyncResult); #endregion #region UpdateDefaultBranch /// <summary> /// Sets or changes the default branch name for the specified repository. /// /// <note>If you use this operation to change the default branch name to the current /// default branch name, a success message is returned even though the default branch /// did not change.</note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateDefaultBranch service method.</param> /// /// <returns>The response from the UpdateDefaultBranch service method, as returned by CodeCommit.</returns> /// <exception cref="Amazon.CodeCommit.Model.BranchDoesNotExistException"> /// The specified branch does not exist. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.BranchNameRequiredException"> /// A branch name is required but was not specified. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionIntegrityChecksFailedException"> /// An encryption integrity check failed. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyAccessDeniedException"> /// An encryption key could not be accessed. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyDisabledException"> /// The encryption key is disabled. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyNotFoundException"> /// No encryption key was found. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyUnavailableException"> /// The encryption key is not available. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.InvalidBranchNameException"> /// The specified branch name is not valid. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.InvalidRepositoryNameException"> /// At least one specified repository name is not valid. /// /// <note>This exception only occurs when a specified repository name is not valid. Other /// exceptions occur when a required repository parameter is missing, or when a specified /// repository does not exist.</note> /// </exception> /// <exception cref="Amazon.CodeCommit.Model.RepositoryDoesNotExistException"> /// The specified repository does not exist. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.RepositoryNameRequiredException"> /// A repository name is required but was not specified. /// </exception> UpdateDefaultBranchResponse UpdateDefaultBranch(UpdateDefaultBranchRequest request); /// <summary> /// Initiates the asynchronous execution of the UpdateDefaultBranch operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateDefaultBranch operation on AmazonCodeCommitClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUpdateDefaultBranch /// operation.</returns> IAsyncResult BeginUpdateDefaultBranch(UpdateDefaultBranchRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the UpdateDefaultBranch operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateDefaultBranch.</param> /// /// <returns>Returns a UpdateDefaultBranchResult from CodeCommit.</returns> UpdateDefaultBranchResponse EndUpdateDefaultBranch(IAsyncResult asyncResult); #endregion #region UpdateRepositoryDescription /// <summary> /// Sets or changes the comment or description for a repository. /// /// <note> /// <para> /// The description field for a repository accepts all HTML characters and all valid Unicode /// characters. Applications that do not HTML-encode the description and display it in /// a web page could expose users to potentially malicious code. Make sure that you HTML-encode /// the description field in any application that uses this API to display the repository /// description on a web page. /// </para> /// </note> /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateRepositoryDescription service method.</param> /// /// <returns>The response from the UpdateRepositoryDescription service method, as returned by CodeCommit.</returns> /// <exception cref="Amazon.CodeCommit.Model.EncryptionIntegrityChecksFailedException"> /// An encryption integrity check failed. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyAccessDeniedException"> /// An encryption key could not be accessed. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyDisabledException"> /// The encryption key is disabled. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyNotFoundException"> /// No encryption key was found. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.EncryptionKeyUnavailableException"> /// The encryption key is not available. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.InvalidRepositoryDescriptionException"> /// The specified repository description is not valid. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.InvalidRepositoryNameException"> /// At least one specified repository name is not valid. /// /// <note>This exception only occurs when a specified repository name is not valid. Other /// exceptions occur when a required repository parameter is missing, or when a specified /// repository does not exist.</note> /// </exception> /// <exception cref="Amazon.CodeCommit.Model.RepositoryDoesNotExistException"> /// The specified repository does not exist. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.RepositoryNameRequiredException"> /// A repository name is required but was not specified. /// </exception> UpdateRepositoryDescriptionResponse UpdateRepositoryDescription(UpdateRepositoryDescriptionRequest request); /// <summary> /// Initiates the asynchronous execution of the UpdateRepositoryDescription operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateRepositoryDescription operation on AmazonCodeCommitClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUpdateRepositoryDescription /// operation.</returns> IAsyncResult BeginUpdateRepositoryDescription(UpdateRepositoryDescriptionRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the UpdateRepositoryDescription operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateRepositoryDescription.</param> /// /// <returns>Returns a UpdateRepositoryDescriptionResult from CodeCommit.</returns> UpdateRepositoryDescriptionResponse EndUpdateRepositoryDescription(IAsyncResult asyncResult); #endregion #region UpdateRepositoryName /// <summary> /// Renames a repository. /// </summary> /// <param name="request">Container for the necessary parameters to execute the UpdateRepositoryName service method.</param> /// /// <returns>The response from the UpdateRepositoryName service method, as returned by CodeCommit.</returns> /// <exception cref="Amazon.CodeCommit.Model.InvalidRepositoryNameException"> /// At least one specified repository name is not valid. /// /// <note>This exception only occurs when a specified repository name is not valid. Other /// exceptions occur when a required repository parameter is missing, or when a specified /// repository does not exist.</note> /// </exception> /// <exception cref="Amazon.CodeCommit.Model.RepositoryDoesNotExistException"> /// The specified repository does not exist. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.RepositoryNameExistsException"> /// The specified repository name already exists. /// </exception> /// <exception cref="Amazon.CodeCommit.Model.RepositoryNameRequiredException"> /// A repository name is required but was not specified. /// </exception> UpdateRepositoryNameResponse UpdateRepositoryName(UpdateRepositoryNameRequest request); /// <summary> /// Initiates the asynchronous execution of the UpdateRepositoryName operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the UpdateRepositoryName operation on AmazonCodeCommitClient.</param> /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param> /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback /// procedure using the AsyncState property.</param> /// /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndUpdateRepositoryName /// operation.</returns> IAsyncResult BeginUpdateRepositoryName(UpdateRepositoryNameRequest request, AsyncCallback callback, object state); /// <summary> /// Finishes the asynchronous execution of the UpdateRepositoryName operation. /// </summary> /// /// <param name="asyncResult">The IAsyncResult returned by the call to BeginUpdateRepositoryName.</param> /// /// <returns>Returns a UpdateRepositoryNameResult from CodeCommit.</returns> UpdateRepositoryNameResponse EndUpdateRepositoryName(IAsyncResult asyncResult); #endregion } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Input; using osu.Framework.Input.Bindings; using osu.Framework.Input.Events; using osu.Framework.Input.StateChanges.Events; using osu.Framework.Input.States; using osu.Framework.Timing; using osu.Game.Configuration; using osu.Game.Input.Bindings; using osu.Game.Input.Handlers; using osu.Game.Screens.Play; using osuTK.Input; using static osu.Game.Input.Handlers.ReplayInputHandler; using JoystickState = osu.Framework.Input.States.JoystickState; using KeyboardState = osu.Framework.Input.States.KeyboardState; using MouseState = osu.Framework.Input.States.MouseState; namespace osu.Game.Rulesets.UI { public abstract class RulesetInputManager<T> : PassThroughInputManager, ICanAttachKeyCounter, IHasReplayHandler where T : struct { protected override InputState CreateInitialState() { var state = base.CreateInitialState(); return new RulesetInputManagerInputState<T>(state.Mouse, state.Keyboard, state.Joystick); } protected readonly KeyBindingContainer<T> KeyBindingContainer; protected override Container<Drawable> Content => KeyBindingContainer; protected RulesetInputManager(RulesetInfo ruleset, int variant, SimultaneousBindingMode unique) { InternalChild = KeyBindingContainer = CreateKeyBindingContainer(ruleset, variant, unique); } #region Action mapping (for replays) public override void HandleInputStateChange(InputStateChangeEvent inputStateChange) { if (inputStateChange is ReplayStateChangeEvent<T> replayStateChanged) { foreach (var action in replayStateChanged.ReleasedActions) KeyBindingContainer.TriggerReleased(action); foreach (var action in replayStateChanged.PressedActions) KeyBindingContainer.TriggerPressed(action); } else { base.HandleInputStateChange(inputStateChange); } } #endregion #region IHasReplayHandler private ReplayInputHandler replayInputHandler; public ReplayInputHandler ReplayInputHandler { get => replayInputHandler; set { if (replayInputHandler != null) RemoveHandler(replayInputHandler); replayInputHandler = value; UseParentInput = replayInputHandler == null; if (replayInputHandler != null) AddHandler(replayInputHandler); } } #endregion #region Clock control private ManualClock clock; private IFrameBasedClock parentClock; protected override void LoadComplete() { base.LoadComplete(); //our clock will now be our parent's clock, but we want to replace this to allow manual control. parentClock = Clock; ProcessCustomClock = false; Clock = new FramedClock(clock = new ManualClock { CurrentTime = parentClock.CurrentTime, Rate = parentClock.Rate, }); } /// <summary> /// Whether we are running up-to-date with our parent clock. /// If not, we will need to keep processing children until we catch up. /// </summary> private bool requireMoreUpdateLoops; /// <summary> /// Whether we are in a valid state (ie. should we keep processing children frames). /// This should be set to false when the replay is, for instance, waiting for future frames to arrive. /// </summary> private bool validState; protected override bool RequiresChildrenUpdate => base.RequiresChildrenUpdate && validState; private bool isAttached => replayInputHandler != null && !UseParentInput; private const int max_catch_up_updates_per_frame = 50; private const double sixty_frame_time = 1000.0 / 60; public override bool UpdateSubTree() { requireMoreUpdateLoops = true; validState = true; int loops = 0; while (validState && requireMoreUpdateLoops && loops++ < max_catch_up_updates_per_frame) { updateClock(); if (validState) { base.UpdateSubTree(); UpdateSubTreeMasking(this, ScreenSpaceDrawQuad.AABBFloat); } } return true; } private void updateClock() { if (parentClock == null) return; clock.Rate = parentClock.Rate; clock.IsRunning = parentClock.IsRunning; var newProposedTime = parentClock.CurrentTime; try { if (Math.Abs(clock.CurrentTime - newProposedTime) > sixty_frame_time * 1.2f) { newProposedTime = clock.Rate > 0 ? Math.Min(newProposedTime, clock.CurrentTime + sixty_frame_time) : Math.Max(newProposedTime, clock.CurrentTime - sixty_frame_time); } if (!isAttached) { clock.CurrentTime = newProposedTime; } else { double? newTime = replayInputHandler.SetFrameFromTime(newProposedTime); if (newTime == null) { // we shouldn't execute for this time value. probably waiting on more replay data. validState = false; requireMoreUpdateLoops = true; clock.CurrentTime = newProposedTime; return; } clock.CurrentTime = newTime.Value; } requireMoreUpdateLoops = clock.CurrentTime != parentClock.CurrentTime; } finally { // The manual clock time has changed in the above code. The framed clock now needs to be updated // to ensure that the its time is valid for our children before input is processed Clock.ProcessFrame(); } } #endregion #region Setting application (disables etc.) private Bindable<bool> mouseDisabled; [BackgroundDependencyLoader] private void load(OsuConfigManager config) { mouseDisabled = config.GetBindable<bool>(OsuSetting.MouseDisableButtons); } protected override bool Handle(UIEvent e) { switch (e) { case MouseDownEvent mouseDown when mouseDown.Button == MouseButton.Left || mouseDown.Button == MouseButton.Right: if (mouseDisabled.Value) return false; break; case MouseUpEvent mouseUp: if (!CurrentState.Mouse.IsPressed(mouseUp.Button)) return false; break; } return base.Handle(e); } #endregion #region Key Counter Attachment public void Attach(KeyCounterCollection keyCounter) { var receptor = new ActionReceptor(keyCounter); Add(receptor); keyCounter.SetReceptor(receptor); keyCounter.AddRange(KeyBindingContainer.DefaultKeyBindings.Select(b => b.GetAction<T>()).Distinct().Select(b => new KeyCounterAction<T>(b))); } public class ActionReceptor : KeyCounterCollection.Receptor, IKeyBindingHandler<T> { public ActionReceptor(KeyCounterCollection target) : base(target) { } public bool OnPressed(T action) => Target.Children.OfType<KeyCounterAction<T>>().Any(c => c.OnPressed(action)); public bool OnReleased(T action) => Target.Children.OfType<KeyCounterAction<T>>().Any(c => c.OnReleased(action)); } #endregion protected virtual RulesetKeyBindingContainer CreateKeyBindingContainer(RulesetInfo ruleset, int variant, SimultaneousBindingMode unique) => new RulesetKeyBindingContainer(ruleset, variant, unique); public class RulesetKeyBindingContainer : DatabasedKeyBindingContainer<T> { public RulesetKeyBindingContainer(RulesetInfo ruleset, int variant, SimultaneousBindingMode unique) : base(ruleset, variant, unique) { } } } /// <summary> /// Expose the <see cref="ReplayInputHandler"/> in a capable <see cref="InputManager"/>. /// </summary> public interface IHasReplayHandler { ReplayInputHandler ReplayInputHandler { get; set; } } /// <summary> /// Supports attaching a <see cref="KeyCounterCollection"/>. /// Keys will be populated automatically and a receptor will be injected inside. /// </summary> public interface ICanAttachKeyCounter { void Attach(KeyCounterCollection keyCounter); } public class RulesetInputManagerInputState<T> : InputState where T : struct { public ReplayState<T> LastReplayState; public RulesetInputManagerInputState(MouseState mouse = null, KeyboardState keyboard = null, JoystickState joystick = null) : base(mouse, keyboard, joystick) { } } }
// 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; using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.IdentifiersShouldNotContainUnderscoresAnalyzer, Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines.CSharpIdentifiersShouldNotContainUnderscoresFixer>; using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.IdentifiersShouldNotContainUnderscoresAnalyzer, Microsoft.CodeQuality.VisualBasic.Analyzers.ApiDesignGuidelines.BasicIdentifiersShouldNotContainUnderscoresFixer>; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests { public class IdentifiersShouldNotContainUnderscoresTests { #region CSharp Tests [Fact] public async Task CA1707_ForAssembly_CSharp() { await new VerifyCS.Test { TestCode = @" public class DoesNotMatter { } ", SolutionTransforms = { (solution, projectId) => solution.WithProjectAssemblyName(projectId, "AssemblyNameHasUnderScore_") }, ExpectedDiagnostics = { GetCA1707CSharpResultAt(line: 2, column: 1, symbolKind: SymbolKind.Assembly, identifierNames: "AssemblyNameHasUnderScore_") } }.RunAsync(); } [Fact] public async Task CA1707_ForAssembly_NoDiagnostics_CSharp() { await new VerifyCS.Test { TestCode = @" public class DoesNotMatter { } ", SolutionTransforms = { (solution, projectId) => solution.WithProjectAssemblyName(projectId, "AssemblyNameHasNoUnderScore") } }.RunAsync(); } [Fact] public async Task CA1707_ForNamespace_CSharp() { await VerifyCS.VerifyAnalyzerAsync(@" namespace OuterNamespace { namespace HasUnderScore_ { public class DoesNotMatter { } } } namespace HasNoUnderScore { public class DoesNotMatter { } }", GetCA1707CSharpResultAt(line: 4, column: 15, symbolKind: SymbolKind.Namespace, identifierNames: "OuterNamespace.HasUnderScore_")); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task CA1707_ForTypes_CSharp() { await VerifyCS.VerifyAnalyzerAsync(@" public class OuterType { public class UnderScoreInName_ { } private class UnderScoreInNameButPrivate_ { } internal class UnderScoreInNameButInternal_ { } } internal class OuterType2 { public class UnderScoreInNameButNotExternallyVisible_ { } } ", GetCA1707CSharpResultAt(line: 4, column: 18, symbolKind: SymbolKind.NamedType, identifierNames: "OuterType.UnderScoreInName_")); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task CA1707_ForFields_CSharp() { await VerifyCS.VerifyAnalyzerAsync(@" public class DoesNotMatter { public const int ConstField_ = 5; public static readonly int StaticReadOnlyField_ = 5; // No diagnostics for the below private string InstanceField_; private static string StaticField_; public string _field; protected string Another_field; } public enum DoesNotMatterEnum { _EnumWithUnderscore, _ } public class C { internal class C2 { public const int ConstField_ = 5; } } ", GetCA1707CSharpResultAt(line: 4, column: 26, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.ConstField_"), GetCA1707CSharpResultAt(line: 5, column: 36, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.StaticReadOnlyField_"), GetCA1707CSharpResultAt(line: 16, column: 5, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatterEnum._EnumWithUnderscore"), GetCA1707CSharpResultAt(line: 17, column: 5, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatterEnum._")); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task CA1707_ForMethods_CSharp() { await VerifyCS.VerifyAnalyzerAsync(@" public class DoesNotMatter { public void PublicM1_() { } private void PrivateM2_() { } // No diagnostic internal void InternalM3_() { } // No diagnostic protected void ProtectedM4_() { } } public interface I1 { void M_(); } public class ImplementI1 : I1 { public void M_() { } // No diagnostic public virtual void M2_() { } } public class Derives : ImplementI1 { public override void M2_() { } // No diagnostic } internal class C { public class DoesNotMatter2 { public void PublicM1_() { } // No diagnostic protected void ProtectedM4_() { } // No diagnostic } }", GetCA1707CSharpResultAt(line: 4, column: 17, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.PublicM1_()"), GetCA1707CSharpResultAt(line: 7, column: 20, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.ProtectedM4_()"), GetCA1707CSharpResultAt(line: 12, column: 10, symbolKind: SymbolKind.Member, identifierNames: "I1.M_()"), GetCA1707CSharpResultAt(line: 18, column: 25, symbolKind: SymbolKind.Member, identifierNames: "ImplementI1.M2_()")); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task CA1707_ForProperties_CSharp() { await VerifyCS.VerifyAnalyzerAsync(@" public class DoesNotMatter { public int PublicP1_ { get; set; } private int PrivateP2_ { get; set; } // No diagnostic internal int InternalP3_ { get; set; } // No diagnostic protected int ProtectedP4_ { get; set; } } public interface I1 { int P_ { get; set; } } public class ImplementI1 : I1 { public int P_ { get; set; } // No diagnostic public virtual int P2_ { get; set; } } public class Derives : ImplementI1 { public override int P2_ { get; set; } // No diagnostic } internal class C { public class DoesNotMatter2 { public int PublicP1_ { get; set; }// No diagnostic protected int ProtectedP4_ { get; set; } // No diagnostic } }", GetCA1707CSharpResultAt(line: 4, column: 16, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.PublicP1_"), GetCA1707CSharpResultAt(line: 7, column: 19, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.ProtectedP4_"), GetCA1707CSharpResultAt(line: 12, column: 9, symbolKind: SymbolKind.Member, identifierNames: "I1.P_"), GetCA1707CSharpResultAt(line: 18, column: 24, symbolKind: SymbolKind.Member, identifierNames: "ImplementI1.P2_")); } [Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")] public async Task CA1707_ForEvents_CSharp() { await VerifyCS.VerifyAnalyzerAsync(@" using System; public class DoesNotMatter { public event EventHandler PublicE1_; private event EventHandler PrivateE2_; // No diagnostic internal event EventHandler InternalE3_; // No diagnostic protected event EventHandler ProtectedE4_; } public interface I1 { event EventHandler E_; } public class ImplementI1 : I1 { public event EventHandler E_;// No diagnostic public virtual event EventHandler E2_; } public class Derives : ImplementI1 { public override event EventHandler E2_; // No diagnostic } internal class C { public class DoesNotMatter { public event EventHandler PublicE1_; // No diagnostic protected event EventHandler ProtectedE4_; // No diagnostic } }", GetCA1707CSharpResultAt(line: 6, column: 31, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.PublicE1_"), GetCA1707CSharpResultAt(line: 9, column: 34, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.ProtectedE4_"), GetCA1707CSharpResultAt(line: 14, column: 24, symbolKind: SymbolKind.Member, identifierNames: "I1.E_"), GetCA1707CSharpResultAt(line: 20, column: 39, symbolKind: SymbolKind.Member, identifierNames: "ImplementI1.E2_")); } [Fact] public async Task CA1707_ForDelegates_CSharp() { await VerifyCS.VerifyAnalyzerAsync(@" public delegate void Dele(int intPublic_, string stringPublic_); internal delegate void Dele2(int intInternal_, string stringInternal_); // No diagnostics public delegate T Del<T>(int t_); ", GetCA1707CSharpResultAt(2, 31, SymbolKind.DelegateParameter, "Dele", "intPublic_"), GetCA1707CSharpResultAt(2, 50, SymbolKind.DelegateParameter, "Dele", "stringPublic_"), GetCA1707CSharpResultAt(4, 30, SymbolKind.DelegateParameter, "Del<T>", "t_")); } [Fact] public async Task CA1707_ForMemberparameters_CSharp() { await VerifyCS.VerifyAnalyzerAsync(@" public class DoesNotMatter { public void PublicM1(int int_) { } private void PrivateM2(int int_) { } // No diagnostic internal void InternalM3(int int_) { } // No diagnostic protected void ProtectedM4(int int_) { } } public interface I { void M(int int_); } public class implementI : I { public void M(int int_) { } } public abstract class Base { public virtual void M1(int int_) { } public abstract void M2(int int_); } public class Der : Base { public override void M2(int int_) { throw new System.NotImplementedException(); } public override void M1(int int_) { base.M1(int_); } }", GetCA1707CSharpResultAt(4, 30, SymbolKind.MemberParameter, "DoesNotMatter.PublicM1(int)", "int_"), GetCA1707CSharpResultAt(7, 36, SymbolKind.MemberParameter, "DoesNotMatter.ProtectedM4(int)", "int_"), GetCA1707CSharpResultAt(12, 16, SymbolKind.MemberParameter, "I.M(int)", "int_"), GetCA1707CSharpResultAt(24, 32, SymbolKind.MemberParameter, "Base.M1(int)", "int_"), GetCA1707CSharpResultAt(28, 33, SymbolKind.MemberParameter, "Base.M2(int)", "int_")); } [Fact] public async Task CA1707_ForTypeTypeParameters_CSharp() { await VerifyCS.VerifyAnalyzerAsync(@" public class DoesNotMatter<T_> { } class NoDiag<U_> { }", GetCA1707CSharpResultAt(2, 28, SymbolKind.TypeTypeParameter, "DoesNotMatter<T_>", "T_")); } [Fact] public async Task CA1707_ForMemberTypeParameters_CSharp() { await VerifyCS.VerifyAnalyzerAsync(@" public class DoesNotMatter22 { public void PublicM1<T1_>() { } private void PrivateM2<U_>() { } // No diagnostic internal void InternalM3<W_>() { } // No diagnostic protected void ProtectedM4<D_>() { } } public interface I { void M<T_>(); } public class implementI : I { public void M<U_>() { throw new System.NotImplementedException(); } } public abstract class Base { public virtual void M1<T_>() { } public abstract void M2<U_>(); } public class Der : Base { public override void M2<U_>() { throw new System.NotImplementedException(); } public override void M1<T_>() { base.M1<T_>(); } }", GetCA1707CSharpResultAt(4, 26, SymbolKind.MethodTypeParameter, "DoesNotMatter22.PublicM1<T1_>()", "T1_"), GetCA1707CSharpResultAt(7, 32, SymbolKind.MethodTypeParameter, "DoesNotMatter22.ProtectedM4<D_>()", "D_"), GetCA1707CSharpResultAt(12, 12, SymbolKind.MethodTypeParameter, "I.M<T_>()", "T_"), GetCA1707CSharpResultAt(25, 28, SymbolKind.MethodTypeParameter, "Base.M1<T_>()", "T_"), GetCA1707CSharpResultAt(29, 29, SymbolKind.MethodTypeParameter, "Base.M2<U_>()", "U_")); } [Fact, WorkItem(947, "https://github.com/dotnet/roslyn-analyzers/issues/947")] public async Task CA1707_ForOperators_CSharp() { await VerifyCS.VerifyAnalyzerAsync(@" public struct S { public static bool operator ==(S left, S right) { return left.Equals(right); } public static bool operator !=(S left, S right) { return !(left == right); } } "); } [Fact, WorkItem(1319, "https://github.com/dotnet/roslyn-analyzers/issues/1319")] public async Task CA1707_CustomOperator_CSharp() { await VerifyCS.VerifyAnalyzerAsync(@" public class Span { public static implicit operator Span(string text) => new Span(text); public static explicit operator string(Span span) => span.GetText(); private string _text; public Span(string text) { this._text = text; } public string GetText() => _text; } "); } [Fact] public async Task CA1707_CSharp_DiscardSymbolParameter_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" public static class MyHelper { public static int GetSomething(this string _) => 42; public static void SomeMethod() { SomeOtherMethod(out _); } public static void SomeOtherMethod(out int p) { p = 42; } }"); } [Fact] public async Task CA1707_CSharp_DiscardSymbolTuple_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" public class SomeClass { public SomeClass() { var (_, d) = GetSomething(); } private static (string, double) GetSomething() => ("""", 0); }"); } [Fact] public async Task CA1707_CSharp_DiscardSymbolPatternMatching_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" public class SomeClass { public SomeClass(object o) { switch (o) { case object _: break; } } }"); } [Fact] public async Task CA1707_CSharp_StandaloneDiscardSymbol_NoDiagnostic() { await VerifyCS.VerifyAnalyzerAsync(@" public class SomeClass { public SomeClass(object o) { _ = GetSomething(); } public int GetSomething() => 42; }"); } [Fact, WorkItem(3121, "https://github.com/dotnet/roslyn-analyzers/issues/3121")] public async Task CA1707_CSharp_GlobalAsaxSpecialMethods() { await VerifyCS.VerifyAnalyzerAsync(@" using System; namespace System.Web { public class HttpApplication {} } public class ValidContext : System.Web.HttpApplication { protected void Application_AuthenticateRequest(object sender, EventArgs e) {} protected void Application_BeginRequest(object sender, EventArgs e) {} protected void Application_End(object sender, EventArgs e) {} protected void Application_EndRequest(object sender, EventArgs e) {} protected void Application_Error(object sender, EventArgs e) {} protected void Application_Init(object sender, EventArgs e) {} protected void Application_Start(object sender, EventArgs e) {} protected void Session_End(object sender, EventArgs e) {} protected void Session_Start(object sender, EventArgs e) {} } public class InvalidContext { protected void Application_AuthenticateRequest(object sender, EventArgs e) {} protected void Application_BeginRequest(object sender, EventArgs e) {} protected void Application_End(object sender, EventArgs e) {} protected void Application_EndRequest(object sender, EventArgs e) {} protected void Application_Error(object sender, EventArgs e) {} protected void Application_Init(object sender, EventArgs e) {} protected void Application_Start(object sender, EventArgs e) {} protected void Session_End(object sender, EventArgs e) {} protected void Session_Start(object sender, EventArgs e) {} }", GetCA1707CSharpResultAt(24, 20, SymbolKind.Member, "InvalidContext.Application_AuthenticateRequest(object, System.EventArgs)"), GetCA1707CSharpResultAt(25, 20, SymbolKind.Member, "InvalidContext.Application_BeginRequest(object, System.EventArgs)"), GetCA1707CSharpResultAt(26, 20, SymbolKind.Member, "InvalidContext.Application_End(object, System.EventArgs)"), GetCA1707CSharpResultAt(27, 20, SymbolKind.Member, "InvalidContext.Application_EndRequest(object, System.EventArgs)"), GetCA1707CSharpResultAt(28, 20, SymbolKind.Member, "InvalidContext.Application_Error(object, System.EventArgs)"), GetCA1707CSharpResultAt(29, 20, SymbolKind.Member, "InvalidContext.Application_Init(object, System.EventArgs)"), GetCA1707CSharpResultAt(30, 20, SymbolKind.Member, "InvalidContext.Application_Start(object, System.EventArgs)"), GetCA1707CSharpResultAt(31, 20, SymbolKind.Member, "InvalidContext.Session_End(object, System.EventArgs)"), GetCA1707CSharpResultAt(32, 20, SymbolKind.Member, "InvalidContext.Session_Start(object, System.EventArgs)")); } #endregion #region Visual Basic Tests [Fact] public async Task CA1707_ForAssembly_VisualBasic() { await new VerifyVB.Test { TestCode = @" Public Class DoesNotMatter End Class ", SolutionTransforms = { (solution, projectId) => solution.WithProjectAssemblyName(projectId, "AssemblyNameHasUnderScore_") }, ExpectedDiagnostics = { GetCA1707BasicResultAt(line: 2, column: 1, symbolKind: SymbolKind.Assembly, identifierNames: "AssemblyNameHasUnderScore_") } }.RunAsync(); } [Fact] public async Task CA1707_ForAssembly_NoDiagnostics_VisualBasic() { await new VerifyVB.Test { TestCode = @" Public Class DoesNotMatter End Class ", SolutionTransforms = { (solution, projectId) => solution.WithProjectAssemblyName(projectId, "AssemblyNameHasNoUnderScore") } }.RunAsync(); } [Fact] public async Task CA1707_ForNamespace_VisualBasic() { await VerifyVB.VerifyAnalyzerAsync(@" Namespace OuterNamespace Namespace HasUnderScore_ Public Class DoesNotMatter End Class End Namespace End Namespace Namespace HasNoUnderScore Public Class DoesNotMatter End Class End Namespace", GetCA1707BasicResultAt(line: 3, column: 15, symbolKind: SymbolKind.Namespace, identifierNames: "OuterNamespace.HasUnderScore_")); } [Fact] public async Task CA1707_ForTypes_VisualBasic() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class OuterType Public Class UnderScoreInName_ End Class Private Class UnderScoreInNameButPrivate_ End Class End Class", GetCA1707BasicResultAt(line: 3, column: 18, symbolKind: SymbolKind.NamedType, identifierNames: "OuterType.UnderScoreInName_")); } [Fact] public async Task CA1707_ForFields_VisualBasic() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class DoesNotMatter Public Const ConstField_ As Integer = 5 Public Shared ReadOnly SharedReadOnlyField_ As Integer = 5 ' No diagnostics for the below Private InstanceField_ As String Private Shared StaticField_ As String Public _field As String Protected Another_field As String End Class Public Enum DoesNotMatterEnum _EnumWithUnderscore End Enum", GetCA1707BasicResultAt(line: 3, column: 18, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.ConstField_"), GetCA1707BasicResultAt(line: 4, column: 28, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.SharedReadOnlyField_"), GetCA1707BasicResultAt(line: 14, column: 5, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatterEnum._EnumWithUnderscore")); } [Fact] public async Task CA1707_ForMethods_VisualBasic() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class DoesNotMatter Public Sub PublicM1_() End Sub ' No diagnostic Private Sub PrivateM2_() End Sub ' No diagnostic Friend Sub InternalM3_() End Sub Protected Sub ProtectedM4_() End Sub End Class Public Interface I1 Sub M_() End Interface Public Class ImplementI1 Implements I1 Public Sub M_() Implements I1.M_ End Sub ' No diagnostic Public Overridable Sub M2_() End Sub End Class Public Class Derives Inherits ImplementI1 ' No diagnostic Public Overrides Sub M2_() End Sub End Class", GetCA1707BasicResultAt(line: 3, column: 16, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.PublicM1_()"), GetCA1707BasicResultAt(line: 11, column: 19, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.ProtectedM4_()"), GetCA1707BasicResultAt(line: 16, column: 9, symbolKind: SymbolKind.Member, identifierNames: "I1.M_()"), GetCA1707BasicResultAt(line: 24, column: 28, symbolKind: SymbolKind.Member, identifierNames: "ImplementI1.M2_()")); } [Fact] public async Task CA1707_ForProperties_VisualBasic() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class DoesNotMatter Public Property PublicP1_() As Integer Get Return 0 End Get Set End Set End Property ' No diagnostic Private Property PrivateP2_() As Integer Get Return 0 End Get Set End Set End Property ' No diagnostic Friend Property InternalP3_() As Integer Get Return 0 End Get Set End Set End Property Protected Property ProtectedP4_() As Integer Get Return 0 End Get Set End Set End Property End Class Public Interface I1 Property P_() As Integer End Interface Public Class ImplementI1 Implements I1 ' No diagnostic Public Property P_() As Integer Implements I1.P_ Get Return 0 End Get Set End Set End Property Public Overridable Property P2_() As Integer Get Return 0 End Get Set End Set End Property End Class Public Class Derives Inherits ImplementI1 ' No diagnostic Public Overrides Property P2_() As Integer Get Return 0 End Get Set End Set End Property End Class", GetCA1707BasicResultAt(line: 3, column: 21, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.PublicP1_"), GetCA1707BasicResultAt(line: 26, column: 24, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.ProtectedP4_"), GetCA1707BasicResultAt(line: 36, column: 14, symbolKind: SymbolKind.Member, identifierNames: "I1.P_"), GetCA1707BasicResultAt(line: 49, column: 33, symbolKind: SymbolKind.Member, identifierNames: "ImplementI1.P2_")); } [Fact] public async Task CA1707_ForEvents_VisualBasic() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class DoesNotMatter Public Event PublicE1_ As System.EventHandler Private Event PrivateE2_ As System.EventHandler ' No diagnostic Friend Event InternalE3_ As System.EventHandler ' No diagnostic Protected Event ProtectedE4_ As System.EventHandler End Class Public Interface I1 Event E_ As System.EventHandler End Interface Public Class ImplementI1 Implements I1 ' No diagnostic Public Event E_ As System.EventHandler Implements I1.E_ Public Event E2_ As System.EventHandler End Class Public Class Derives Inherits ImplementI1 ' No diagnostic Public Shadows Event E2_ As System.EventHandler End Class", GetCA1707BasicResultAt(line: 3, column: 18, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.PublicE1_"), GetCA1707BasicResultAt(line: 8, column: 21, symbolKind: SymbolKind.Member, identifierNames: "DoesNotMatter.ProtectedE4_"), GetCA1707BasicResultAt(line: 12, column: 11, symbolKind: SymbolKind.Member, identifierNames: "I1.E_"), GetCA1707BasicResultAt(line: 19, column: 18, symbolKind: SymbolKind.Member, identifierNames: "ImplementI1.E2_"), GetCA1707BasicResultAt(line: 25, column: 26, symbolKind: SymbolKind.Member, identifierNames: "Derives.E2_")); } [Fact] public async Task CA1707_ForDelegates_VisualBasic() { await VerifyVB.VerifyAnalyzerAsync(@" Public Delegate Sub Dele(intPublic_ As Integer, stringPublic_ As String) ' No diagnostics Friend Delegate Sub Dele2(intInternal_ As Integer, stringInternal_ As String) Public Delegate Function Del(Of T)(t_ As Integer) As T ", GetCA1707BasicResultAt(2, 26, SymbolKind.DelegateParameter, "Dele", "intPublic_"), GetCA1707BasicResultAt(2, 49, SymbolKind.DelegateParameter, "Dele", "stringPublic_"), GetCA1707BasicResultAt(5, 36, SymbolKind.DelegateParameter, "Del(Of T)", "t_")); } [Fact] public async Task CA1707_ForMemberparameters_VisualBasic() { await VerifyVB.VerifyAnalyzerAsync(@"Public Class DoesNotMatter Public Sub PublicM1(int_ As Integer) End Sub Private Sub PrivateM2(int_ As Integer) End Sub ' No diagnostic Friend Sub InternalM3(int_ As Integer) End Sub ' No diagnostic Protected Sub ProtectedM4(int_ As Integer) End Sub End Class Public Interface I Sub M(int_ As Integer) End Interface Public Class implementI Implements I Private Sub I_M(int_ As Integer) Implements I.M End Sub End Class Public MustInherit Class Base Public Overridable Sub M1(int_ As Integer) End Sub Public MustOverride Sub M2(int_ As Integer) End Class Public Class Der Inherits Base Public Overrides Sub M2(int_ As Integer) Throw New System.NotImplementedException() End Sub Public Overrides Sub M1(int_ As Integer) MyBase.M1(int_) End Sub End Class", GetCA1707BasicResultAt(2, 25, SymbolKind.MemberParameter, "DoesNotMatter.PublicM1(Integer)", "int_"), GetCA1707BasicResultAt(10, 31, SymbolKind.MemberParameter, "DoesNotMatter.ProtectedM4(Integer)", "int_"), GetCA1707BasicResultAt(15, 11, SymbolKind.MemberParameter, "I.M(Integer)", "int_"), GetCA1707BasicResultAt(25, 31, SymbolKind.MemberParameter, "Base.M1(Integer)", "int_"), GetCA1707BasicResultAt(28, 32, SymbolKind.MemberParameter, "Base.M2(Integer)", "int_")); } [Fact] public async Task CA1707_ForTypeTypeParameters_VisualBasic() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class DoesNotMatter(Of T_) End Class Class NoDiag(Of U_) End Class", GetCA1707BasicResultAt(2, 31, SymbolKind.TypeTypeParameter, "DoesNotMatter(Of T_)", "T_")); } [Fact] public async Task CA1707_ForMemberTypeParameters_VisualBasic() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class DoesNotMatter22 Public Sub PublicM1(Of T1_)() End Sub Private Sub PrivateM2(Of U_)() End Sub Friend Sub InternalM3(Of W_)() End Sub Protected Sub ProtectedM4(Of D_)() End Sub End Class Public Interface I Sub M(Of T_)() End Interface Public Class implementI Implements I Public Sub M(Of U_)() Implements I.M Throw New System.NotImplementedException() End Sub End Class Public MustInherit Class Base Public Overridable Sub M1(Of T_)() End Sub Public MustOverride Sub M2(Of U_)() End Class Public Class Der Inherits Base Public Overrides Sub M2(Of U_)() Throw New System.NotImplementedException() End Sub Public Overrides Sub M1(Of T_)() MyBase.M1(Of T_)() End Sub End Class", GetCA1707BasicResultAt(3, 28, SymbolKind.MethodTypeParameter, "DoesNotMatter22.PublicM1(Of T1_)()", "T1_"), GetCA1707BasicResultAt(9, 34, SymbolKind.MethodTypeParameter, "DoesNotMatter22.ProtectedM4(Of D_)()", "D_"), GetCA1707BasicResultAt(14, 14, SymbolKind.MethodTypeParameter, "I.M(Of T_)()", "T_"), GetCA1707BasicResultAt(25, 34, SymbolKind.MethodTypeParameter, "Base.M1(Of T_)()", "T_"), GetCA1707BasicResultAt(28, 35, SymbolKind.MethodTypeParameter, "Base.M2(Of U_)()", "U_")); } [Fact, WorkItem(947, "https://github.com/dotnet/roslyn-analyzers/issues/947")] public async Task CA1707_ForOperators_VisualBasic() { await VerifyVB.VerifyAnalyzerAsync(@" Public Structure S Public Shared Operator =(left As S, right As S) As Boolean Return left.Equals(right) End Operator Public Shared Operator <>(left As S, right As S) As Boolean Return Not (left = right) End Operator End Structure "); } [Fact, WorkItem(1319, "https://github.com/dotnet/roslyn-analyzers/issues/1319")] public async Task CA1707_CustomOperator_VisualBasic() { await VerifyVB.VerifyAnalyzerAsync(@" Public Class Span Public Shared Narrowing Operator CType(ByVal text As String) As Span Return New Span(text) End Operator Public Shared Widening Operator CType(ByVal span As Span) As String Return span.GetText() End Operator Private _text As String Public Sub New(ByVal text) _text = text End Sub Public Function GetText() As String Return _text End Function End Class "); } [Fact, WorkItem(3121, "https://github.com/dotnet/roslyn-analyzers/issues/3121")] public async Task CA1707_VisualBasic_GlobalAsaxSpecialMethods() { await VerifyVB.VerifyAnalyzerAsync(@" Imports System Namespace System.Web Public Class HttpApplication End Class End Namespace Public Class ValidContext Inherits System.Web.HttpApplication Protected Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs) End Sub Protected Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs) End Sub Protected Sub Application_End(ByVal sender As Object, ByVal e As EventArgs) End Sub Protected Sub Application_EndRequest(ByVal sender As Object, ByVal e As EventArgs) End Sub Protected Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs) End Sub Protected Sub Application_Init(ByVal sender As Object, ByVal e As EventArgs) End Sub Protected Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) End Sub Protected Sub Session_End(ByVal sender As Object, ByVal e As EventArgs) End Sub Protected Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs) End Sub End Class Public Class InvalidContext Protected Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs) End Sub Protected Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs) End Sub Protected Sub Application_End(ByVal sender As Object, ByVal e As EventArgs) End Sub Protected Sub Application_EndRequest(ByVal sender As Object, ByVal e As EventArgs) End Sub Protected Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs) End Sub Protected Sub Application_Init(ByVal sender As Object, ByVal e As EventArgs) End Sub Protected Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs) End Sub Protected Sub Session_End(ByVal sender As Object, ByVal e As EventArgs) End Sub Protected Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs) End Sub End Class", GetCA1707BasicResultAt(41, 19, SymbolKind.Member, "InvalidContext.Application_AuthenticateRequest(Object, System.EventArgs)"), GetCA1707BasicResultAt(44, 19, SymbolKind.Member, "InvalidContext.Application_BeginRequest(Object, System.EventArgs)"), GetCA1707BasicResultAt(47, 19, SymbolKind.Member, "InvalidContext.Application_End(Object, System.EventArgs)"), GetCA1707BasicResultAt(50, 19, SymbolKind.Member, "InvalidContext.Application_EndRequest(Object, System.EventArgs)"), GetCA1707BasicResultAt(53, 19, SymbolKind.Member, "InvalidContext.Application_Error(Object, System.EventArgs)"), GetCA1707BasicResultAt(56, 19, SymbolKind.Member, "InvalidContext.Application_Init(Object, System.EventArgs)"), GetCA1707BasicResultAt(59, 19, SymbolKind.Member, "InvalidContext.Application_Start(Object, System.EventArgs)"), GetCA1707BasicResultAt(62, 19, SymbolKind.Member, "InvalidContext.Session_End(Object, System.EventArgs)"), GetCA1707BasicResultAt(65, 19, SymbolKind.Member, "InvalidContext.Session_Start(Object, System.EventArgs)")); } #endregion #region Helpers private static DiagnosticResult GetCA1707CSharpResultAt(int line, int column, SymbolKind symbolKind, params string[] identifierNames) #pragma warning disable RS0030 // Do not used banned APIs => VerifyCS.Diagnostic(GetApproriateRule(symbolKind)) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(identifierNames); private static DiagnosticResult GetCA1707BasicResultAt(int line, int column, SymbolKind symbolKind, params string[] identifierNames) #pragma warning disable RS0030 // Do not used banned APIs => VerifyVB.Diagnostic(GetApproriateRule(symbolKind)) .WithLocation(line, column) #pragma warning restore RS0030 // Do not used banned APIs .WithArguments(identifierNames); private static DiagnosticDescriptor GetApproriateRule(SymbolKind symbolKind) { return symbolKind switch { SymbolKind.Assembly => IdentifiersShouldNotContainUnderscoresAnalyzer.AssemblyRule, SymbolKind.Namespace => IdentifiersShouldNotContainUnderscoresAnalyzer.NamespaceRule, SymbolKind.NamedType => IdentifiersShouldNotContainUnderscoresAnalyzer.TypeRule, SymbolKind.Member => IdentifiersShouldNotContainUnderscoresAnalyzer.MemberRule, SymbolKind.DelegateParameter => IdentifiersShouldNotContainUnderscoresAnalyzer.DelegateParameterRule, SymbolKind.MemberParameter => IdentifiersShouldNotContainUnderscoresAnalyzer.MemberParameterRule, SymbolKind.TypeTypeParameter => IdentifiersShouldNotContainUnderscoresAnalyzer.TypeTypeParameterRule, SymbolKind.MethodTypeParameter => IdentifiersShouldNotContainUnderscoresAnalyzer.MethodTypeParameterRule, _ => throw new NotSupportedException("Unknown Symbol Kind"), }; } private enum SymbolKind { Assembly, Namespace, NamedType, Member, DelegateParameter, MemberParameter, TypeTypeParameter, MethodTypeParameter } #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. #if ENABLEDATABINDING using System; using System.Xml; using System.Xml.XPath; using System.Xml.Schema; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; namespace System.Xml.XPath.DataBinding { public sealed class XPathDocumentView : IBindingList, ITypedList { ArrayList rows; Shape rowShape; XPathNode ndRoot; XPathDocument document; string xpath; IXmlNamespaceResolver namespaceResolver; IXmlNamespaceResolver xpathResolver; // // Constructors // public XPathDocumentView(XPathDocument document) : this(document, (IXmlNamespaceResolver)null) { } public XPathDocumentView(XPathDocument document, IXmlNamespaceResolver namespaceResolver) { if (null == document) throw new ArgumentNullException(nameof(document)); this.document = document; this.ndRoot = document.Root; if (null == this.ndRoot) throw new ArgumentException(nameof(document)); this.namespaceResolver = namespaceResolver; ArrayList rows = new ArrayList(); this.rows = rows; Debug.Assert(XPathNodeType.Root == this.ndRoot.NodeType); XPathNode nd = this.ndRoot.Child; while (null != nd) { if (XPathNodeType.Element == nd.NodeType) rows.Add(nd); nd = nd.Sibling; } DeriveShapeFromRows(); } public XPathDocumentView(XPathDocument document, string xpath) : this(document, xpath, null, true) { } public XPathDocumentView(XPathDocument document, string xpath, IXmlNamespaceResolver namespaceResolver) : this(document, xpath, namespaceResolver, false) { } public XPathDocumentView(XPathDocument document, string xpath, IXmlNamespaceResolver namespaceResolver, bool showPrefixes) { if (null == document) throw new ArgumentNullException(nameof(document)); this.xpath = xpath; this.document = document; this.ndRoot = document.Root; if (null == this.ndRoot) throw new ArgumentException(nameof(document)); this.ndRoot = document.Root; this.xpathResolver = namespaceResolver; if (showPrefixes) this.namespaceResolver = namespaceResolver; ArrayList rows = new ArrayList(); this.rows = rows; InitFromXPath(this.ndRoot, xpath); } internal XPathDocumentView(XPathNode root, ArrayList rows, Shape rowShape) { this.rows = rows; this.rowShape = rowShape; this.ndRoot = root; } // // public properties public XPathDocument Document { get { return this.document; } } public String XPath { get { return xpath; } } // // IEnumerable Implementation public IEnumerator GetEnumerator() { return new RowEnumerator(this); } // // ICollection implementation public int Count { get { return this.rows.Count; } } public bool IsSynchronized { get { return false ; } } public object SyncRoot { get { return null; } } public void CopyTo(Array array, int index) { object o; ArrayList rows = this.rows; for (int i=0; i < rows.Count; i++) o = this[i]; // force creation lazy of row object rows.CopyTo(array, index); } public void CopyTo(XPathNodeView[] array, int index) { object o; ArrayList rows = this.rows; for (int i=0; i < rows.Count; i++) o = this[i]; // force creation lazy of row object rows.CopyTo(array, index); } // // IList Implementation bool IList.IsReadOnly { get { return true; } } bool IList.IsFixedSize { get { return true; } } bool IList.Contains(object value) { return this.rows.Contains(value); } void IList.Remove(object value) { throw new NotSupportedException("IList.Remove"); } void IList.RemoveAt(int index) { throw new NotSupportedException("IList.RemoveAt"); } void IList.Clear() { throw new NotSupportedException("IList.Clear"); } int IList.Add(object value) { throw new NotSupportedException("IList.Add"); } void IList.Insert(int index, object value) { throw new NotSupportedException("IList.Insert"); } int IList.IndexOf( object value ) { return this.rows.IndexOf(value); } object IList.this[int index] { get { object val = this.rows[index]; if (val is XPathNodeView) return val; XPathNodeView xiv = FillRow((XPathNode)val, this.rowShape); this.rows[index] = xiv; return xiv; } set { throw new NotSupportedException("IList.this[]"); } } public bool Contains(XPathNodeView value) { return this.rows.Contains(value); } public int Add(XPathNodeView value) { throw new NotSupportedException("IList.Add"); } public void Insert(int index, XPathNodeView value) { throw new NotSupportedException("IList.Insert"); } public int IndexOf(XPathNodeView value) { return this.rows.IndexOf(value); } public void Remove(XPathNodeView value) { throw new NotSupportedException("IList.Remove"); } public XPathNodeView this[int index] { get { object val = this.rows[index]; XPathNodeView nodeView; nodeView = val as XPathNodeView; if (nodeView != null) { return nodeView; } nodeView = FillRow((XPathNode)val, this.rowShape); this.rows[index] = nodeView; return nodeView; } set { throw new NotSupportedException("IList.this[]"); } } // // IBindingList Implementation public bool AllowEdit { get { return false; } } public bool AllowAdd { get { return false; } } public bool AllowRemove { get { return false; } } public bool AllowNew { get { return false; } } public object AddNew() { throw new NotSupportedException("IBindingList.AddNew"); } public bool SupportsChangeNotification { get { return false; } } public event ListChangedEventHandler ListChanged { add { throw new NotSupportedException("IBindingList.ListChanged"); } remove { throw new NotSupportedException("IBindingList.ListChanged"); } } public bool SupportsSearching { get { return false; } } public bool SupportsSorting { get { return false; } } public bool IsSorted { get { return false; } } public PropertyDescriptor SortProperty { get { throw new NotSupportedException("IBindingList.SortProperty"); } } public ListSortDirection SortDirection { get { throw new NotSupportedException("IBindingList.SortDirection"); } } public void AddIndex( PropertyDescriptor descriptor ) { throw new NotSupportedException("IBindingList.AddIndex"); } public void ApplySort( PropertyDescriptor descriptor, ListSortDirection direction ) { throw new NotSupportedException("IBindingList.ApplySort"); } public int Find(PropertyDescriptor propertyDescriptor, object key) { throw new NotSupportedException("IBindingList.Find"); } public void RemoveIndex(PropertyDescriptor propertyDescriptor) { throw new NotSupportedException("IBindingList.RemoveIndex"); } public void RemoveSort() { throw new NotSupportedException("IBindingList.RemoveSort"); } // // ITypedList Implementation public string GetListName(PropertyDescriptor[] listAccessors) { if( listAccessors == null ) { return this.rowShape.Name; } else { return listAccessors[listAccessors.Length-1].Name; } } public PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors) { Shape shape = null; if( listAccessors == null ) { shape = this.rowShape; } else { XPathNodeViewPropertyDescriptor propdesc = listAccessors[listAccessors.Length-1] as XPathNodeViewPropertyDescriptor; if (null != propdesc) shape = propdesc.Shape; } if (null == shape) throw new ArgumentException(nameof(listAccessors)); return new PropertyDescriptorCollection(shape.PropertyDescriptors); } // // Internal Implementation internal Shape RowShape { get { return this.rowShape; } } internal void SetRows(ArrayList rows) { Debug.Assert(this.rows == null); this.rows = rows; } XPathNodeView FillRow(XPathNode ndRow, Shape shape) { object[] columns; XPathNode nd; switch (shape.BindingType) { case BindingType.Text: case BindingType.Attribute: columns = new object[1]; columns[0] = ndRow; return new XPathNodeView(this, ndRow, columns); case BindingType.Repeat: columns = new object[1]; nd = TreeNavigationHelper.GetContentChild(ndRow); columns[0] = FillColumn(new ContentIterator(nd, shape), shape); return new XPathNodeView(this, ndRow, columns); case BindingType.Sequence: case BindingType.Choice: case BindingType.All: int subShapesCount = shape.SubShapes.Count; columns = new object[subShapesCount]; if (shape.BindingType == BindingType.Sequence && shape.SubShape(0).BindingType == BindingType.Attribute) { FillAttributes(ndRow, shape, columns); } Shape lastSubShape = (Shape)shape.SubShapes[subShapesCount - 1]; if (lastSubShape.BindingType == BindingType.Text) { //Attributes followed by simpe content or mixed content columns[subShapesCount - 1] = ndRow; return new XPathNodeView(this, ndRow, columns); } else { nd = TreeNavigationHelper.GetContentChild(ndRow); return FillSubRow(new ContentIterator(nd, shape), shape, columns); } default: // should not map to a row #if DEBUG throw new NotSupportedException("Unable to bind row to: "+shape.BindingType.ToString()); #else throw new NotSupportedException(); #endif } } void FillAttributes(XPathNode nd, Shape shape, object[] cols) { int i = 0; while (i < cols.Length) { Shape attrShape = shape.SubShape(i); if (attrShape.BindingType != BindingType.Attribute) break; XmlQualifiedName name = attrShape.AttributeName; XPathNode ndAttr = nd.GetAttribute( name.Name, name.Namespace ); if (null != ndAttr) cols[i] = ndAttr; i++; } } object FillColumn(ContentIterator iter, Shape shape) { object val; switch (shape.BindingType) { case BindingType.Element: val = iter.Node; iter.Next(); break; case BindingType.ElementNested: { ArrayList rows = new ArrayList(); rows.Add(iter.Node); iter.Next(); val = new XPathDocumentView(null, rows, shape.NestedShape); break; } case BindingType.Repeat: { ArrayList rows = new ArrayList(); Shape subShape = shape.SubShape(0); if (subShape.BindingType == BindingType.ElementNested) { Shape nestShape = subShape.NestedShape; XPathDocumentView xivc = new XPathDocumentView(null, null, nestShape); XPathNode nd; while (null != (nd = iter.Node) && subShape.IsParticleMatch(iter.Particle)) { rows.Add(nd); iter.Next(); } xivc.SetRows(rows); val = xivc; } else { XPathDocumentView xivc = new XPathDocumentView(null, null, subShape); XPathNode nd; while (null != (nd = iter.Node) && shape.IsParticleMatch(iter.Particle)) { rows.Add(xivc.FillSubRow(iter, subShape, null)); } xivc.SetRows(rows); val = xivc; } break; } case BindingType.Sequence: case BindingType.Choice: case BindingType.All: { XPathDocumentView docview = new XPathDocumentView(null, null, shape); ArrayList rows = new ArrayList(); rows.Add(docview.FillSubRow(iter, shape, null)); docview.SetRows(rows); val = docview; break; } default: case BindingType.Text: case BindingType.Attribute: throw new NotSupportedException(); } return val; } XPathNodeView FillSubRow(ContentIterator iter, Shape shape, object[] columns) { if (null == columns) { int colCount = shape.SubShapes.Count; if (0 == colCount) colCount = 1; columns = new object[colCount]; } switch (shape.BindingType) { case BindingType.Element: columns[0] = FillColumn(iter, shape); break; case BindingType.Sequence: { int iPrev = -1; int i; while (null != iter.Node) { i = shape.FindMatchingSubShape(iter.Particle); if (i <= iPrev) break; columns[i] = FillColumn(iter, shape.SubShape(i)); iPrev = i; } break; } case BindingType.All: { while (null != iter.Node) { int i = shape.FindMatchingSubShape(iter.Particle); if (-1 == i || null != columns[i]) break; columns[i] = FillColumn(iter, shape.SubShape(i)); } break; } case BindingType.Choice: { int i = shape.FindMatchingSubShape(iter.Particle); if (-1 != i) { columns[i] = FillColumn(iter, shape.SubShape(i)); } break; } case BindingType.Repeat: default: // should not map to a row throw new NotSupportedException(); } return new XPathNodeView(this, null, columns); } // // XPath support // void InitFromXPath(XPathNode ndRoot, string xpath) { XPathStep[] steps = ParseXPath(xpath, this.xpathResolver); ArrayList rows = this.rows; rows.Clear(); PopulateFromXPath(ndRoot, steps, 0); DeriveShapeFromRows(); } void DeriveShapeFromRows() { object schemaInfo = null; for (int i=0; (i<rows.Count) && (null==schemaInfo); i++) { XPathNode nd = rows[i] as XPathNode; Debug.Assert(null != nd && (XPathNodeType.Attribute == nd.NodeType || XPathNodeType.Element == nd.NodeType)); if (null != nd) { if (XPathNodeType.Attribute == nd.NodeType) schemaInfo = nd.SchemaAttribute; else schemaInfo = nd.SchemaElement; } } if (0 == rows.Count) { throw new NotImplementedException("XPath failed to match an elements"); } if (null == schemaInfo) { rows.Clear(); throw new XmlException(SR.XmlDataBinding_NoSchemaType, (string[])null); } ShapeGenerator shapeGen = new ShapeGenerator(this.namespaceResolver); XmlSchemaElement xse = schemaInfo as XmlSchemaElement; if (null != xse) this.rowShape = shapeGen.GenerateFromSchema(xse); else this.rowShape = shapeGen.GenerateFromSchema((XmlSchemaAttribute)schemaInfo); } void PopulateFromXPath(XPathNode nd, XPathStep[] steps, int step) { string ln = steps[step].name.Name; string ns = steps[step].name.Namespace; if (XPathNodeType.Attribute == steps[step].type) { XPathNode ndAttr = nd.GetAttribute( ln, ns, true); if (null != ndAttr) { if (null != ndAttr.SchemaAttribute) this.rows.Add(ndAttr); } } else { XPathNode ndChild = TreeNavigationHelper.GetElementChild(nd, ln, ns, true); if (null != ndChild) { int nextStep = step+1; do { if (steps.Length == nextStep) { if (null != ndChild.SchemaType) this.rows.Add(ndChild); } else { PopulateFromXPath(ndChild, steps, nextStep); } ndChild = TreeNavigationHelper.GetElementSibling(ndChild, ln, ns, true); } while (null != ndChild); } } } // This is the limited grammar we support // Path ::= '/ ' ( Step '/')* ( QName | '@' QName ) // Step ::= '.' | QName // This is encoded as an array of XPathStep structs struct XPathStep { internal XmlQualifiedName name; internal XPathNodeType type; } // Parse xpath (limited to above grammar), using provided namespaceResolver // to resolve prefixes. XPathStep[] ParseXPath(string xpath, IXmlNamespaceResolver xnr) { int pos; int stepCount = 1; for (pos=1; pos<(xpath.Length-1); pos++) { if ( ('/' == xpath[pos]) && ('.' != xpath[pos+1]) ) stepCount++; } XPathStep[] steps = new XPathStep[stepCount]; pos = 0; int i = 0; for (;;) { if (pos >= xpath.Length) throw new XmlException(SR.XmlDataBinding_XPathEnd, (string[])null); if ('/' != xpath[pos]) throw new XmlException(SR.XmlDataBinding_XPathRequireSlash, (string[])null); pos++; char ch = xpath[pos]; if (ch == '.') { pos++; // again... } else if ('@' == ch) { if (0 == i) throw new XmlException(SR.XmlDataBinding_XPathAttrNotFirst, (string[])null); pos++; if (pos >= xpath.Length) throw new XmlException(SR.XmlDataBinding_XPathEnd, (string[])null); steps[i].name = ParseQName(xpath, ref pos, xnr); steps[i].type = XPathNodeType.Attribute; i++; if (pos != xpath.Length) throw new XmlException(SR.XmlDataBinding_XPathAttrLast, (string[])null); break; } else { steps[i].name = ParseQName(xpath, ref pos, xnr); steps[i].type = XPathNodeType.Element; i++; if (pos == xpath.Length) break; } } Debug.Assert(i == steps.Length); return steps; } // Parse a QName from the string, and resolve prefix XmlQualifiedName ParseQName(string xpath, ref int pos, IXmlNamespaceResolver xnr) { string nm = ParseName(xpath, ref pos); if (pos < xpath.Length && ':' == xpath[pos]) { pos++; string ns = (null==xnr) ? null : xnr.LookupNamespace(nm); if (null == ns || 0 == ns.Length) throw new XmlException(SR.Sch_UnresolvedPrefix, nm); return new XmlQualifiedName(ParseName(xpath, ref pos), ns); } else { return new XmlQualifiedName(nm); } } // Parse a NCNAME from the string string ParseName(string xpath, ref int pos) { char ch; int start = pos++; while (pos < xpath.Length && '/' != (ch = xpath[pos]) && ':' != ch) pos++; string nm = xpath.Substring(start, pos - start); if (!XmlReader.IsName(nm)) throw new XmlException(SR.Xml_InvalidNameChars, (string[])null); return this.document.NameTable.Add(nm); } // // Helper classes // class ContentIterator { XPathNode node; ContentValidator contentValidator; ValidationState currentState; object currentParticle; public ContentIterator(XPathNode nd, Shape shape) { this.node = nd; XmlSchemaElement xse = shape.XmlSchemaElement; Debug.Assert(null != xse); SchemaElementDecl decl = xse.ElementDecl; Debug.Assert(null != decl); this.contentValidator = decl.ContentValidator; this.currentState = new ValidationState(); this.contentValidator.InitValidation(this.currentState); this.currentState.ProcessContents = XmlSchemaContentProcessing.Strict; if (nd != null) Advance(); } public XPathNode Node { get { return this.node; } } public object Particle { get { return this.currentParticle; } } public bool Next() { if (null != this.node) { this.node = TreeNavigationHelper.GetContentSibling(this.node, XPathNodeType.Element); if (node != null) Advance(); return null != this.node; } return false; } private void Advance() { XPathNode nd = this.node; int errorCode; this.currentParticle = this.contentValidator.ValidateElement(new XmlQualifiedName(nd.LocalName, nd.NamespaceUri), this.currentState, out errorCode); if (null == this.currentParticle || 0 != errorCode) { this.node = null; } } } // Helper class to implement enumerator over rows // We can't just use ArrayList enumerator because // sometims rows may be lazily constructed sealed class RowEnumerator : IEnumerator { XPathDocumentView collection; int pos; internal RowEnumerator(XPathDocumentView collection) { this.collection = collection; this.pos = -1; } public object Current { get { if (this.pos < 0 || this.pos >= this.collection.Count) return null; return this.collection[this.pos]; } } public void Reset() { this.pos = -1; } public bool MoveNext() { this.pos++; int max = this.collection.Count; if (this.pos > max) this.pos = max; return this.pos < max; } } } } #endif