context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Text; using Microsoft.PythonTools.Debugger; using Microsoft.PythonTools.DkmDebugger.Proxies; using Microsoft.PythonTools.DkmDebugger.Proxies.Structs; using Microsoft.PythonTools.Parsing; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.Breakpoints; using Microsoft.VisualStudio.Debugger.CallStack; using Microsoft.VisualStudio.Debugger.CustomRuntimes; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Native; namespace Microsoft.PythonTools.DkmDebugger { // This class implements functionality that is logically a part of TraceManager, but has to be implemented on LocalComponent // and LocalStackWalkingComponent side due to DKM API location restrictions. internal class TraceManagerLocalHelper : DkmDataItem { // There's one of each - StepIn is owned by LocalComponent, StepOut is owned by LocalStackWalkingComponent. // See the comment on the latter for explanation on why this is necessary. public enum Kind { StepIn, StepOut } // Layout of this struct must always remain in sync with DebuggerHelper/trace.cpp. [StructLayout(LayoutKind.Sequential, Pack = 8)] public struct PyObject_FieldOffsets { public readonly long ob_type; public PyObject_FieldOffsets(DkmProcess process) { var fields = StructProxy.GetStructFields<PyObject, PyObject.PyObject_Fields>(process); ob_type = fields.ob_type.Offset; } } // Layout of this struct must always remain in sync with DebuggerHelper/trace.cpp. [StructLayout(LayoutKind.Sequential, Pack = 8)] public struct PyVarObject_FieldOffsets { public readonly long ob_size; public PyVarObject_FieldOffsets(DkmProcess process) { var fields = StructProxy.GetStructFields<PyVarObject, PyVarObject.PyVarObject_Fields>(process); ob_size = fields.ob_size.Offset; } } // Layout of this struct must always remain in sync with DebuggerHelper/trace.cpp. [StructLayout(LayoutKind.Sequential, Pack = 8)] private struct PyCodeObject_FieldOffsets { public readonly long co_varnames, co_filename, co_name; public PyCodeObject_FieldOffsets(DkmProcess process) { var fields = StructProxy.GetStructFields<PyCodeObject, PyCodeObject.Fields>(process); co_varnames = fields.co_varnames.Offset; co_filename = fields.co_filename.Offset; co_name = fields.co_name.Offset; } } // Layout of this struct must always remain in sync with DebuggerHelper/trace.cpp. [StructLayout(LayoutKind.Sequential, Pack = 8)] private struct PyFrameObject_FieldOffsets { public readonly long f_code, f_globals, f_locals, f_lineno; public PyFrameObject_FieldOffsets(DkmProcess process) { var fields = StructProxy.GetStructFields<PyFrameObject, PyFrameObject.Fields>(process); f_code = fields.f_code.Offset; f_globals = fields.f_globals.Offset; f_locals = fields.f_locals.Offset; f_lineno = fields.f_lineno.Offset; } } // Layout of this struct must always remain in sync with DebuggerHelper/trace.cpp. [StructLayout(LayoutKind.Sequential, Pack = 8)] private struct PyBytesObject_FieldOffsets { public readonly long ob_sval; public PyBytesObject_FieldOffsets(DkmProcess process) { var fields = StructProxy.GetStructFields<PyBytesObject, PyBytesObject.Fields>(process); ob_sval = fields.ob_sval.Offset; } } // Layout of this struct must always remain in sync with DebuggerHelper/trace.cpp. [StructLayout(LayoutKind.Sequential, Pack = 8)] private struct PyUnicodeObject27_FieldOffsets { public readonly long length, str; public PyUnicodeObject27_FieldOffsets(DkmProcess process) { var fields = StructProxy.GetStructFields<PyUnicodeObject27, PyUnicodeObject27.Fields>(process); length = fields.length.Offset; str = fields.str.Offset; } } // Layout of this struct must always remain in sync with DebuggerHelper/trace.cpp. [StructLayout(LayoutKind.Sequential, Pack = 8)] private struct PyUnicodeObject33_FieldOffsets { public readonly long sizeof_PyASCIIObject, sizeof_PyCompactUnicodeObject; public readonly long length, state, wstr, wstr_length, data; public PyUnicodeObject33_FieldOffsets(DkmProcess process) { sizeof_PyASCIIObject = StructProxy.SizeOf<PyASCIIObject>(process); sizeof_PyCompactUnicodeObject = StructProxy.SizeOf<PyUnicodeObject33>(process); var asciiFields = StructProxy.GetStructFields<PyASCIIObject, PyASCIIObject.Fields>(process); length = asciiFields.length.Offset; state = asciiFields.state.Offset; wstr = asciiFields.wstr.Offset; var compactFields = StructProxy.GetStructFields<PyCompactUnicodeObject, PyCompactUnicodeObject.Fields>(process); wstr_length = compactFields.wstr_length.Offset; var unicodeFields = StructProxy.GetStructFields<PyUnicodeObject33, PyUnicodeObject33.Fields>(process); data = unicodeFields.data.Offset; } } // Layout of this struct must always remain in sync with DebuggerHelper/trace.cpp. [StructLayout(LayoutKind.Sequential, Pack = 8)] private struct FieldOffsets { public PyObject_FieldOffsets PyObject; public PyVarObject_FieldOffsets PyVarObject; public PyFrameObject_FieldOffsets PyFrameObject; public PyCodeObject_FieldOffsets PyCodeObject; public PyBytesObject_FieldOffsets PyBytesObject; public PyUnicodeObject27_FieldOffsets PyUnicodeObject27; public PyUnicodeObject33_FieldOffsets PyUnicodeObject33; public FieldOffsets(DkmProcess process, PythonRuntimeInfo pyrtInfo) { PyObject = new PyObject_FieldOffsets(process); PyVarObject = new PyVarObject_FieldOffsets(process); PyFrameObject = new PyFrameObject_FieldOffsets(process); PyCodeObject = new PyCodeObject_FieldOffsets(process); PyBytesObject = new PyBytesObject_FieldOffsets(process); if (pyrtInfo.LanguageVersion <= PythonLanguageVersion.V27) { PyUnicodeObject27 = new PyUnicodeObject27_FieldOffsets(process); PyUnicodeObject33 = new PyUnicodeObject33_FieldOffsets(); } else { PyUnicodeObject27 = new PyUnicodeObject27_FieldOffsets(); PyUnicodeObject33 = new PyUnicodeObject33_FieldOffsets(process); } } } // Layout of this struct must always remain in sync with DebuggerHelper/trace.cpp. [StructLayout(LayoutKind.Sequential, Pack = 8)] private struct Types { public ulong PyBytes_Type; public ulong PyUnicode_Type; public Types(DkmProcess process, PythonRuntimeInfo pyrtInfo) { PyBytes_Type = PyObject.GetPyType<PyBytesObject>(process).Address; if (pyrtInfo.LanguageVersion <= PythonLanguageVersion.V27) { PyUnicode_Type = PyObject.GetPyType<PyUnicodeObject27>(process).Address; } else { PyUnicode_Type = PyObject.GetPyType<PyUnicodeObject33>(process).Address; } } } // Layout of this struct must always remain in sync with DebuggerHelper/trace.cpp. [StructLayout(LayoutKind.Sequential, Pack = 8)] private struct FunctionPointers { public ulong Py_DecRef; public ulong PyFrame_FastToLocals; public ulong PyRun_StringFlags; public ulong PyErr_Fetch; public ulong PyErr_Restore; public ulong PyErr_Occurred; public ulong PyObject_Str; public FunctionPointers(DkmProcess process, PythonRuntimeInfo pyrtInfo) { Py_DecRef = pyrtInfo.DLLs.Python.GetFunctionAddress("Py_DecRef"); PyFrame_FastToLocals = pyrtInfo.DLLs.Python.GetFunctionAddress("PyFrame_FastToLocals"); PyRun_StringFlags = pyrtInfo.DLLs.Python.GetFunctionAddress("PyRun_StringFlags"); PyErr_Fetch = pyrtInfo.DLLs.Python.GetFunctionAddress("PyErr_Fetch"); PyErr_Restore = pyrtInfo.DLLs.Python.GetFunctionAddress("PyErr_Restore"); PyErr_Occurred = pyrtInfo.DLLs.Python.GetFunctionAddress("PyErr_Occurred"); PyObject_Str = pyrtInfo.DLLs.Python.GetFunctionAddress("PyObject_Str"); } } private readonly DkmProcess _process; private readonly PythonRuntimeInfo _pyrtInfo; private readonly PythonDllBreakpointHandlers _handlers; private readonly DkmNativeInstructionAddress _traceFunc; private readonly UInt32Proxy _pyTracingPossible; private readonly ByteProxy _isTracing; // A step-in gate is a function inside the Python interpreter or one of the libaries that may call out // to native user code such that it may be a potential target of a step-in operation. For every gate, // we record its address in the process, and create a breakpoint. The breakpoints are initially disabled, // and only get enabled when a step-in operation is initiated - and then disabled again once it completes. private struct StepInGate { public DkmRuntimeInstructionBreakpoint Breakpoint; public StepInGateHandler Handler; public bool HasMultipleExitPoints; // see StepInGateAttribute } /// <summary> /// A handler for a step-in gate, run either when a breakpoint at the entry of the gate is hit, or /// when a step-in is executed while the gate is the topmost frame on the stack. The handler should /// compute any potential runtime exits and pass them to <see cref="OnPotentialRuntimeExit"/>. /// </summary> /// <param name="useRegisters"> /// If true, the handler cannot rely on symbolic expression evaluation to compute the values of any /// parameters passed to the gate, and should instead retrieve them directly from the CPU registers. /// <remarks> /// This is currently only true on x64 when entry breakpoint is hit, because x64 uses registers for /// argument passing (x86 cdecl uses the stack), and function prolog does not necessarily copy /// values to the corresponding stack locations for them - so C++ expression evaluator will produce /// incorrect results for arguments, or fail to evaluate them altogether. /// </remarks> /// </param> public delegate void StepInGateHandler(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters); private readonly List<StepInGate> _stepInGates = new List<StepInGate>(); // Breakpoints corresponding to the native functions outside of Python runtime that can potentially // be called by Python. These lists are dynamically filled for every new step operation, when one of // the Python DLL breakpoints above is hit. They are cleared after that step operation completes. private readonly List<DkmRuntimeBreakpoint> _stepInTargetBreakpoints = new List<DkmRuntimeBreakpoint>(); private readonly List<DkmRuntimeBreakpoint> _stepOutTargetBreakpoints = new List<DkmRuntimeBreakpoint>(); public unsafe TraceManagerLocalHelper(DkmProcess process, Kind kind) { _process = process; _pyrtInfo = process.GetPythonRuntimeInfo(); _traceFunc = _pyrtInfo.DLLs.DebuggerHelper.GetExportedFunctionAddress("TraceFunc"); _isTracing = _pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<ByteProxy>("isTracing"); _pyTracingPossible = _pyrtInfo.DLLs.Python.GetStaticVariable<UInt32Proxy>("_Py_TracingPossible"); if (kind == Kind.StepIn) { var fieldOffsets = _pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<CliStructProxy<FieldOffsets>>("fieldOffsets"); fieldOffsets.Write(new FieldOffsets(process, _pyrtInfo)); var types = _pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<CliStructProxy<Types>>("types"); types.Write(new Types(process, _pyrtInfo)); var functionPointers = _pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<CliStructProxy<FunctionPointers>>("functionPointers"); functionPointers.Write(new FunctionPointers(process, _pyrtInfo)); var stringEquals = _pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<PointerProxy>("stringEquals"); if (_pyrtInfo.LanguageVersion <= PythonLanguageVersion.V27) { stringEquals.Write(_pyrtInfo.DLLs.DebuggerHelper.GetExportedFunctionAddress("StringEquals27").GetPointer()); } else { stringEquals.Write(_pyrtInfo.DLLs.DebuggerHelper.GetExportedFunctionAddress("StringEquals33").GetPointer()); } foreach (var interp in PyInterpreterState.GetInterpreterStates(process)) { foreach (var tstate in interp.GetThreadStates()) { RegisterTracing(tstate); } } _handlers = new PythonDllBreakpointHandlers(this); LocalComponent.CreateRuntimeDllFunctionExitBreakpoints(_pyrtInfo.DLLs.Python, "new_threadstate", _handlers.new_threadstate, enable: true); foreach (var methodInfo in _handlers.GetType().GetMethods()) { var stepInAttr = (StepInGateAttribute)Attribute.GetCustomAttribute(methodInfo, typeof(StepInGateAttribute)); if (stepInAttr != null && (stepInAttr.MinVersion == PythonLanguageVersion.None || _pyrtInfo.LanguageVersion >= stepInAttr.MinVersion) && (stepInAttr.MaxVersion == PythonLanguageVersion.None || _pyrtInfo.LanguageVersion <= stepInAttr.MaxVersion)) { var handler = (StepInGateHandler)Delegate.CreateDelegate(typeof(StepInGateHandler), _handlers, methodInfo); AddStepInGate(handler, _pyrtInfo.DLLs.Python, methodInfo.Name, stepInAttr.HasMultipleExitPoints); } } if (_pyrtInfo.DLLs.CTypes != null) { OnCTypesLoaded(_pyrtInfo.DLLs.CTypes); } } } private void AddStepInGate(StepInGateHandler handler, DkmNativeModuleInstance module, string funcName, bool hasMultipleExitPoints) { var gate = new StepInGate { Handler = handler, HasMultipleExitPoints = hasMultipleExitPoints, Breakpoint = LocalComponent.CreateRuntimeDllFunctionBreakpoint(module, funcName, (thread, frameBase, vframe, retAddr) => handler(thread, frameBase, vframe, useRegisters: thread.Process.Is64Bit())) }; _stepInGates.Add(gate); } public void OnCTypesLoaded(DkmNativeModuleInstance moduleInstance) { AddStepInGate(_handlers._call_function_pointer, moduleInstance, "_call_function_pointer", hasMultipleExitPoints: false); } public unsafe void RegisterTracing(PyThreadState tstate) { tstate.use_tracing.Write(1); tstate.c_tracefunc.Write(_traceFunc.GetPointer()); _pyTracingPossible.Write(_pyTracingPossible.Read() + 1); _isTracing.Write(1); } public void OnBeginStepIn(DkmThread thread) { var frameInfo = new RemoteComponent.GetCurrentFrameInfoRequest { ThreadId = thread.UniqueId }.SendLower(thread.Process); var workList = DkmWorkList.Create(null); var topFrame = thread.GetTopStackFrame(); var curAddr = (topFrame != null) ? topFrame.InstructionAddress as DkmNativeInstructionAddress : null; foreach (var gate in _stepInGates) { gate.Breakpoint.Enable(); // A step-in may happen when we are stopped inside a step-in gate function. For example, when the gate function // calls out to user code more than once, and the user then steps out from the first call; we're now inside the // gate, but the runtime exit breakpoints for that gate have been cleared after the previous step-in completed. // To correctly handle this scenario, we need to check whether we're inside a gate with multiple exit points, and // if so, call the associated gate handler (as it the entry breakpoint for the gate is hit) so that it re-enables // the runtime exit breakpoints for that gate. if (gate.HasMultipleExitPoints && curAddr != null) { var addr = (DkmNativeInstructionAddress)gate.Breakpoint.InstructionAddress; if (addr.IsInSameFunction(curAddr)) { gate.Handler(thread, frameInfo.FrameBase, frameInfo.VFrame, useRegisters: false); } } } } public void OnBeginStepOut(DkmThread thread) { // When we're stepping out while in Python code, there are two possibilities. Either the stack looks like this: // // PythonFrame1 // PythonFrame2 // // or else it looks like this: // // PythonFrame // [Native to Python transition] // NativeFrame // // In both cases, we use native breakpoints on the return address to catch the end of step-out operation. // For Python-to-native step-out, this is the only option. For Python-to-Python, it would seem that TraceFunc // can detect it via PyTrace_RETURN, but it doesn't actually know whether the return is to Python or to // native at the point where it's reported - and, in any case, we need to let PyEval_EvalFrameEx to return // before reporting the completion of that step-out (otherwise we will show the returning frame in call stack). // Find the destination for step-out by walking the call stack and finding either the first native frame // outside of Python and helper DLLs, or the second Python frame. var inspectionSession = DkmInspectionSession.Create(_process, null); var frameFormatOptions = new DkmFrameFormatOptions(DkmVariableInfoFlags.None, DkmFrameNameFormatOptions.None, DkmEvaluationFlags.None, 10000, 10); var stackContext = DkmStackContext.Create(inspectionSession, thread, DkmCallStackFilterOptions.None, frameFormatOptions, null, null); DkmStackFrame frame = null; for (int pyFrameCount = 0; pyFrameCount != 2; ) { DkmStackFrame[] frames = null; var workList = DkmWorkList.Create(null); stackContext.GetNextFrames(workList, 1, (result) => { frames = result.Frames; }); workList.Execute(); if (frames == null || frames.Length != 1) { return; } frame = frames[0]; var frameModuleInstance = frame.ModuleInstance; if (frameModuleInstance is DkmNativeModuleInstance && frameModuleInstance != _pyrtInfo.DLLs.Python && frameModuleInstance != _pyrtInfo.DLLs.DebuggerHelper && frameModuleInstance != _pyrtInfo.DLLs.CTypes) { break; } else if (frame.RuntimeInstance != null && frame.RuntimeInstance.Id.RuntimeType == Guids.PythonRuntimeTypeGuid) { ++pyFrameCount; } } var nativeAddr = frame.InstructionAddress as DkmNativeInstructionAddress; if (nativeAddr == null) { var customAddr = frame.InstructionAddress as DkmCustomInstructionAddress; if (customAddr == null) { return; } var loc = new SourceLocation(customAddr.AdditionalData, thread.Process); nativeAddr = loc.NativeAddress; if (nativeAddr == null) { return; } } var bp = DkmRuntimeInstructionBreakpoint.Create(Guids.PythonStepTargetSourceGuid, thread, nativeAddr, false, null); bp.Enable(); _stepOutTargetBreakpoints.Add(bp); } public void OnStepComplete() { foreach (var gate in _stepInGates) { gate.Breakpoint.Disable(); } foreach (var bp in _stepInTargetBreakpoints) { bp.Close(); } _stepInTargetBreakpoints.Clear(); foreach (var bp in _stepOutTargetBreakpoints) { bp.Close(); } _stepOutTargetBreakpoints.Clear(); } // Sets a breakpoint on a given function pointer, that represents some code outside of the Python DLL that can potentially // be invoked as a result of the current step-in operation (in which case it is the step-in target). private void OnPotentialRuntimeExit(DkmThread thread, ulong funcPtr) { if (funcPtr == 0) { return; } if (_pyrtInfo.DLLs.Python.ContainsAddress(funcPtr)) { return; } else if (_pyrtInfo.DLLs.DebuggerHelper != null && _pyrtInfo.DLLs.DebuggerHelper.ContainsAddress(funcPtr)) { return; } else if (_pyrtInfo.DLLs.CTypes != null && _pyrtInfo.DLLs.CTypes.ContainsAddress(funcPtr)) { return; } var bp = _process.CreateBreakpoint(Guids.PythonStepTargetSourceGuid, funcPtr); bp.Enable(); _stepInTargetBreakpoints.Add(bp); } // Indicates that the breakpoint handler is for a Python-to-native step-in gate. [AttributeUsage(AttributeTargets.Method)] private class StepInGateAttribute : Attribute { public PythonLanguageVersion MinVersion { get; set; } public PythonLanguageVersion MaxVersion { get; set; } /// <summary> /// If true, this step-in gate function has more than one runtime exit point that can be executed in /// a single pass through the body of the function. For example, creating an instance of an object is /// a single gate that invokes both tp_new and tp_init sequentially. /// </summary> public bool HasMultipleExitPoints { get; set; } } private class PythonDllBreakpointHandlers { private readonly TraceManagerLocalHelper _owner; public PythonDllBreakpointHandlers(TraceManagerLocalHelper owner) { _owner = owner; } public void new_threadstate(DkmThread thread, ulong frameBase, ulong vframe, ulong returnAddress) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); // Addressing this local by name does not work for release builds, so read the return value directly from the register instead. var tstate = new PyThreadState(thread.Process, cppEval.EvaluateReturnValueUInt64()); if (tstate == null) { return; } _owner.RegisterTracing(tstate); } // This step-in gate is not marked [StepInGate] because it doesn't live in pythonXX.dll, and so we register it manually. public void _call_function_pointer(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); ulong pProc = cppEval.EvaluateUInt64(useRegisters ? "@rdx" : "pProc"); _owner.OnPotentialRuntimeExit(thread, pProc); } [StepInGate] public void call_function(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); int oparg = cppEval.EvaluateInt32(useRegisters ? "@rdx" : "oparg"); int na = oparg & 0xff; int nk = (oparg >> 8) & 0xff; int n = na + 2 * nk; ulong func = cppEval.EvaluateUInt64( "*((*(PyObject***){0}) - {1} - 1)", useRegisters ? "@rcx" : "pp_stack", n); var obj = PyObject.FromAddress(process, func); ulong ml_meth = cppEval.EvaluateUInt64( "((PyObject*){0})->ob_type == &PyCFunction_Type ? ((PyCFunctionObject*){0})->m_ml->ml_meth : 0", func); _owner.OnPotentialRuntimeExit(thread, ml_meth); } [StepInGate] public void PyCFunction_Call(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); ulong ml_meth = cppEval.EvaluateUInt64( "((PyObject*){0})->ob_type == &PyCFunction_Type ? ((PyCFunctionObject*){0})->m_ml->ml_meth : 0", useRegisters ? "@rcx" : "func"); _owner.OnPotentialRuntimeExit(thread, ml_meth); } [StepInGate] public void getset_get(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string descrVar = useRegisters ? "((PyGetSetDescrObject*)@rcx)" : "descr"; ulong get = cppEval.EvaluateUInt64(descrVar + "->d_getset->get"); _owner.OnPotentialRuntimeExit(thread, get); } [StepInGate] public void getset_set(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string descrVar = useRegisters ? "((PyGetSetDescrObject*)@rcx)" : "descr"; ulong set = cppEval.EvaluateUInt64(descrVar + "->d_getset->set"); _owner.OnPotentialRuntimeExit(thread, set); } [StepInGate(HasMultipleExitPoints = true)] public void type_call(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string typeVar = useRegisters ? "((PyTypeObject*)@rcx)" : "type"; ulong tp_new = cppEval.EvaluateUInt64(typeVar + "->tp_new"); _owner.OnPotentialRuntimeExit(thread, tp_new); ulong tp_init = cppEval.EvaluateUInt64(typeVar + "->tp_init"); _owner.OnPotentialRuntimeExit(thread, tp_init); } [StepInGate] public void PyType_GenericNew(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string typeVar = useRegisters ? "((PyTypeObject*)@rcx)" : "type"; ulong tp_alloc = cppEval.EvaluateUInt64(typeVar + "->tp_alloc"); _owner.OnPotentialRuntimeExit(thread, tp_alloc); } [StepInGate] public void PyObject_Print(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string opVar = useRegisters ? "((PyObject*)@rcx)" : "op"; ulong tp_print = cppEval.EvaluateUInt64(opVar + "->ob_type->tp_print"); _owner.OnPotentialRuntimeExit(thread, tp_print); } [StepInGate] public void PyObject_GetAttrString(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string vVar = useRegisters ? "((PyObject*)@rcx)" : "v"; ulong tp_getattr = cppEval.EvaluateUInt64(vVar + "->ob_type->tp_getattr"); _owner.OnPotentialRuntimeExit(thread, tp_getattr); } [StepInGate] public void PyObject_SetAttrString(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string vVar = useRegisters ? "((PyObject*)@rcx)" : "v"; ulong tp_setattr = cppEval.EvaluateUInt64(vVar + "->ob_type->tp_setattr"); _owner.OnPotentialRuntimeExit(thread, tp_setattr); } [StepInGate] public void PyObject_GetAttr(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string vVar = useRegisters ? "((PyObject*)@rcx)" : "v"; ulong tp_getattr = cppEval.EvaluateUInt64(vVar + "->ob_type->tp_getattr"); _owner.OnPotentialRuntimeExit(thread, tp_getattr); ulong tp_getattro = cppEval.EvaluateUInt64(vVar + "->ob_type->tp_getattro"); _owner.OnPotentialRuntimeExit(thread, tp_getattro); } [StepInGate] public void PyObject_SetAttr(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string vVar = useRegisters ? "((PyObject*)@rcx)" : "v"; ulong tp_setattr = cppEval.EvaluateUInt64(vVar + "->ob_type->tp_setattr"); _owner.OnPotentialRuntimeExit(thread, tp_setattr); ulong tp_setattro = cppEval.EvaluateUInt64(vVar + "->ob_type->tp_setattro"); _owner.OnPotentialRuntimeExit(thread, tp_setattro); } [StepInGate] public void PyObject_Repr(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string vVar = useRegisters ? "((PyObject*)@rcx)" : "v"; ulong tp_repr = cppEval.EvaluateUInt64(vVar + "->ob_type->tp_repr"); _owner.OnPotentialRuntimeExit(thread, tp_repr); } [StepInGate] public void PyObject_Hash(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string vVar = useRegisters ? "((PyObject*)@rcx)" : "v"; ulong tp_hash = cppEval.EvaluateUInt64(vVar + "->ob_type->tp_hash"); _owner.OnPotentialRuntimeExit(thread, tp_hash); } [StepInGate] public void PyObject_Call(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string funcVar = useRegisters ? "((PyObject*)@rcx)" : "func"; ulong tp_call = cppEval.EvaluateUInt64(funcVar + "->ob_type->tp_call"); _owner.OnPotentialRuntimeExit(thread, tp_call); } [StepInGate] public void PyObject_Str(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string vVar = useRegisters ? "((PyObject*)@rcx)" : "v"; ulong tp_str = cppEval.EvaluateUInt64(vVar + "->ob_type->tp_str"); _owner.OnPotentialRuntimeExit(thread, tp_str); } [StepInGate(MaxVersion = PythonLanguageVersion.V27, HasMultipleExitPoints = true)] public void do_cmp(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string vVar = useRegisters ? "((PyObject*)@rcx)" : "v"; string wVar = useRegisters ? "((PyObject*)@rdx)" : "w"; ulong tp_compare1 = cppEval.EvaluateUInt64(vVar + "->ob_type->tp_compare"); _owner.OnPotentialRuntimeExit(thread, tp_compare1); ulong tp_richcompare1 = cppEval.EvaluateUInt64(vVar + "->ob_type->tp_richcompare"); _owner.OnPotentialRuntimeExit(thread, tp_richcompare1); ulong tp_compare2 = cppEval.EvaluateUInt64(wVar + "->ob_type->tp_compare"); _owner.OnPotentialRuntimeExit(thread, tp_compare2); ulong tp_richcompare2 = cppEval.EvaluateUInt64(wVar + "->ob_type->tp_richcompare"); _owner.OnPotentialRuntimeExit(thread, tp_richcompare2); } [StepInGate(MaxVersion = PythonLanguageVersion.V27, HasMultipleExitPoints = true)] public void PyObject_RichCompare(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string vVar = useRegisters ? "((PyObject*)@rcx)" : "v"; string wVar = useRegisters ? "((PyObject*)@rdx)" : "w"; ulong tp_compare1 = cppEval.EvaluateUInt64(vVar + "->ob_type->tp_compare"); _owner.OnPotentialRuntimeExit(thread, tp_compare1); ulong tp_richcompare1 = cppEval.EvaluateUInt64(vVar + "->ob_type->tp_richcompare"); _owner.OnPotentialRuntimeExit(thread, tp_richcompare1); ulong tp_compare2 = cppEval.EvaluateUInt64(wVar + "->ob_type->tp_compare"); _owner.OnPotentialRuntimeExit(thread, tp_compare2); ulong tp_richcompare2 = cppEval.EvaluateUInt64(wVar + "->ob_type->tp_richcompare"); _owner.OnPotentialRuntimeExit(thread, tp_richcompare2); } [StepInGate(MinVersion = PythonLanguageVersion.V33, HasMultipleExitPoints = true)] public void do_richcompare(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string vVar = useRegisters ? "((PyObject*)@rcx)" : "v"; string wVar = useRegisters ? "((PyObject*)@rdx)" : "w"; ulong tp_richcompare1 = cppEval.EvaluateUInt64(vVar + "->ob_type->tp_richcompare"); _owner.OnPotentialRuntimeExit(thread, tp_richcompare1); ulong tp_richcompare2 = cppEval.EvaluateUInt64(wVar + "->ob_type->tp_richcompare"); _owner.OnPotentialRuntimeExit(thread, tp_richcompare2); } [StepInGate] public void PyObject_GetIter(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string oVar = useRegisters ? "((PyObject*)@rcx)" : "o"; ulong tp_iter = cppEval.EvaluateUInt64(oVar + "->ob_type->tp_iter"); _owner.OnPotentialRuntimeExit(thread, tp_iter); } [StepInGate] public void PyIter_Next(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string iterVar = useRegisters ? "((PyObject*)@rcx)" : "iter"; ulong tp_iternext = cppEval.EvaluateUInt64(iterVar + "->ob_type->tp_iternext"); _owner.OnPotentialRuntimeExit(thread, tp_iternext); } [StepInGate] public void builtin_next(DkmThread thread, ulong frameBase, ulong vframe, bool useRegisters) { var process = thread.Process; var cppEval = new CppExpressionEvaluator(thread, frameBase, vframe); string argsVar = useRegisters ? "((PyTupleObject*)@rdx)" : "((PyTupleObject*)args)"; ulong tp_iternext = cppEval.EvaluateUInt64(argsVar + "->ob_item[0]->ob_type->tp_iternext"); _owner.OnPotentialRuntimeExit(thread, tp_iternext); } } } }
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 Firebase.Editor { using System; using System.IO; using System.Collections.Generic; // For CommandLine. using GooglePlayServices; using UnityEditor; using UnityEngine; /// <summary> /// Finds a Python script. /// </summary> internal class PythonExecutor { /// <summary> /// Path to the generic and window python script relative to the Unity project /// directory. /// </summary> private string scriptPath; /// <summary> /// Filename of the script without the path. /// </summary> private string scriptFilename; /// <summary> /// GUID of the script if it isn't found in scriptPath. /// </summary> private string scriptGuid; /// <summary> /// Filename of the windows script runner. /// </summary> private string windowsScriptFilename; /// <summary> /// GUID of the windows script runner if it isn't found in scriptPath. /// </summary> private string windowsScriptGuid; /// <summary> /// Construct a python script executor. /// </summary> /// <param name="scriptPath">Path of scriptFilename and windowsScriptFilename /// </param> /// <param name="scriptFilename">Filename of the python script under scriptPath. /// </param> /// <param name="scriptGuid">Asset GUID of scriptFilename.</param> /// <param name="windowsScriptFilename">Filename of the python script on Windows /// under scriptPath.</param> /// <param name="windowsScriptGuid">Asset GUID of windowsScriptFilename.</param> public PythonExecutor(string scriptPath, string scriptFilename, string scriptGuid, string windowsScriptFilename, string windowsScriptGuid) { this.scriptPath = scriptPath; this.scriptFilename = scriptFilename; this.scriptGuid = scriptGuid; this.windowsScriptFilename = windowsScriptFilename; this.windowsScriptGuid = windowsScriptGuid; } /// <summary> /// Search for a script by asset GUID, falling back to the specified filename. /// </summary> /// <param name="guid">GUID of the asset to search for.</param> /// <param name="filename">Fallback filename of the asset.</param> /// <returns>Path to the script if found in the asset database or the full path to the /// script based upon the specified filename, falling back to the expected relative path /// in the project if the file isn't found.</returns> public string FindScript(string guid, string filename) { string path = Path.Combine(scriptPath, filename); string assetPath = AssetDatabase.GUIDToAssetPath(guid); if (!String.IsNullOrEmpty(assetPath)) path = assetPath; return File.Exists(path) ? Path.GetFullPath(path) : path; } /// <summary> /// Get / find the Windows script. /// </summary> /// <returns>Path to the Windows executable if found, null otherwise.</returns> private string WindowsScriptPath { get { if (Application.platform == RuntimePlatform.WindowsEditor) { string path = FindScript(windowsScriptGuid, windowsScriptFilename); if (File.Exists(path)) return path; } return null; } } /// <summary> /// Get / find the script. /// </summary> public string ScriptPath { get { string path = WindowsScriptPath; return String.IsNullOrEmpty(path) ? FindScript(scriptGuid, scriptFilename) : path; } } private const string PYTHON_INTERPRETER = "python"; /// <summary> /// Get the executable to run the script. /// </summary> public string Executable { get { return Application.platform == RuntimePlatform.WindowsEditor ? ScriptPath : PYTHON_INTERPRETER; } } /// <summary> /// Build an argument list to run the script. /// </summary> /// <param name="arguments">List of arguments to pass to the script.</param> /// <returns>List of arguments to pass to the Executable to run the script.</returns> public IEnumerable<string> GetArguments(IEnumerable<string> arguments) { if (Executable != PYTHON_INTERPRETER) return arguments; var argsWithScript = new List<string>(); argsWithScript.Add(String.Format("\"{0}\"", ScriptPath)); argsWithScript.AddRange(arguments); return argsWithScript; } /// <summary> /// Get a command line string from a set of arguments. /// </summary> /// <param name="arguments">List of arguments to pass to the script.</param> /// <returns>Command line string for debugging purposes.</returns> public string GetCommand(IEnumerable<string> arguments) { var executableWithArgs = new List<string>(); executableWithArgs.Add(String.Format("\"{0}\"", Executable)); executableWithArgs.AddRange(GetArguments(arguments)); return String.Join(" ", executableWithArgs.ToArray()); } /// <summary> /// If execution fails on Windows 7/8, suggest potential remidies. /// </summary> private CommandLine.Result SuggestWorkaroundsOnFailure(CommandLine.Result result) { if (result.exitCode != 0 && Executable != PYTHON_INTERPRETER) { Debug.LogWarning(String.Format(DocRef.PythonScriptExecutionFailed, result.message, Executable)); } return result; } /// <summary> /// Execute the script. /// </summary> /// <param name="arguments">Arguments to pass to the script, built with /// GetArguments().</param> /// <param name="workingDirectory">Directory to execute the tool from.</param> /// <param name="envVars">Additional environment variables to set for the command.</param> /// <param name="ioHandler">Allows a caller to provide interactive input and also handle /// both output and error streams from a single delegate.</param> /// <returns>CommandLineTool result if successful, raises an exception if it's not /// possible to execute the tool.</returns> public CommandLine.Result Run(IEnumerable<string> arguments, string workingDirectory = null, Dictionary<string, string> envVars = null, CommandLine.IOHandler ioHandler = null) { return SuggestWorkaroundsOnFailure( CommandLine.Run( Executable, String.Join(" ", (new List<string>(arguments)).ToArray()), workingDirectory: workingDirectory, envVars: envVars, ioHandler: ioHandler)); } /// <summary> /// Execute the script. /// </summary> /// <param name="arguments">Arguments to pass to the script, built with /// GetArguments().</param> /// <param name="completionDelegate">Called when the tool completes. This is always /// called from the main thread.</param> /// <param name="workingDirectory">Directory to execute the tool from.</param> /// <param name="envVars">Additional environment variables to set for the command.</param> /// <param name="ioHandler">Allows a caller to provide interactive input and also handle /// both output and error streams from a single delegate.</param> public void RunAsync(IEnumerable<string> arguments, CommandLine.CompletionHandler completionDelegate, string workingDirectory = null, Dictionary<string, string> envVars = null, CommandLine.IOHandler ioHandler = null) { CommandLine.RunAsync( Executable, String.Join(" ", (new List<string>(arguments)).ToArray()), (CommandLine.Result result) => { completionDelegate(SuggestWorkaroundsOnFailure(result)); }, workingDirectory: workingDirectory, envVars: envVars, ioHandler: ioHandler); } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; // <auto-generated /> namespace SouthwindRepository{ /// <summary> /// Strongly-typed collection for the QuarterlyOrder class. /// </summary> [Serializable] public partial class QuarterlyOrderCollection : ReadOnlyList<QuarterlyOrder, QuarterlyOrderCollection> { public QuarterlyOrderCollection() {} } /// <summary> /// This is Read-only wrapper class for the quarterly orders view. /// </summary> [Serializable] public partial class QuarterlyOrder : ReadOnlyRecord<QuarterlyOrder>, IReadOnlyRecord { #region Default Settings protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema Accessor public static TableSchema.Table Schema { get { if (BaseSchema == null) { SetSQLProps(); } return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("quarterly orders", TableType.View, DataService.GetInstance("SouthwindRepository")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @""; //columns TableSchema.TableColumn colvarCustomerID = new TableSchema.TableColumn(schema); colvarCustomerID.ColumnName = "CustomerID"; colvarCustomerID.DataType = DbType.AnsiStringFixedLength; colvarCustomerID.MaxLength = 5; colvarCustomerID.AutoIncrement = false; colvarCustomerID.IsNullable = true; colvarCustomerID.IsPrimaryKey = false; colvarCustomerID.IsForeignKey = false; colvarCustomerID.IsReadOnly = false; schema.Columns.Add(colvarCustomerID); TableSchema.TableColumn colvarCompanyName = new TableSchema.TableColumn(schema); colvarCompanyName.ColumnName = "CompanyName"; colvarCompanyName.DataType = DbType.String; colvarCompanyName.MaxLength = 40; colvarCompanyName.AutoIncrement = false; colvarCompanyName.IsNullable = true; colvarCompanyName.IsPrimaryKey = false; colvarCompanyName.IsForeignKey = false; colvarCompanyName.IsReadOnly = false; schema.Columns.Add(colvarCompanyName); TableSchema.TableColumn colvarCity = new TableSchema.TableColumn(schema); colvarCity.ColumnName = "City"; colvarCity.DataType = DbType.String; colvarCity.MaxLength = 15; colvarCity.AutoIncrement = false; colvarCity.IsNullable = true; colvarCity.IsPrimaryKey = false; colvarCity.IsForeignKey = false; colvarCity.IsReadOnly = false; schema.Columns.Add(colvarCity); TableSchema.TableColumn colvarCountry = new TableSchema.TableColumn(schema); colvarCountry.ColumnName = "Country"; colvarCountry.DataType = DbType.String; colvarCountry.MaxLength = 15; colvarCountry.AutoIncrement = false; colvarCountry.IsNullable = true; colvarCountry.IsPrimaryKey = false; colvarCountry.IsForeignKey = false; colvarCountry.IsReadOnly = false; schema.Columns.Add(colvarCountry); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["SouthwindRepository"].AddSchema("quarterly orders",schema); } } #endregion #region Query Accessor public static Query CreateQuery() { return new Query(Schema); } #endregion #region .ctors public QuarterlyOrder() { SetSQLProps(); SetDefaults(); MarkNew(); } public QuarterlyOrder(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) { ForceDefaults(); } MarkNew(); } public QuarterlyOrder(object keyID) { SetSQLProps(); LoadByKey(keyID); } public QuarterlyOrder(string columnName, object columnValue) { SetSQLProps(); LoadByParam(columnName,columnValue); } #endregion #region Props [XmlAttribute("CustomerID")] [Bindable(true)] public string CustomerID { get { return GetColumnValue<string>("CustomerID"); } set { SetColumnValue("CustomerID", value); } } [XmlAttribute("CompanyName")] [Bindable(true)] public string CompanyName { get { return GetColumnValue<string>("CompanyName"); } set { SetColumnValue("CompanyName", value); } } [XmlAttribute("City")] [Bindable(true)] public string City { get { return GetColumnValue<string>("City"); } set { SetColumnValue("City", value); } } [XmlAttribute("Country")] [Bindable(true)] public string Country { get { return GetColumnValue<string>("Country"); } set { SetColumnValue("Country", value); } } #endregion #region Columns Struct public struct Columns { public static string CustomerID = @"CustomerID"; public static string CompanyName = @"CompanyName"; public static string City = @"City"; public static string Country = @"Country"; } #endregion #region IAbstractRecord Members public new CT GetColumnValue<CT>(string columnName) { return base.GetColumnValue<CT>(columnName); } public object GetColumnValue(string columnName) { return base.GetColumnValue<object>(columnName); } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.EditAndContinue; using Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Notification; using Microsoft.CodeAnalysis.Text; using Microsoft.DiaSymReader; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Utilities; using Roslyn.Utilities; using ShellInterop = Microsoft.VisualStudio.Shell.Interop; using VsTextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan; using VsThreading = Microsoft.VisualStudio.Threading; using Document = Microsoft.CodeAnalysis.Document; using Microsoft.CodeAnalysis.Debugging; namespace Microsoft.VisualStudio.LanguageServices.Implementation.EditAndContinue { internal sealed class VsENCRebuildableProjectImpl { private readonly AbstractProject _vsProject; // number of projects that are in the debug state: private static int s_debugStateProjectCount; // number of projects that are in the break state: private static int s_breakStateProjectCount; // projects that entered the break state: private static readonly List<KeyValuePair<ProjectId, ProjectReadOnlyReason>> s_breakStateEnteredProjects = new List<KeyValuePair<ProjectId, ProjectReadOnlyReason>>(); // active statements of projects that entered the break state: private static readonly List<VsActiveStatement> s_pendingActiveStatements = new List<VsActiveStatement>(); private static VsReadOnlyDocumentTracker s_readOnlyDocumentTracker; internal static readonly TraceLog log = new TraceLog(2048, "EnC"); private static Solution s_breakStateEntrySolution; private static EncDebuggingSessionInfo s_encDebuggingSessionInfo; private readonly IEditAndContinueWorkspaceService _encService; private readonly IActiveStatementTrackingService _trackingService; private readonly EditAndContinueDiagnosticUpdateSource _diagnosticProvider; private readonly IDebugEncNotify _debugEncNotify; private readonly INotificationService _notifications; private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactoryService; #region Per Project State private bool _changesApplied; // maps VS Active Statement Id, which is unique within this project, to our id private Dictionary<uint, ActiveStatementId> _activeStatementIds; private ProjectAnalysisSummary _lastEditSessionSummary = ProjectAnalysisSummary.NoChanges; private HashSet<uint> _activeMethods; private List<VsExceptionRegion> _exceptionRegions; private EmitBaseline _committedBaseline; private EmitBaseline _pendingBaseline; private Project _projectBeingEmitted; private ImmutableArray<DocumentId> _documentsWithEmitError = ImmutableArray<DocumentId>.Empty; /// <summary> /// Initialized when the project switches to debug state. /// Null if the project has no output file or we can't read the MVID. /// </summary> private ModuleMetadata _metadata; private ISymUnmanagedReader3 _pdbReader; private IntPtr _pdbReaderObjAsStream; #endregion private bool IsDebuggable { get { return _metadata != null; } } internal VsENCRebuildableProjectImpl(AbstractProject project) { _vsProject = project; _encService = _vsProject.Workspace.Services.GetService<IEditAndContinueWorkspaceService>(); _trackingService = _vsProject.Workspace.Services.GetService<IActiveStatementTrackingService>(); _notifications = _vsProject.Workspace.Services.GetService<INotificationService>(); _debugEncNotify = (IDebugEncNotify)project.ServiceProvider.GetService(typeof(ShellInterop.SVsShellDebugger)); var componentModel = (IComponentModel)project.ServiceProvider.GetService(typeof(SComponentModel)); _diagnosticProvider = componentModel.GetService<EditAndContinueDiagnosticUpdateSource>(); _editorAdaptersFactoryService = componentModel.GetService<IVsEditorAdaptersFactoryService>(); Debug.Assert(_encService != null); Debug.Assert(_trackingService != null); Debug.Assert(_diagnosticProvider != null); Debug.Assert(_editorAdaptersFactoryService != null); } // called from an edit filter if an edit of a read-only buffer is attempted: internal bool OnEdit(DocumentId documentId) { SessionReadOnlyReason sessionReason; ProjectReadOnlyReason projectReason; if (_encService.IsProjectReadOnly(documentId.ProjectId, out sessionReason, out projectReason)) { OnReadOnlyDocumentEditAttempt(documentId, sessionReason, projectReason); return true; } return false; } private void OnReadOnlyDocumentEditAttempt( DocumentId documentId, SessionReadOnlyReason sessionReason, ProjectReadOnlyReason projectReason) { if (sessionReason == SessionReadOnlyReason.StoppedAtException) { _debugEncNotify.NotifyEncEditAttemptedAtInvalidStopState(); return; } var visualStudioWorkspace = _vsProject.Workspace as VisualStudioWorkspaceImpl; var hostProject = visualStudioWorkspace?.GetHostProject(documentId.ProjectId) as AbstractProject; if (hostProject?.EditAndContinueImplOpt?._metadata != null) { _debugEncNotify.NotifyEncEditDisallowedByProject(hostProject.Hierarchy); return; } // NotifyEncEditDisallowedByProject is broken if the project isn't built at the time the debugging starts (debugger bug 877586). string message; if (sessionReason == SessionReadOnlyReason.Running) { message = "Changes are not allowed while code is running."; } else { Debug.Assert(sessionReason == SessionReadOnlyReason.None); switch (projectReason) { case ProjectReadOnlyReason.MetadataNotAvailable: message = "Changes are not allowed if the project wasn't built when debugging started."; break; case ProjectReadOnlyReason.NotLoaded: message = "Changes are not allowed if the assembly has not been loaded."; break; default: throw ExceptionUtilities.UnexpectedValue(projectReason); } } _notifications.SendNotification(message, title: FeaturesResources.Edit_and_Continue1, severity: NotificationSeverity.Error); } /// <summary> /// Since we can't await asynchronous operations we need to wait for them to complete. /// The default SynchronizationContext.Wait pumps messages giving the debugger a chance to /// reenter our EnC implementation. To avoid that we use a specialized SynchronizationContext /// that doesn't pump messages. We need to make sure though that the async methods we wait for /// don't dispatch to foreground thread, otherwise we would end up in a deadlock. /// </summary> private static VsThreading.SpecializedSyncContext NonReentrantContext { get { return VsThreading.ThreadingTools.Apply(VsThreading.NoMessagePumpSyncContext.Default); } } public bool HasCustomMetadataEmitter() { return true; } /// <summary> /// Invoked when the debugger transitions from Design mode to Run mode or Break mode. /// </summary> public int StartDebuggingPE() { try { log.Write("Enter Debug Mode: project '{0}'", _vsProject.DisplayName); // EnC service is global (per solution), but the debugger calls this for each project. // Avoid starting the debug session if it has already been started. if (_encService.DebuggingSession == null) { Debug.Assert(s_debugStateProjectCount == 0); Debug.Assert(s_breakStateProjectCount == 0); Debug.Assert(s_breakStateEnteredProjects.Count == 0); _encService.OnBeforeDebuggingStateChanged(DebuggingState.Design, DebuggingState.Run); _encService.StartDebuggingSession(_vsProject.Workspace.CurrentSolution); s_encDebuggingSessionInfo = new EncDebuggingSessionInfo(); s_readOnlyDocumentTracker = new VsReadOnlyDocumentTracker(_encService, _editorAdaptersFactoryService, _vsProject); } string outputPath = _vsProject.TryGetObjOutputPath(); // The project doesn't produce a debuggable binary or we can't read it. // Continue on since the debugger ignores HResults and we need to handle subsequent calls. if (outputPath != null) { try { InjectFault_MvidRead(); _metadata = ModuleMetadata.CreateFromStream(new FileStream(outputPath, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete)); _metadata.GetModuleVersionId(); } catch (FileNotFoundException) { // If the project isn't referenced by the project being debugged it might not be built. // In that case EnC is never allowed for the project, and thus we can assume the project hasn't entered debug state. log.Write("StartDebuggingPE: '{0}' metadata file not found: '{1}'", _vsProject.DisplayName, outputPath); _metadata = null; } catch (Exception e) { log.Write("StartDebuggingPE: error reading MVID of '{0}' ('{1}'): {2}", _vsProject.DisplayName, outputPath, e.Message); _metadata = null; var descriptor = new DiagnosticDescriptor("Metadata", "Metadata", ServicesVSResources.Error_while_reading_0_colon_1, DiagnosticCategory.EditAndContinue, DiagnosticSeverity.Error, isEnabledByDefault: true, customTags: DiagnosticCustomTags.EditAndContinue); _diagnosticProvider.ReportDiagnostics( new EncErrorId(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.DebuggerErrorId), _encService.DebuggingSession.InitialSolution, _vsProject.Id, new[] { Diagnostic.Create(descriptor, Location.None, outputPath, e.Message) }); } } else { log.Write("StartDebuggingPE: project has no output path '{0}'", _vsProject.DisplayName); _metadata = null; } if (_metadata != null) { // The debugger doesn't call EnterBreakStateOnPE for projects that don't have MVID. // However a project that's initially not loaded (but it might be in future) enters // both the debug and break states. s_debugStateProjectCount++; } _activeMethods = new HashSet<uint>(); _exceptionRegions = new List<VsExceptionRegion>(); _activeStatementIds = new Dictionary<uint, ActiveStatementId>(); // The HResult is ignored by the debugger. return VSConstants.S_OK; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } public int StopDebuggingPE() { try { log.Write("Exit Debug Mode: project '{0}'", _vsProject.DisplayName); Debug.Assert(s_breakStateEnteredProjects.Count == 0); // Clear the solution stored while projects were entering break mode. // It should be cleared as soon as all tracked projects enter the break mode // but if the entering break mode fails for some projects we should avoid leaking the solution. Debug.Assert(s_breakStateEntrySolution == null); s_breakStateEntrySolution = null; // EnC service is global (per solution), but the debugger calls this for each project. // Avoid ending the debug session if it has already been ended. if (_encService.DebuggingSession != null) { _encService.OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Design); _encService.EndDebuggingSession(); LogEncSession(); s_encDebuggingSessionInfo = null; s_readOnlyDocumentTracker.Dispose(); s_readOnlyDocumentTracker = null; } if (_metadata != null) { _metadata.Dispose(); _metadata = null; s_debugStateProjectCount--; } else { // an error might have been reported: var errorId = new EncErrorId(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.DebuggerErrorId); _diagnosticProvider.ClearDiagnostics(errorId, _vsProject.Workspace.CurrentSolution, _vsProject.Id, documentIdOpt: null); } _activeMethods = null; _exceptionRegions = null; _committedBaseline = null; _activeStatementIds = null; Debug.Assert((_pdbReaderObjAsStream == IntPtr.Zero) || (_pdbReader == null)); if (_pdbReader != null) { Marshal.ReleaseComObject(_pdbReader); _pdbReader = null; } // The HResult is ignored by the debugger. return VSConstants.S_OK; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } private static void LogEncSession() { var sessionId = DebugLogMessage.GetNextId(); Logger.Log(FunctionId.Debugging_EncSession, DebugLogMessage.Create(sessionId, s_encDebuggingSessionInfo)); foreach (var editSession in s_encDebuggingSessionInfo.EditSessions) { var editSessionId = DebugLogMessage.GetNextId(); Logger.Log(FunctionId.Debugging_EncSession_EditSession, DebugLogMessage.Create(sessionId, editSessionId, editSession)); if (editSession.EmitDeltaErrorIds != null) { foreach (var error in editSession.EmitDeltaErrorIds) { Logger.Log(FunctionId.Debugging_EncSession_EditSession_EmitDeltaErrorId, DebugLogMessage.Create(sessionId, editSessionId, error)); } } foreach (var rudeEdit in editSession.RudeEdits) { Logger.Log(FunctionId.Debugging_EncSession_EditSession_RudeEdit, DebugLogMessage.Create(sessionId, editSessionId, rudeEdit, blocking: editSession.HadRudeEdits)); } } } /// <summary> /// Get MVID and file name of the project's output file. /// </summary> /// <remarks> /// The MVID is used by the debugger to identify modules loaded into debuggee that correspond to this project. /// The path seems to be unused. /// /// The output file path might be different from the path of the module loaded into the process. /// For example, the binary produced by the C# compiler is stores in obj directory, /// and then copied to bin directory from which it is loaded to the debuggee. /// /// The binary produced by the compiler can also be rewritten by post-processing tools. /// The debugger assumes that the MVID of the compiler's output file at the time we start debugging session /// is the same as the MVID of the module loaded into debuggee. The original MVID might be different though. /// </remarks> public int GetPEidentity(Guid[] pMVID, string[] pbstrPEName) { Debug.Assert(_encService.DebuggingSession != null); if (_metadata == null) { return VSConstants.E_FAIL; } if (pMVID != null && pMVID.Length != 0) { pMVID[0] = _metadata.GetModuleVersionId(); } if (pbstrPEName != null && pbstrPEName.Length != 0) { var outputPath = _vsProject.TryGetObjOutputPath(); Debug.Assert(outputPath != null); pbstrPEName[0] = Path.GetFileName(outputPath); } return VSConstants.S_OK; } /// <summary> /// Called by the debugger when entering a Break state. /// </summary> /// <param name="encBreakReason">Reason for transition to Break state.</param> /// <param name="pActiveStatements">Statements active when the debuggee is stopped.</param> /// <param name="cActiveStatements">Length of <paramref name="pActiveStatements"/>.</param> public int EnterBreakStateOnPE(Interop.ENC_BREAKSTATE_REASON encBreakReason, ShellInterop.ENC_ACTIVE_STATEMENT[] pActiveStatements, uint cActiveStatements) { try { using (NonReentrantContext) { log.Write("Enter {2}Break Mode: project '{0}', AS#: {1}", _vsProject.DisplayName, pActiveStatements != null ? pActiveStatements.Length : -1, encBreakReason == ENC_BREAKSTATE_REASON.ENC_BREAK_EXCEPTION ? "Exception " : ""); Debug.Assert(cActiveStatements == (pActiveStatements != null ? pActiveStatements.Length : 0)); Debug.Assert(s_breakStateProjectCount < s_debugStateProjectCount); Debug.Assert(s_breakStateProjectCount > 0 || _exceptionRegions.Count == 0); Debug.Assert(s_breakStateProjectCount == s_breakStateEnteredProjects.Count); Debug.Assert(IsDebuggable); if (s_breakStateEntrySolution == null) { _encService.OnBeforeDebuggingStateChanged(DebuggingState.Run, DebuggingState.Break); s_breakStateEntrySolution = _vsProject.Workspace.CurrentSolution; // TODO: This is a workaround for a debugger bug in which not all projects exit the break state. // Reset the project count. s_breakStateProjectCount = 0; } ProjectReadOnlyReason state; if (pActiveStatements != null) { AddActiveStatements(s_breakStateEntrySolution, pActiveStatements); state = ProjectReadOnlyReason.None; } else { // unfortunately the debugger doesn't provide details: state = ProjectReadOnlyReason.NotLoaded; } // If pActiveStatements is null the EnC Manager failed to retrieve the module corresponding // to the project in the debuggee. We won't include such projects in the edit session. s_breakStateEnteredProjects.Add(KeyValuePair.Create(_vsProject.Id, state)); s_breakStateProjectCount++; // EnC service is global, but the debugger calls this for each project. // Avoid starting the edit session until all projects enter break state. if (s_breakStateEnteredProjects.Count == s_debugStateProjectCount) { Debug.Assert(_encService.EditSession == null); Debug.Assert(s_pendingActiveStatements.TrueForAll(s => s.Owner._activeStatementIds.Count == 0)); var byDocument = new Dictionary<DocumentId, ImmutableArray<ActiveStatementSpan>>(); // note: fills in activeStatementIds of projects that own the active statements: GroupActiveStatements(s_pendingActiveStatements, byDocument); // When stopped at exception: All documents are read-only, but the files might be changed outside of VS. // So we start an edit session as usual and report a rude edit for all changes we see. bool stoppedAtException = encBreakReason == ENC_BREAKSTATE_REASON.ENC_BREAK_EXCEPTION; var projectStates = ImmutableDictionary.CreateRange(s_breakStateEnteredProjects); _encService.StartEditSession(s_breakStateEntrySolution, byDocument, projectStates, stoppedAtException); _trackingService.StartTracking(_encService.EditSession); s_readOnlyDocumentTracker.UpdateWorkspaceDocuments(); // When tracking is started the tagger is notified and the active statements are highlighted. // Add the handler that notifies the debugger *after* that initial tagger notification, // so that it's not triggered unless an actual change in leaf AS occurs. _trackingService.TrackingSpansChanged += TrackingSpansChanged; } } // The debugger ignores the result. return VSConstants.S_OK; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } finally { // TODO: This is a workaround for a debugger bug. // Ensure that the state gets reset even if if `GroupActiveStatements` throws an exception. if (s_breakStateEnteredProjects.Count == s_debugStateProjectCount) { // we don't need these anymore: s_pendingActiveStatements.Clear(); s_breakStateEnteredProjects.Clear(); s_breakStateEntrySolution = null; } } } private void TrackingSpansChanged(bool leafChanged) { //log.Write("Tracking spans changed: {0}", leafChanged); //if (leafChanged) //{ // // fire and forget: // Application.Current.Dispatcher.InvokeAsync(() => // { // log.Write("Notifying debugger of active statement change."); // var debugNotify = (IDebugEncNotify)_vsProject.ServiceProvider.GetService(typeof(ShellInterop.SVsShellDebugger)); // debugNotify.NotifyEncUpdateCurrentStatement(); // }); //} } private struct VsActiveStatement { public readonly DocumentId DocumentId; public readonly uint StatementId; public readonly ActiveStatementSpan Span; public readonly VsENCRebuildableProjectImpl Owner; public VsActiveStatement(VsENCRebuildableProjectImpl owner, uint statementId, DocumentId documentId, ActiveStatementSpan span) { this.Owner = owner; this.StatementId = statementId; this.DocumentId = documentId; this.Span = span; } } private struct VsExceptionRegion { public readonly uint ActiveStatementId; public readonly int Ordinal; public readonly uint MethodToken; public readonly LinePositionSpan Span; public VsExceptionRegion(uint activeStatementId, int ordinal, uint methodToken, LinePositionSpan span) { this.ActiveStatementId = activeStatementId; this.Span = span; this.MethodToken = methodToken; this.Ordinal = ordinal; } } // See InternalApis\vsl\inc\encbuild.idl private const int TEXT_POSITION_ACTIVE_STATEMENT = 1; private void AddActiveStatements(Solution solution, ShellInterop.ENC_ACTIVE_STATEMENT[] vsActiveStatements) { Debug.Assert(_activeMethods.Count == 0); Debug.Assert(_exceptionRegions.Count == 0); foreach (var vsActiveStatement in vsActiveStatements) { log.DebugWrite("+AS[{0}]: {1} {2} {3} {4} '{5}'", vsActiveStatement.id, vsActiveStatement.tsPosition.iStartLine, vsActiveStatement.tsPosition.iStartIndex, vsActiveStatement.tsPosition.iEndLine, vsActiveStatement.tsPosition.iEndIndex, vsActiveStatement.filename); // TODO (tomat): // Active statement is in user hidden code. The only information that we have from the debugger // is the method token. We don't need to track the statement (it's not in user code anyways), // but we should probably track the list of such methods in order to preserve their local variables. // Not sure what's exactly the scenario here, perhaps modifying async method/iterator? // Dev12 just ignores these. if (vsActiveStatement.posType != TEXT_POSITION_ACTIVE_STATEMENT) { continue; } var flags = (ActiveStatementFlags)vsActiveStatement.ASINFO; // Finds a document id in the solution with the specified file path. DocumentId documentId = solution.GetDocumentIdsWithFilePath(vsActiveStatement.filename) .Where(dId => dId.ProjectId == _vsProject.Id).SingleOrDefault(); if (documentId != null) { var document = solution.GetDocument(documentId); Debug.Assert(document != null); SourceText source = document.GetTextAsync(default(CancellationToken)).Result; LinePositionSpan lineSpan = vsActiveStatement.tsPosition.ToLinePositionSpan(); // If the PDB is out of sync with the source we might get bad spans. var sourceLines = source.Lines; if (lineSpan.End.Line >= sourceLines.Count || sourceLines.GetPosition(lineSpan.End) > sourceLines[sourceLines.Count - 1].EndIncludingLineBreak) { log.Write("AS out of bounds (line count is {0})", source.Lines.Count); continue; } SyntaxNode syntaxRoot = document.GetSyntaxRootAsync(default(CancellationToken)).Result; var analyzer = document.Project.LanguageServices.GetService<IEditAndContinueAnalyzer>(); s_pendingActiveStatements.Add(new VsActiveStatement( this, vsActiveStatement.id, document.Id, new ActiveStatementSpan(flags, lineSpan))); bool isLeaf = (flags & ActiveStatementFlags.LeafFrame) != 0; var ehRegions = analyzer.GetExceptionRegions(source, syntaxRoot, lineSpan, isLeaf); for (int i = 0; i < ehRegions.Length; i++) { _exceptionRegions.Add(new VsExceptionRegion( vsActiveStatement.id, i, vsActiveStatement.methodToken, ehRegions[i])); } } _activeMethods.Add(vsActiveStatement.methodToken); } } private static void GroupActiveStatements( IEnumerable<VsActiveStatement> activeStatements, Dictionary<DocumentId, ImmutableArray<ActiveStatementSpan>> byDocument) { var spans = new List<ActiveStatementSpan>(); foreach (var grouping in activeStatements.GroupBy(s => s.DocumentId)) { var documentId = grouping.Key; foreach (var activeStatement in grouping.OrderBy(s => s.Span.Span.Start)) { int ordinal = spans.Count; // register vsid with the project that owns the active statement: activeStatement.Owner._activeStatementIds.Add(activeStatement.StatementId, new ActiveStatementId(documentId, ordinal)); spans.Add(activeStatement.Span); } byDocument.Add(documentId, spans.AsImmutable()); spans.Clear(); } } /// <summary> /// Returns the number of exception regions around current active statements. /// This is called when the project is entering a break right after /// <see cref="EnterBreakStateOnPE"/> and prior to <see cref="GetExceptionSpans"/>. /// </summary> /// <remarks> /// Called by EnC manager. /// </remarks> public int GetExceptionSpanCount(out uint pcExceptionSpan) { pcExceptionSpan = (uint)_exceptionRegions.Count; return VSConstants.S_OK; } /// <summary> /// Returns information about exception handlers in the source. /// </summary> /// <remarks> /// Called by EnC manager. /// </remarks> public int GetExceptionSpans(uint celt, ShellInterop.ENC_EXCEPTION_SPAN[] rgelt, ref uint pceltFetched) { Debug.Assert(celt == rgelt.Length); Debug.Assert(celt == _exceptionRegions.Count); for (int i = 0; i < _exceptionRegions.Count; i++) { rgelt[i] = new ShellInterop.ENC_EXCEPTION_SPAN() { id = (uint)i, methodToken = _exceptionRegions[i].MethodToken, tsPosition = _exceptionRegions[i].Span.ToVsTextSpan() }; } pceltFetched = celt; return VSConstants.S_OK; } /// <summary> /// Called by the debugger whenever it needs to determine a position of an active statement. /// E.g. the user clicks on a frame in a call stack. /// </summary> /// <remarks> /// Called when applying change, when setting current IP, a notification is received from /// <see cref="IDebugEncNotify.NotifyEncUpdateCurrentStatement"/>, etc. /// In addition this API is exposed on IDebugENC2 COM interface so it can be used anytime by other components. /// </remarks> public int GetCurrentActiveStatementPosition(uint vsId, VsTextSpan[] ptsNewPosition) { try { using (NonReentrantContext) { Debug.Assert(IsDebuggable); var session = _encService.EditSession; var ids = _activeStatementIds; // Can be called anytime, even outside of an edit/debug session. // We might not have an active statement available if PDB got out of sync with the source. ActiveStatementId id; if (session == null || ids == null || !ids.TryGetValue(vsId, out id)) { log.Write("GetCurrentActiveStatementPosition failed for AS {0}.", vsId); return VSConstants.E_FAIL; } Document document = _vsProject.Workspace.CurrentSolution.GetDocument(id.DocumentId); SourceText text = document.GetTextAsync(default(CancellationToken)).Result; // Try to get spans from the tracking service first. // We might get an imprecise result if the document analysis hasn't been finished yet and // the active statement has structurally changed, but that's ok. The user won't see an updated tag // for the statement until the analysis finishes anyways. TextSpan span; LinePositionSpan lineSpan; if (_trackingService.TryGetSpan(id, text, out span) && span.Length > 0) { lineSpan = text.Lines.GetLinePositionSpan(span); } else { var activeSpans = session.GetDocumentAnalysis(document).GetValue(default(CancellationToken)).ActiveStatements; if (activeSpans.IsDefault) { // The document has syntax errors and the tracking span is gone. log.Write("Position not available for AS {0} due to syntax errors", vsId); return VSConstants.E_FAIL; } lineSpan = activeSpans[id.Ordinal]; } ptsNewPosition[0] = lineSpan.ToVsTextSpan(); log.DebugWrite("AS position: {0} {1} {2}", vsId, lineSpan, session.BaseActiveStatements[id.DocumentId][id.Ordinal].Flags); return VSConstants.S_OK; } } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } /// <summary> /// Returns the state of the changes made to the source. /// The EnC manager calls this to determine whether there are any changes to the source /// and if so whether there are any rude edits. /// </summary> public int GetENCBuildState(ShellInterop.ENC_BUILD_STATE[] pENCBuildState) { try { using (NonReentrantContext) { Debug.Assert(pENCBuildState != null && pENCBuildState.Length == 1); // GetENCBuildState is called outside of edit session (at least) in following cases: // 1) when the debugger is determining whether a source file checksum matches the one in PDB. // 2) when the debugger is setting the next statement and a change is pending // See CDebugger::SetNextStatement(CTextPos* pTextPos, bool WarnOnFunctionChange): // // pENC2->ExitBreakState(); // >>> hr = GetCodeContextOfPosition(pTextPos, &pCodeContext, &pProgram, true, true); // pENC2->EnterBreakState(m_pSession, GetEncBreakReason()); // // The debugger seem to expect ENC_NOT_MODIFIED in these cases, otherwise errors occur. if (_changesApplied || _encService.EditSession == null) { _lastEditSessionSummary = ProjectAnalysisSummary.NoChanges; } else { // Fetch the latest snapshot of the project and get an analysis summary for any changes // made since the break mode was entered. var currentProject = _vsProject.Workspace.CurrentSolution.GetProject(_vsProject.Id); if (currentProject == null) { // If the project has yet to be loaded into the solution (which may be the case, // since they are loaded on-demand), then it stands to reason that it has not yet // been modified. // TODO (https://github.com/dotnet/roslyn/issues/1204): this check should be unnecessary. _lastEditSessionSummary = ProjectAnalysisSummary.NoChanges; log.Write($"Project '{_vsProject.DisplayName}' has not yet been loaded into the solution"); } else { _projectBeingEmitted = currentProject; _lastEditSessionSummary = GetProjectAnalysisSummary(_projectBeingEmitted); } _encService.EditSession.LogBuildState(_lastEditSessionSummary); } switch (_lastEditSessionSummary) { case ProjectAnalysisSummary.NoChanges: pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_NOT_MODIFIED; break; case ProjectAnalysisSummary.CompilationErrors: pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_COMPILE_ERRORS; break; case ProjectAnalysisSummary.RudeEdits: pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_NONCONTINUABLE_ERRORS; break; case ProjectAnalysisSummary.ValidChanges: case ProjectAnalysisSummary.ValidInsignificantChanges: // The debugger doesn't distinguish between these two. pENCBuildState[0] = ShellInterop.ENC_BUILD_STATE.ENC_APPLY_READY; break; default: throw ExceptionUtilities.Unreachable; } log.Write("EnC state of '{0}' queried: {1}{2}", _vsProject.DisplayName, pENCBuildState[0], _encService.EditSession != null ? "" : " (no session)"); return VSConstants.S_OK; } } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } private ProjectAnalysisSummary GetProjectAnalysisSummary(Project project) { if (!IsDebuggable) { return ProjectAnalysisSummary.NoChanges; } var cancellationToken = default(CancellationToken); return _encService.EditSession.GetProjectAnalysisSummaryAsync(project, cancellationToken).Result; } public int ExitBreakStateOnPE() { try { using (NonReentrantContext) { // The debugger calls Exit without previously calling Enter if the project's MVID isn't available. if (!IsDebuggable) { return VSConstants.S_OK; } log.Write("Exit Break Mode: project '{0}'", _vsProject.DisplayName); // EnC service is global, but the debugger calls this for each project. // Avoid ending the edit session if it has already been ended. if (_encService.EditSession != null) { Debug.Assert(s_breakStateProjectCount == s_debugStateProjectCount); _encService.OnBeforeDebuggingStateChanged(DebuggingState.Break, DebuggingState.Run); _encService.EditSession.LogEditSession(s_encDebuggingSessionInfo); _encService.EndEditSession(); _trackingService.EndTracking(); s_readOnlyDocumentTracker.UpdateWorkspaceDocuments(); _trackingService.TrackingSpansChanged -= TrackingSpansChanged; } _exceptionRegions.Clear(); _activeMethods.Clear(); _activeStatementIds.Clear(); s_breakStateProjectCount--; Debug.Assert(s_breakStateProjectCount >= 0); _changesApplied = false; _diagnosticProvider.ClearDiagnostics( new EncErrorId(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.EmitErrorId), _vsProject.Workspace.CurrentSolution, _vsProject.Id, _documentsWithEmitError); _documentsWithEmitError = ImmutableArray<DocumentId>.Empty; } // HResult ignored by the debugger return VSConstants.S_OK; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } public unsafe int BuildForEnc(object pUpdatePE) { try { log.Write("Applying changes to {0}", _vsProject.DisplayName); Debug.Assert(_encService.EditSession != null); Debug.Assert(!_encService.EditSession.StoppedAtException); // Non-debuggable project has no changes. Debug.Assert(IsDebuggable); if (_changesApplied) { log.Write("Changes already applied to {0}, can't apply again", _vsProject.DisplayName); throw ExceptionUtilities.Unreachable; } // The debugger always calls GetENCBuildState right before BuildForEnc. Debug.Assert(_projectBeingEmitted != null); Debug.Assert(_lastEditSessionSummary == GetProjectAnalysisSummary(_projectBeingEmitted)); // The debugger should have called GetENCBuildState before calling BuildForEnc. // Unfortunately, there is no way how to tell the debugger that the changes were not significant, // so we'll to emit an empty delta. See bug 839558. Debug.Assert(_lastEditSessionSummary == ProjectAnalysisSummary.ValidInsignificantChanges || _lastEditSessionSummary == ProjectAnalysisSummary.ValidChanges); var updater = (IDebugUpdateInMemoryPE2)pUpdatePE; if (_committedBaseline == null) { var hr = MarshalPdbReader(updater, out _pdbReaderObjAsStream); if (hr != VSConstants.S_OK) { return hr; } _committedBaseline = EmitBaseline.CreateInitialBaseline(_metadata, GetBaselineEncDebugInfo); } // ISymUnmanagedReader can only be accessed from an MTA thread, // so dispatch it to one of thread pool threads, which are MTA. var emitTask = Task.Factory.SafeStartNew(EmitProjectDelta, CancellationToken.None, TaskScheduler.Default); Deltas delta; using (NonReentrantContext) { delta = emitTask.Result; if (delta == null) { // Non-fatal Watson has already been reported by the emit task return VSConstants.E_FAIL; } } var errorId = new EncErrorId(_encService.DebuggingSession, EditAndContinueDiagnosticUpdateSource.EmitErrorId); // Clear diagnostics, in case the project was built before and failed due to errors. _diagnosticProvider.ClearDiagnostics(errorId, _projectBeingEmitted.Solution, _vsProject.Id, _documentsWithEmitError); if (!delta.EmitResult.Success) { var errors = delta.EmitResult.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error); _documentsWithEmitError = _diagnosticProvider.ReportDiagnostics(errorId, _projectBeingEmitted.Solution, _vsProject.Id, errors); _encService.EditSession.LogEmitProjectDeltaErrors(errors.Select(e => e.Id)); return VSConstants.E_FAIL; } _documentsWithEmitError = ImmutableArray<DocumentId>.Empty; SetFileUpdates(updater, delta.LineEdits); updater.SetDeltaIL(delta.IL.Value, (uint)delta.IL.Value.Length); updater.SetDeltaPdb(SymUnmanagedStreamFactory.CreateStream(delta.Pdb.Stream)); updater.SetRemapMethods(delta.Pdb.UpdatedMethods, (uint)delta.Pdb.UpdatedMethods.Length); updater.SetDeltaMetadata(delta.Metadata.Bytes, (uint)delta.Metadata.Bytes.Length); _pendingBaseline = delta.EmitResult.Baseline; #if DEBUG fixed (byte* deltaMetadataPtr = &delta.Metadata.Bytes[0]) { var reader = new System.Reflection.Metadata.MetadataReader(deltaMetadataPtr, delta.Metadata.Bytes.Length); var moduleDef = reader.GetModuleDefinition(); log.DebugWrite("Gen {0}: MVID={1}, BaseId={2}, EncId={3}", moduleDef.Generation, reader.GetGuid(moduleDef.Mvid), reader.GetGuid(moduleDef.BaseGenerationId), reader.GetGuid(moduleDef.GenerationId)); } #endif return VSConstants.S_OK; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } private unsafe void SetFileUpdates( IDebugUpdateInMemoryPE2 updater, List<KeyValuePair<DocumentId, ImmutableArray<LineChange>>> edits) { int totalEditCount = edits.Sum(e => e.Value.Length); if (totalEditCount == 0) { return; } var lineUpdates = new LINEUPDATE[totalEditCount]; fixed (LINEUPDATE* lineUpdatesPtr = lineUpdates) { int index = 0; var fileUpdates = new FILEUPDATE[edits.Count]; for (int f = 0; f < fileUpdates.Length; f++) { var documentId = edits[f].Key; var deltas = edits[f].Value; fileUpdates[f].FileName = _vsProject.GetDocumentOrAdditionalDocument(documentId).FilePath; fileUpdates[f].LineUpdateCount = (uint)deltas.Length; fileUpdates[f].LineUpdates = (IntPtr)(lineUpdatesPtr + index); for (int l = 0; l < deltas.Length; l++) { lineUpdates[index + l].Line = (uint)deltas[l].OldLine; lineUpdates[index + l].UpdatedLine = (uint)deltas[l].NewLine; } index += deltas.Length; } // The updater makes a copy of all data, we can release the buffer after the call. updater.SetFileUpdates(fileUpdates, (uint)fileUpdates.Length); } } private Deltas EmitProjectDelta() { Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA); var emitTask = _encService.EditSession.EmitProjectDeltaAsync(_projectBeingEmitted, _committedBaseline, default(CancellationToken)); return emitTask.Result; } /// <summary> /// Returns EnC debug information for initial version of the specified method. /// </summary> /// <exception cref="InvalidDataException">The debug information data is corrupt or can't be retrieved from the debugger.</exception> private EditAndContinueMethodDebugInformation GetBaselineEncDebugInfo(MethodDefinitionHandle methodHandle) { Debug.Assert(Thread.CurrentThread.GetApartmentState() == ApartmentState.MTA); if (_pdbReader == null) { // Unmarshal the symbol reader (being marshalled cross thread from STA -> MTA). Debug.Assert(_pdbReaderObjAsStream != IntPtr.Zero); object pdbReaderObjMta; var exception = Marshal.GetExceptionForHR(NativeMethods.GetObjectForStream(_pdbReaderObjAsStream, out pdbReaderObjMta)); if (exception != null) { // likely a bug in the compiler/debugger FatalError.ReportWithoutCrash(exception); throw new InvalidDataException(exception.Message, exception); } _pdbReaderObjAsStream = IntPtr.Zero; _pdbReader = (ISymUnmanagedReader3)pdbReaderObjMta; } int methodToken = MetadataTokens.GetToken(methodHandle); byte[] debugInfo; try { debugInfo = _pdbReader.GetCustomDebugInfoBytes(methodToken, methodVersion: 1); } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) // likely a bug in the compiler/debugger { throw new InvalidDataException(e.Message, e); } try { ImmutableArray<byte> localSlots, lambdaMap; if (debugInfo != null) { localSlots = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(debugInfo, CustomDebugInfoKind.EditAndContinueLocalSlotMap); lambdaMap = CustomDebugInfoReader.TryGetCustomDebugInfoRecord(debugInfo, CustomDebugInfoKind.EditAndContinueLambdaMap); } else { localSlots = lambdaMap = default(ImmutableArray<byte>); } return EditAndContinueMethodDebugInformation.Create(localSlots, lambdaMap); } catch (InvalidOperationException e) when (FatalError.ReportWithoutCrash(e)) // likely a bug in the compiler/debugger { // TODO: CustomDebugInfoReader should throw InvalidDataException throw new InvalidDataException(e.Message, e); } } public int EncApplySucceeded(int hrApplyResult) { try { log.Write("Change applied to {0}", _vsProject.DisplayName); Debug.Assert(IsDebuggable); Debug.Assert(_encService.EditSession != null); Debug.Assert(!_encService.EditSession.StoppedAtException); Debug.Assert(_pendingBaseline != null); // Since now on until exiting the break state, we consider the changes applied and the project state should be NoChanges. _changesApplied = true; _committedBaseline = _pendingBaseline; _pendingBaseline = null; return VSConstants.S_OK; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } /// <summary> /// Called when changes are being applied. /// </summary> /// <param name="exceptionRegionId"> /// The value of <see cref="ShellInterop.ENC_EXCEPTION_SPAN.id"/>. /// Set by <see cref="GetExceptionSpans(uint, ShellInterop.ENC_EXCEPTION_SPAN[], ref uint)"/> to the index into <see cref="_exceptionRegions"/>. /// </param> /// <param name="ptsNewPosition">Output value holder.</param> public int GetCurrentExceptionSpanPosition(uint exceptionRegionId, VsTextSpan[] ptsNewPosition) { try { using (NonReentrantContext) { Debug.Assert(IsDebuggable); Debug.Assert(_encService.EditSession != null); Debug.Assert(!_encService.EditSession.StoppedAtException); Debug.Assert(ptsNewPosition.Length == 1); var exceptionRegion = _exceptionRegions[(int)exceptionRegionId]; var session = _encService.EditSession; var asid = _activeStatementIds[exceptionRegion.ActiveStatementId]; var document = _projectBeingEmitted.GetDocument(asid.DocumentId); var analysis = session.GetDocumentAnalysis(document).GetValue(default(CancellationToken)); var regions = analysis.ExceptionRegions; // the method shouldn't be called in presence of errors: Debug.Assert(!analysis.HasChangesAndErrors); Debug.Assert(!regions.IsDefault); // Absence of rude edits guarantees that the exception regions around AS haven't semantically changed. // Only their spans might have changed. ptsNewPosition[0] = regions[asid.Ordinal][exceptionRegion.Ordinal].ToVsTextSpan(); } return VSConstants.S_OK; } catch (Exception e) when (FatalError.ReportWithoutCrash(e)) { return VSConstants.E_FAIL; } } private static int MarshalPdbReader(IDebugUpdateInMemoryPE2 updater, out IntPtr pdbReaderPointer) { // ISymUnmanagedReader can only be accessed from an MTA thread, however, we need // fetch the IUnknown instance (call IENCSymbolReaderProvider.GetSymbolReader) here // in the STA. To further complicate things, we need to return synchronously from // this method. Waiting for the MTA thread to complete so we can return synchronously // blocks the STA thread, so we need to make sure the CLR doesn't try to marshal // ISymUnmanagedReader calls made in an MTA back to the STA for execution (if this // happens we'll be deadlocked). We'll use CoMarshalInterThreadInterfaceInStream to // achieve this. First, we'll marshal the object in a Stream and pass a Stream pointer // over to the MTA. In the MTA, we'll get the Stream from the pointer and unmarshal // the object. The reader object was originally created on an MTA thread, and the // instance we retrieved in the STA was a proxy. When we unmarshal the Stream in the // MTA, it "unwraps" the proxy, allowing us to directly call the implementation. // Another way to achieve this would be for the symbol reader to implement IAgileObject, // but the symbol reader we use today does not. If that changes, we should consider // removing this marshal/unmarshal code. IENCDebugInfo debugInfo; updater.GetENCDebugInfo(out debugInfo); var symbolReaderProvider = (IENCSymbolReaderProvider)debugInfo; object pdbReaderObjSta; symbolReaderProvider.GetSymbolReader(out pdbReaderObjSta); int hr = NativeMethods.GetStreamForObject(pdbReaderObjSta, out pdbReaderPointer); Marshal.ReleaseComObject(pdbReaderObjSta); return hr; } #region Testing #if DEBUG // Fault injection: // If set we'll fail to read MVID of specified projects to test error reporting. internal static ImmutableArray<string> InjectMvidReadingFailure; private void InjectFault_MvidRead() { if (!InjectMvidReadingFailure.IsDefault && InjectMvidReadingFailure.Contains(_vsProject.DisplayName)) { throw new IOException("Fault injection"); } } #else [Conditional("DEBUG")] private void InjectFault_MvidRead() { } #endif #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.Hashing.Algorithms.Tests { public abstract class HmacTests { // RFC2202 defines the test vectors for HMACMD5 and HMACSHA1 // RFC4231 defines the test vectors for HMACSHA{224,256,384,512} // They share the same datasets for cases 1-5, but cases 6 and 7 differ. private readonly byte[][] _testKeys; private readonly byte[][] _testData; protected HmacTests(byte[][] testKeys, byte[][] testData) { _testKeys = testKeys; _testData = testData; } protected abstract HMAC Create(); protected abstract HashAlgorithm CreateHashAlgorithm(); protected abstract int BlockSize { get; } protected void VerifyHmac( int testCaseId, string digest, int truncateSize = -1) { byte[] digestBytes = ByteUtils.HexToByteArray(digest); byte[] computedDigest; using (HMAC hmac = Create()) { Assert.True(hmac.HashSize > 0); byte[] key = (byte[])_testKeys[testCaseId].Clone(); hmac.Key = key; // make sure the getter returns different objects each time Assert.NotSame(key, hmac.Key); Assert.NotSame(hmac.Key, hmac.Key); // make sure the setter didn't cache the exact object we passed in key[0] = (byte)(key[0] + 1); Assert.NotEqual<byte>(key, hmac.Key); computedDigest = hmac.ComputeHash(_testData[testCaseId]); } if (truncateSize != -1) { byte[] tmp = new byte[truncateSize]; Array.Copy(computedDigest, 0, tmp, 0, truncateSize); computedDigest = tmp; } Assert.Equal(digestBytes, computedDigest); } protected void VerifyHmac_KeyAlreadySet( HMAC hmac, int testCaseId, string digest) { byte[] digestBytes = ByteUtils.HexToByteArray(digest); byte[] computedDigest; computedDigest = hmac.ComputeHash(_testData[testCaseId]); Assert.Equal(digestBytes, computedDigest); } protected void VerifyHmacRfc2104_2() { // Ensure that keys shorter than the threshold don't get altered. using (HMAC hmac = Create()) { byte[] key = new byte[BlockSize]; hmac.Key = key; byte[] retrievedKey = hmac.Key; Assert.Equal<byte>(key, retrievedKey); } // Ensure that keys longer than the threshold are adjusted via Rfc2104 Section 2. using (HMAC hmac = Create()) { byte[] overSizedKey = new byte[BlockSize + 1]; hmac.Key = overSizedKey; byte[] actualKey = hmac.Key; byte[] expectedKey = CreateHashAlgorithm().ComputeHash(overSizedKey); Assert.Equal<byte>(expectedKey, actualKey); // Also ensure that the hashing operation uses the adjusted key. byte[] data = new byte[100]; hmac.Key = expectedKey; byte[] expectedHash = hmac.ComputeHash(data); hmac.Key = overSizedKey; byte[] actualHash = hmac.ComputeHash(data); Assert.Equal<byte>(expectedHash, actualHash); } } [Fact] public void InvalidInput_Null() { using (HMAC hash = Create()) { AssertExtensions.Throws<ArgumentNullException>("buffer", () => hash.ComputeHash((byte[])null)); AssertExtensions.Throws<ArgumentNullException>("buffer", () => hash.ComputeHash(null, 0, 0)); Assert.Throws<NullReferenceException>(() => hash.ComputeHash((Stream)null)); } } [Fact] public void InvalidInput_NegativeOffset() { using (HMAC hash = Create()) { AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => hash.ComputeHash(Array.Empty<byte>(), -1, 0)); } } [Fact] public void InvalidInput_NegativeCount() { using (HMAC hash = Create()) { AssertExtensions.Throws<ArgumentException>(null, () => hash.ComputeHash(Array.Empty<byte>(), 0, -1)); } } [Fact] public void InvalidInput_TooBigOffset() { using (HMAC hash = Create()) { AssertExtensions.Throws<ArgumentException>(null, () => hash.ComputeHash(Array.Empty<byte>(), 1, 0)); } } [Fact] public void InvalidInput_TooBigCount() { byte[] nonEmpty = new byte[53]; using (HMAC hash = Create()) { AssertExtensions.Throws<ArgumentException>(null, () => hash.ComputeHash(nonEmpty, 0, nonEmpty.Length + 1)); AssertExtensions.Throws<ArgumentException>(null, () => hash.ComputeHash(nonEmpty, 1, nonEmpty.Length)); AssertExtensions.Throws<ArgumentException>(null, () => hash.ComputeHash(nonEmpty, 2, nonEmpty.Length - 1)); AssertExtensions.Throws<ArgumentException>(null, () => hash.ComputeHash(Array.Empty<byte>(), 0, 1)); } } [Fact] public void BoundaryCondition_Count0() { byte[] nonEmpty = new byte[53]; using (HMAC hash = Create()) { byte[] emptyHash = hash.ComputeHash(Array.Empty<byte>()); byte[] shouldBeEmptyHash = hash.ComputeHash(nonEmpty, nonEmpty.Length, 0); Assert.Equal(emptyHash, shouldBeEmptyHash); shouldBeEmptyHash = hash.ComputeHash(nonEmpty, 0, 0); Assert.Equal(emptyHash, shouldBeEmptyHash); nonEmpty[0] = 0xFF; nonEmpty[nonEmpty.Length - 1] = 0x77; shouldBeEmptyHash = hash.ComputeHash(nonEmpty, nonEmpty.Length, 0); Assert.Equal(emptyHash, shouldBeEmptyHash); shouldBeEmptyHash = hash.ComputeHash(nonEmpty, 0, 0); Assert.Equal(emptyHash, shouldBeEmptyHash); } } [Fact] public void OffsetAndCountRespected() { byte[] dataA = { 1, 1, 2, 3, 5, 8 }; byte[] dataB = { 0, 1, 1, 2, 3, 5, 8, 13 }; using (HMAC hash = Create()) { byte[] baseline = hash.ComputeHash(dataA); // Skip the 0 byte, and stop short of the 13. byte[] offsetData = hash.ComputeHash(dataB, 1, dataA.Length); Assert.Equal(baseline, offsetData); } } } }
using System; using System.Xml; using System.Collections.Generic; using System.IO; using System.Reflection; using Ecosim.SceneData.Action; namespace Ecosim.SceneData { /** * Data values are (optionally) calculated by a function in the ConversionAction, * else we have a Calculation with other calculations */ public class CalculatedData : Data { public class Calculation { public class ParameterCalculation { public const string XML_ELEMENT = "paramcalc"; public string paramName; public float multiplier; public Data data; private int _year = -1; public int year { set { if (value != _year) { _year = value; // Update the data value if (scene == null) { scene = EditorCtrl.self.scene; } // Get the data by the year if (year > -1) { data = scene.progression.GetData (paramName, year); } else { data = scene.progression.GetData (paramName); } } } get { return _year; } } private Scene scene; public ParameterCalculation () { } public ParameterCalculation (string paramName) { this.paramName = paramName; } public static ParameterCalculation Load (XmlTextReader reader, Scene scene) { ParameterCalculation result = new ParameterCalculation(); result.paramName = reader.GetAttribute("parameter"); result.multiplier = float.Parse(reader.GetAttribute("multiplier")); IOUtil.ReadUntilEndElement(reader, XML_ELEMENT); return result; } public void Save(XmlTextWriter writer, Scene scene) { writer.WriteStartElement(XML_ELEMENT); writer.WriteAttributeString ("parameter", paramName); writer.WriteAttributeString ("multiplier", multiplier.ToString()); writer.WriteEndElement(); } public void UpdateReferences (Scene scene) { this.scene = scene; if (year != -1) { data = scene.progression.GetData (paramName, year); } else { data = scene.progression.GetData (paramName); } } } public const string XML_ELEMENT = "calcrule"; public string paramName; public int offset; public ParameterCalculation[] calculations; public CalculatedData data; public Calculation () { calculations = new ParameterCalculation[0]; } public Calculation (string paramName) { this.paramName = paramName; calculations = new ParameterCalculation[0]; } public static Calculation Load (XmlTextReader reader, Scene scene) { Calculation result = new Calculation(); result.paramName = reader.GetAttribute ("parameter"); result.offset = int.Parse (reader.GetAttribute ("offset").ToLower()); List<ParameterCalculation> calculations = new List<ParameterCalculation>(); if (!reader.IsEmptyElement) { while (reader.Read()) { XmlNodeType nType = reader.NodeType; if ((nType == XmlNodeType.Element) && (reader.Name.ToLower () == ParameterCalculation.XML_ELEMENT)) { ParameterCalculation pr = ParameterCalculation.Load (reader, scene); if (pr != null) { calculations.Add (pr); } } else if ((nType == XmlNodeType.EndElement) && (reader.Name.ToLower () == XML_ELEMENT)) { break; } } } result.calculations = calculations.ToArray(); return result; } public void Save(XmlTextWriter writer, Scene scene) { writer.WriteStartElement(XML_ELEMENT); writer.WriteAttributeString ("parameter", paramName); writer.WriteAttributeString ("offset", offset.ToString()); foreach (ParameterCalculation p in calculations) { p.Save (writer, scene); } writer.WriteEndElement(); } public void UpdateReferences (Scene scene) { data = scene.progression.GetData <CalculatedData> (paramName); data.calculation = this; foreach (ParameterCalculation p in calculations) { p.UpdateReferences (scene); } } public static void Save (string path, Calculation[] calculations, Scene scene) { Directory.CreateDirectory (path); XmlTextWriter writer = new XmlTextWriter (path + "calculations.xml", System.Text.Encoding.UTF8); writer.WriteStartDocument (true); writer.WriteStartElement("calculations"); foreach (Calculation c in calculations) { c.Save (writer, scene); } writer.WriteEndElement (); writer.WriteEndDocument (); writer.Close(); } public static Calculation[] LoadAll (string path, Scene scene) { List<Calculation> list = new List<Calculation>(); string url = path + "calculations.xml"; if (File.Exists (url)) { XmlTextReader reader = new XmlTextReader (new System.IO.StreamReader (url)); try { while (reader.Read ()) { XmlNodeType nType = reader.NodeType; if ((nType == XmlNodeType.Element) && (reader.Name.ToLower() == Calculation.XML_ELEMENT)) { Calculation c = Calculation.Load (reader, scene); if (c != null) list.Add (c); } } } finally { reader.Close (); } } return list.ToArray(); } } public CalculatedData (Scene scene) : base (scene) { } public CalculatedData (Scene scene, string name) : base(scene) { this.name = name; } private int _year = -1; public int year { set { if (value != _year) { _year = value; foreach (Calculation.ParameterCalculation pc in calculation.calculations) { pc.year = year; } } } get { return _year; } } private Calculation _calculation; public Calculation calculation { get { if (_calculation == null) { foreach (Calculation c in EditorCtrl.self.scene.calculations) { if (c.paramName == this.name) { c.data = this; calculation = c; break; } } } return _calculation; } set { _calculation = value; } } private readonly string name; private MethodInfo getValueMI; private ConversionAction.GetFn getFn; private bool retrievedGetFn; public override void Save (BinaryWriter writer, Progression progression) { writer.Write ("CalculatedData"); writer.Write (width); writer.Write (height); writer.Write (name); } static CalculatedData LoadInternal (BinaryReader reader, Progression progression) { int width = reader.ReadInt32 (); int height = reader.ReadInt32 (); string name = reader.ReadString (); EnforceValidSize (progression.scene, width, height); CalculatedData result = new CalculatedData (progression.scene, name); return result; } /** * Sets all values in bitmap to zero */ public override void Clear () { // We use a warning instead of an exception because we don't always know we're trying to adjust // a calculated data //throw new System.NotSupportedException("operation not supported on calculated data"); Log.LogWarning ("Operation not supported on calculated data"); } /** * set data value val at x, y */ public override void Set (int x, int y, int val) { // We use a warning instead of an exception because we don't always know we're trying to adjust // a calculated data. //throw new System.NotSupportedException ("Can't set values on calculated data"); Log.LogWarning ("Can't set values on calculated data"); } public override int Get (int x, int y) { // Check if we need to find to getFn if (getFn == null && !retrievedGetFn) { retrievedGetFn = true; if (scene.progression.conversionHandler != null) { getFn = scene.progression.conversionHandler.GetDataDelegate (name); /*if (getFn == null) { throw new System.NotSupportedException("no valid function '" + name + "' defined in conversion action."); }*/ } } // We have a GetFn delegate found in the scripts if (getFn != null) { try { return getFn(x, y); } catch (TargetException te) { Log.LogException (te); getFn = null; return 0; } } else { // We'll handle the combined data via the created rules if (calculation == null) { UnityEngine.Debug.LogError ("No calculation found in " + this.name + "(" + this.GetHashCode () + ")"); return 0; } float calculatedValue = (float)calculation.offset; foreach (Calculation.ParameterCalculation p in calculation.calculations) { if (p.data != null) { int dataVal = p.data.Get (x, y); if (dataVal > 0) { calculatedValue += (float)dataVal * p.multiplier; } } } return UnityEngine.Mathf.Clamp ((int)calculatedValue, GetMin(), GetMax()); } } public override int GetMin() { return 0; } public override int GetMax() { return 255; } public override Data CloneAndResize(Progression targetProgression, int offsetX, int offsetY) { return new CalculatedData (targetProgression.scene, name); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Net.Sockets; using System.Net.Test.Common; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.NetworkInformation.Tests { public class NetworkInterfaceBasicTest { private readonly ITestOutputHelper _log; public NetworkInterfaceBasicTest() { _log = TestLogging.GetInstance(); } // dotnet: /d/git/corefx/src/Native/Unix/Common/pal_safecrt.h:47: errno_t memcpy_s(void *, size_t, const void *, size_t): Assertion `sizeInBytes >= count' failed. [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/dotnet/corefx/issues/15513 public void BasicTest_GetNetworkInterfaces_AtLeastOne() { Assert.NotEqual<int>(0, NetworkInterface.GetAllNetworkInterfaces().Length); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Not all APIs are supported on Linux and OSX public void BasicTest_AccessInstanceProperties_NoExceptions() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("- NetworkInterface -"); _log.WriteLine("Name: " + nic.Name); _log.WriteLine("Description: " + nic.Description); _log.WriteLine("ID: " + nic.Id); _log.WriteLine("IsReceiveOnly: " + nic.IsReceiveOnly); _log.WriteLine("Type: " + nic.NetworkInterfaceType); _log.WriteLine("Status: " + nic.OperationalStatus); _log.WriteLine("Speed: " + nic.Speed); // Validate NIC speed overflow. // We've found that certain WiFi adapters will return speed of -1 when not connected. // We've found that Wi-Fi Direct Virtual Adapters return speed of -1 even when up. Assert.InRange(nic.Speed, -1, long.MaxValue); _log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast); _log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress()); } } // dotnet: /d/git/corefx/src/Native/Unix/Common/pal_safecrt.h:47: errno_t memcpy_s(void *, size_t, const void *, size_t): Assertion `sizeInBytes >= count' failed. [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/dotnet/corefx/issues/15513 [PlatformSpecific(TestPlatforms.Linux)] // Some APIs are not supported on Linux public void BasicTest_AccessInstanceProperties_NoExceptions_Linux() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("- NetworkInterface -"); _log.WriteLine("Name: " + nic.Name); string description = nic.Description; Assert.False(string.IsNullOrEmpty(description), "NetworkInterface.Description should not be null or empty."); _log.WriteLine("Description: " + description); string id = nic.Id; Assert.False(string.IsNullOrEmpty(id), "NetworkInterface.Id should not be null or empty."); _log.WriteLine("ID: " + id); Assert.Throws<PlatformNotSupportedException>(() => nic.IsReceiveOnly); _log.WriteLine("Type: " + nic.NetworkInterfaceType); _log.WriteLine("Status: " + nic.OperationalStatus); try { _log.WriteLine("Speed: " + nic.Speed); Assert.InRange(nic.Speed, -1, long.MaxValue); } // We cannot guarantee this works on all devices. catch (PlatformNotSupportedException pnse) { _log.WriteLine(pnse.ToString()); } _log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast); _log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress()); } } [Fact] [PlatformSpecific(TestPlatforms.OSX)] // Some APIs are not supported on OSX public void BasicTest_AccessInstanceProperties_NoExceptions_Osx() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("- NetworkInterface -"); _log.WriteLine("Name: " + nic.Name); string description = nic.Description; Assert.False(string.IsNullOrEmpty(description), "NetworkInterface.Description should not be null or empty."); _log.WriteLine("Description: " + description); string id = nic.Id; Assert.False(string.IsNullOrEmpty(id), "NetworkInterface.Id should not be null or empty."); _log.WriteLine("ID: " + id); Assert.Throws<PlatformNotSupportedException>(() => nic.IsReceiveOnly); _log.WriteLine("Type: " + nic.NetworkInterfaceType); _log.WriteLine("Status: " + nic.OperationalStatus); _log.WriteLine("Speed: " + nic.Speed); Assert.InRange(nic.Speed, 0, long.MaxValue); _log.WriteLine("SupportsMulticast: " + nic.SupportsMulticast); _log.WriteLine("GetPhysicalAddress(): " + nic.GetPhysicalAddress()); } } // dotnet: /d/git/corefx/src/Native/Unix/Common/pal_safecrt.h:47: errno_t memcpy_s(void *, size_t, const void *, size_t): Assertion `sizeInBytes >= count' failed. [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/dotnet/corefx/issues/15513 [Trait("IPv4", "true")] public void BasicTest_StaticLoopbackIndex_MatchesLoopbackNetworkInterface() { Assert.True(Capability.IPv4Support()); _log.WriteLine("Loopback IPv4 index: " + NetworkInterface.LoopbackInterfaceIndex); foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { foreach (UnicastIPAddressInformation unicast in nic.GetIPProperties().UnicastAddresses) { if (unicast.Address.Equals(IPAddress.Loopback)) { Assert.Equal<int>(nic.GetIPProperties().GetIPv4Properties().Index, NetworkInterface.LoopbackInterfaceIndex); return; // Only check IPv4 loopback } } } } // dotnet: /d/git/corefx/src/Native/Unix/Common/pal_safecrt.h:47: errno_t memcpy_s(void *, size_t, const void *, size_t): Assertion `sizeInBytes >= count' failed. [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/dotnet/corefx/issues/15513 [Trait("IPv4", "true")] public void BasicTest_StaticLoopbackIndex_ExceptionIfV4NotSupported() { Assert.True(Capability.IPv4Support()); _log.WriteLine("Loopback IPv4 index: " + NetworkInterface.LoopbackInterfaceIndex); } // dotnet: /d/git/corefx/src/Native/Unix/Common/pal_safecrt.h:47: errno_t memcpy_s(void *, size_t, const void *, size_t): Assertion `sizeInBytes >= count' failed. [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/dotnet/corefx/issues/15513 [Trait("IPv6", "true")] public void BasicTest_StaticIPv6LoopbackIndex_MatchesLoopbackNetworkInterface() { Assert.True(Capability.IPv6Support()); _log.WriteLine("Loopback IPv6 index: " + NetworkInterface.IPv6LoopbackInterfaceIndex); foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { foreach (UnicastIPAddressInformation unicast in nic.GetIPProperties().UnicastAddresses) { if (unicast.Address.Equals(IPAddress.IPv6Loopback)) { Assert.Equal<int>( nic.GetIPProperties().GetIPv6Properties().Index, NetworkInterface.IPv6LoopbackInterfaceIndex); return; // Only check IPv6 loopback. } } } } // dotnet: /d/git/corefx/src/Native/Unix/Common/pal_safecrt.h:47: errno_t memcpy_s(void *, size_t, const void *, size_t): Assertion `sizeInBytes >= count' failed. [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/dotnet/corefx/issues/15513 [Trait("IPv6", "true")] public void BasicTest_StaticIPv6LoopbackIndex_ExceptionIfV6NotSupported() { Assert.True(Capability.IPv6Support()); _log.WriteLine("Loopback IPv6 index: " + NetworkInterface.IPv6LoopbackInterfaceIndex); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Not all APIs are supported on Linux and OSX public void BasicTest_GetIPInterfaceStatistics_Success() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceStatistics stats = nic.GetIPStatistics(); _log.WriteLine("- Stats for : " + nic.Name); _log.WriteLine("BytesReceived: " + stats.BytesReceived); _log.WriteLine("BytesSent: " + stats.BytesSent); _log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded); _log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors); _log.WriteLine("IncomingUnknownProtocolPackets: " + stats.IncomingUnknownProtocolPackets); _log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived); _log.WriteLine("NonUnicastPacketsSent: " + stats.NonUnicastPacketsSent); _log.WriteLine("OutgoingPacketsDiscarded: " + stats.OutgoingPacketsDiscarded); _log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors); _log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength); _log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived); _log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent); } } // dotnet: /d/git/corefx/src/Native/Unix/Common/pal_safecrt.h:47: errno_t memcpy_s(void *, size_t, const void *, size_t): Assertion `sizeInBytes >= count' failed. [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/dotnet/corefx/issues/15513 [PlatformSpecific(TestPlatforms.Linux)] // Some APIs are not supported on Linux public void BasicTest_GetIPInterfaceStatistics_Success_Linux() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceStatistics stats = nic.GetIPStatistics(); _log.WriteLine("- Stats for : " + nic.Name); _log.WriteLine("BytesReceived: " + stats.BytesReceived); _log.WriteLine("BytesSent: " + stats.BytesSent); _log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded); _log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors); Assert.Throws<PlatformNotSupportedException>(() => stats.IncomingUnknownProtocolPackets); _log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived); Assert.Throws<PlatformNotSupportedException>(() => stats.NonUnicastPacketsSent); _log.WriteLine("OutgoingPacketsDiscarded: " + stats.OutgoingPacketsDiscarded); _log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors); _log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength); _log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived); _log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent); } } [Fact] [PlatformSpecific(TestPlatforms.OSX)] // Some APIs are not supported on OSX public void BasicTest_GetIPInterfaceStatistics_Success_OSX() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceStatistics stats = nic.GetIPStatistics(); _log.WriteLine("- Stats for : " + nic.Name); _log.WriteLine("BytesReceived: " + stats.BytesReceived); _log.WriteLine("BytesSent: " + stats.BytesSent); _log.WriteLine("IncomingPacketsDiscarded: " + stats.IncomingPacketsDiscarded); _log.WriteLine("IncomingPacketsWithErrors: " + stats.IncomingPacketsWithErrors); _log.WriteLine("IncomingUnknownProtocolPackets: " + stats.IncomingUnknownProtocolPackets); _log.WriteLine("NonUnicastPacketsReceived: " + stats.NonUnicastPacketsReceived); _log.WriteLine("NonUnicastPacketsSent: " + stats.NonUnicastPacketsSent); Assert.Throws<PlatformNotSupportedException>(() => stats.OutgoingPacketsDiscarded); _log.WriteLine("OutgoingPacketsWithErrors: " + stats.OutgoingPacketsWithErrors); _log.WriteLine("OutputQueueLength: " + stats.OutputQueueLength); _log.WriteLine("UnicastPacketsReceived: " + stats.UnicastPacketsReceived); _log.WriteLine("UnicastPacketsSent: " + stats.UnicastPacketsSent); } } // dotnet: /d/git/corefx/src/Native/Unix/Common/pal_safecrt.h:47: errno_t memcpy_s(void *, size_t, const void *, size_t): Assertion `sizeInBytes >= count' failed. [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/dotnet/corefx/issues/15513 public void BasicTest_GetIsNetworkAvailable_Success() { Assert.True(NetworkInterface.GetIsNetworkAvailable()); } // dotnet: /d/git/corefx/src/Native/Unix/Common/pal_safecrt.h:47: errno_t memcpy_s(void *, size_t, const void *, size_t): Assertion `sizeInBytes >= count' failed. [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/dotnet/corefx/issues/15513 [PlatformSpecific(~TestPlatforms.OSX)] [InlineData(false)] [InlineData(true)] public async Task NetworkInterface_LoopbackInterfaceIndex_MatchesReceivedPackets(bool ipv6) { using (var client = new Socket(SocketType.Dgram, ProtocolType.Udp)) using (var server = new Socket(SocketType.Dgram, ProtocolType.Udp)) { server.Bind(new IPEndPoint(ipv6 ? IPAddress.IPv6Loopback : IPAddress.Loopback, 0)); var serverEndPoint = (IPEndPoint)server.LocalEndPoint; Task<SocketReceiveMessageFromResult> receivedTask = server.ReceiveMessageFromAsync(new ArraySegment<byte>(new byte[1]), SocketFlags.None, serverEndPoint); while (!receivedTask.IsCompleted) { client.SendTo(new byte[] { 42 }, serverEndPoint); await Task.Delay(1); } Assert.Equal( (await receivedTask).PacketInformation.Interface, ipv6 ? NetworkInterface.IPv6LoopbackInterfaceIndex : NetworkInterface.LoopbackInterfaceIndex); } } } }
// 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.Collections.Generic; using System.Globalization; using System.Runtime.Serialization; namespace System { [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public abstract class StringComparer : IComparer, IEqualityComparer, IComparer<string>, IEqualityComparer<string> { private static readonly CultureAwareComparer s_invariantCulture = new CultureAwareComparer(CultureInfo.InvariantCulture, false); private static readonly CultureAwareComparer s_invariantCultureIgnoreCase = new CultureAwareComparer(CultureInfo.InvariantCulture, true); private static readonly OrdinalCaseSensitiveComparer s_ordinal = new OrdinalCaseSensitiveComparer(); private static readonly OrdinalIgnoreCaseComparer s_ordinalIgnoreCase = new OrdinalIgnoreCaseComparer(); public static StringComparer InvariantCulture { get { return s_invariantCulture; } } public static StringComparer InvariantCultureIgnoreCase { get { return s_invariantCultureIgnoreCase; } } public static StringComparer CurrentCulture { get { return new CultureAwareComparer(CultureInfo.CurrentCulture, false); } } public static StringComparer CurrentCultureIgnoreCase { get { return new CultureAwareComparer(CultureInfo.CurrentCulture, true); } } public static StringComparer Ordinal { get { return s_ordinal; } } public static StringComparer OrdinalIgnoreCase { get { return s_ordinalIgnoreCase; } } // Convert a StringComparison to a StringComparer public static StringComparer FromComparison(StringComparison comparisonType) { switch (comparisonType) { case StringComparison.CurrentCulture: return CurrentCulture; case StringComparison.CurrentCultureIgnoreCase: return CurrentCultureIgnoreCase; case StringComparison.InvariantCulture: return InvariantCulture; case StringComparison.InvariantCultureIgnoreCase: return InvariantCultureIgnoreCase; case StringComparison.Ordinal: return Ordinal; case StringComparison.OrdinalIgnoreCase: return OrdinalIgnoreCase; default: throw new ArgumentException(SR.NotSupported_StringComparison, nameof(comparisonType)); } } public static StringComparer Create(CultureInfo culture, bool ignoreCase) { if (culture == null) { throw new ArgumentNullException(nameof(culture)); } return new CultureAwareComparer(culture, ignoreCase); } public int Compare(object x, object y) { if (x == y) return 0; if (x == null) return -1; if (y == null) return 1; String sa = x as String; if (sa != null) { String sb = y as String; if (sb != null) { return Compare(sa, sb); } } IComparable ia = x as IComparable; if (ia != null) { return ia.CompareTo(y); } throw new ArgumentException(SR.Argument_ImplementIComparable); } public new bool Equals(Object x, Object y) { if (x == y) return true; if (x == null || y == null) return false; String sa = x as String; if (sa != null) { String sb = y as String; if (sb != null) { return Equals(sa, sb); } } return x.Equals(y); } public int GetHashCode(object obj) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } string s = obj as string; if (s != null) { return GetHashCode(s); } return obj.GetHashCode(); } public abstract int Compare(String x, String y); public abstract bool Equals(String x, String y); public abstract int GetHashCode(string obj); } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public sealed class CultureAwareComparer : StringComparer { private readonly CompareInfo _compareInfo; // Do not rename (binary serialization) private readonly bool _ignoreCase; // Do not rename (binary serialization) internal CultureAwareComparer(CultureInfo culture, bool ignoreCase) { _compareInfo = culture.CompareInfo; _ignoreCase = ignoreCase; } private CompareOptions Options => _ignoreCase ? CompareOptions.IgnoreCase : CompareOptions.None; public override int Compare(string x, string y) { if (object.ReferenceEquals(x, y)) return 0; if (x == null) return -1; if (y == null) return 1; return _compareInfo.Compare(x, y, Options); } public override bool Equals(string x, string y) { if (object.ReferenceEquals(x, y)) return true; if (x == null || y == null) return false; return _compareInfo.Compare(x, y, Options) == 0; } public override int GetHashCode(string obj) { if (obj == null) { throw new ArgumentNullException(nameof(obj)); } return _compareInfo.GetHashCodeOfString(obj, Options); } // Equals method for the comparer itself. public override bool Equals(object obj) { CultureAwareComparer comparer = obj as CultureAwareComparer; return comparer != null && _ignoreCase == comparer._ignoreCase && _compareInfo.Equals(comparer._compareInfo); } public override int GetHashCode() { int hashCode = _compareInfo.GetHashCode(); return _ignoreCase ? ~hashCode : hashCode; } } [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public class OrdinalComparer : StringComparer { private readonly bool _ignoreCase; // Do not rename (binary serialization) internal OrdinalComparer(bool ignoreCase) { _ignoreCase = ignoreCase; } public override int Compare(string x, string y) { if (ReferenceEquals(x, y)) return 0; if (x == null) return -1; if (y == null) return 1; if (_ignoreCase) { return string.Compare(x, y, StringComparison.OrdinalIgnoreCase); } return string.CompareOrdinal(x, y); } public override bool Equals(string x, string y) { if (ReferenceEquals(x, y)) return true; if (x == null || y == null) return false; if (_ignoreCase) { if (x.Length != y.Length) { return false; } return (string.Compare(x, y, StringComparison.OrdinalIgnoreCase) == 0); } return x.Equals(y); } public override int GetHashCode(string obj) { if (obj == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj); } if (_ignoreCase) { return TextInfo.GetHashCodeOrdinalIgnoreCase(obj); } return obj.GetHashCode(); } // Equals method for the comparer itself. public override bool Equals(object obj) { OrdinalComparer comparer = obj as OrdinalComparer; if (comparer == null) { return false; } return (this._ignoreCase == comparer._ignoreCase); } public override int GetHashCode() { int hashCode = nameof(OrdinalComparer).GetHashCode(); return _ignoreCase ? (~hashCode) : hashCode; } } [Serializable] internal sealed class OrdinalCaseSensitiveComparer : OrdinalComparer, ISerializable { public OrdinalCaseSensitiveComparer() : base(false) { } public override int Compare(string x, string y) => string.CompareOrdinal(x, y); public override bool Equals(string x, string y) => string.Equals(x, y); public override int GetHashCode(string obj) { if (obj == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj); } return obj.GetHashCode(); } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.SetType(typeof(OrdinalComparer)); info.AddValue("_ignoreCase", false); } } [Serializable] internal sealed class OrdinalIgnoreCaseComparer : OrdinalComparer, ISerializable { public OrdinalIgnoreCaseComparer() : base(true) { } public override int Compare(string x, string y) => string.Compare(x, y, StringComparison.OrdinalIgnoreCase); public override bool Equals(string x, string y) => string.Equals(x, y, StringComparison.OrdinalIgnoreCase); public override int GetHashCode(string obj) { if (obj == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.obj); } return TextInfo.GetHashCodeOrdinalIgnoreCase(obj); } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.SetType(typeof(OrdinalComparer)); info.AddValue("_ignoreCase", true); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace JavaJanitor.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Numerics; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Microsoft.PythonTools.DkmDebugger.Proxies; using Microsoft.PythonTools.DkmDebugger.Proxies.Structs; using Microsoft.PythonTools.Parsing; using Microsoft.PythonTools.Parsing.Ast; using Microsoft.VisualStudio.Debugger; using Microsoft.VisualStudio.Debugger.CallStack; using Microsoft.VisualStudio.Debugger.Evaluation; namespace Microsoft.PythonTools.DkmDebugger { internal class ExpressionEvaluator : DkmDataItem { // Value of this constant must always remain in sync with DebuggerHelper/trace.cpp. private const int ExpressionEvaluationBufferSize = 0x1000; private const int MaxDebugChildren = 1000; private const int ExpressionEvaluationTimeout = 3000; // ms private readonly DkmProcess _process; private readonly UInt64Proxy _evalLoopThreadId, _evalLoopFrame, _evalLoopResult, _evalLoopExcType, _evalLoopExcValue, _evalLoopExcStr; private readonly UInt32Proxy _evalLoopSEHCode; private readonly CStringProxy _evalLoopInput; public ExpressionEvaluator(DkmProcess process) { _process = process; var pyrtInfo = process.GetPythonRuntimeInfo(); _evalLoopThreadId = pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<UInt64Proxy>("evalLoopThreadId"); _evalLoopFrame = pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<UInt64Proxy>("evalLoopFrame"); _evalLoopResult = pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<UInt64Proxy>("evalLoopResult"); _evalLoopExcType = pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<UInt64Proxy>("evalLoopExcType"); _evalLoopExcValue = pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<UInt64Proxy>("evalLoopExcValue"); _evalLoopExcStr = pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<UInt64Proxy>("evalLoopExcStr"); _evalLoopSEHCode = pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<UInt32Proxy>("evalLoopSEHCode"); _evalLoopInput = pyrtInfo.DLLs.DebuggerHelper.GetExportedStaticVariable<CStringProxy>("evalLoopInput"); LocalComponent.CreateRuntimeDllExportedFunctionBreakpoint(pyrtInfo.DLLs.DebuggerHelper, "OnEvalComplete", OnEvalComplete, enable: true); } private interface IPythonEvaluationResult { List<DkmEvaluationResult> GetChildren(ExpressionEvaluator exprEval, DkmEvaluationResult result, DkmInspectionContext inspectionContext); } private interface IPythonEvaluationResultAsync { void GetChildren(DkmEvaluationResult result, DkmWorkList workList, int initialRequestSize, DkmInspectionContext inspectionContext, DkmCompletionRoutine<DkmGetChildrenAsyncResult> completionRoutine); } private class RawEvaluationResult : DkmDataItem { public object Value { get; set; } } /// <summary> /// Data item attached to a <see cref="DkmEvaluationResult"/> that represents a Python object (a variable, field of another object, collection item etc). /// </summary> private class PyObjectEvaluationResult : DkmDataItem, IPythonEvaluationResult { // Maps CLR types as returned from IValueStore.Read() to corresponding Python types. // Used to compute the expected Python type for a T_* slot of a native object, since we don't have the actual PyObject value yet. private static readonly Dictionary<Type, string> _typeMapping = new Dictionary<Type, string>() { { typeof(sbyte), "int" }, { typeof(byte), "int" }, { typeof(short), "int" }, { typeof(ushort), "int" }, { typeof(int), "int" }, { typeof(uint), "int" }, { typeof(long), "int" }, { typeof(ulong), "int" }, { typeof(float), "float" }, { typeof(double), "float" }, { typeof(Complex), "complex" }, { typeof(bool), "bool" }, { typeof(string), "str" }, { typeof(AsciiString), "bytes" }, }; // 2.x-specific mappings that override the ones above. private static readonly Dictionary<Type, string> _typeMapping2x = new Dictionary<Type, string>() { { typeof(string), "unicode" }, { typeof(AsciiString), "str" }, }; public PyObjectEvaluationResult(DkmProcess process, string fullName, IValueStore<PyObject> valueStore, string cppTypeName, bool hasCppView, bool isOwned) { Process = process; FullName = fullName; ValueStore = valueStore; CppTypeName = cppTypeName; HasCppView = hasCppView; IsOwned = isOwned; } public DkmProcess Process { get; private set; } public string FullName { get; private set; } public IValueStore<PyObject> ValueStore { get; private set; } /// <summary> /// Should this object show a child [C++ view] node? /// </summary> public bool HasCppView { get; private set; } /// <summary> /// Name of the C++ struct type corresponding to this object value. /// </summary> public string CppTypeName { get; private set; } /// <summary> /// Name of the native module containing <see cref="CppTypeName"/>. /// </summary> public string CppTypeModuleName { get; private set; } /// <summary> /// Whether this object needs to be decref'd once the evaluation result goes away. /// </summary> public bool IsOwned { get; private set; } protected override void OnClose() { base.OnClose(); if (IsOwned) { var obj = ValueStore.Read(); Process.GetDataItem<PyObjectAllocator>().QueueForDecRef(obj); } } public List<DkmEvaluationResult> GetChildren(ExpressionEvaluator exprEval, DkmEvaluationResult result, DkmInspectionContext inspectionContext) { var stackFrame = result.StackFrame; var cppEval = new CppExpressionEvaluator(inspectionContext, stackFrame); var obj = ValueStore.Read(); var evalResults = new List<DkmEvaluationResult>(); var reprOptions = new ReprOptions(inspectionContext); var reprBuilder = new ReprBuilder(reprOptions); if (DebuggerOptions.ShowCppViewNodes && !HasCppView) { if (CppTypeName == null) { // Try to guess the object's C++ type by looking at function pointers in its PyTypeObject. If they are pointing // into a module for which symbols are available, C++ EE should be able to resolve them into something like // "0x1e120d50 {python33_d.dll!list_dealloc(PyListObject *)}". If we are lucky, one of those functions will have // the first argument declared as a strongly typed pointer, rather than PyObject* or void*. CppTypeName = "PyObject"; CppTypeModuleName = null; foreach (string methodField in _methodFields) { var funcPtrEvalResult = cppEval.TryEvaluateObject(null, "PyObject", obj.Address, ".ob_type->" + methodField) as DkmSuccessEvaluationResult; if (funcPtrEvalResult == null || funcPtrEvalResult.Value.IndexOf('{') < 0) { continue; } var match = _cppFirstArgTypeFromFuncPtrRegex.Match(funcPtrEvalResult.Value); string module = match.Groups["module"].Value; string firstArgType = match.Groups["type"].Value; if (firstArgType != "void" && firstArgType != "PyObject" && firstArgType != "_object") { CppTypeName = firstArgType; CppTypeModuleName = module; break; } } } string cppExpr = CppExpressionEvaluator.GetExpressionForObject(CppTypeModuleName, CppTypeName, obj.Address, ",!"); var evalResult = DkmIntermediateEvaluationResult.Create( inspectionContext, stackFrame, "[C++ view]", "{C++}" + cppExpr, cppExpr, CppExpressionEvaluator.CppLanguage, stackFrame.Process.GetNativeRuntimeInstance(), null); evalResults.Add(evalResult); } int i = 0; foreach (var child in obj.GetDebugChildren(reprOptions).Take(MaxDebugChildren)) { if (child.Name == null) { reprBuilder.Clear(); reprBuilder.AppendFormat("[{0:PY}]", i++); child.Name = reprBuilder.ToString(); } DkmEvaluationResult evalResult; if (child.ValueStore is IValueStore<PyObject>) { evalResult = exprEval.CreatePyObjectEvaluationResult(inspectionContext, stackFrame, FullName, child, cppEval); } else { var value = child.ValueStore.Read(); reprBuilder.Clear(); reprBuilder.AppendLiteral(value); string type = null; if (Process.GetPythonRuntimeInfo().LanguageVersion <= PythonLanguageVersion.V27) { _typeMapping2x.TryGetValue(value.GetType(), out type); } if (type == null) { _typeMapping.TryGetValue(value.GetType(), out type); } var flags = DkmEvaluationResultFlags.ReadOnly; if (value is string) { flags |= DkmEvaluationResultFlags.RawString; } string childFullName = child.Name; if (FullName != null) { if (childFullName.EndsWith("()")) { // len() childFullName = childFullName.Substring(0, childFullName.Length - 2) + "(" + FullName + ")"; } else { if (!childFullName.StartsWith("[")) { // [0], ['fob'] etc childFullName = "." + childFullName; } childFullName = FullName + childFullName; } } evalResult = DkmSuccessEvaluationResult.Create( inspectionContext, stackFrame, child.Name, childFullName, flags, reprBuilder.ToString(), null, type, child.Category, child.AccessType, child.StorageType, child.TypeModifierFlags, null, null, null, new RawEvaluationResult { Value = value }); } evalResults.Add(evalResult); } return evalResults; } } /// <summary> /// Data item attached to the <see cref="DkmEvaluationResult"/> representing the [Globals] node. /// </summary> private class GlobalsEvaluationResult : DkmDataItem, IPythonEvaluationResult { public PyDictObject Globals { get; set; } public List<DkmEvaluationResult> GetChildren(ExpressionEvaluator exprEval, DkmEvaluationResult result, DkmInspectionContext inspectionContext) { var stackFrame = result.StackFrame; var cppEval = new CppExpressionEvaluator(inspectionContext, stackFrame); var evalResults = new List<DkmEvaluationResult>(); foreach (var pair in Globals.ReadElements()) { var name = pair.Key as IPyBaseStringObject; if (name == null) { continue; } var evalResult = exprEval.CreatePyObjectEvaluationResult(inspectionContext, stackFrame, null, new PythonEvaluationResult(pair.Value, name.ToString()), cppEval); evalResults.Add(evalResult); } return evalResults.OrderBy(er => er.Name).ToList(); } } /// <summary> /// Data item attached to the <see cref="DkmEvaluationResult"/> representing the [C++ view] node. /// </summary> private class CppViewEvaluationResult : DkmDataItem, IPythonEvaluationResultAsync { public DkmSuccessEvaluationResult CppEvaluationResult { get; set; } public void GetChildren(DkmEvaluationResult result, DkmWorkList workList, int initialRequestSize, DkmInspectionContext inspectionContext, DkmCompletionRoutine<DkmGetChildrenAsyncResult> completionRoutine) { CppEvaluationResult.GetChildren(workList, initialRequestSize, CppEvaluationResult.InspectionContext, (cppResult) => { completionRoutine(cppResult); }); } } private class EvaluationResults : DkmDataItem { public IEnumerable<DkmEvaluationResult> Results { get; set; } } // Names of fields of PyTypeObject struct that contain function pointers corresponding to standard methods of the type. // These are in rough descending order of probability of being non-null and strongly typed (so that we don't waste time eval'ing unnecessary). private static readonly string[] _methodFields = { "tp_init", "tp_dealloc", "tp_repr", "tp_hash", "tp_str", "tp_call", "tp_iter", "tp_iternext", "tp_richcompare", "tp_print", "tp_del", "tp_clear", "tp_traverse", "tp_getattr", "tp_setattr", "tp_getattro", "tp_setattro", }; // Given something like "0x1e120d50 {python33_d.dll!list_dealloc(PyListObject *)}", extract "python33_d.dll" and "PyListObject". private static readonly Regex _cppFirstArgTypeFromFuncPtrRegex = new Regex(@"^.*?\{(?<module>.*?)\!.*?\((?<type>[0-9A-Za-z_:]*?)\s*\*(,.*?)?\)\}$", RegexOptions.CultureInvariant); /// <summary> /// Create a DkmEvaluationResult representing a Python object. /// </summary> /// <param name="cppEval">C++ evaluator to use to provide the [C++ view] node for this object.</param> /// <param name="cppTypeName"> /// C++ struct name corresponding to this object type, for use by [C++ view] node. If not specified, it will be inferred from values of /// various function pointers in <c>ob_type</c>, if possible. <c>PyObject</c> is the ultimate fallback. /// </param> public DkmEvaluationResult CreatePyObjectEvaluationResult(DkmInspectionContext inspectionContext, DkmStackWalkFrame stackFrame, string parentName, PythonEvaluationResult pyEvalResult, CppExpressionEvaluator cppEval, string cppTypeName = null, bool hasCppView = false, bool isOwned = false) { var name = pyEvalResult.Name; var valueStore = pyEvalResult.ValueStore as IValueStore<PyObject>; if (valueStore == null) { Debug.Fail("Non-PyObject PythonEvaluationResult passed to CreateEvaluationResult."); throw new ArgumentException(); } var valueObj = valueStore.Read(); string typeName = valueObj.ob_type.Read().tp_name.Read().ReadUnicode(); var reprOptions = new ReprOptions(inspectionContext); string repr = valueObj.Repr(reprOptions); var flags = pyEvalResult.Flags; if (DebuggerOptions.ShowCppViewNodes || valueObj.GetDebugChildren(reprOptions).Any()) { flags |= DkmEvaluationResultFlags.Expandable; } if (!(valueStore is IWritableDataProxy)) { flags |= DkmEvaluationResultFlags.ReadOnly; } if (valueObj is IPyBaseStringObject) { flags |= DkmEvaluationResultFlags.RawString; } var boolObj = valueObj as IPyBoolObject; if (boolObj != null) { flags |= DkmEvaluationResultFlags.Boolean; if (boolObj.ToBoolean()) { flags |= DkmEvaluationResultFlags.BooleanTrue; } } string fullName = name; if (parentName != null) { if (!fullName.StartsWith("[")) { fullName = "." + fullName; } fullName = parentName + fullName; } var pyObjEvalResult = new PyObjectEvaluationResult(stackFrame.Process, fullName, valueStore, cppTypeName, hasCppView, isOwned); return DkmSuccessEvaluationResult.Create( inspectionContext, stackFrame, name, fullName, flags, repr, null, typeName, pyEvalResult.Category, pyEvalResult.AccessType, pyEvalResult.StorageType, pyEvalResult.TypeModifierFlags, null, null, null, pyObjEvalResult); } public void GetFrameLocals(DkmInspectionContext inspectionContext, DkmWorkList workList, DkmStackWalkFrame stackFrame, DkmCompletionRoutine<DkmGetFrameLocalsAsyncResult> completionRoutine) { var pythonFrame = PyFrameObject.TryCreate(stackFrame); if (pythonFrame == null) { Debug.Fail("Non-Python frame passed to GetFrameLocals."); throw new NotSupportedException(); } var cppEval = new CppExpressionEvaluator(inspectionContext, stackFrame); var evalResults = new List<DkmEvaluationResult>(); var f_code = pythonFrame.f_code.Read(); var f_localsplus = pythonFrame.f_localsplus; // Process cellvars and freevars first, because function arguments can appear in both cellvars and varnames if the argument is captured by a closure, // in which case we want to use the cellvar because the regular var slot will then be unused by Python (and in Python 3.4+, nulled out). var namesSeen = new HashSet<string>(); var cellNames = f_code.co_cellvars.Read().ReadElements().Concat(f_code.co_freevars.Read().ReadElements()); var cellSlots = f_localsplus.Skip(f_code.co_nlocals.Read()); foreach (var pair in cellNames.Zip(cellSlots, (nameObj, cellSlot) => new { nameObj, cellSlot = cellSlot })) { var nameObj = pair.nameObj; var cellSlot = pair.cellSlot; var name = (nameObj.Read() as IPyBaseStringObject).ToStringOrNull(); if (name == null) { continue; } namesSeen.Add(name); if (cellSlot.IsNull) { continue; } var cell = cellSlot.Read() as PyCellObject; if (cell == null) { continue; } var localPtr = cell.ob_ref; if (localPtr.IsNull) { continue; } var evalResult = CreatePyObjectEvaluationResult(inspectionContext, stackFrame, null, new PythonEvaluationResult(localPtr, name), cppEval); evalResults.Add(evalResult); } PyTupleObject co_varnames = f_code.co_varnames.Read(); foreach (var pair in co_varnames.ReadElements().Zip(f_localsplus, (nameObj, varSlot) => new { nameObj, cellSlot = varSlot })) { var nameObj = pair.nameObj; var varSlot = pair.cellSlot; var name = (nameObj.Read() as IPyBaseStringObject).ToStringOrNull(); if (name == null) { continue; } // Check for function argument that was promoted to a cell. if (!namesSeen.Add(name)) { continue; } if (varSlot.IsNull) { continue; } var evalResult = CreatePyObjectEvaluationResult(inspectionContext, stackFrame, null, new PythonEvaluationResult(varSlot, name), cppEval); evalResults.Add(evalResult); } var globals = pythonFrame.f_globals.TryRead(); if (globals != null) { var globalsEvalResult = new GlobalsEvaluationResult { Globals = globals }; DkmEvaluationResult evalResult = DkmSuccessEvaluationResult.Create( inspectionContext, stackFrame, "[Globals]", null, DkmEvaluationResultFlags.ReadOnly | DkmEvaluationResultFlags.Expandable, null, null, null, DkmEvaluationResultCategory.Property, DkmEvaluationResultAccessType.None, DkmEvaluationResultStorageType.None, DkmEvaluationResultTypeModifierFlags.None, null, null, null, globalsEvalResult); // If it is a top-level module frame, show globals inline; otherwise, show them under the [Globals] node. if (f_code.co_name.Read().ToStringOrNull() == "<module>") { evalResults.AddRange(globalsEvalResult.GetChildren(this, evalResult, inspectionContext)); } else { evalResults.Add(evalResult); // Show any globals that are directly referenced by the function inline even in local frames. var globalVars = (from pair in globals.ReadElements() let nameObj = pair.Key as IPyBaseStringObject where nameObj != null select new { Name = nameObj.ToString(), Value = pair.Value } ).ToLookup(v => v.Name, v => v.Value); PyTupleObject co_names = f_code.co_names.Read(); foreach (var nameObj in co_names.ReadElements()) { var name = (nameObj.Read() as IPyBaseStringObject).ToStringOrNull(); if (name == null) { continue; } // If this is a used name but it was not in varnames or freevars, it is a directly referenced global. if (!namesSeen.Add(name)) { continue; } var varSlot = globalVars[name].FirstOrDefault(); if (varSlot.Process != null) { evalResult = CreatePyObjectEvaluationResult(inspectionContext, stackFrame, null, new PythonEvaluationResult(varSlot, name), cppEval); evalResults.Add(evalResult); } } } } var enumContext = DkmEvaluationResultEnumContext.Create(evalResults.Count, stackFrame, inspectionContext, new EvaluationResults { Results = evalResults.OrderBy(er => er.Name) }); completionRoutine(new DkmGetFrameLocalsAsyncResult(enumContext)); } public void GetChildren(DkmEvaluationResult result, DkmWorkList workList, int initialRequestSize, DkmInspectionContext inspectionContext, DkmCompletionRoutine<DkmGetChildrenAsyncResult> completionRoutine) { var asyncEvalResult = result.GetDataItem<CppViewEvaluationResult>(); if (asyncEvalResult != null) { asyncEvalResult.GetChildren(result, workList, initialRequestSize, inspectionContext, completionRoutine); return; } var pyEvalResult = (IPythonEvaluationResult)result.GetDataItem<PyObjectEvaluationResult>() ?? (IPythonEvaluationResult)result.GetDataItem<GlobalsEvaluationResult>(); if (pyEvalResult != null) { var childResults = pyEvalResult.GetChildren(this, result, inspectionContext); completionRoutine( new DkmGetChildrenAsyncResult( new DkmEvaluationResult[0], DkmEvaluationResultEnumContext.Create( childResults.Count, result.StackFrame, inspectionContext, new EvaluationResults { Results = childResults.ToArray() }))); return; } Debug.Fail("GetChildren called on an unsupported DkmEvaluationResult."); throw new NotSupportedException(); } public void GetItems(DkmEvaluationResultEnumContext enumContext, DkmWorkList workList, int startIndex, int count, DkmCompletionRoutine<DkmEvaluationEnumAsyncResult> completionRoutine) { var evalResults = enumContext.GetDataItem<EvaluationResults>(); if (evalResults == null) { Debug.Fail("GetItems called on a DkmEvaluationResultEnumContext without an associated EvaluationResults."); throw new NotSupportedException(); } var result = evalResults.Results.Skip(startIndex).Take(count).ToArray(); completionRoutine(new DkmEvaluationEnumAsyncResult(result)); } public void EvaluateExpression(DkmInspectionContext inspectionContext, DkmWorkList workList, DkmLanguageExpression expression, DkmStackWalkFrame stackFrame, DkmCompletionRoutine<DkmEvaluateExpressionAsyncResult> completionRoutine) { var name = expression.Text; GetFrameLocals(inspectionContext, workList, stackFrame, getFrameLocalsResult => { getFrameLocalsResult.EnumContext.GetItems(workList, 0, int.MaxValue, localGetItemsResult => { var vars = localGetItemsResult.Items.OfType<DkmSuccessEvaluationResult>(); var globals = vars.FirstOrDefault(er => er.Name == "[Globals]"); if (globals == null) { if (!EvaluateExpressionByWalkingObjects(vars, inspectionContext, workList, expression, stackFrame, completionRoutine)) { EvaluateExpressionViaInterpreter(inspectionContext, workList, expression, stackFrame, completionRoutine); } } else { globals.GetChildren(workList, 0, inspectionContext, globalsGetChildrenResult => { globalsGetChildrenResult.EnumContext.GetItems(workList, 0, int.MaxValue, globalsGetItemsResult => { vars = vars.Concat(globalsGetItemsResult.Items.OfType<DkmSuccessEvaluationResult>()); if (!EvaluateExpressionByWalkingObjects(vars, inspectionContext, workList, expression, stackFrame, completionRoutine)) { EvaluateExpressionViaInterpreter(inspectionContext, workList, expression, stackFrame, completionRoutine); } }); }); } }); }); } /// <summary> /// Tries to evaluate the given expression by treating it as a chain of member access and indexing operations (e.g. <c>fob[0].oar.baz['abc'].blah</c>), /// and looking up the corresponding members in data model provided by <see cref="GetFrameLocals"/>. /// </summary> /// <param name="vars">List of variables, in the context of which the expression is evaluated.</param> /// <returns> /// <c>true</c> if evaluation was successful, or if it failed and no fallback is possible (e.g. expression is invalid). /// <c>false</c> if evaluation was not successful due to the limitations of this evaluator, and it may be possible to evaluate it correctly by other means. /// </returns> private bool EvaluateExpressionByWalkingObjects(IEnumerable<DkmSuccessEvaluationResult> vars, DkmInspectionContext inspectionContext, DkmWorkList workList, DkmLanguageExpression expression, DkmStackWalkFrame stackFrame, DkmCompletionRoutine<DkmEvaluateExpressionAsyncResult> completionRoutine) { var pyrtInfo = stackFrame.Thread.Process.GetPythonRuntimeInfo(); var parserOptions = new ParserOptions { ErrorSink = new StringErrorSink() }; var parser = Parser.CreateParser(new StringReader(expression.Text), pyrtInfo.LanguageVersion, parserOptions); var expr = ((ReturnStatement)parser.ParseTopExpression().Body).Expression; string errorText = parserOptions.ErrorSink.ToString(); if (!string.IsNullOrEmpty(errorText)) { completionRoutine(new DkmEvaluateExpressionAsyncResult(DkmFailedEvaluationResult.Create( inspectionContext, stackFrame, expression.Text, expression.Text, errorText, DkmEvaluationResultFlags.Invalid, null))); return true; } // Unroll the AST into a sequence of member access and indexing operations, if possible. var path = new Stack<string>(); var reprBuilder = new ReprBuilder(new ReprOptions(stackFrame.Thread.Process)); while (true) { var memberExpr = expr as MemberExpression; if (memberExpr != null) { path.Push(memberExpr.Name); expr = memberExpr.Target; continue; } var indexingExpr = expr as IndexExpression; if (indexingExpr != null) { var indexExpr = indexingExpr.Index as ConstantExpression; if (indexExpr != null) { reprBuilder.Clear(); reprBuilder.AppendFormat("[{0:PY}]", indexExpr.Value); path.Push(reprBuilder.ToString()); expr = indexingExpr.Target; continue; } } break; } var varExpr = expr as NameExpression; if (varExpr == null) { return false; } path.Push(varExpr.Name); // Walk the path through Locals while (true) { var name = path.Pop(); var evalResult = vars.FirstOrDefault(er => er.Name == name); if (evalResult == null) { return false; } if (path.Count == 0) { // Clone the evaluation result, but use expression text as its name. DkmDataItem dataItem = (DkmDataItem)evalResult.GetDataItem<PyObjectEvaluationResult>() ?? (DkmDataItem)evalResult.GetDataItem<GlobalsEvaluationResult>() ?? (DkmDataItem)evalResult.GetDataItem<CppViewEvaluationResult>() ?? (DkmDataItem)evalResult.GetDataItem<RawEvaluationResult>(); evalResult = DkmSuccessEvaluationResult.Create( evalResult.InspectionContext, evalResult.StackFrame, expression.Text, expression.Text, evalResult.Flags, evalResult.Value, evalResult.EditableValue, evalResult.Type, evalResult.Category, evalResult.Access, evalResult.StorageType, evalResult.TypeModifierFlags, evalResult.Address, evalResult.CustomUIVisualizers, evalResult.ExternalModules, dataItem); completionRoutine(new DkmEvaluateExpressionAsyncResult(evalResult)); return true; } var childWorkList = DkmWorkList.Create(null); evalResult.GetChildren(childWorkList, 0, inspectionContext, getChildrenResult => getChildrenResult.EnumContext.GetItems(childWorkList, 0, int.MaxValue, getItemsResult => vars = getItemsResult.Items.OfType<DkmSuccessEvaluationResult>())); childWorkList.Execute(); } } private AutoResetEvent _evalCompleteEvent, _evalAbortedEvent; private void EvaluateExpressionViaInterpreter(DkmInspectionContext inspectionContext, DkmWorkList workList, DkmLanguageExpression expression, DkmStackWalkFrame stackFrame, DkmCompletionRoutine<DkmEvaluateExpressionAsyncResult> completionRoutine) { var thread = stackFrame.Thread; var process = thread.Process; if (_evalLoopThreadId.Read() != (ulong)thread.SystemPart.Id) { completionRoutine(new DkmEvaluateExpressionAsyncResult(DkmFailedEvaluationResult.Create( inspectionContext, stackFrame, expression.Text, expression.Text, "Arbitrary Python expressions can only be evaluated on a thread which is stopped in Python code at a breakpoint or " + "after a step-in or a step-over operation. Only expressions involving global and local variables, object field access, " + "and indexing of built-in collection types with literals can be evaluated in the current context.", DkmEvaluationResultFlags.Invalid, null))); return; } var pythonFrame = PyFrameObject.TryCreate(stackFrame); if (pythonFrame == null) { completionRoutine(new DkmEvaluateExpressionAsyncResult(DkmFailedEvaluationResult.Create( inspectionContext, stackFrame, expression.Text, expression.Text, "Could not obtain a Python frame object for the current frame.", DkmEvaluationResultFlags.Invalid, null))); return; } byte[] input = Encoding.UTF8.GetBytes(expression.Text + "\0"); if (input.Length > ExpressionEvaluationBufferSize) { completionRoutine(new DkmEvaluateExpressionAsyncResult(DkmFailedEvaluationResult.Create( inspectionContext, stackFrame, expression.Text, expression.Text, "Expression is too long.", DkmEvaluationResultFlags.Invalid, null))); return; } _evalLoopFrame.Write(pythonFrame.Address); process.WriteMemory(_evalLoopInput.Address, input); bool timedOut; using (_evalCompleteEvent = new AutoResetEvent(false)) { thread.BeginFuncEvalExecution(DkmFuncEvalFlags.None); timedOut = !_evalCompleteEvent.WaitOne(ExpressionEvaluationTimeout); _evalCompleteEvent = null; } if (timedOut) { new RemoteComponent.AbortingEvalExecutionRequest().SendLower(process); // We need to stop the process before we can report end of func eval completion using (_evalAbortedEvent = new AutoResetEvent(false)) { process.AsyncBreak(false); if (!_evalAbortedEvent.WaitOne(20000)) { // This is a catastrophic error, since we can't report func eval completion unless we can stop the process, // and VS will hang until we do report completion. At this point we can only kill the debuggee so that the // VS at least gets back to a reasonable state. _evalAbortedEvent = null; process.Terminate(1); completionRoutine(DkmEvaluateExpressionAsyncResult.CreateErrorResult(new Exception("Couldn't abort a failed expression evaluation."))); return; } _evalAbortedEvent = null; } completionRoutine(new DkmEvaluateExpressionAsyncResult(DkmFailedEvaluationResult.Create( inspectionContext, stackFrame, expression.Text, expression.Text, "Evaluation timed out.", DkmEvaluationResultFlags.Invalid, null))); return; } ulong objPtr = _evalLoopResult.Read(); var obj = PyObject.FromAddress(process, objPtr); var exc_type = PyObject.FromAddress(process, _evalLoopExcType.Read()); var exc_value = PyObject.FromAddress(process, _evalLoopExcValue.Read()); var exc_str = (PyObject.FromAddress(process, _evalLoopExcStr.Read()) as IPyBaseStringObject).ToStringOrNull(); var sehCode = _evalLoopSEHCode.Read(); if (obj != null) { var cppEval = new CppExpressionEvaluator(inspectionContext, stackFrame); var pyEvalResult = new PythonEvaluationResult(obj, expression.Text) { Flags = DkmEvaluationResultFlags.SideEffect }; var evalResult = CreatePyObjectEvaluationResult(inspectionContext, stackFrame, null, pyEvalResult, cppEval, null, hasCppView: true, isOwned: true); _evalLoopResult.Write(0); // don't let the eval loop decref the object - we will do it ourselves later, when eval result is closed completionRoutine(new DkmEvaluateExpressionAsyncResult(evalResult)); } else if (sehCode != 0) { string errorText = string.Format("Structured exception {0:x08} ", sehCode); if (Enum.IsDefined(typeof(EXCEPTION_CODE), sehCode)) { errorText += "(" + (EXCEPTION_CODE)sehCode + ") "; } errorText += "raised while evaluating expression"; completionRoutine(new DkmEvaluateExpressionAsyncResult(DkmFailedEvaluationResult.Create( inspectionContext, stackFrame, expression.Text, expression.Text, errorText, DkmEvaluationResultFlags.Invalid, null))); } else if (exc_type != null) { string typeName; var typeObject = exc_type as PyTypeObject; if (typeObject != null) { typeName = typeObject.tp_name.Read().ReadUnicode(); } else { typeName = "<unknown exception type>"; } completionRoutine(new DkmEvaluateExpressionAsyncResult(DkmFailedEvaluationResult.Create( inspectionContext, stackFrame, expression.Text, expression.Text, typeName + " raised while evaluating expression: " + exc_str, DkmEvaluationResultFlags.Invalid, null))); } else { completionRoutine(new DkmEvaluateExpressionAsyncResult(DkmFailedEvaluationResult.Create( inspectionContext, stackFrame, expression.Text, expression.Text, "Unknown error occurred while evaluating expression.", DkmEvaluationResultFlags.Invalid, null))); } } private void OnEvalComplete(DkmThread thread, ulong frameBase, ulong vframe, ulong returnAddress) { var e = _evalCompleteEvent; if (e != null) { new RemoteComponent.EndFuncEvalExecutionRequest { ThreadId = thread.UniqueId }.SendLower(thread.Process); e.Set(); } } public void OnAsyncBreakComplete(DkmThread thread) { var e = _evalAbortedEvent; if (e != null) { new RemoteComponent.EndFuncEvalExecutionRequest { ThreadId = thread.UniqueId }.SendLower(thread.Process); e.Set(); } } public string GetUnderlyingString(DkmEvaluationResult result) { var rawResult = result.GetDataItem<RawEvaluationResult>(); if (rawResult != null && rawResult.Value is string) { return (string)rawResult.Value; } var objResult = result.GetDataItem<PyObjectEvaluationResult>(); if (objResult == null) { return null; } var str = objResult.ValueStore.Read() as IPyBaseStringObject; return str.ToStringOrNull(); } private class StringErrorSink : ErrorSink { private readonly StringBuilder _builder = new StringBuilder(); public override void Add(string message, int[] lineLocations, int startIndex, int endIndex, int errorCode, Severity severity) { _builder.AppendLine(message); } public override string ToString() { return _builder.ToString(); } } public unsafe void SetValueAsString(DkmEvaluationResult result, string value, int timeout, out string errorText) { var pyEvalResult = result.GetDataItem<PyObjectEvaluationResult>(); if (pyEvalResult == null) { Debug.Fail("SetValueAsString called on a DkmEvaluationResult without an associated PyObjectEvaluationResult."); throw new NotSupportedException(); } var proxy = pyEvalResult.ValueStore as IWritableDataProxy; if (proxy == null) { Debug.Fail("SetValueAsString called on a DkmEvaluationResult that does not correspond to an IWritableDataProxy."); throw new InvalidOperationException(); } errorText = null; var process = result.StackFrame.Process; var pyrtInfo = process.GetPythonRuntimeInfo(); var parserOptions = new ParserOptions { ErrorSink = new StringErrorSink() }; var parser = Parser.CreateParser(new StringReader(value), pyrtInfo.LanguageVersion, parserOptions); var body = (ReturnStatement)parser.ParseTopExpression().Body; errorText = parserOptions.ErrorSink.ToString(); if (!string.IsNullOrEmpty(errorText)) { return; } var expr = body.Expression; while (true) { var parenExpr = expr as ParenthesisExpression; if (parenExpr == null) { break; } expr = parenExpr.Expression; } int sign; expr = ForceExplicitSign(expr, out sign); PyObject newObj = null; var constExpr = expr as ConstantExpression; if (constExpr != null) { if (constExpr.Value == null) { newObj = PyObject.None(process); } else if (constExpr.Value is bool) { // In 2.7, 'True' and 'False' are reported as identifiers, not literals, and are handled separately below. newObj = PyBoolObject33.Create(process, (bool)constExpr.Value); } else if (constExpr.Value is string) { if (pyrtInfo.LanguageVersion <= PythonLanguageVersion.V27) { newObj = PyUnicodeObject27.Create(process, (string)constExpr.Value); } else { newObj = PyUnicodeObject33.Create(process, (string)constExpr.Value); } } else if (constExpr.Value is AsciiString) { newObj = PyBytesObject.Create(process, (AsciiString)constExpr.Value); } } else { var unaryExpr = expr as UnaryExpression; if (unaryExpr != null && sign != 0) { constExpr = unaryExpr.Expression as ConstantExpression; if (constExpr != null) { if (constExpr.Value is BigInteger) { newObj = PyLongObject.Create(process, (BigInteger)constExpr.Value * sign); } else if (constExpr.Value is int) { if (pyrtInfo.LanguageVersion <= PythonLanguageVersion.V27) { newObj = PyIntObject.Create(process, (int)constExpr.Value * sign); } else { newObj = PyLongObject.Create(process, (int)constExpr.Value * sign); } } else if (constExpr.Value is double) { newObj = PyFloatObject.Create(process, (double)constExpr.Value * sign); } else if (constExpr.Value is Complex) { newObj = PyComplexObject.Create(process, (Complex)constExpr.Value * sign); } } } else { var binExpr = expr as BinaryExpression; if (binExpr != null && (binExpr.Operator == PythonOperator.Add || binExpr.Operator == PythonOperator.Subtract)) { int realSign; var realExpr = ForceExplicitSign(binExpr.Left, out realSign) as UnaryExpression; int imagSign; var imagExpr = ForceExplicitSign(binExpr.Right, out imagSign) as UnaryExpression; if (realExpr != null && realSign != 0 && imagExpr != null && imagSign != 0) { var realConst = realExpr.Expression as ConstantExpression; var imagConst = imagExpr.Expression as ConstantExpression; if (realConst != null && imagConst != null) { var realVal = (realConst.Value as int? ?? realConst.Value as double?) as IConvertible; var imagVal = imagConst.Value as Complex?; if (realVal != null && imagVal != null) { double real = realVal.ToDouble(null) * realSign; double imag = imagVal.Value.Imaginary * imagSign * (binExpr.Operator == PythonOperator.Add ? 1 : -1); newObj = PyComplexObject.Create(process, new Complex(real, imag)); } } } } else { if (pyrtInfo.LanguageVersion <= PythonLanguageVersion.V27) { // 'True' and 'False' are not literals in 2.x, but we want to treat them as such. var name = expr as NameExpression; if (name != null) { if (name.Name == "True") { newObj = PyBoolObject27.Create(process, true); } else if (name.Name == "False") { newObj = PyBoolObject27.Create(process, false); } } } } } } if (newObj != null) { var oldObj = proxy.Read() as PyObject; if (oldObj != null) { // We can't free the original value without running some code in the process, and it may be holding heap locks. // So don't decrement refcount now, but instead add it to the list of objects for TraceFunc to GC when it gets // a chance to run next time. _process.GetDataItem<PyObjectAllocator>().QueueForDecRef(oldObj); } newObj.ob_refcnt.Increment(); proxy.Write(newObj); } else { errorText = "Only boolean, numeric or string literals and None are supported."; } } private static Expression ForceExplicitSign(Expression expr, out int sign) { var constExpr = expr as ConstantExpression; if (constExpr != null && (constExpr.Value is int || constExpr.Value is double || constExpr.Value is BigInteger || constExpr.Value is Complex)) { sign = 1; return new UnaryExpression(PythonOperator.Pos, constExpr); } var unaryExpr = expr as UnaryExpression; if (unaryExpr != null) { switch (unaryExpr.Op) { case PythonOperator.Pos: sign = 1; return unaryExpr; case PythonOperator.Negate: sign = -1; return unaryExpr; } } sign = 0; return expr; } } internal class PythonEvaluationResult { /// <summary> /// A store containing the evaluated value. /// </summary> public IValueStore ValueStore { get; set; } /// <summary> /// For named results, name of the result. For unnamed results, <c>null</c>. /// </summary> public string Name { get; set; } public DkmEvaluationResultCategory Category { get; set; } public DkmEvaluationResultAccessType AccessType { get; set; } public DkmEvaluationResultStorageType StorageType { get; set; } public DkmEvaluationResultTypeModifierFlags TypeModifierFlags { get; set; } public DkmEvaluationResultFlags Flags { get; set; } public PythonEvaluationResult(IValueStore valueStore, string name = null) { ValueStore = valueStore; Name = name; Category = DkmEvaluationResultCategory.Data; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace WebappTokenCode.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //----------------------------------------------------------------------- // </copyright> // <summary>Test the ProjectMetadataElement class.</summary> //----------------------------------------------------------------------- using System; using System.IO; using System.Xml; using Microsoft.Build.Construction; using Microsoft.VisualStudio.TestTools.UnitTesting; using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException; namespace Microsoft.Build.UnitTests.OM.Construction { /// <summary> /// Tests for the ProjectMetadataElement class /// </summary> [TestClass] public class ProjectMetadataElement_Tests { /// <summary> /// Read simple metadatum /// </summary> [TestMethod] public void ReadMetadata() { ProjectMetadataElement metadatum = GetMetadataXml(); Assert.AreEqual("m", metadatum.Name); Assert.AreEqual("m1", metadatum.Value); Assert.AreEqual("c", metadatum.Condition); } /// <summary> /// Read metadatum with invalid attribute /// </summary> [TestMethod] [ExpectedException(typeof(InvalidProjectFileException))] public void ReadInvalidAttribute() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1'> <m Condition='c' XX='YY'/> </i> </ItemGroup> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } /// <summary> /// Read metadatum with invalid name characters (but legal xml) /// </summary> [TestMethod] [ExpectedException(typeof(InvalidProjectFileException))] public void ReadInvalidName() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1'> <" + "\u03A3" + @"/> </i> </ItemGroup> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } /// <summary> /// Read metadatum with invalid built-in metadata name /// </summary> [TestMethod] [ExpectedException(typeof(InvalidProjectFileException))] public void ReadInvalidBuiltInName() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1'> <Filename/> </i> </ItemGroup> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } /// <summary> /// Read metadatum with invalid built-in element name /// </summary> [TestMethod] [ExpectedException(typeof(InvalidProjectFileException))] public void ReadInvalidBuiltInElementName() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1'> <PropertyGroup/> </i> </ItemGroup> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } /// <summary> /// Set metadatum value /// </summary> [TestMethod] public void SetValue() { ProjectMetadataElement metadatum = GetMetadataXml(); metadatum.Value = "m1b"; Assert.AreEqual("m1b", metadatum.Value); } /// <summary> /// Rename /// </summary> [TestMethod] public void SetName() { ProjectMetadataElement metadatum = GetMetadataXml(); metadatum.Name = "m2"; Assert.AreEqual("m2", metadatum.Name); Assert.AreEqual(true, metadatum.ContainingProject.HasUnsavedChanges); } /// <summary> /// Rename to same value should not mark dirty /// </summary> [TestMethod] public void SetNameSame() { ProjectMetadataElement metadatum = GetMetadataXml(); Helpers.ClearDirtyFlag(metadatum.ContainingProject); metadatum.Name = "m"; Assert.AreEqual("m", metadatum.Name); Assert.AreEqual(false, metadatum.ContainingProject.HasUnsavedChanges); } /// <summary> /// Rename to illegal name /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentException))] public void SetNameIllegal() { ProjectMetadataElement metadatum = GetMetadataXml(); metadatum.Name = "ImportGroup"; } /// <summary> /// Set metadatum value to empty /// </summary> [TestMethod] public void SetEmptyValue() { ProjectMetadataElement metadatum = GetMetadataXml(); metadatum.Value = String.Empty; Assert.AreEqual(String.Empty, metadatum.Value); } /// <summary> /// Set metadatum value to null /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void SetInvalidNullValue() { ProjectMetadataElement metadatum = GetMetadataXml(); metadatum.Value = null; } /// <summary> /// Read a metadatum containing an expression like @(..) but whose parent is an ItemDefinitionGroup /// </summary> [TestMethod] [ExpectedException(typeof(InvalidProjectFileException))] public void ReadInvalidItemExpressionInMetadata() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemDefinitionGroup> <i> <m1>@(x)</m1> </i> </ItemDefinitionGroup> </Project> "; ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } /// <summary> /// Read a metadatum containing an expression like @(..) but whose parent is NOT an ItemDefinitionGroup /// </summary> [TestMethod] public void ReadValidItemExpressionInMetadata() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1'> <m1>@(x)</m1> </i> </ItemGroup> </Project> "; // Should not throw ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); } /// <summary> /// Helper to get a ProjectMetadataElement for a simple metadatum /// </summary> private static ProjectMetadataElement GetMetadataXml() { string content = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' > <ItemGroup> <i Include='i1'> <m Condition='c'>m1</m> </i> </ItemGroup> </Project> "; ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content))); ProjectItemGroupElement itemGroup = (ProjectItemGroupElement)Helpers.GetFirst(project.Children); ProjectItemElement item = Helpers.GetFirst(itemGroup.Items); ProjectMetadataElement metadata = Helpers.GetFirst(item.Metadata); return metadata; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ApplicationSecurityGroupsOperations operations. /// </summary> internal partial class ApplicationSecurityGroupsOperations : IServiceOperations<NetworkManagementClient>, IApplicationSecurityGroupsOperations { /// <summary> /// Initializes a new instance of the ApplicationSecurityGroupsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ApplicationSecurityGroupsOperations(NetworkManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// Deletes the specified application security group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationSecurityGroupName'> /// The name of the application security group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string applicationSecurityGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, applicationSecurityGroupName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets information about the specified application security group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationSecurityGroupName'> /// The name of the application security group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ApplicationSecurityGroup>> GetWithHttpMessagesAsync(string resourceGroupName, string applicationSecurityGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (applicationSecurityGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "applicationSecurityGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("applicationSecurityGroupName", applicationSecurityGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationSecurityGroups/{applicationSecurityGroupName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{applicationSecurityGroupName}", System.Uri.EscapeDataString(applicationSecurityGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ApplicationSecurityGroup>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ApplicationSecurityGroup>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates an application security group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationSecurityGroupName'> /// The name of the application security group. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update ApplicationSecurityGroup /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<ApplicationSecurityGroup>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string applicationSecurityGroupName, ApplicationSecurityGroup parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<ApplicationSecurityGroup> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, applicationSecurityGroupName, parameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets all application security groups in a subscription. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ApplicationSecurityGroup>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAll", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/applicationSecurityGroups").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ApplicationSecurityGroup>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ApplicationSecurityGroup>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the application security groups in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ApplicationSecurityGroup>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationSecurityGroups").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ApplicationSecurityGroup>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ApplicationSecurityGroup>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the specified application security group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationSecurityGroupName'> /// The name of the application security group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string applicationSecurityGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (applicationSecurityGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "applicationSecurityGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("applicationSecurityGroupName", applicationSecurityGroupName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationSecurityGroups/{applicationSecurityGroupName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{applicationSecurityGroupName}", System.Uri.EscapeDataString(applicationSecurityGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 202 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Creates or updates an application security group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='applicationSecurityGroupName'> /// The name of the application security group. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update ApplicationSecurityGroup /// operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ApplicationSecurityGroup>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string applicationSecurityGroupName, ApplicationSecurityGroup parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (applicationSecurityGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "applicationSecurityGroupName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } string apiVersion = "2017-09-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("applicationSecurityGroupName", applicationSecurityGroupName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/applicationSecurityGroups/{applicationSecurityGroupName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{applicationSecurityGroupName}", System.Uri.EscapeDataString(applicationSecurityGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ApplicationSecurityGroup>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ApplicationSecurityGroup>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ApplicationSecurityGroup>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all application security groups in a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ApplicationSecurityGroup>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAllNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ApplicationSecurityGroup>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ApplicationSecurityGroup>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the application security groups in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ApplicationSecurityGroup>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ApplicationSecurityGroup>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ApplicationSecurityGroup>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime; using System.Runtime.Serialization; using System.ServiceModel.Dispatcher; using System.Text; using Microsoft.Xml; namespace System.ServiceModel.Channels { public abstract class AddressHeader { private ParameterHeader _header; protected AddressHeader() { } internal bool IsReferenceProperty { get { BufferedAddressHeader bah = this as BufferedAddressHeader; return bah != null && bah.IsReferencePropertyHeader; } } public abstract string Name { get; } public abstract string Namespace { get; } public static AddressHeader CreateAddressHeader(object value) { Type type = GetObjectType(value); return CreateAddressHeader(value, DataContractSerializerDefaults.CreateSerializer(type, int.MaxValue/*maxItems*/)); } public static AddressHeader CreateAddressHeader(object value, XmlObjectSerializer serializer) { if (serializer == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serializer")); return new XmlObjectSerializerAddressHeader(value, serializer); } public static AddressHeader CreateAddressHeader(string name, string ns, object value) { return CreateAddressHeader(name, ns, value, DataContractSerializerDefaults.CreateSerializer(GetObjectType(value), name, ns, int.MaxValue/*maxItems*/)); } internal static AddressHeader CreateAddressHeader(XmlDictionaryString name, XmlDictionaryString ns, object value) { return new DictionaryAddressHeader(name, ns, value); } public static AddressHeader CreateAddressHeader(string name, string ns, object value, XmlObjectSerializer serializer) { if (serializer == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serializer")); return new XmlObjectSerializerAddressHeader(name, ns, value, serializer); } private static Type GetObjectType(object value) { return (value == null) ? typeof(object) : value.GetType(); } public override bool Equals(object obj) { AddressHeader hdr = obj as AddressHeader; if (hdr == null) return false; StringBuilder builder = new StringBuilder(); string hdr1 = GetComparableForm(builder); builder.Remove(0, builder.Length); string hdr2 = hdr.GetComparableForm(builder); if (hdr1.Length != hdr2.Length) return false; if (string.CompareOrdinal(hdr1, hdr2) != 0) return false; return true; } internal string GetComparableForm() { return GetComparableForm(new StringBuilder()); } internal string GetComparableForm(StringBuilder builder) { return EndpointAddressProcessor.GetComparableForm(builder, GetComparableReader()); } public override int GetHashCode() { return GetComparableForm().GetHashCode(); } public T GetValue<T>() { return GetValue<T>(DataContractSerializerDefaults.CreateSerializer(typeof(T), this.Name, this.Namespace, int.MaxValue/*maxItems*/)); } public T GetValue<T>(XmlObjectSerializer serializer) { if (serializer == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("serializer")); using (XmlDictionaryReader reader = GetAddressHeaderReader()) { if (serializer.IsStartObject(reader)) return (T)serializer.ReadObject(reader); else throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(string.Format(SRServiceModel.ExpectedElementMissing, Name, Namespace))); } } public virtual XmlDictionaryReader GetAddressHeaderReader() { XmlBuffer buffer = new XmlBuffer(int.MaxValue); XmlDictionaryWriter writer = buffer.OpenSection(XmlDictionaryReaderQuotas.Max); WriteAddressHeader(writer); buffer.CloseSection(); buffer.Close(); return buffer.GetReader(0); } private XmlDictionaryReader GetComparableReader() { throw ExceptionHelper.PlatformNotSupported(); } protected virtual void OnWriteStartAddressHeader(XmlDictionaryWriter writer) { writer.WriteStartElement(Name, Namespace); } protected abstract void OnWriteAddressHeaderContents(XmlDictionaryWriter writer); public MessageHeader ToMessageHeader() { if (_header == null) _header = new ParameterHeader(this); return _header; } public void WriteAddressHeader(XmlWriter writer) { WriteAddressHeader(XmlDictionaryWriter.CreateDictionaryWriter(writer)); } public void WriteAddressHeader(XmlDictionaryWriter writer) { if (writer == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("writer")); WriteStartAddressHeader(writer); WriteAddressHeaderContents(writer); writer.WriteEndElement(); } public void WriteStartAddressHeader(XmlDictionaryWriter writer) { if (writer == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("writer")); OnWriteStartAddressHeader(writer); } public void WriteAddressHeaderContents(XmlDictionaryWriter writer) { if (writer == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("writer")); OnWriteAddressHeaderContents(writer); } internal class ParameterHeader : MessageHeader { private AddressHeader _parameter; public override bool IsReferenceParameter { get { return true; } } public override string Name { get { return _parameter.Name; } } public override string Namespace { get { return _parameter.Namespace; } } public ParameterHeader(AddressHeader parameter) { _parameter = parameter; } protected override void OnWriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion) { if (messageVersion == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("messageVersion")); WriteStartHeader(writer, _parameter, messageVersion.Addressing); } protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { WriteHeaderContents(writer, _parameter); } internal static void WriteStartHeader(XmlDictionaryWriter writer, AddressHeader parameter, AddressingVersion addressingVersion) { parameter.WriteStartAddressHeader(writer); if (addressingVersion == AddressingVersion.WSAddressing10) { writer.WriteAttributeString(XD.AddressingDictionary.IsReferenceParameter, XD.Addressing10Dictionary.Namespace, "true"); } } internal static void WriteHeaderContents(XmlDictionaryWriter writer, AddressHeader parameter) { parameter.WriteAddressHeaderContents(writer); } } internal class XmlObjectSerializerAddressHeader : AddressHeader { private XmlObjectSerializer _serializer; private object _objectToSerialize; private string _name; private string _ns; public XmlObjectSerializerAddressHeader(object objectToSerialize, XmlObjectSerializer serializer) { _serializer = serializer; _objectToSerialize = objectToSerialize; throw ExceptionHelper.PlatformNotSupported(); } public XmlObjectSerializerAddressHeader(string name, string ns, object objectToSerialize, XmlObjectSerializer serializer) { if ((null == name) || (name.Length == 0)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("name")); } _serializer = serializer; _objectToSerialize = objectToSerialize; _name = name; _ns = ns; } public override string Name { get { return _name; } } public override string Namespace { get { return _ns; } } private object ThisLock { get { return this; } } protected override void OnWriteAddressHeaderContents(XmlDictionaryWriter writer) { lock (ThisLock) { _serializer.WriteObjectContent(writer, _objectToSerialize); } } } internal class DictionaryAddressHeader : XmlObjectSerializerAddressHeader { private XmlDictionaryString _name; private XmlDictionaryString _ns; public DictionaryAddressHeader(XmlDictionaryString name, XmlDictionaryString ns, object value) : base(name.Value, ns.Value, value, DataContractSerializerDefaults.CreateSerializer(GetObjectType(value), name, ns, int.MaxValue/*maxItems*/)) { _name = name; _ns = ns; } protected override void OnWriteStartAddressHeader(XmlDictionaryWriter writer) { writer.WriteStartElement(_name, _ns); } } } internal class BufferedAddressHeader : AddressHeader { private string _name; private string _ns; private XmlBuffer _buffer; private bool _isReferenceProperty; public BufferedAddressHeader(XmlDictionaryReader reader) { _buffer = new XmlBuffer(int.MaxValue); XmlDictionaryWriter writer = _buffer.OpenSection(reader.Quotas); Fx.Assert(reader.NodeType == XmlNodeType.Element, ""); _name = reader.LocalName; _ns = reader.NamespaceURI; Fx.Assert(_name != null, ""); Fx.Assert(_ns != null, ""); writer.WriteNode(reader, false); _buffer.CloseSection(); _buffer.Close(); _isReferenceProperty = false; } public BufferedAddressHeader(XmlDictionaryReader reader, bool isReferenceProperty) : this(reader) { _isReferenceProperty = isReferenceProperty; } public bool IsReferencePropertyHeader { get { return _isReferenceProperty; } } public override string Name { get { return _name; } } public override string Namespace { get { return _ns; } } public override XmlDictionaryReader GetAddressHeaderReader() { return _buffer.GetReader(0); } protected override void OnWriteStartAddressHeader(XmlDictionaryWriter writer) { XmlDictionaryReader reader = GetAddressHeaderReader(); writer.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI); writer.WriteAttributes(reader, false); reader.Dispose(); } protected override void OnWriteAddressHeaderContents(XmlDictionaryWriter writer) { XmlDictionaryReader reader = GetAddressHeaderReader(); reader.ReadStartElement(); while (reader.NodeType != XmlNodeType.EndElement) writer.WriteNode(reader, false); reader.ReadEndElement(); reader.Dispose(); } } }
using System.Collections.Generic; using TimedText.Formatting; using TimedText.Timing; namespace TimedText { /// <summary> /// The tt element serves as the root, document element of a document /// instance. The tt element accepts as its children zero or one head /// element followed by zero or one body element. /// </summary> public class TtElement : TimedTextElementBase { #region Private variables HeadElement m_head; BodyElement m_body; #endregion #region map ID's to regions. private Dictionary<string, RegionElement> m_regions; public Dictionary<string, RegionElement> Regions { get { return m_regions; } } public override BodyElement Body { get { return m_body; } set { m_body = value; } } public HeadElement Head { get { return m_head; } set { m_head = value; } } #endregion #region map ID's to agents. private Dictionary<string, Metadata.AgentElement> m_agents; public Dictionary<string, Metadata.AgentElement> Agents { get { return m_agents; } } #endregion #region map ID's to smpte images. private Dictionary<string, Smpte.ImageElement> m_images; public Dictionary<string, Smpte.ImageElement> Images { get { return m_images; } } #endregion #region map ID's to style. for referential styles private Dictionary<string, StyleElement> m_styles; public Dictionary<string, StyleElement> Styles { get { return m_styles; } } #endregion #region map parameter values private Dictionary<string, string> m_parameters; public Dictionary<string, string> Parameters { get { return m_parameters; } } #endregion #region Constructor public TtElement() { m_parameters = new Dictionary<string, string>(); m_styles = new Dictionary<string, StyleElement>(); m_agents = new Dictionary<string, Metadata.AgentElement>(); m_regions = new Dictionary<string, RegionElement>(); m_images = new Dictionary<string, Smpte.ImageElement>(); } #endregion #region Formatting /// <summary> /// return the root formatting object /// </summary> /// <param name="regionId"></param> /// <param name="tick"></param> /// <returns></returns> public override FormattingObject GetFormattingObject(TimeCode tick) { // if there is no body. then empty regions would be pruned // see 9.3.3. part 5. map each non-empty region element to // an fo:block-container element... if (m_body == null) return null; if (!m_body.TemporallyActive(tick)) return null; #region create single root and flow for the document. var root = new Formatting.Root(this); var flow = new Formatting.Flow(null); flow.Parent = root; root.Children.Add(flow); #endregion #region add a block container to the flow for each temporally active region foreach (var region in Regions.Values) { if (region.TemporallyActive(tick)) { var blockContainer = region.GetFormattingObject(tick); #region apply animations on regions foreach (var child in region.Children) { if (child is SetElement) { var fo = ((child as SetElement).GetFormattingObject(tick)); if (fo is Animation) { blockContainer.Animations.Add(fo as Animation); } } } #endregion blockContainer.Parent = flow; flow.Children.Add(blockContainer); #region create a new subtree for the body element /// select it into this region by adding its children /// to block container var block = m_body.GetFormattingObject(tick); if (block != null) { block.Prune(region.Id); // deselect any content not for this region if (block.Children.Count > 0) { if (block.Children[0].Children.Count > 0) { blockContainer.Children.Add(block); block.Parent = blockContainer; } } } #endregion } } #endregion return root; } #endregion #region validity /* <tt tts:extent = string xml:id = ID xml:lang = string (required) xml:space = (default|preserve) : default {any attribute in TT Parameter namespace ...} {any attribute not in default or any TT namespace ...}> Content: head?, body? </tt> */ /// <summary> /// Check tt element attribute validity /// </summary> protected override void ValidAttributes() { ValidateAttributes(true, false, false, false, false, false); if (Language == null) { Error("TT element must specify xml:lang attribute "); } } /// <summary> /// Check tt element validity /// </summary> protected override void ValidElements() { bool isValid = true; // we need an extra check to validate the root attributes in order // to ensure parameters are parsed. ValidAttributes(); #region check this elements model switch (Children.Count) { case 0: return; case 1: { #region test if child element is head or body if (Children[0] is HeadElement) { m_head = Children[0] as HeadElement; isValid = true; } else if (Children[0] is BodyElement) { m_body = Children[0] as BodyElement; m_head = new HeadElement(); Children.Clear(); Children.Add(m_head); Children.Add(m_body); isValid = true; } else { isValid = false; } #endregion } break; case 2: { #region Check first child is head, and second is body if (Children[0] is HeadElement) { m_head = Children[0] as HeadElement; } if (Children[1] is BodyElement) { m_body = Children[1] as BodyElement; } else { isValid = (m_body != null && m_head != null); } #endregion } break; default: { #region Cannot be valid isValid = false; #endregion } break; } #endregion if (!isValid) { Error("erroneous child in " + this.ToString()); } #region now check each of the children is individually valid foreach (TimedTextElementBase element in Children) { element.Valid(); } #endregion #region Add default region if none was specified if (isValid && Regions.Count < 1) { LayoutElement defaultLayout = new LayoutElement(); defaultLayout.LocalName = "layout"; defaultLayout.Namespace = m_head.Namespace; m_head.Children.Add(defaultLayout); defaultLayout.Parent = m_head; RegionElement defaultRegion = new RegionElement(); defaultRegion.SetLocalStyle("backgroundColor", "black"); defaultRegion.SetLocalStyle("color", "white"); defaultLayout.Children.Add(defaultRegion); defaultRegion.Parent = defaultLayout; defaultRegion.Id = RegionElement.DefaultRegionName; defaultRegion.Root = Root; Root.Regions[defaultRegion.Id] = defaultRegion; } #endregion } #endregion } }
/* * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: support@ultracart.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter; namespace com.ultracart.admin.v2.Model { /// <summary> /// OrderCheckout /// </summary> [DataContract] public partial class OrderCheckout : IEquatable<OrderCheckout>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="OrderCheckout" /> class. /// </summary> /// <param name="comments">Comments from the customer. Rarely used on the single page checkout..</param> /// <param name="customField1">Custom field 1.</param> /// <param name="customField2">Custom field 2.</param> /// <param name="customField3">Custom field 3.</param> /// <param name="customField4">Custom field 4.</param> /// <param name="customField5">Custom field 5.</param> /// <param name="customField6">Custom field 6.</param> /// <param name="customField7">Custom field 7.</param> /// <param name="customerIpAddress">IP address of the customer when placing the order.</param> /// <param name="screenBrandingThemeCode">Screen branding theme code associated with the order (legacy checkout).</param> /// <param name="storefrontHostName">StoreFront host name associated with the order.</param> /// <param name="upsellPathCode">Upsell path code assigned during the checkout that the customer went through.</param> public OrderCheckout(string comments = default(string), string customField1 = default(string), string customField2 = default(string), string customField3 = default(string), string customField4 = default(string), string customField5 = default(string), string customField6 = default(string), string customField7 = default(string), string customerIpAddress = default(string), string screenBrandingThemeCode = default(string), string storefrontHostName = default(string), string upsellPathCode = default(string)) { this.Comments = comments; this.CustomField1 = customField1; this.CustomField2 = customField2; this.CustomField3 = customField3; this.CustomField4 = customField4; this.CustomField5 = customField5; this.CustomField6 = customField6; this.CustomField7 = customField7; this.CustomerIpAddress = customerIpAddress; this.ScreenBrandingThemeCode = screenBrandingThemeCode; this.StorefrontHostName = storefrontHostName; this.UpsellPathCode = upsellPathCode; } /// <summary> /// Comments from the customer. Rarely used on the single page checkout. /// </summary> /// <value>Comments from the customer. Rarely used on the single page checkout.</value> [DataMember(Name="comments", EmitDefaultValue=false)] public string Comments { get; set; } /// <summary> /// Custom field 1 /// </summary> /// <value>Custom field 1</value> [DataMember(Name="custom_field1", EmitDefaultValue=false)] public string CustomField1 { get; set; } /// <summary> /// Custom field 2 /// </summary> /// <value>Custom field 2</value> [DataMember(Name="custom_field2", EmitDefaultValue=false)] public string CustomField2 { get; set; } /// <summary> /// Custom field 3 /// </summary> /// <value>Custom field 3</value> [DataMember(Name="custom_field3", EmitDefaultValue=false)] public string CustomField3 { get; set; } /// <summary> /// Custom field 4 /// </summary> /// <value>Custom field 4</value> [DataMember(Name="custom_field4", EmitDefaultValue=false)] public string CustomField4 { get; set; } /// <summary> /// Custom field 5 /// </summary> /// <value>Custom field 5</value> [DataMember(Name="custom_field5", EmitDefaultValue=false)] public string CustomField5 { get; set; } /// <summary> /// Custom field 6 /// </summary> /// <value>Custom field 6</value> [DataMember(Name="custom_field6", EmitDefaultValue=false)] public string CustomField6 { get; set; } /// <summary> /// Custom field 7 /// </summary> /// <value>Custom field 7</value> [DataMember(Name="custom_field7", EmitDefaultValue=false)] public string CustomField7 { get; set; } /// <summary> /// IP address of the customer when placing the order /// </summary> /// <value>IP address of the customer when placing the order</value> [DataMember(Name="customer_ip_address", EmitDefaultValue=false)] public string CustomerIpAddress { get; set; } /// <summary> /// Screen branding theme code associated with the order (legacy checkout) /// </summary> /// <value>Screen branding theme code associated with the order (legacy checkout)</value> [DataMember(Name="screen_branding_theme_code", EmitDefaultValue=false)] public string ScreenBrandingThemeCode { get; set; } /// <summary> /// StoreFront host name associated with the order /// </summary> /// <value>StoreFront host name associated with the order</value> [DataMember(Name="storefront_host_name", EmitDefaultValue=false)] public string StorefrontHostName { get; set; } /// <summary> /// Upsell path code assigned during the checkout that the customer went through /// </summary> /// <value>Upsell path code assigned during the checkout that the customer went through</value> [DataMember(Name="upsell_path_code", EmitDefaultValue=false)] public string UpsellPathCode { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class OrderCheckout {\n"); sb.Append(" Comments: ").Append(Comments).Append("\n"); sb.Append(" CustomField1: ").Append(CustomField1).Append("\n"); sb.Append(" CustomField2: ").Append(CustomField2).Append("\n"); sb.Append(" CustomField3: ").Append(CustomField3).Append("\n"); sb.Append(" CustomField4: ").Append(CustomField4).Append("\n"); sb.Append(" CustomField5: ").Append(CustomField5).Append("\n"); sb.Append(" CustomField6: ").Append(CustomField6).Append("\n"); sb.Append(" CustomField7: ").Append(CustomField7).Append("\n"); sb.Append(" CustomerIpAddress: ").Append(CustomerIpAddress).Append("\n"); sb.Append(" ScreenBrandingThemeCode: ").Append(ScreenBrandingThemeCode).Append("\n"); sb.Append(" StorefrontHostName: ").Append(StorefrontHostName).Append("\n"); sb.Append(" UpsellPathCode: ").Append(UpsellPathCode).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as OrderCheckout); } /// <summary> /// Returns true if OrderCheckout instances are equal /// </summary> /// <param name="input">Instance of OrderCheckout to be compared</param> /// <returns>Boolean</returns> public bool Equals(OrderCheckout input) { if (input == null) return false; return ( this.Comments == input.Comments || (this.Comments != null && this.Comments.Equals(input.Comments)) ) && ( this.CustomField1 == input.CustomField1 || (this.CustomField1 != null && this.CustomField1.Equals(input.CustomField1)) ) && ( this.CustomField2 == input.CustomField2 || (this.CustomField2 != null && this.CustomField2.Equals(input.CustomField2)) ) && ( this.CustomField3 == input.CustomField3 || (this.CustomField3 != null && this.CustomField3.Equals(input.CustomField3)) ) && ( this.CustomField4 == input.CustomField4 || (this.CustomField4 != null && this.CustomField4.Equals(input.CustomField4)) ) && ( this.CustomField5 == input.CustomField5 || (this.CustomField5 != null && this.CustomField5.Equals(input.CustomField5)) ) && ( this.CustomField6 == input.CustomField6 || (this.CustomField6 != null && this.CustomField6.Equals(input.CustomField6)) ) && ( this.CustomField7 == input.CustomField7 || (this.CustomField7 != null && this.CustomField7.Equals(input.CustomField7)) ) && ( this.CustomerIpAddress == input.CustomerIpAddress || (this.CustomerIpAddress != null && this.CustomerIpAddress.Equals(input.CustomerIpAddress)) ) && ( this.ScreenBrandingThemeCode == input.ScreenBrandingThemeCode || (this.ScreenBrandingThemeCode != null && this.ScreenBrandingThemeCode.Equals(input.ScreenBrandingThemeCode)) ) && ( this.StorefrontHostName == input.StorefrontHostName || (this.StorefrontHostName != null && this.StorefrontHostName.Equals(input.StorefrontHostName)) ) && ( this.UpsellPathCode == input.UpsellPathCode || (this.UpsellPathCode != null && this.UpsellPathCode.Equals(input.UpsellPathCode)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Comments != null) hashCode = hashCode * 59 + this.Comments.GetHashCode(); if (this.CustomField1 != null) hashCode = hashCode * 59 + this.CustomField1.GetHashCode(); if (this.CustomField2 != null) hashCode = hashCode * 59 + this.CustomField2.GetHashCode(); if (this.CustomField3 != null) hashCode = hashCode * 59 + this.CustomField3.GetHashCode(); if (this.CustomField4 != null) hashCode = hashCode * 59 + this.CustomField4.GetHashCode(); if (this.CustomField5 != null) hashCode = hashCode * 59 + this.CustomField5.GetHashCode(); if (this.CustomField6 != null) hashCode = hashCode * 59 + this.CustomField6.GetHashCode(); if (this.CustomField7 != null) hashCode = hashCode * 59 + this.CustomField7.GetHashCode(); if (this.CustomerIpAddress != null) hashCode = hashCode * 59 + this.CustomerIpAddress.GetHashCode(); if (this.ScreenBrandingThemeCode != null) hashCode = hashCode * 59 + this.ScreenBrandingThemeCode.GetHashCode(); if (this.StorefrontHostName != null) hashCode = hashCode * 59 + this.StorefrontHostName.GetHashCode(); if (this.UpsellPathCode != null) hashCode = hashCode * 59 + this.UpsellPathCode.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { // CustomField1 (string) maxLength if(this.CustomField1 != null && this.CustomField1.Length > 50) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for CustomField1, length must be less than 50.", new [] { "CustomField1" }); } // CustomField2 (string) maxLength if(this.CustomField2 != null && this.CustomField2.Length > 50) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for CustomField2, length must be less than 50.", new [] { "CustomField2" }); } // CustomField3 (string) maxLength if(this.CustomField3 != null && this.CustomField3.Length > 50) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for CustomField3, length must be less than 50.", new [] { "CustomField3" }); } // CustomField4 (string) maxLength if(this.CustomField4 != null && this.CustomField4.Length > 50) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for CustomField4, length must be less than 50.", new [] { "CustomField4" }); } // CustomField5 (string) maxLength if(this.CustomField5 != null && this.CustomField5.Length > 75) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for CustomField5, length must be less than 75.", new [] { "CustomField5" }); } // CustomField6 (string) maxLength if(this.CustomField6 != null && this.CustomField6.Length > 50) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for CustomField6, length must be less than 50.", new [] { "CustomField6" }); } // CustomField7 (string) maxLength if(this.CustomField7 != null && this.CustomField7.Length > 50) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for CustomField7, length must be less than 50.", new [] { "CustomField7" }); } // ScreenBrandingThemeCode (string) maxLength if(this.ScreenBrandingThemeCode != null && this.ScreenBrandingThemeCode.Length > 10) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for ScreenBrandingThemeCode, length must be less than 10.", new [] { "ScreenBrandingThemeCode" }); } yield break; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO; using System.Threading; namespace System.Xml { /// <include file='doc\XmlCharType.uex' path='docs/doc[@for="XmlCharType"]/*' /> /// <internalonly/> /// <devdoc> /// The XmlCharType class is used for quick character type recognition /// which is optimized for the first 127 ascii characters. /// </devdoc> unsafe internal struct XmlCharType { // 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 // 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; // 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; // 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; } } private static volatile byte* s_CharProperties; internal byte* charProperties; private static void InitInstance() { lock (StaticLock) { if (s_CharProperties != null) { return; } UnmanagedMemoryStream memStream = (UnmanagedMemoryStream)typeof(XmlWriter).Assembly.GetManifestResourceStream("XmlCharType.bin"); Debug.Assert(memStream.Length == CharPropertiesSize); byte* chProps = memStream.PositionPointer; Thread.MemoryBarrier(); // For weak memory models (IA64) s_CharProperties = chProps; } } private XmlCharType(byte* charProperties) { 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; } // 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 == ':'; } // 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 == ':'; } // 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 static void SplitSurrogateChar(int combinedChar, out char lowChar, out char highChar) { int v = combinedChar - 0x10000; lowChar = (char)(SurLowStart + v % 1024); highChar = (char)(SurHighStart + v / 1024); } 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 } }
// 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 Microsoft.Data.Entity; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Relational.Migrations.Infrastructure; using PartsUnlimited.Models; namespace PartsUnlimited.Models.Migrations { [ContextType(typeof(PartsUnlimitedContext))] partial class PartsUnlimitedContextModelSnapshot : ModelSnapshot { public override void BuildModel(ModelBuilder builder) { builder .Annotation("SqlServer:ValueGeneration", "Identity"); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => { b.Property<string>("Id") .GenerateValueOnAdd(); b.Property<string>("ConcurrencyStamp") .ConcurrencyToken(); b.Property<string>("Name"); b.Property<string>("NormalizedName"); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetRoles"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId"); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetRoleClaims"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Property<int>("Id") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId"); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetUserClaims"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .GenerateValueOnAdd(); b.Property<string>("ProviderKey") .GenerateValueOnAdd(); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId"); b.Key("LoginProvider", "ProviderKey"); b.Annotation("Relational:TableName", "AspNetUserLogins"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.Key("UserId", "RoleId"); b.Annotation("Relational:TableName", "AspNetUserRoles"); }); builder.Entity("PartsUnlimited.Models.ApplicationUser", b => { b.Property<string>("Id") .GenerateValueOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .ConcurrencyToken(); b.Property<string>("Email"); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("Name"); b.Property<string>("NormalizedEmail"); b.Property<string>("NormalizedUserName"); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName"); b.Key("Id"); b.Annotation("Relational:TableName", "AspNetUsers"); }); builder.Entity("PartsUnlimited.Models.CartItem", b => { b.Property<int>("CartItemId") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity); b.Property<string>("CartId"); b.Property<int>("Count"); b.Property<DateTime>("DateCreated"); b.Property<int>("ProductId"); b.Key("CartItemId"); }); builder.Entity("PartsUnlimited.Models.Category", b => { b.Property<int>("CategoryId") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity); b.Property<string>("Description"); b.Property<string>("ImageUrl"); b.Property<string>("Name"); b.Key("CategoryId"); }); builder.Entity("PartsUnlimited.Models.Order", b => { b.Property<int>("OrderId") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity); b.Property<string>("Address"); b.Property<string>("City"); b.Property<string>("Country"); b.Property<string>("Email"); b.Property<string>("Name"); b.Property<DateTime>("OrderDate"); b.Property<string>("Phone"); b.Property<string>("PostalCode"); b.Property<bool>("Processed"); b.Property<string>("State"); b.Property<decimal>("Total"); b.Property<string>("Username"); b.Key("OrderId"); }); builder.Entity("PartsUnlimited.Models.OrderDetail", b => { b.Property<int>("OrderDetailId") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity); b.Property<int>("OrderId"); b.Property<int>("ProductId"); b.Property<int>("Quantity"); b.Property<decimal>("UnitPrice"); b.Key("OrderDetailId"); }); builder.Entity("PartsUnlimited.Models.Product", b => { b.Property<int>("ProductId") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity); b.Property<int>("CategoryId"); b.Property<DateTime>("Created"); b.Property<string>("Description"); b.Property<int>("Inventory"); b.Property<int>("LeadTime"); b.Property<decimal>("Price"); b.Property<string>("ProductArtUrl"); b.Property<string>("ProductDetails"); b.Property<int>("RecommendationId"); b.Property<decimal>("SalePrice"); b.Property<string>("SkuNumber"); b.Property<string>("Title"); b.Key("ProductId"); }); builder.Entity("PartsUnlimited.Models.Raincheck", b => { b.Property<int>("RaincheckId") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity); b.Property<string>("Name"); b.Property<int>("ProductId"); b.Property<int>("Quantity"); b.Property<double>("SalePrice"); b.Property<int>("StoreId"); b.Key("RaincheckId"); }); builder.Entity("PartsUnlimited.Models.Store", b => { b.Property<int>("StoreId") .GenerateValueOnAdd() .StoreGeneratedPattern(StoreGeneratedPattern.Identity); b.Property<string>("Name"); b.Key("StoreId"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .InverseCollection() .ForeignKey("RoleId"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Reference("PartsUnlimited.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Reference("PartsUnlimited.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); builder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Reference("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .InverseCollection() .ForeignKey("RoleId"); b.Reference("PartsUnlimited.Models.ApplicationUser") .InverseCollection() .ForeignKey("UserId"); }); builder.Entity("PartsUnlimited.Models.CartItem", b => { b.Reference("PartsUnlimited.Models.Product") .InverseCollection() .ForeignKey("ProductId"); }); builder.Entity("PartsUnlimited.Models.OrderDetail", b => { b.Reference("PartsUnlimited.Models.Order") .InverseCollection() .ForeignKey("OrderId"); b.Reference("PartsUnlimited.Models.Product") .InverseCollection() .ForeignKey("ProductId"); }); builder.Entity("PartsUnlimited.Models.Product", b => { b.Reference("PartsUnlimited.Models.Category") .InverseCollection() .ForeignKey("CategoryId"); }); builder.Entity("PartsUnlimited.Models.Raincheck", b => { b.Reference("PartsUnlimited.Models.Product") .InverseCollection() .ForeignKey("ProductId"); b.Reference("PartsUnlimited.Models.Store") .InverseCollection() .ForeignKey("StoreId"); }); } } }
// 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.Xml; using OLEDB.Test.ModuleCore; using System.IO; using XmlReaderTest.Common; using System.Collections; namespace XmlReaderTest.CustomReaderTest { [TestModule(Name = "CustomReader Test", Desc = "CustomReader Test")] public partial class CReaderTestModule : CGenericTestModule { public override int Init(object objParam) { int ret = base.Init(objParam); string strFile = String.Empty; TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.GENERIC); TestFiles.CreateTestFile(ref strFile, EREADER_TYPE.XSLT_COPY); ReaderFactory = new CustomReaderFactory(); return ret; } public override int Terminate(object objParam) { return base.Terminate(objParam); } } //////////////////////////////////////////////////////////////// // CustomInheritedReader factory // //////////////////////////////////////////////////////////////// internal class CustomReaderFactory : ReaderFactory { public override XmlReader Create(MyDict<string, object> options) { string tcDesc = (string)options[ReaderFactory.HT_CURDESC]; string tcVar = (string)options[ReaderFactory.HT_CURVAR]; CError.Compare(tcDesc == "custominheritedreader", "Invalid testcase"); Stream stream = (Stream)options[ReaderFactory.HT_STREAM]; string filename = (string)options[ReaderFactory.HT_FILENAME]; string fragment = (string)options[ReaderFactory.HT_FRAGMENT]; StringReader sr = (StringReader)options[ReaderFactory.HT_STRINGREADER]; if (sr != null) { return new CustomReader(sr, false); } if (stream != null) { return new CustomReader(stream); } if (fragment != null) { return new CustomReader(new StringReader(fragment), true); } if (filename != null) { return new CustomReader(filename); } throw new CTestFailedException("CustomReader not created"); } } [TestCase(Name = "InvalidXML", Desc = "CustomInheritedReader")] internal class TCInvalidXMLReader : TCInvalidXML { } [TestCase(Name = "ErrorCondition", Desc = "CustomInheritedReader")] internal class TCErrorConditionReader : TCErrorCondition { } [TestCase(Name = "XMLException", Desc = "CustomInheritedReader")] public class TCXMLExceptionReader : TCXMLException { } [TestCase(Name = "LinePos", Desc = "CustomInheritedReader")] public class TCLinePosReader : TCLinePos { } [TestCase(Name = "ReadOuterXml", Desc = "CustomInheritedReader")] internal class TCReadOuterXmlReader : TCReadOuterXml { } [TestCase(Name = "AttributeAccess", Desc = "CustomInheritedReader")] internal class TCAttributeAccessReader : TCAttributeAccess { } [TestCase(Name = "This(Name) and This(Name, Namespace)", Desc = "CustomInheritedReader")] internal class TCThisNameReader : TCThisName { } [TestCase(Name = "MoveToAttribute(Name) and MoveToAttribute(Name, Namespace)", Desc = "CustomInheritedReader")] internal class TCMoveToAttributeReader : TCMoveToAttribute { } [TestCase(Name = "GetAttribute (Ordinal)", Desc = "CustomInheritedReader")] internal class TCGetAttributeOrdinalReader : TCGetAttributeOrdinal { } [TestCase(Name = "GetAttribute(Name) and GetAttribute(Name, Namespace)", Desc = "CustomInheritedReader")] internal class TCGetAttributeNameReader : TCGetAttributeName { } [TestCase(Name = "This [Ordinal]", Desc = "CustomInheritedReader")] internal class TCThisOrdinalReader : TCThisOrdinal { } [TestCase(Name = "MoveToAttribute(Ordinal)", Desc = "CustomInheritedReader")] internal class TCMoveToAttributeOrdinalReader : TCMoveToAttributeOrdinal { } [TestCase(Name = "MoveToFirstAttribute()", Desc = "CustomInheritedReader")] internal class TCMoveToFirstAttributeReader : TCMoveToFirstAttribute { } [TestCase(Name = "MoveToNextAttribute()", Desc = "CustomInheritedReader")] internal class TCMoveToNextAttributeReader : TCMoveToNextAttribute { } [TestCase(Name = "Attribute Test when NodeType != Attributes", Desc = "CustomInheritedReader")] internal class TCAttributeTestReader : TCAttributeTest { } [TestCase(Name = "Attributes test on XmlDeclaration DCR52258", Desc = "CustomInheritedReader")] internal class TCAttributeXmlDeclarationReader : TCAttributeXmlDeclaration { } [TestCase(Name = "xmlns as local name DCR50345", Desc = "CustomInheritedReader")] internal class TCXmlnsReader : TCXmlns { } [TestCase(Name = "bounded namespace to xmlns prefix DCR50881", Desc = "CustomInheritedReader")] internal class TCXmlnsPrefixReader : TCXmlnsPrefix { } [TestCase(Name = "ReadState", Desc = "CustomInheritedReader")] internal class TCReadStateReader : TCReadState { } [TestCase(Name = "ReadInnerXml", Desc = "CustomInheritedReader")] internal class TCReadInnerXmlReader : TCReadInnerXml { } [TestCase(Name = "MoveToContent", Desc = "CustomInheritedReader")] internal class TCMoveToContentReader : TCMoveToContent { } [TestCase(Name = "IsStartElement", Desc = "CustomInheritedReader")] internal class TCIsStartElementReader : TCIsStartElement { } [TestCase(Name = "ReadStartElement", Desc = "CustomInheritedReader")] internal class TCReadStartElementReader : TCReadStartElement { } [TestCase(Name = "ReadEndElement", Desc = "CustomInheritedReader")] internal class TCReadEndElementReader : TCReadEndElement { } [TestCase(Name = "ResolveEntity and ReadAttributeValue", Desc = "CustomInheritedReader")] internal class TCResolveEntityReader : TCResolveEntity { } [TestCase(Name = "ReadAttributeValue", Desc = "CustomInheritedReader")] internal class TCReadAttributeValueReader : TCReadAttributeValue { } [TestCase(Name = "Read", Desc = "CustomInheritedReader")] internal class TCReadReader : TCRead2 { } [TestCase(Name = "Read Subtree", Desc = "CustomInheritedReader")] internal class TCReadSubtreeReader : TCReadSubtree { } [TestCase(Name = "ReadToDescendant", Desc = "CustomInheritedReader")] internal class TCReadToDescendantReader : TCReadToDescendant { } [TestCase(Name = "ReadToNextSibling", Desc = "CustomInheritedReader")] internal class TCReadToNextSiblingReader : TCReadToNextSibling { } [TestCase(Name = "ReadToFollowing", Desc = "CustomInheritedReader")] internal class TCReadToFollowingReader : TCReadToFollowing { } [TestCase(Name = "MoveToElement", Desc = "CustomInheritedReader")] internal class TCMoveToElementReader : TCMoveToElement { } [TestCase(Name = "Buffer Boundary", Desc = "CustomInheritedReader")] internal class TCBufferBoundariesReader : TCBufferBoundaries { } [TestCase(Name = "Dispose", Desc = "CustomInheritedReader")] internal class TCDisposeReader : TCDispose { } [TestCase(Name = "TCXmlNodeIntegrityTestFile", Desc = "TCXmlNodeIntegrityTestFile")] internal class TCXmlNodeIntegrityTestFile : TCXMLIntegrityBase { } [TestCase(Name = "ReadValue", Desc = "CustomInheritedReader")] internal class TCReadValueReader : TCReadValue { } [TestCase(Name = "ReadContentAsBase64", Desc = "CustomInheritedReader")] internal class TCReadContentAsBase64Reader : TCReadContentAsBase64 { } [TestCase(Name = "ReadElementContentAsBase64", Desc = "CustomInheritedReader")] internal class TCReadElementContentAsBase64Reader : TCReadElementContentAsBase64 { } [TestCase(Name = "ReadContentAsBinHex", Desc = "CustomInheritedReader")] internal class TCReadContentAsBinHexReader : TCReadContentAsBinHex { } [TestCase(Name = "ReadElementContentAsBinHex", Desc = "CustomInheritedReader")] internal class TCReadElementContentAsBinHexReader : TCReadElementContentAsBinHex { } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // // File: Border.cs // // Description: Contains the Border Decorator class. // Spec at http://avalon/layout/Specs/Border.xml // // History: // 06/05/2003 : greglett - Added to WCP branch (was BBPPresenter.cs in old branch) // 07/19/2004 : t-jaredg - Update to allow for greater flexibility, etc. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.PresentationFramework; using MS.Utility; using System; using System.Diagnostics; using System.Windows.Threading; using System.Windows.Media; namespace System.Windows.Controls { /// <summary> /// The Border decorator is used to draw a border and/or background around another element. /// </summary> public class Border : Decorator { //------------------------------------------------------------------- // // Constructors // //------------------------------------------------------------------- #region Constructors /// <summary> /// Default DependencyObject constructor /// </summary> /// <remarks> /// Automatic determination of current Dispatcher. Use alternative constructor /// that accepts a Dispatcher for best performance. /// </remarks> public Border() : base() { } #endregion //------------------------------------------------------------------- // // Public Methods // //------------------------------------------------------------------- //------------------------------------------------------------------- // // Public Properties // //------------------------------------------------------------------- #region Public Properties /// <summary> /// The BorderThickness property defined how thick a border to draw. The property's value is a /// <see cref="System.Windows.Thickness" /> containing values for each of the Left, Top, Right, /// and Bottom sides. Values of Auto are interpreted as zero. /// </summary> public Thickness BorderThickness { get { return (Thickness) GetValue(BorderThicknessProperty); } set { SetValue(BorderThicknessProperty, value); } } /// <summary> /// The Padding property inflates the effective size of the child by the specified thickness. This /// achieves the same effect as adding margin on the child, but is present here for convenience. /// </summary> public Thickness Padding { get { return (Thickness) GetValue(PaddingProperty); } set { SetValue(PaddingProperty, value); } } /// <summary> /// The CornerRadius property allows users to control the roundness of the corners independently by /// setting a radius value for each corner. Radius values that are too large are scaled so that they /// smoothly blend from corner to corner. /// </summary> public CornerRadius CornerRadius { get { return (CornerRadius) GetValue(CornerRadiusProperty); } set { SetValue(CornerRadiusProperty, value); } } /// <summary> /// The BorderBrush property defines the brush used to fill the border region. /// </summary> public Brush BorderBrush { get { return (Brush) GetValue(BorderBrushProperty); } set { SetValue(BorderBrushProperty, value); } } /// <summary> /// The Background property defines the brush used to fill the area within the border. /// </summary> public Brush Background { get { return (Brush) GetValue(BackgroundProperty); } set { SetValue(BackgroundProperty, value); } } /// <summary> /// DependencyProperty for <see cref="BorderThickness" /> property. /// </summary> [CommonDependencyProperty] public static readonly DependencyProperty BorderThicknessProperty = DependencyProperty.Register("BorderThickness", typeof(Thickness), typeof(Border), new FrameworkPropertyMetadata( new Thickness(), FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender, new PropertyChangedCallback(OnClearPenCache)), new ValidateValueCallback(IsThicknessValid)); private static void OnClearPenCache(DependencyObject d, DependencyPropertyChangedEventArgs e) { Border border = (Border)d; border.LeftPenCache = null; border.RightPenCache = null; border.TopPenCache = null; border.BottomPenCache = null; } private static bool IsThicknessValid(object value) { Thickness t = (Thickness)value; return t.IsValid(false, false, false, false); } /// <summary> /// DependencyProperty for <see cref="Padding" /> property. /// </summary> public static readonly DependencyProperty PaddingProperty = DependencyProperty.Register("Padding", typeof(Thickness), typeof(Border), new FrameworkPropertyMetadata( new Thickness(), FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender), new ValidateValueCallback(IsThicknessValid)); /// <summary> /// DependencyProperty for <see cref="CornerRadius" /> property. /// </summary> public static readonly DependencyProperty CornerRadiusProperty = DependencyProperty.Register("CornerRadius", typeof(CornerRadius), typeof(Border), new FrameworkPropertyMetadata( new CornerRadius(), FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender), new ValidateValueCallback(IsCornerRadiusValid)); private static bool IsCornerRadiusValid(object value) { CornerRadius cr = (CornerRadius)value; return (cr.IsValid(false, false, false, false)); } /// <summary> /// DependencyProperty for <see cref="BorderBrush" /> property. /// </summary> [CommonDependencyProperty] public static readonly DependencyProperty BorderBrushProperty = DependencyProperty.Register("BorderBrush", typeof(Brush), typeof(Border), new FrameworkPropertyMetadata( (Brush)null, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.SubPropertiesDoNotAffectRender, new PropertyChangedCallback(OnClearPenCache))); /// <summary> /// DependencyProperty for <see cref="Background" /> property. /// </summary> [CommonDependencyProperty] public static readonly DependencyProperty BackgroundProperty = Panel.BackgroundProperty.AddOwner(typeof(Border), new FrameworkPropertyMetadata( (Brush)null, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.SubPropertiesDoNotAffectRender)); #endregion Public Properties //------------------------------------------------------------------- // // Protected Methods // //------------------------------------------------------------------- #region Protected Methods /// <summary> /// Updates DesiredSize of the Border. Called by parent UIElement. This is the first pass of layout. /// </summary> /// <remarks> /// Border determines its desired size it needs from the specified border the child: its sizing /// properties, margin, and requested size. /// </remarks> /// <param name="constraint">Constraint size is an "upper limit" that the return value should not exceed.</param> /// <returns>The Decorator's desired size.</returns> protected override Size MeasureOverride(Size constraint) { UIElement child = Child; Size mySize = new Size(); Thickness borders = this.BorderThickness; if (this.UseLayoutRounding && !FrameworkAppContextSwitches.DoNotApplyLayoutRoundingToMarginsAndBorderThickness) { double dpiScaleX = FrameworkElement.DpiScaleX; double dpiScaleY = FrameworkElement.DpiScaleY; borders = new Thickness(UIElement.RoundLayoutValue(borders.Left, dpiScaleX), UIElement.RoundLayoutValue(borders.Top, dpiScaleY), UIElement.RoundLayoutValue(borders.Right, dpiScaleX), UIElement.RoundLayoutValue(borders.Bottom, dpiScaleY)); } // Compute the chrome size added by the various elements Size border = HelperCollapseThickness(borders); Size padding = HelperCollapseThickness(this.Padding); //If we have a child if (child != null) { // Combine into total decorating size Size combined = new Size(border.Width + padding.Width, border.Height + padding.Height); // Remove size of border only from child's reference size. Size childConstraint = new Size(Math.Max(0.0, constraint.Width - combined.Width), Math.Max(0.0, constraint.Height - combined.Height)); child.Measure(childConstraint); Size childSize = child.DesiredSize; // Now use the returned size to drive our size, by adding back the margins, etc. mySize.Width = childSize.Width + combined.Width; mySize.Height = childSize.Height + combined.Height; } else { // Combine into total decorating size mySize = new Size(border.Width + padding.Width, border.Height + padding.Height); } return mySize; } /// <summary> /// Border computes the position of its single child and applies its child's alignments to the child. /// /// </summary> /// <param name="finalSize">The size reserved for this element by the parent</param> /// <returns>The actual ink area of the element, typically the same as finalSize</returns> protected override Size ArrangeOverride(Size finalSize) { Thickness borders = BorderThickness; if (this.UseLayoutRounding && !FrameworkAppContextSwitches.DoNotApplyLayoutRoundingToMarginsAndBorderThickness) { double dpiScaleX = FrameworkElement.DpiScaleX; double dpiScaleY = FrameworkElement.DpiScaleY; borders = new Thickness(UIElement.RoundLayoutValue(borders.Left, dpiScaleX), UIElement.RoundLayoutValue(borders.Top, dpiScaleY), UIElement.RoundLayoutValue(borders.Right, dpiScaleX), UIElement.RoundLayoutValue(borders.Bottom, dpiScaleY)); } Rect boundRect = new Rect(finalSize); Rect innerRect = HelperDeflateRect(boundRect, borders); // arrange child UIElement child = Child; if (child != null) { Rect childRect = HelperDeflateRect(innerRect, Padding); child.Arrange(childRect); } CornerRadius radii = CornerRadius; Brush borderBrush = BorderBrush; bool uniformCorners = AreUniformCorners(radii); // decide which code path to execute. complex (geometry path based) rendering // is used if one of the following is true: // 1. there are non-uniform rounded corners _useComplexRenderCodePath = !uniformCorners; if ( !_useComplexRenderCodePath && borderBrush != null ) { SolidColorBrush originIndependentBrush = borderBrush as SolidColorBrush; bool uniformBorders = borders.IsUniform; _useComplexRenderCodePath = // 2. the border brush is origin dependent (the only origin independent brush is a solid color brush) (originIndependentBrush == null) // 3. the border brush is semi-transtarent solid color brush AND border thickness is not uniform // (for uniform semi-transparent border Border.OnRender draws rectangle outline - so it works fine) || ((originIndependentBrush.Color.A < 0xff) && !uniformBorders) // 4. there are rounded corners AND the border thickness is not uniform || (!DoubleUtil.IsZero(radii.TopLeft) && !uniformBorders); } if (_useComplexRenderCodePath) { Radii innerRadii = new Radii(radii, borders, false); StreamGeometry backgroundGeometry = null; // calculate border / background rendering geometry if (!DoubleUtil.IsZero(innerRect.Width) && !DoubleUtil.IsZero(innerRect.Height)) { backgroundGeometry = new StreamGeometry(); using (StreamGeometryContext ctx = backgroundGeometry.Open()) { GenerateGeometry(ctx, innerRect, innerRadii); } backgroundGeometry.Freeze(); BackgroundGeometryCache = backgroundGeometry; } else { BackgroundGeometryCache = null; } if (!DoubleUtil.IsZero(boundRect.Width) && !DoubleUtil.IsZero(boundRect.Height)) { Radii outerRadii = new Radii(radii, borders, true); StreamGeometry borderGeometry = new StreamGeometry(); using (StreamGeometryContext ctx = borderGeometry.Open()) { GenerateGeometry(ctx, boundRect, outerRadii); if (backgroundGeometry != null) { GenerateGeometry(ctx, innerRect, innerRadii); } } borderGeometry.Freeze(); BorderGeometryCache = borderGeometry; } else { BorderGeometryCache = null; } } else { BackgroundGeometryCache = null; BorderGeometryCache = null; } return (finalSize); } /// <summary> /// In addition to the child, Border renders a background + border. The background is drawn inside the border. /// </summary> protected override void OnRender(DrawingContext dc) { bool useLayoutRounding = this.UseLayoutRounding; if (_useComplexRenderCodePath) { Brush brush; StreamGeometry borderGeometry = BorderGeometryCache; if ( borderGeometry != null && (brush = BorderBrush) != null ) { dc.DrawGeometry(brush, null, borderGeometry); } StreamGeometry backgroundGeometry = BackgroundGeometryCache; if ( backgroundGeometry != null && (brush = Background) != null ) { dc.DrawGeometry(brush, null, backgroundGeometry); } } else { Thickness border = BorderThickness; Brush borderBrush; CornerRadius cornerRadius = CornerRadius; double outerCornerRadius = cornerRadius.TopLeft; // Already validated that all corners have the same radius bool roundedCorners = !DoubleUtil.IsZero(outerCornerRadius); // If we have a brush with which to draw the border, do so. // NB: We double draw corners right now. Corner handling is tricky (bevelling, &c...) and // we need a firm spec before doing "the right thing." (greglett, ffortes) if (!border.IsZero && (borderBrush = BorderBrush) != null) { // Initialize the first pen. Note that each pen is created via new() // and frozen if possible. Doing this avoids the pen // being copied when used in the DrawLine methods. Pen pen = LeftPenCache; if (pen == null) { pen = new Pen(); pen.Brush = borderBrush; if (useLayoutRounding) { pen.Thickness = UIElement.RoundLayoutValue(border.Left, FrameworkElement.DpiScaleX); } else { pen.Thickness = border.Left; } if (borderBrush.IsFrozen) { pen.Freeze(); } LeftPenCache = pen; } double halfThickness; if (border.IsUniform) { halfThickness = pen.Thickness * 0.5; // Create rect w/ border thickness, and round if applying layout rounding. Rect rect = new Rect(new Point(halfThickness, halfThickness), new Point(RenderSize.Width - halfThickness, RenderSize.Height - halfThickness)); if (roundedCorners) { dc.DrawRoundedRectangle( null, pen, rect, outerCornerRadius, outerCornerRadius); } else { dc.DrawRectangle( null, pen, rect); } } else { // Nonuniform border; stroke each edge. if (DoubleUtil.GreaterThan(border.Left, 0)) { halfThickness = pen.Thickness * 0.5; dc.DrawLine( pen, new Point(halfThickness, 0), new Point(halfThickness, RenderSize.Height)); } if (DoubleUtil.GreaterThan(border.Right, 0)) { pen = RightPenCache; if (pen == null) { pen = new Pen(); pen.Brush = borderBrush; if (useLayoutRounding) { pen.Thickness = UIElement.RoundLayoutValue(border.Right, FrameworkElement.DpiScaleX); } else { pen.Thickness = border.Right; } if (borderBrush.IsFrozen) { pen.Freeze(); } RightPenCache = pen; } halfThickness = pen.Thickness * 0.5; dc.DrawLine( pen, new Point(RenderSize.Width - halfThickness, 0), new Point(RenderSize.Width - halfThickness, RenderSize.Height)); } if (DoubleUtil.GreaterThan(border.Top, 0)) { pen = TopPenCache; if (pen == null) { pen = new Pen(); pen.Brush = borderBrush; if (useLayoutRounding) { pen.Thickness = UIElement.RoundLayoutValue(border.Top, FrameworkElement.DpiScaleY); } else { pen.Thickness = border.Top; } if (borderBrush.IsFrozen) { pen.Freeze(); } TopPenCache = pen; } halfThickness = pen.Thickness * 0.5; dc.DrawLine( pen, new Point(0, halfThickness), new Point(RenderSize.Width, halfThickness)); } if (DoubleUtil.GreaterThan(border.Bottom, 0)) { pen = BottomPenCache; if (pen == null) { pen = new Pen(); pen.Brush = borderBrush; if (useLayoutRounding) { pen.Thickness = UIElement.RoundLayoutValue(border.Bottom, FrameworkElement.DpiScaleY); } else { pen.Thickness = border.Bottom; } if (borderBrush.IsFrozen) { pen.Freeze(); } BottomPenCache = pen; } halfThickness = pen.Thickness * 0.5; dc.DrawLine( pen, new Point(0, RenderSize.Height - halfThickness), new Point(RenderSize.Width, RenderSize.Height - halfThickness)); } } } // Draw background in rectangle inside border. Brush background = Background; if (background != null) { // Intialize background Point ptTL, ptBR; if (useLayoutRounding) { ptTL = new Point(UIElement.RoundLayoutValue(border.Left, FrameworkElement.DpiScaleX), UIElement.RoundLayoutValue(border.Top, FrameworkElement.DpiScaleY)); if(FrameworkAppContextSwitches.DoNotApplyLayoutRoundingToMarginsAndBorderThickness) { ptBR = new Point(UIElement.RoundLayoutValue(RenderSize.Width - border.Right, FrameworkElement.DpiScaleX), UIElement.RoundLayoutValue(RenderSize.Height - border.Bottom, FrameworkElement.DpiScaleY)); } else { ptBR = new Point(RenderSize.Width - UIElement.RoundLayoutValue(border.Right, FrameworkElement.DpiScaleX), RenderSize.Height - UIElement.RoundLayoutValue(border.Bottom, FrameworkElement.DpiScaleY)); } } else { ptTL = new Point(border.Left, border.Top); ptBR = new Point(RenderSize.Width - border.Right, RenderSize.Height - border.Bottom); } // Do not draw background if the borders are so large that they overlap. if (ptBR.X > ptTL.X && ptBR.Y > ptTL.Y) { if (roundedCorners) { Radii innerRadii = new Radii(cornerRadius, border, false); // Determine the inner edge radius double innerCornerRadius = innerRadii.TopLeft; // Already validated that all corners have the same radius dc.DrawRoundedRectangle(background, null, new Rect(ptTL, ptBR), innerCornerRadius, innerCornerRadius); } else { dc.DrawRectangle(background, null, new Rect(ptTL, ptBR)); } } } } } #endregion Protected Methods //------------------------------------------------------------------- // // Private Methods // //------------------------------------------------------------------- #region Private Methods // Helper function to add up the left and right size as width, as well as the top and bottom size as height private static Size HelperCollapseThickness(Thickness th) { return new Size(th.Left + th.Right, th.Top + th.Bottom); } private static bool AreUniformCorners(CornerRadius borderRadii) { double topLeft = borderRadii.TopLeft; return DoubleUtil.AreClose(topLeft, borderRadii.TopRight) && DoubleUtil.AreClose(topLeft, borderRadii.BottomLeft) && DoubleUtil.AreClose(topLeft, borderRadii.BottomRight); } /// Helper to deflate rectangle by thickness private static Rect HelperDeflateRect(Rect rt, Thickness thick) { return new Rect(rt.Left + thick.Left, rt.Top + thick.Top, Math.Max(0.0, rt.Width - thick.Left - thick.Right), Math.Max(0.0, rt.Height - thick.Top - thick.Bottom)); } /// <summary> /// Generates a StreamGeometry. /// </summary> /// <param name="ctx">An already opened StreamGeometryContext.</param> /// <param name="rect">Rectangle for geomentry conversion.</param> /// <param name="radii">Corner radii.</param> /// <returns>Result geometry.</returns> private static void GenerateGeometry(StreamGeometryContext ctx, Rect rect, Radii radii) { // // compute the coordinates of the key points // Point topLeft = new Point(radii.LeftTop, 0); Point topRight = new Point(rect.Width - radii.RightTop, 0); Point rightTop = new Point(rect.Width, radii.TopRight); Point rightBottom = new Point(rect.Width, rect.Height - radii.BottomRight); Point bottomRight = new Point(rect.Width - radii.RightBottom, rect.Height); Point bottomLeft = new Point(radii.LeftBottom, rect.Height); Point leftBottom = new Point(0, rect.Height - radii.BottomLeft); Point leftTop = new Point(0, radii.TopLeft); // // check keypoints for overlap and resolve by partitioning radii according to // the percentage of each one. // // top edge is handled here if (topLeft.X > topRight.X) { double v = (radii.LeftTop) / (radii.LeftTop + radii.RightTop) * rect.Width; topLeft.X = v; topRight.X = v; } // right edge if (rightTop.Y > rightBottom.Y) { double v = (radii.TopRight) / (radii.TopRight + radii.BottomRight) * rect.Height; rightTop.Y = v; rightBottom.Y = v; } // bottom edge if (bottomRight.X < bottomLeft.X) { double v = (radii.LeftBottom) / (radii.LeftBottom + radii.RightBottom) * rect.Width; bottomRight.X = v; bottomLeft.X = v; } // left edge if (leftBottom.Y < leftTop.Y) { double v = (radii.TopLeft) / (radii.TopLeft + radii.BottomLeft) * rect.Height; leftBottom.Y = v; leftTop.Y = v; } // // add on offsets // Vector offset = new Vector(rect.TopLeft.X, rect.TopLeft.Y); topLeft += offset; topRight += offset; rightTop += offset; rightBottom += offset; bottomRight += offset; bottomLeft += offset; leftBottom += offset; leftTop += offset; // // create the border geometry // ctx.BeginFigure(topLeft, true /* is filled */, true /* is closed */); // Top line ctx.LineTo(topRight, true /* is stroked */, false /* is smooth join */); // Upper-right corner double radiusX = rect.TopRight.X - topRight.X; double radiusY = rightTop.Y - rect.TopRight.Y; if (!DoubleUtil.IsZero(radiusX) || !DoubleUtil.IsZero(radiusY)) { ctx.ArcTo(rightTop, new Size(radiusX, radiusY), 0, false, SweepDirection.Clockwise, true, false); } // Right line ctx.LineTo(rightBottom, true /* is stroked */, false /* is smooth join */); // Lower-right corner radiusX = rect.BottomRight.X - bottomRight.X; radiusY = rect.BottomRight.Y - rightBottom.Y; if (!DoubleUtil.IsZero(radiusX) || !DoubleUtil.IsZero(radiusY)) { ctx.ArcTo(bottomRight, new Size(radiusX, radiusY), 0, false, SweepDirection.Clockwise, true, false); } // Bottom line ctx.LineTo(bottomLeft, true /* is stroked */, false /* is smooth join */); // Lower-left corner radiusX = bottomLeft.X - rect.BottomLeft.X; radiusY = rect.BottomLeft.Y - leftBottom.Y; if (!DoubleUtil.IsZero(radiusX) || !DoubleUtil.IsZero(radiusY)) { ctx.ArcTo(leftBottom, new Size(radiusX, radiusY), 0, false, SweepDirection.Clockwise, true, false); } // Left line ctx.LineTo(leftTop, true /* is stroked */, false /* is smooth join */); // Upper-left corner radiusX = topLeft.X - rect.TopLeft.X; radiusY = leftTop.Y - rect.TopLeft.Y; if (!DoubleUtil.IsZero(radiusX) || !DoubleUtil.IsZero(radiusY)) { ctx.ArcTo(topLeft, new Size(radiusX, radiusY), 0, false, SweepDirection.Clockwise, true, false); } } // // This property // 1. Finds the correct initial size for the _effectiveValues store on the current DependencyObject // 2. This is a performance optimization // internal override int EffectiveValuesInitialSize { get { return 9; } } #endregion Private Methods //------------------------------------------------------------------- // // Private Fields // //------------------------------------------------------------------- #region Private Fields private bool _useComplexRenderCodePath; #endregion Private Fields #region Cache private static readonly UncommonField<StreamGeometry> BorderGeometryField = new UncommonField<StreamGeometry>(); private static readonly UncommonField<StreamGeometry> BackgroundGeometryField = new UncommonField<StreamGeometry>(); private static readonly UncommonField<Pen> LeftPenField = new UncommonField<Pen>(); private static readonly UncommonField<Pen> RightPenField = new UncommonField<Pen>(); private static readonly UncommonField<Pen> TopPenField = new UncommonField<Pen>(); private static readonly UncommonField<Pen> BottomPenField = new UncommonField<Pen>(); private StreamGeometry BorderGeometryCache { get { return BorderGeometryField.GetValue(this); } set { if (value == null) { BorderGeometryField.ClearValue(this); } else { BorderGeometryField.SetValue(this, value); } } } private StreamGeometry BackgroundGeometryCache { get { return BackgroundGeometryField.GetValue(this); } set { if (value == null) { BackgroundGeometryField.ClearValue(this); } else { BackgroundGeometryField.SetValue(this, value); } } } private Pen LeftPenCache { get { return LeftPenField.GetValue(this); } set { if (value == null) { LeftPenField.ClearValue(this); } else { LeftPenField.SetValue(this, value); } } } private Pen RightPenCache { get { return RightPenField.GetValue(this); } set { if (value == null) { RightPenField.ClearValue(this); } else { RightPenField.SetValue(this, value); } } } private Pen TopPenCache { get { return TopPenField.GetValue(this); } set { if (value == null) { TopPenField.ClearValue(this); } else { TopPenField.SetValue(this, value); } } } private Pen BottomPenCache { get { return BottomPenField.GetValue(this); } set { if (value == null) { BottomPenField.ClearValue(this); } else { BottomPenField.SetValue(this, value); } } } #endregion Cache //------------------------------------------------------------------- // // Private Structures Classes // //------------------------------------------------------------------- #region Private Structures Classes private struct Radii { internal Radii(CornerRadius radii, Thickness borders, bool outer) { double left = 0.5 * borders.Left; double top = 0.5 * borders.Top; double right = 0.5 * borders.Right; double bottom = 0.5 * borders.Bottom; if (outer) { if (DoubleUtil.IsZero(radii.TopLeft)) { LeftTop = TopLeft = 0.0; } else { LeftTop = radii.TopLeft + left; TopLeft = radii.TopLeft + top; } if (DoubleUtil.IsZero(radii.TopRight)) { TopRight = RightTop = 0.0; } else { TopRight = radii.TopRight + top; RightTop = radii.TopRight + right; } if (DoubleUtil.IsZero(radii.BottomRight)) { RightBottom = BottomRight = 0.0; } else { RightBottom = radii.BottomRight + right; BottomRight = radii.BottomRight + bottom; } if (DoubleUtil.IsZero(radii.BottomLeft)) { BottomLeft = LeftBottom = 0.0; } else { BottomLeft = radii.BottomLeft + bottom; LeftBottom = radii.BottomLeft + left; } } else { LeftTop = Math.Max(0.0, radii.TopLeft - left); TopLeft = Math.Max(0.0, radii.TopLeft - top); TopRight = Math.Max(0.0, radii.TopRight - top); RightTop = Math.Max(0.0, radii.TopRight - right); RightBottom = Math.Max(0.0, radii.BottomRight - right); BottomRight = Math.Max(0.0, radii.BottomRight - bottom); BottomLeft = Math.Max(0.0, radii.BottomLeft - bottom); LeftBottom = Math.Max(0.0, radii.BottomLeft - left); } } internal double LeftTop; internal double TopLeft; internal double TopRight; internal double RightTop; internal double RightBottom; internal double BottomRight; internal double BottomLeft; internal double LeftBottom; } #endregion Private Structures Classes } }
//----------------------------------------------------------------------- // <copyright file="ActorPublisher.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Concurrent; using System.Threading; using Akka.Actor; using Akka.Pattern; using Akka.Streams.Dsl; using Akka.Streams.Implementation; using Reactive.Streams; namespace Akka.Streams.Actors { #region Internal messages public sealed class Subscribe<T> : INoSerializationVerificationNeeded { public readonly ISubscriber<T> Subscriber; public Subscribe(ISubscriber<T> subscriber) { Subscriber = subscriber; } } [Serializable] public enum LifecycleState { PreSubscriber, Active, Canceled, Completed, CompleteThenStop, ErrorEmitted } #endregion public interface IActorPublisherMessage { } /// <summary> /// This message is delivered to the <see cref="ActorPublisher{T}"/> actor when the stream /// subscriber requests more elements. /// </summary> [Serializable] public sealed class Request : IActorPublisherMessage { public readonly long Count; public Request(long count) { Count = count; } } /// <summary> /// This message is delivered to the <see cref="ActorPublisher{T}"/> actor when the stream /// subscriber cancels the subscription. /// </summary> [Serializable] public sealed class Cancel : IActorPublisherMessage { public static readonly Cancel Instance = new Cancel(); private Cancel() { } } /// <summary> /// This message is delivered to the <see cref="ActorPublisher{T}"/> actor in order to signal /// the exceeding of an subscription timeout. Once the actor receives this message, this /// publisher will already be in cancelled state, thus the actor should clean-up and stop itself. /// </summary> [Serializable] public sealed class SubscriptionTimeoutExceeded : IActorPublisherMessage { public static readonly SubscriptionTimeoutExceeded Instance = new SubscriptionTimeoutExceeded(); private SubscriptionTimeoutExceeded() { } } /// <summary> /// <para> /// Extend this actor to make it a stream publisher that keeps track of the subscription life cycle and /// requested elements. /// </para> /// <para> /// Create a <see cref="IPublisher{T}"/> backed by this actor with <see cref="ActorPublisher.Create{T}"/>. /// </para> /// <para> /// It can be attached to a <see cref="ISubscriber{T}"/> or be used as an input source for a /// <see cref="IFlow{T,TMat}"/>. You can only attach one subscriber to this publisher. /// </para> /// <para> /// The life cycle state of the subscription is tracked with the following boolean members: /// <see cref="IsActive"/>, <see cref="IsCompleted"/>, <see cref="IsErrorEmitted"/>, /// and <see cref="IsCanceled"/>. /// </para> /// <para> /// You send elements to the stream by calling <see cref="OnNext"/>. You are allowed to send as many /// elements as have been requested by the stream subscriber. This amount can be inquired with /// <see cref="TotalDemand"/>. It is only allowed to use <see cref="OnNext"/> when <see cref="IsActive"/> /// <see cref="TotalDemand"/> &gt; 0, otherwise <see cref="OnNext"/> will throw /// <see cref="IllegalStateException"/>. /// </para> /// <para> /// When the stream subscriber requests more elements the <see cref="Request"/> message /// is delivered to this actor, and you can act on that event. The <see cref="TotalDemand"/> /// is updated automatically. /// </para> /// <para> /// When the stream subscriber cancels the subscription the <see cref="Cancel"/> message /// is delivered to this actor. After that subsequent calls to <see cref="OnNext"/> will be ignored. /// </para> /// <para> /// You can complete the stream by calling <see cref="OnComplete"/>. After that you are not allowed to /// call <see cref="OnNext"/>, <see cref="OnError"/> and <see cref="OnComplete"/>. /// </para> /// <para> /// You can terminate the stream with failure by calling <see cref="OnError"/>. After that you are not allowed to /// call <see cref="OnNext"/>, <see cref="OnError"/> and <see cref="OnComplete"/>. /// </para> /// <para> /// If you suspect that this <see cref="ActorPublisher{T}"/> may never get subscribed to, /// you can override the <see cref="SubscriptionTimeout"/> method to provide a timeout after which /// this Publisher should be considered canceled. The actor will be notified when /// the timeout triggers via an <see cref="SubscriptionTimeoutExceeded"/> message and MUST then /// perform cleanup and stop itself. /// </para> /// <para> /// If the actor is stopped the stream will be completed, unless it was not already terminated with /// failure, completed or canceled. /// </para> /// </summary> public abstract class ActorPublisher<T> : ActorBase { private readonly ActorPublisherState _state = ActorPublisherState.Instance.Apply(Context.System); private long _demand; private LifecycleState _lifecycleState = LifecycleState.PreSubscriber; private ISubscriber<T> _subscriber; private ICancelable _scheduledSubscriptionTimeout = NoopSubscriptionTimeout.Instance; // case and stop fields are used only when combined with LifecycleState.ErrorEmitted private OnErrorBlock _onError; protected ActorPublisher() { SubscriptionTimeout = Timeout.InfiniteTimeSpan; } /// <summary> /// Subscription timeout after which this actor will become Canceled and reject any incoming "late" subscriber. /// /// The actor will receive an <see cref="SubscriptionTimeoutExceeded"/> message upon which it /// MUST react by performing all necessary cleanup and stopping itself. /// /// Use this feature in order to avoid leaking actors when you suspect that this Publisher may never get subscribed to by some Subscriber. /// </summary> /// <summary> /// <para> /// Subscription timeout after which this actor will become Canceled and reject any incoming "late" subscriber. /// </para> /// <para> /// The actor will receive an <see cref="SubscriptionTimeoutExceeded"/> message upon which it /// MUST react by performing all necessary cleanup and stopping itself. /// </para> /// <para> /// Use this feature in order to avoid leaking actors when you suspect that this Publisher /// may never get subscribed to by some Subscriber. /// </para> /// </summary> public TimeSpan SubscriptionTimeout { get; protected set; } /// <summary> /// The state when the publisher is active, i.e. before the subscriber is attached /// and when an subscriber is attached. It is allowed to /// call <see cref="OnComplete"/> and <see cref="OnError"/> in this state. It is /// allowed to call <see cref="OnNext"/> in this state when <see cref="TotalDemand"/> /// is greater than zero. /// </summary> public bool IsActive => _lifecycleState == LifecycleState.Active || _lifecycleState == LifecycleState.PreSubscriber; /// <summary> /// Total number of requested elements from the stream subscriber. /// This actor automatically keeps tracks of this amount based on /// incoming request messages and outgoing <see cref="OnNext"/>. /// </summary> public long TotalDemand => _demand; /// <summary> /// The terminal state after calling <see cref="OnComplete"/>. It is not allowed to /// <see cref="OnNext"/>, <see cref="OnError"/>, and <see cref="OnComplete"/> in this state. /// </summary> public bool IsCompleted => _lifecycleState == LifecycleState.Completed; /// <summary> /// The terminal state after calling <see cref="OnError"/>. It is not allowed to /// call <see cref="OnNext"/>, <see cref="OnError"/>, and <see cref="OnComplete"/> in this state. /// </summary> public bool IsErrorEmitted => _lifecycleState == LifecycleState.ErrorEmitted; /// <summary> /// The state after the stream subscriber has canceled the subscription. /// It is allowed to call <see cref="OnNext"/>, <see cref="OnError"/>, and <see cref="OnComplete"/> in /// this state, but the calls will not perform anything. /// </summary> public bool IsCanceled => _lifecycleState == LifecycleState.Canceled; /// <summary> /// Send an element to the stream subscriber. You are allowed to send as many elements /// as have been requested by the stream subscriber. This amount can be inquired with /// <see cref="TotalDemand"/>. It is only allowed to use <see cref="OnNext"/> when /// <see cref="IsActive"/> and <see cref="TotalDemand"/> &gt; 0, /// otherwise <see cref="OnNext"/> will throw <see cref="IllegalStateException"/>. /// </summary> public void OnNext(T element) { switch (_lifecycleState) { case LifecycleState.Active: case LifecycleState.PreSubscriber: case LifecycleState.CompleteThenStop: if (_demand > 0) { _demand--; ReactiveStreamsCompliance.TryOnNext(_subscriber, element); } else { throw new IllegalStateException( "OnNext is not allowed when the stream has not requested elements, total demand was 0"); } break; case LifecycleState.ErrorEmitted: throw new IllegalStateException("OnNext must not be called after OnError"); case LifecycleState.Completed: throw new IllegalStateException("OnNext must not be called after OnComplete"); case LifecycleState.Canceled: break; } } /// <summary> /// Complete the stream. After that you are not allowed to /// call <see cref="OnNext"/>, <see cref="OnError"/> and <see cref="OnComplete"/>. /// </summary> public void OnComplete() { switch (_lifecycleState) { case LifecycleState.Active: case LifecycleState.PreSubscriber: case LifecycleState.CompleteThenStop: _lifecycleState = LifecycleState.Completed; _onError = null; if (_subscriber != null) { // otherwise onComplete will be called when the subscription arrives try { ReactiveStreamsCompliance.TryOnComplete(_subscriber); } finally { _subscriber = null; } } break; case LifecycleState.ErrorEmitted: throw new IllegalStateException("OnComplete must not be called after OnError"); case LifecycleState.Completed: throw new IllegalStateException("OnComplete must only be called once"); case LifecycleState.Canceled: break; } } /// <summary> /// <para> /// Complete the stream. After that you are not allowed to /// call <see cref="OnNext"/>, <see cref="OnError"/> and <see cref="OnComplete"/>. /// </para> /// <para> /// After signalling completion the Actor will then stop itself as it has completed the protocol. /// When <see cref="OnComplete"/> is called before any <see cref="ISubscriber{T}"/> has had the chance to subscribe /// to this <see cref="ActorPublisher{T}"/> the completion signal (and therefore stopping of the Actor as well) /// will be delayed until such <see cref="ISubscriber{T}"/> arrives. /// </para> /// </summary> public void OnCompleteThenStop() { switch (_lifecycleState) { case LifecycleState.Active: case LifecycleState.PreSubscriber: _lifecycleState = LifecycleState.CompleteThenStop; _onError = null; if (_subscriber != null) { // otherwise onComplete will be called when the subscription arrives try { ReactiveStreamsCompliance.TryOnComplete(_subscriber); } finally { Context.Stop(Self); } } break; default: OnComplete(); break; } } /// <summary> /// Terminate the stream with failure. After that you are not allowed to /// call <see cref="OnNext"/>, <see cref="OnError"/> and <see cref="OnComplete"/>. /// </summary> public void OnError(Exception cause) { switch (_lifecycleState) { case LifecycleState.Active: case LifecycleState.PreSubscriber: case LifecycleState.CompleteThenStop: _lifecycleState = LifecycleState.ErrorEmitted; _onError = new OnErrorBlock(cause, false); if (_subscriber != null) { // otherwise onError will be called when the subscription arrives try { ReactiveStreamsCompliance.TryOnError(_subscriber, cause); } finally { _subscriber = null; } } break; case LifecycleState.ErrorEmitted: throw new IllegalStateException("OnError must only be called once"); case LifecycleState.Completed: throw new IllegalStateException("OnError must not be called after OnComplete"); case LifecycleState.Canceled: break; } } /// <summary> /// <para> /// Terminate the stream with failure. After that you are not allowed to /// call <see cref="OnNext"/>, <see cref="OnError"/> and <see cref="OnComplete"/>. /// </para> /// <para> /// After signalling the Error the Actor will then stop itself as it has completed the protocol. /// When <see cref="OnError"/> is called before any <see cref="ISubscriber{T}"/> has had the chance to subscribe /// to this <see cref="ActorPublisher{T}"/> the error signal (and therefore stopping of the Actor as well) /// will be delayed until such <see cref="ISubscriber{T}"/> arrives. /// </para> /// </summary> public void OnErrorThenStop(Exception cause) { switch (_lifecycleState) { case LifecycleState.Active: case LifecycleState.PreSubscriber: _lifecycleState = LifecycleState.ErrorEmitted; _onError = new OnErrorBlock(cause, stop: true); if (_subscriber != null) { // otherwise onError will be called when the subscription arrives try { ReactiveStreamsCompliance.TryOnError(_subscriber, cause); } finally { Context.Stop(Self); } } break; default: OnError(cause); break; } } #region Internal API protected override bool AroundReceive(Receive receive, object message) { if (message is Request) { var req = (Request) message; if (req.Count < 1) { if (_lifecycleState == LifecycleState.Active) OnError(new IllegalStateException("Number of requested elements must be positive")); else base.AroundReceive(receive, message); } else { _demand += req.Count; if (_demand < 0) _demand = long.MaxValue; // long overflow: effectively unbounded base.AroundReceive(receive, message); } } else if (message is Subscribe<T>) { var sub = (Subscribe<T>) message; var subscriber = sub.Subscriber; switch (_lifecycleState) { case LifecycleState.PreSubscriber: _scheduledSubscriptionTimeout.Cancel(); _subscriber = subscriber; _lifecycleState = LifecycleState.Active; ReactiveStreamsCompliance.TryOnSubscribe(subscriber, new ActorPublisherSubscription(Self)); break; case LifecycleState.ErrorEmitted: if (_onError.Stop) Context.Stop(Self); ReactiveStreamsCompliance.TryOnSubscribe(subscriber, CancelledSubscription.Instance); ReactiveStreamsCompliance.TryOnError(subscriber, _onError.Cause); break; case LifecycleState.Completed: ReactiveStreamsCompliance.TryOnSubscribe(subscriber, CancelledSubscription.Instance); ReactiveStreamsCompliance.TryOnComplete(subscriber); break; case LifecycleState.CompleteThenStop: Context.Stop(Self); ReactiveStreamsCompliance.TryOnSubscribe(subscriber, CancelledSubscription.Instance); ReactiveStreamsCompliance.TryOnComplete(subscriber); break; case LifecycleState.Active: case LifecycleState.Canceled: ReactiveStreamsCompliance.TryOnSubscribe(subscriber, CancelledSubscription.Instance); ReactiveStreamsCompliance.TryOnError(subscriber, _subscriber == subscriber ? new IllegalStateException("Cannot subscribe the same subscriber multiple times") : new IllegalStateException("Only supports one subscriber")); break; } } else if (message is Cancel) { CancelSelf(); base.AroundReceive(receive, message); } else if (message is SubscriptionTimeoutExceeded) { if (!_scheduledSubscriptionTimeout.IsCancellationRequested) { CancelSelf(); base.AroundReceive(receive, message); } } else return base.AroundReceive(receive, message); return true; } private void CancelSelf() { _lifecycleState = LifecycleState.Canceled; _subscriber = null; _onError = null; _demand = 0L; } public override void AroundPreStart() { base.AroundPreStart(); if (SubscriptionTimeout != Timeout.InfiniteTimeSpan) { _scheduledSubscriptionTimeout = new Cancelable(Context.System.Scheduler); Context.System.Scheduler.ScheduleTellOnce(SubscriptionTimeout, Self, SubscriptionTimeoutExceeded.Instance, Self, _scheduledSubscriptionTimeout); } } public override void AroundPreRestart(Exception cause, object message) { // some state must survive restart _state.Set(Self, new ActorPublisherState.State(UntypedSubscriber.FromTyped(_subscriber), _demand, _lifecycleState)); base.AroundPreRestart(cause, message); } public override void AroundPostRestart(Exception cause, object message) { var s = _state.Remove(Self); if (s != null) { _subscriber = UntypedSubscriber.ToTyped<T>(s.Subscriber); _demand = s.Demand; _lifecycleState = s.LifecycleState; } base.AroundPostRestart(cause, message); } public override void AroundPostStop() { _state.Remove(Self); try { if (_lifecycleState == LifecycleState.Active) ReactiveStreamsCompliance.TryOnComplete(_subscriber); } finally { base.AroundPostStop(); } } #endregion } public static class ActorPublisher { public static IPublisher<T> Create<T>(IActorRef @ref) => new ActorPublisherImpl<T>(@ref); } public sealed class ActorPublisherImpl<T> : IPublisher<T> { private readonly IActorRef _ref; public ActorPublisherImpl(IActorRef @ref) { if(@ref == null) throw new ArgumentNullException(nameof(@ref), "ActorPublisherImpl requires IActorRef to be defined"); _ref = @ref; } public void Subscribe(ISubscriber<T> subscriber) { if (subscriber == null) throw new ArgumentNullException(nameof(subscriber), "Subscriber must not be null"); _ref.Tell(new Subscribe<T>(subscriber)); } } public sealed class ActorPublisherSubscription : ISubscription { private readonly IActorRef _ref; public ActorPublisherSubscription(IActorRef @ref) { if (@ref == null) throw new ArgumentNullException(nameof(@ref), "ActorPublisherSubscription requires IActorRef to be defined"); _ref = @ref; } public void Request(long n) => _ref.Tell(new Request(n)); public void Cancel() => _ref.Tell(Actors.Cancel.Instance); } public sealed class OnErrorBlock { public readonly Exception Cause; public readonly bool Stop; public OnErrorBlock(Exception cause, bool stop) { Cause = cause; Stop = stop; } } internal class ActorPublisherState : ExtensionIdProvider<ActorPublisherState>, IExtension { public sealed class State { public readonly IUntypedSubscriber Subscriber; public readonly long Demand; public readonly LifecycleState LifecycleState; public State(IUntypedSubscriber subscriber, long demand, LifecycleState lifecycleState) { Subscriber = subscriber; Demand = demand; LifecycleState = lifecycleState; } } private readonly ConcurrentDictionary<IActorRef, State> _state = new ConcurrentDictionary<IActorRef, State>(); public static readonly ActorPublisherState Instance = new ActorPublisherState(); private ActorPublisherState() { } public State Get(IActorRef actorRef) { State state; return _state.TryGetValue(actorRef, out state) ? state : null; } public void Set(IActorRef actorRef, State s) => _state.AddOrUpdate(actorRef, s, (@ref, oldState) => s); public State Remove(IActorRef actorRef) { State s; return _state.TryRemove(actorRef, out s) ? s : null; } public override ActorPublisherState CreateExtension(ExtendedActorSystem system) => new ActorPublisherState(); } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: operations/rpc/out_of_order_record_svc.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace HOLMS.Types.Operations.RPC { /// <summary>Holder for reflection information generated from operations/rpc/out_of_order_record_svc.proto</summary> public static partial class OutOfOrderRecordSvcReflection { #region Descriptor /// <summary>File descriptor for operations/rpc/out_of_order_record_svc.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static OutOfOrderRecordSvcReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CixvcGVyYXRpb25zL3JwYy9vdXRfb2Zfb3JkZXJfcmVjb3JkX3N2Yy5wcm90", "bxIaaG9sbXMudHlwZXMub3BlcmF0aW9ucy5ycGMaMW9wZXJhdGlvbnMvb3V0", "X29mX29yZGVyL291dF9vZl9vcmRlcl9yZWNvcmQucHJvdG8aO29wZXJhdGlv", "bnMvb3V0X29mX29yZGVyL291dF9vZl9vcmRlcl9yZWNvcmRfaW5kaWNhdG9y", "LnByb3RvGjJ0ZW5hbmN5X2NvbmZpZy9pbmRpY2F0b3JzL3Byb3BlcnR5X2lu", "ZGljYXRvci5wcm90byJoCh5PdXRPZk9yZGVyUmVjb3JkU3ZjQWxsUmVzcG9u", "c2USRgoHcmVjb3JkcxgBIAMoCzI1LmhvbG1zLnR5cGVzLm9wZXJhdGlvbnMu", "b3V0X29mX29yZGVyLk91dE9mT3JkZXJSZWNvcmQiswEKH091dE9mT3JkZXJS", "ZWNvcmRHZXRCeUlkUmVzcG9uc2USSQoGcmVzdWx0GAEgASgOMjkuaG9sbXMu", "dHlwZXMub3BlcmF0aW9ucy5ycGMuT3V0T2ZPcmRlclJlY29yZEdldEJ5SWRS", "ZXN1bHQSRQoGcmVjb3JkGAIgASgLMjUuaG9sbXMudHlwZXMub3BlcmF0aW9u", "cy5vdXRfb2Zfb3JkZXIuT3V0T2ZPcmRlclJlY29yZCKGAQogT3V0T2ZPcmRl", "clJlY29yZFN2Y0NyZWF0ZVJlcXVlc3QSRQoGcmVjb3JkGAEgASgLMjUuaG9s", "bXMudHlwZXMub3BlcmF0aW9ucy5vdXRfb2Zfb3JkZXIuT3V0T2ZPcmRlclJl", "Y29yZBIbChNob2xkX2Ryb3BfcmVxdWVzdGVkGAIgASgIIrEBCh5PdXRPZk9y", "ZGVyUmVjb3JkQ3JlYXRlUmVzcG9uc2USSAoGcmVzdWx0GAEgASgOMjguaG9s", "bXMudHlwZXMub3BlcmF0aW9ucy5ycGMuT3V0T2ZPcmRlclJlY29yZENyZWF0", "ZVJlc3VsdBJFCgZyZWNvcmQYAiABKAsyNS5ob2xtcy50eXBlcy5vcGVyYXRp", "b25zLm91dF9vZl9vcmRlci5PdXRPZk9yZGVyUmVjb3JkIoYBCiBPdXRPZk9y", "ZGVyUmVjb3JkU3ZjVXBkYXRlUmVxdWVzdBJFCgZyZWNvcmQYASABKAsyNS5o", "b2xtcy50eXBlcy5vcGVyYXRpb25zLm91dF9vZl9vcmRlci5PdXRPZk9yZGVy", "UmVjb3JkEhsKE2hvbGRfZHJvcF9yZXF1ZXN0ZWQYAiABKAgisQEKHk91dE9m", "T3JkZXJSZWNvcmRVcGRhdGVSZXNwb25zZRJICgZyZXN1bHQYASABKA4yOC5o", "b2xtcy50eXBlcy5vcGVyYXRpb25zLnJwYy5PdXRPZk9yZGVyUmVjb3JkVXBk", "YXRlUmVzdWx0EkUKBnJlY29yZBgCIAEoCzI1LmhvbG1zLnR5cGVzLm9wZXJh", "dGlvbnMub3V0X29mX29yZGVyLk91dE9mT3JkZXJSZWNvcmQiagoeT3V0T2ZP", "cmRlclJlY29yZERlbGV0ZVJlc3BvbnNlEkgKBnJlc3VsdBgBIAEoDjI4Lmhv", "bG1zLnR5cGVzLm9wZXJhdGlvbnMucnBjLk91dE9mT3JkZXJSZWNvcmREZWxl", "dGVSZXN1bHQqYQodT3V0T2ZPcmRlclJlY29yZEdldEJ5SWRSZXN1bHQSHQoZ", "T1VUX09GX09SREVSX1JFQ09SRF9GT1VORBAAEiEKHU9VVF9PRl9PUkRFUl9S", "RUNPUkRfTk9UX0ZPVU5EEAEq6QIKHE91dE9mT3JkZXJSZWNvcmRDcmVhdGVS", "ZXN1bHQSJgoiT1VUX09GX09SREVSX1JFQ09SRF9DUkVBVEVfU1VDQ0VTUxAA", "Ei0KKU9VVF9PRl9PUkRFUl9SRUNPUkRfQ1JFQVRFX01BSU5UX0NPTkZMSUNU", "EAESMwovT1VUX09GX09SREVSX1JFQ09SRF9DUkVBVEVfUkVTRVJWQVRJT05f", "Q09ORkxJQ1QQAhItCilPVVRfT0ZfT1JERVJfUkVDT1JEX0NSRUFURV9ST09N", "X05PVF9GT1VORBADEigKJE9VVF9PRl9PUkRFUl9SRUNPUkRfQ1JFQVRFX05P", "X1NVUFBMWRAEEjEKLU9VVF9PRl9PUkRFUl9SRUNPUkRfQ1JFQVRFX09DQ1VQ", "QU5DWV9DT05GTElDVBAFEjEKLU9VVF9PRl9PUkRFUl9SRUNPUkRfQ1JFQVRF", "X0hPTERfRFJPUF9SRVFVSVJFRBAGKqIDChxPdXRPZk9yZGVyUmVjb3JkVXBk", "YXRlUmVzdWx0EikKJU9VVF9PRl9PUkRFUl9SRUNPUkRfVVBEQVRFX1NVQ0NF", "U1NGVUwQABIuCipPVVRfT0ZfT1JERVJfUkVDT1JEX1VQREFURV9QUklPUl9O", "T1RfRk9VTkQQARItCilPVVRfT0ZfT1JERVJfUkVDT1JEX1VQREFURV9NQUlO", "VF9DT05GTElDVBACEjMKL09VVF9PRl9PUkRFUl9SRUNPUkRfVVBEQVRFX1JF", "U0VSVkFUSU9OX0NPTkZMSUNUEAMSLQopT1VUX09GX09SREVSX1JFQ09SRF9V", "UERBVEVfUk9PTV9OT1RfRk9VTkQQBBIuCipPVVRfT0ZfT1JERVJfUkVDT1JE", "X1VQREFURV9OT19BVkFJTEFCSUxJVFkQBRIxCi1PVVRfT0ZfT1JERVJfUkVD", "T1JEX1VQREFURV9PQ0NVUEFOQ1lfQ09ORkxJQ1QQBhIxCi1PVVRfT0ZfT1JE", "RVJfUkVDT1JEX1VQREFURV9IT0xEX0RST1BfUkVRVUlSRUQQByp5ChxPdXRP", "Zk9yZGVyUmVjb3JkRGVsZXRlUmVzdWx0EikKJU9VVF9PRl9PUkRFUl9SRUNP", "UkRfREVMRVRFX1NVQ0NFU1NGVUwQABIuCipPVVRfT0ZfT1JERVJfUkVDT1JE", "X0RFTEVURV9QUklPUl9OT1RfRk9VTkQQATKsBQoTT3V0T2ZPcmRlclJlY29y", "ZFN2YxJ7CgNBbGwSOC5ob2xtcy50eXBlcy50ZW5hbmN5X2NvbmZpZy5pbmRp", "Y2F0b3JzLlByb3BlcnR5SW5kaWNhdG9yGjouaG9sbXMudHlwZXMub3BlcmF0", "aW9ucy5ycGMuT3V0T2ZPcmRlclJlY29yZFN2Y0FsbFJlc3BvbnNlEoYBCgdH", "ZXRCeUlkEj4uaG9sbXMudHlwZXMub3BlcmF0aW9ucy5vdXRfb2Zfb3JkZXIu", "T3V0T2ZPcmRlclJlY29yZEluZGljYXRvcho7LmhvbG1zLnR5cGVzLm9wZXJh", "dGlvbnMucnBjLk91dE9mT3JkZXJSZWNvcmRHZXRCeUlkUmVzcG9uc2USggEK", "BkNyZWF0ZRI8LmhvbG1zLnR5cGVzLm9wZXJhdGlvbnMucnBjLk91dE9mT3Jk", "ZXJSZWNvcmRTdmNDcmVhdGVSZXF1ZXN0GjouaG9sbXMudHlwZXMub3BlcmF0", "aW9ucy5ycGMuT3V0T2ZPcmRlclJlY29yZENyZWF0ZVJlc3BvbnNlEoIBCgZV", "cGRhdGUSPC5ob2xtcy50eXBlcy5vcGVyYXRpb25zLnJwYy5PdXRPZk9yZGVy", "UmVjb3JkU3ZjVXBkYXRlUmVxdWVzdBo6LmhvbG1zLnR5cGVzLm9wZXJhdGlv", "bnMucnBjLk91dE9mT3JkZXJSZWNvcmRVcGRhdGVSZXNwb25zZRKEAQoGRGVs", "ZXRlEj4uaG9sbXMudHlwZXMub3BlcmF0aW9ucy5vdXRfb2Zfb3JkZXIuT3V0", "T2ZPcmRlclJlY29yZEluZGljYXRvcho6LmhvbG1zLnR5cGVzLm9wZXJhdGlv", "bnMucnBjLk91dE9mT3JkZXJSZWNvcmREZWxldGVSZXNwb25zZUIdqgIaSE9M", "TVMuVHlwZXMuT3BlcmF0aW9ucy5SUENiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecordReflection.Descriptor, global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecordIndicatorReflection.Descriptor, global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicatorReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(new[] {typeof(global::HOLMS.Types.Operations.RPC.OutOfOrderRecordGetByIdResult), typeof(global::HOLMS.Types.Operations.RPC.OutOfOrderRecordCreateResult), typeof(global::HOLMS.Types.Operations.RPC.OutOfOrderRecordUpdateResult), typeof(global::HOLMS.Types.Operations.RPC.OutOfOrderRecordDeleteResult), }, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcAllResponse), global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcAllResponse.Parser, new[]{ "Records" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Operations.RPC.OutOfOrderRecordGetByIdResponse), global::HOLMS.Types.Operations.RPC.OutOfOrderRecordGetByIdResponse.Parser, new[]{ "Result", "Record" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcCreateRequest), global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcCreateRequest.Parser, new[]{ "Record", "HoldDropRequested" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Operations.RPC.OutOfOrderRecordCreateResponse), global::HOLMS.Types.Operations.RPC.OutOfOrderRecordCreateResponse.Parser, new[]{ "Result", "Record" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcUpdateRequest), global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcUpdateRequest.Parser, new[]{ "Record", "HoldDropRequested" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Operations.RPC.OutOfOrderRecordUpdateResponse), global::HOLMS.Types.Operations.RPC.OutOfOrderRecordUpdateResponse.Parser, new[]{ "Result", "Record" }, null, null, null), new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Operations.RPC.OutOfOrderRecordDeleteResponse), global::HOLMS.Types.Operations.RPC.OutOfOrderRecordDeleteResponse.Parser, new[]{ "Result" }, null, null, null) })); } #endregion } #region Enums public enum OutOfOrderRecordGetByIdResult { [pbr::OriginalName("OUT_OF_ORDER_RECORD_FOUND")] OutOfOrderRecordFound = 0, [pbr::OriginalName("OUT_OF_ORDER_RECORD_NOT_FOUND")] OutOfOrderRecordNotFound = 1, } public enum OutOfOrderRecordCreateResult { [pbr::OriginalName("OUT_OF_ORDER_RECORD_CREATE_SUCCESS")] OutOfOrderRecordCreateSuccess = 0, [pbr::OriginalName("OUT_OF_ORDER_RECORD_CREATE_MAINT_CONFLICT")] OutOfOrderRecordCreateMaintConflict = 1, [pbr::OriginalName("OUT_OF_ORDER_RECORD_CREATE_RESERVATION_CONFLICT")] OutOfOrderRecordCreateReservationConflict = 2, [pbr::OriginalName("OUT_OF_ORDER_RECORD_CREATE_ROOM_NOT_FOUND")] OutOfOrderRecordCreateRoomNotFound = 3, [pbr::OriginalName("OUT_OF_ORDER_RECORD_CREATE_NO_SUPPLY")] OutOfOrderRecordCreateNoSupply = 4, [pbr::OriginalName("OUT_OF_ORDER_RECORD_CREATE_OCCUPANCY_CONFLICT")] OutOfOrderRecordCreateOccupancyConflict = 5, [pbr::OriginalName("OUT_OF_ORDER_RECORD_CREATE_HOLD_DROP_REQUIRED")] OutOfOrderRecordCreateHoldDropRequired = 6, } public enum OutOfOrderRecordUpdateResult { [pbr::OriginalName("OUT_OF_ORDER_RECORD_UPDATE_SUCCESSFUL")] OutOfOrderRecordUpdateSuccessful = 0, [pbr::OriginalName("OUT_OF_ORDER_RECORD_UPDATE_PRIOR_NOT_FOUND")] OutOfOrderRecordUpdatePriorNotFound = 1, [pbr::OriginalName("OUT_OF_ORDER_RECORD_UPDATE_MAINT_CONFLICT")] OutOfOrderRecordUpdateMaintConflict = 2, [pbr::OriginalName("OUT_OF_ORDER_RECORD_UPDATE_RESERVATION_CONFLICT")] OutOfOrderRecordUpdateReservationConflict = 3, [pbr::OriginalName("OUT_OF_ORDER_RECORD_UPDATE_ROOM_NOT_FOUND")] OutOfOrderRecordUpdateRoomNotFound = 4, [pbr::OriginalName("OUT_OF_ORDER_RECORD_UPDATE_NO_AVAILABILITY")] OutOfOrderRecordUpdateNoAvailability = 5, [pbr::OriginalName("OUT_OF_ORDER_RECORD_UPDATE_OCCUPANCY_CONFLICT")] OutOfOrderRecordUpdateOccupancyConflict = 6, [pbr::OriginalName("OUT_OF_ORDER_RECORD_UPDATE_HOLD_DROP_REQUIRED")] OutOfOrderRecordUpdateHoldDropRequired = 7, } public enum OutOfOrderRecordDeleteResult { [pbr::OriginalName("OUT_OF_ORDER_RECORD_DELETE_SUCCESSFUL")] OutOfOrderRecordDeleteSuccessful = 0, [pbr::OriginalName("OUT_OF_ORDER_RECORD_DELETE_PRIOR_NOT_FOUND")] OutOfOrderRecordDeletePriorNotFound = 1, } #endregion #region Messages public sealed partial class OutOfOrderRecordSvcAllResponse : pb::IMessage<OutOfOrderRecordSvcAllResponse> { private static readonly pb::MessageParser<OutOfOrderRecordSvcAllResponse> _parser = new pb::MessageParser<OutOfOrderRecordSvcAllResponse>(() => new OutOfOrderRecordSvcAllResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<OutOfOrderRecordSvcAllResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OutOfOrderRecordSvcAllResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OutOfOrderRecordSvcAllResponse(OutOfOrderRecordSvcAllResponse other) : this() { records_ = other.records_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OutOfOrderRecordSvcAllResponse Clone() { return new OutOfOrderRecordSvcAllResponse(this); } /// <summary>Field number for the "records" field.</summary> public const int RecordsFieldNumber = 1; private static readonly pb::FieldCodec<global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecord> _repeated_records_codec = pb::FieldCodec.ForMessage(10, global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecord.Parser); private readonly pbc::RepeatedField<global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecord> records_ = new pbc::RepeatedField<global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecord>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecord> Records { get { return records_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as OutOfOrderRecordSvcAllResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(OutOfOrderRecordSvcAllResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if(!records_.Equals(other.records_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; hash ^= records_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { records_.WriteTo(output, _repeated_records_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; size += records_.CalculateSize(_repeated_records_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(OutOfOrderRecordSvcAllResponse other) { if (other == null) { return; } records_.Add(other.records_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { records_.AddEntriesFrom(input, _repeated_records_codec); break; } } } } } public sealed partial class OutOfOrderRecordGetByIdResponse : pb::IMessage<OutOfOrderRecordGetByIdResponse> { private static readonly pb::MessageParser<OutOfOrderRecordGetByIdResponse> _parser = new pb::MessageParser<OutOfOrderRecordGetByIdResponse>(() => new OutOfOrderRecordGetByIdResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<OutOfOrderRecordGetByIdResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcReflection.Descriptor.MessageTypes[1]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OutOfOrderRecordGetByIdResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OutOfOrderRecordGetByIdResponse(OutOfOrderRecordGetByIdResponse other) : this() { result_ = other.result_; Record = other.record_ != null ? other.Record.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OutOfOrderRecordGetByIdResponse Clone() { return new OutOfOrderRecordGetByIdResponse(this); } /// <summary>Field number for the "result" field.</summary> public const int ResultFieldNumber = 1; private global::HOLMS.Types.Operations.RPC.OutOfOrderRecordGetByIdResult result_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Operations.RPC.OutOfOrderRecordGetByIdResult Result { get { return result_; } set { result_ = value; } } /// <summary>Field number for the "record" field.</summary> public const int RecordFieldNumber = 2; private global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecord record_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecord Record { get { return record_; } set { record_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as OutOfOrderRecordGetByIdResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(OutOfOrderRecordGetByIdResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Result != other.Result) return false; if (!object.Equals(Record, other.Record)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Result != 0) hash ^= Result.GetHashCode(); if (record_ != null) hash ^= Record.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Result != 0) { output.WriteRawTag(8); output.WriteEnum((int) Result); } if (record_ != null) { output.WriteRawTag(18); output.WriteMessage(Record); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Result != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Result); } if (record_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Record); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(OutOfOrderRecordGetByIdResponse other) { if (other == null) { return; } if (other.Result != 0) { Result = other.Result; } if (other.record_ != null) { if (record_ == null) { record_ = new global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecord(); } Record.MergeFrom(other.Record); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { result_ = (global::HOLMS.Types.Operations.RPC.OutOfOrderRecordGetByIdResult) input.ReadEnum(); break; } case 18: { if (record_ == null) { record_ = new global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecord(); } input.ReadMessage(record_); break; } } } } } public sealed partial class OutOfOrderRecordSvcCreateRequest : pb::IMessage<OutOfOrderRecordSvcCreateRequest> { private static readonly pb::MessageParser<OutOfOrderRecordSvcCreateRequest> _parser = new pb::MessageParser<OutOfOrderRecordSvcCreateRequest>(() => new OutOfOrderRecordSvcCreateRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<OutOfOrderRecordSvcCreateRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcReflection.Descriptor.MessageTypes[2]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OutOfOrderRecordSvcCreateRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OutOfOrderRecordSvcCreateRequest(OutOfOrderRecordSvcCreateRequest other) : this() { Record = other.record_ != null ? other.Record.Clone() : null; holdDropRequested_ = other.holdDropRequested_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OutOfOrderRecordSvcCreateRequest Clone() { return new OutOfOrderRecordSvcCreateRequest(this); } /// <summary>Field number for the "record" field.</summary> public const int RecordFieldNumber = 1; private global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecord record_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecord Record { get { return record_; } set { record_ = value; } } /// <summary>Field number for the "hold_drop_requested" field.</summary> public const int HoldDropRequestedFieldNumber = 2; private bool holdDropRequested_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool HoldDropRequested { get { return holdDropRequested_; } set { holdDropRequested_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as OutOfOrderRecordSvcCreateRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(OutOfOrderRecordSvcCreateRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Record, other.Record)) return false; if (HoldDropRequested != other.HoldDropRequested) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (record_ != null) hash ^= Record.GetHashCode(); if (HoldDropRequested != false) hash ^= HoldDropRequested.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (record_ != null) { output.WriteRawTag(10); output.WriteMessage(Record); } if (HoldDropRequested != false) { output.WriteRawTag(16); output.WriteBool(HoldDropRequested); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (record_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Record); } if (HoldDropRequested != false) { size += 1 + 1; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(OutOfOrderRecordSvcCreateRequest other) { if (other == null) { return; } if (other.record_ != null) { if (record_ == null) { record_ = new global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecord(); } Record.MergeFrom(other.Record); } if (other.HoldDropRequested != false) { HoldDropRequested = other.HoldDropRequested; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (record_ == null) { record_ = new global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecord(); } input.ReadMessage(record_); break; } case 16: { HoldDropRequested = input.ReadBool(); break; } } } } } public sealed partial class OutOfOrderRecordCreateResponse : pb::IMessage<OutOfOrderRecordCreateResponse> { private static readonly pb::MessageParser<OutOfOrderRecordCreateResponse> _parser = new pb::MessageParser<OutOfOrderRecordCreateResponse>(() => new OutOfOrderRecordCreateResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<OutOfOrderRecordCreateResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcReflection.Descriptor.MessageTypes[3]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OutOfOrderRecordCreateResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OutOfOrderRecordCreateResponse(OutOfOrderRecordCreateResponse other) : this() { result_ = other.result_; Record = other.record_ != null ? other.Record.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OutOfOrderRecordCreateResponse Clone() { return new OutOfOrderRecordCreateResponse(this); } /// <summary>Field number for the "result" field.</summary> public const int ResultFieldNumber = 1; private global::HOLMS.Types.Operations.RPC.OutOfOrderRecordCreateResult result_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Operations.RPC.OutOfOrderRecordCreateResult Result { get { return result_; } set { result_ = value; } } /// <summary>Field number for the "record" field.</summary> public const int RecordFieldNumber = 2; private global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecord record_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecord Record { get { return record_; } set { record_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as OutOfOrderRecordCreateResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(OutOfOrderRecordCreateResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Result != other.Result) return false; if (!object.Equals(Record, other.Record)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Result != 0) hash ^= Result.GetHashCode(); if (record_ != null) hash ^= Record.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Result != 0) { output.WriteRawTag(8); output.WriteEnum((int) Result); } if (record_ != null) { output.WriteRawTag(18); output.WriteMessage(Record); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Result != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Result); } if (record_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Record); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(OutOfOrderRecordCreateResponse other) { if (other == null) { return; } if (other.Result != 0) { Result = other.Result; } if (other.record_ != null) { if (record_ == null) { record_ = new global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecord(); } Record.MergeFrom(other.Record); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { result_ = (global::HOLMS.Types.Operations.RPC.OutOfOrderRecordCreateResult) input.ReadEnum(); break; } case 18: { if (record_ == null) { record_ = new global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecord(); } input.ReadMessage(record_); break; } } } } } public sealed partial class OutOfOrderRecordSvcUpdateRequest : pb::IMessage<OutOfOrderRecordSvcUpdateRequest> { private static readonly pb::MessageParser<OutOfOrderRecordSvcUpdateRequest> _parser = new pb::MessageParser<OutOfOrderRecordSvcUpdateRequest>(() => new OutOfOrderRecordSvcUpdateRequest()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<OutOfOrderRecordSvcUpdateRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcReflection.Descriptor.MessageTypes[4]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OutOfOrderRecordSvcUpdateRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OutOfOrderRecordSvcUpdateRequest(OutOfOrderRecordSvcUpdateRequest other) : this() { Record = other.record_ != null ? other.Record.Clone() : null; holdDropRequested_ = other.holdDropRequested_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OutOfOrderRecordSvcUpdateRequest Clone() { return new OutOfOrderRecordSvcUpdateRequest(this); } /// <summary>Field number for the "record" field.</summary> public const int RecordFieldNumber = 1; private global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecord record_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecord Record { get { return record_; } set { record_ = value; } } /// <summary>Field number for the "hold_drop_requested" field.</summary> public const int HoldDropRequestedFieldNumber = 2; private bool holdDropRequested_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool HoldDropRequested { get { return holdDropRequested_; } set { holdDropRequested_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as OutOfOrderRecordSvcUpdateRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(OutOfOrderRecordSvcUpdateRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Record, other.Record)) return false; if (HoldDropRequested != other.HoldDropRequested) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (record_ != null) hash ^= Record.GetHashCode(); if (HoldDropRequested != false) hash ^= HoldDropRequested.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (record_ != null) { output.WriteRawTag(10); output.WriteMessage(Record); } if (HoldDropRequested != false) { output.WriteRawTag(16); output.WriteBool(HoldDropRequested); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (record_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Record); } if (HoldDropRequested != false) { size += 1 + 1; } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(OutOfOrderRecordSvcUpdateRequest other) { if (other == null) { return; } if (other.record_ != null) { if (record_ == null) { record_ = new global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecord(); } Record.MergeFrom(other.Record); } if (other.HoldDropRequested != false) { HoldDropRequested = other.HoldDropRequested; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (record_ == null) { record_ = new global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecord(); } input.ReadMessage(record_); break; } case 16: { HoldDropRequested = input.ReadBool(); break; } } } } } public sealed partial class OutOfOrderRecordUpdateResponse : pb::IMessage<OutOfOrderRecordUpdateResponse> { private static readonly pb::MessageParser<OutOfOrderRecordUpdateResponse> _parser = new pb::MessageParser<OutOfOrderRecordUpdateResponse>(() => new OutOfOrderRecordUpdateResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<OutOfOrderRecordUpdateResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcReflection.Descriptor.MessageTypes[5]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OutOfOrderRecordUpdateResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OutOfOrderRecordUpdateResponse(OutOfOrderRecordUpdateResponse other) : this() { result_ = other.result_; Record = other.record_ != null ? other.Record.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OutOfOrderRecordUpdateResponse Clone() { return new OutOfOrderRecordUpdateResponse(this); } /// <summary>Field number for the "result" field.</summary> public const int ResultFieldNumber = 1; private global::HOLMS.Types.Operations.RPC.OutOfOrderRecordUpdateResult result_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Operations.RPC.OutOfOrderRecordUpdateResult Result { get { return result_; } set { result_ = value; } } /// <summary>Field number for the "record" field.</summary> public const int RecordFieldNumber = 2; private global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecord record_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecord Record { get { return record_; } set { record_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as OutOfOrderRecordUpdateResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(OutOfOrderRecordUpdateResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Result != other.Result) return false; if (!object.Equals(Record, other.Record)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Result != 0) hash ^= Result.GetHashCode(); if (record_ != null) hash ^= Record.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Result != 0) { output.WriteRawTag(8); output.WriteEnum((int) Result); } if (record_ != null) { output.WriteRawTag(18); output.WriteMessage(Record); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Result != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Result); } if (record_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Record); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(OutOfOrderRecordUpdateResponse other) { if (other == null) { return; } if (other.Result != 0) { Result = other.Result; } if (other.record_ != null) { if (record_ == null) { record_ = new global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecord(); } Record.MergeFrom(other.Record); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { result_ = (global::HOLMS.Types.Operations.RPC.OutOfOrderRecordUpdateResult) input.ReadEnum(); break; } case 18: { if (record_ == null) { record_ = new global::HOLMS.Types.Operations.OutOfOrder.OutOfOrderRecord(); } input.ReadMessage(record_); break; } } } } } public sealed partial class OutOfOrderRecordDeleteResponse : pb::IMessage<OutOfOrderRecordDeleteResponse> { private static readonly pb::MessageParser<OutOfOrderRecordDeleteResponse> _parser = new pb::MessageParser<OutOfOrderRecordDeleteResponse>(() => new OutOfOrderRecordDeleteResponse()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<OutOfOrderRecordDeleteResponse> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Operations.RPC.OutOfOrderRecordSvcReflection.Descriptor.MessageTypes[6]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OutOfOrderRecordDeleteResponse() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OutOfOrderRecordDeleteResponse(OutOfOrderRecordDeleteResponse other) : this() { result_ = other.result_; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public OutOfOrderRecordDeleteResponse Clone() { return new OutOfOrderRecordDeleteResponse(this); } /// <summary>Field number for the "result" field.</summary> public const int ResultFieldNumber = 1; private global::HOLMS.Types.Operations.RPC.OutOfOrderRecordDeleteResult result_ = 0; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Operations.RPC.OutOfOrderRecordDeleteResult Result { get { return result_; } set { result_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as OutOfOrderRecordDeleteResponse); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(OutOfOrderRecordDeleteResponse other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Result != other.Result) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (Result != 0) hash ^= Result.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (Result != 0) { output.WriteRawTag(8); output.WriteEnum((int) Result); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (Result != 0) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Result); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(OutOfOrderRecordDeleteResponse other) { if (other == null) { return; } if (other.Result != 0) { Result = other.Result; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { result_ = (global::HOLMS.Types.Operations.RPC.OutOfOrderRecordDeleteResult) input.ReadEnum(); break; } } } } } #endregion } #endregion Designer generated code
namespace Fixtures.SwaggerBatBodyInteger { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; public static partial class IntModelExtensions { /// <summary> /// Get null Int value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static int? GetNull(this IIntModel operations) { return Task.Factory.StartNew(s => ((IIntModel)s).GetNullAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get null Int value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<int?> GetNullAsync( this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<int?> result = await operations.GetNullWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Get invalid Int value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static int? GetInvalid(this IIntModel operations) { return Task.Factory.StartNew(s => ((IIntModel)s).GetInvalidAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get invalid Int value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<int?> GetInvalidAsync( this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<int?> result = await operations.GetInvalidWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Get overflow Int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static int? GetOverflowInt32(this IIntModel operations) { return Task.Factory.StartNew(s => ((IIntModel)s).GetOverflowInt32Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get overflow Int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<int?> GetOverflowInt32Async( this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<int?> result = await operations.GetOverflowInt32WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Get underflow Int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static int? GetUnderflowInt32(this IIntModel operations) { return Task.Factory.StartNew(s => ((IIntModel)s).GetUnderflowInt32Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get underflow Int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<int?> GetUnderflowInt32Async( this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<int?> result = await operations.GetUnderflowInt32WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Get overflow Int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static long? GetOverflowInt64(this IIntModel operations) { return Task.Factory.StartNew(s => ((IIntModel)s).GetOverflowInt64Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get overflow Int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<long?> GetOverflowInt64Async( this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<long?> result = await operations.GetOverflowInt64WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Get underflow Int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static long? GetUnderflowInt64(this IIntModel operations) { return Task.Factory.StartNew(s => ((IIntModel)s).GetUnderflowInt64Async(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get underflow Int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<long?> GetUnderflowInt64Async( this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<long?> result = await operations.GetUnderflowInt64WithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Put max int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='intBody'> /// </param> public static void PutMax32(this IIntModel operations, int? intBody) { Task.Factory.StartNew(s => ((IIntModel)s).PutMax32Async(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put max int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='intBody'> /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task PutMax32Async( this IIntModel operations, int? intBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutMax32WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Put max int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='intBody'> /// </param> public static void PutMax64(this IIntModel operations, long? intBody) { Task.Factory.StartNew(s => ((IIntModel)s).PutMax64Async(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put max int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='intBody'> /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task PutMax64Async( this IIntModel operations, long? intBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutMax64WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Put min int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='intBody'> /// </param> public static void PutMin32(this IIntModel operations, int? intBody) { Task.Factory.StartNew(s => ((IIntModel)s).PutMin32Async(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put min int32 value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='intBody'> /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task PutMin32Async( this IIntModel operations, int? intBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutMin32WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Put min int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='intBody'> /// </param> public static void PutMin64(this IIntModel operations, long? intBody) { Task.Factory.StartNew(s => ((IIntModel)s).PutMin64Async(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Put min int64 value /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='intBody'> /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task PutMin64Async( this IIntModel operations, long? intBody, CancellationToken cancellationToken = default(CancellationToken)) { await operations.PutMin64WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false); } } }
using System; using System.Collections.Generic; using System.Net.Http; using System.Security.Claims; using System.Security.Cryptography; using System.Threading.Tasks; using System.Web; using System.Web.Http; using System.Web.Http.ModelBinding; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.OAuth; using Secured.Models; using Secured.Providers; using Secured.Results; using System.Linq; using Secured.Filters; namespace Secured.Controllers { [Authorize] [RoutePrefix("api/Account")] public class AccountController : ApiController { private const string LocalLoginProvider = "Local"; private ApplicationSignInManager _signInManager; private ApplicationUserManager _userManager; public AccountController() { AccessTokenFormat = Startup.OAuthOptions.AccessTokenFormat; } public AccountController(ApplicationUserManager userManager, ISecureDataFormat<AuthenticationTicket> accessTokenFormat) { UserManager = userManager; AccessTokenFormat = accessTokenFormat; } public ApplicationSignInManager SignInManager { get { return _signInManager ?? Request.GetOwinContext().Get<ApplicationSignInManager>(); } private set { _signInManager = value; } } public ApplicationUserManager UserManager { get { return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>(); } private set { _userManager = value; } } public ISecureDataFormat<AuthenticationTicket> AccessTokenFormat { get; private set; } // GET api/Account/UserInfo [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)] [Route("UserInfo")] public UserInfoViewModel GetUserInfo() { ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); var roleClaimValues = ((ClaimsIdentity)User.Identity).FindAll(ClaimTypes.Role).Select(c => c.Value); var roles = string.Join(",", roleClaimValues); return new UserInfoViewModel { UserName = User.Identity.GetUserName(), Email = ((ClaimsIdentity)User.Identity).FindFirstValue(ClaimTypes.Email), HasRegistered = externalLogin == null, LoginProvider = externalLogin != null ? externalLogin.LoginProvider : null, UserRoles = roles }; } [AllowAnonymous] [Route("Login")] public async Task<IHttpActionResult> Login(LoginViewModel model) { if (!ModelState.IsValid) { return BadRequest("Valid username and password required."); } var result = await this.SignInManager.PasswordSignInAsync(model.Id, model.Password, model.Remember, false); if (result != SignInStatus.Success) { var user = await this.UserManager.FindByEmailAsync(model.Id); if (user != null) { result = await this.SignInManager.PasswordSignInAsync(user.UserName, model.Password, model.Remember, false); } } switch (result) { case SignInStatus.Success: return Ok(); case SignInStatus.Failure: return BadRequest("login failed"); case SignInStatus.LockedOut: return BadRequest("account locked out"); case SignInStatus.RequiresVerification: return BadRequest("verification required"); default: return BadRequest("unknown login error"); } } // POST api/Account/Logout [Route("Logout")] public IHttpActionResult Logout() { Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType); return Ok(); } // GET api/Account/ManageInfo?returnUrl=%2F&generateState=true [Route("ManageInfo")] public async Task<ManageInfoViewModel> GetManageInfo(string returnUrl, bool generateState = false) { IdentityUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId()); if (user == null) { return null; } List<UserLoginInfoViewModel> logins = new List<UserLoginInfoViewModel>(); foreach (IdentityUserLogin linkedAccount in user.Logins) { logins.Add(new UserLoginInfoViewModel { LoginProvider = linkedAccount.LoginProvider, ProviderKey = linkedAccount.ProviderKey }); } if (user.PasswordHash != null) { logins.Add(new UserLoginInfoViewModel { LoginProvider = LocalLoginProvider, ProviderKey = user.UserName, }); } return new ManageInfoViewModel { LocalLoginProvider = LocalLoginProvider, Email = user.Email, UserName = user.UserName, Logins = logins, ExternalLoginProviders = GetExternalLogins(returnUrl, generateState) }; } // POST api/Account/ChangePassword [Route("ChangePassword")] public async Task<IHttpActionResult> ChangePassword(ChangePasswordBindingModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } IdentityResult result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword, model.NewPassword); if (!result.Succeeded) { return GetErrorResult(result); } return Ok(); } // POST api/Account/SetPassword [Route("SetPassword")] public async Task<IHttpActionResult> SetPassword(SetPasswordBindingModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } IdentityResult result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword); if (!result.Succeeded) { return GetErrorResult(result); } return Ok(); } // POST api/Account/AddExternalLogin [Route("AddExternalLogin")] public async Task<IHttpActionResult> AddExternalLogin(AddExternalLoginBindingModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); AuthenticationTicket ticket = AccessTokenFormat.Unprotect(model.ExternalAccessToken); if (ticket == null || ticket.Identity == null || (ticket.Properties != null && ticket.Properties.ExpiresUtc.HasValue && ticket.Properties.ExpiresUtc.Value < DateTimeOffset.UtcNow)) { return BadRequest("External login failure."); } ExternalLoginData externalData = ExternalLoginData.FromIdentity(ticket.Identity); if (externalData == null) { return BadRequest("The external login is already associated with an account."); } IdentityResult result = await UserManager.AddLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(externalData.LoginProvider, externalData.ProviderKey)); if (!result.Succeeded) { return GetErrorResult(result); } return Ok(); } // POST api/Account/RemoveLogin [Route("RemoveLogin")] public async Task<IHttpActionResult> RemoveLogin(RemoveLoginBindingModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } IdentityResult result; if (model.LoginProvider == LocalLoginProvider) { result = await UserManager.RemovePasswordAsync(User.Identity.GetUserId()); } else { result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(), new UserLoginInfo(model.LoginProvider, model.ProviderKey)); } if (!result.Succeeded) { return GetErrorResult(result); } return Ok(); } // GET api/Account/ExternalLogin [OverrideAuthentication] [HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)] [AllowAnonymous] [Route("ExternalLogin", Name = "ExternalLogin")] public async Task<IHttpActionResult> GetExternalLogin(string provider, string error = null) { if (error != null) { return Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error)); } if (!User.Identity.IsAuthenticated) { return new ChallengeResult(provider, this); } ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); if (externalLogin == null) { return InternalServerError(); } if (externalLogin.LoginProvider != provider) { Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); return new ChallengeResult(provider, this); } ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey)); bool hasRegistered = user != null; if (hasRegistered) { Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(oAuthIdentity); Authentication.SignIn(properties, oAuthIdentity, cookieIdentity); } else { IEnumerable<Claim> claims = externalLogin.GetClaims(); ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType); Authentication.SignIn(identity); } return Ok(); } // GET api/Account/ExternalLogins?returnUrl=%2F&generateState=true [AllowAnonymous] [Route("ExternalLogins")] public IEnumerable<ExternalLoginViewModel> GetExternalLogins(string returnUrl, bool generateState = false) { IEnumerable<AuthenticationDescription> descriptions = Authentication.GetExternalAuthenticationTypes(); List<ExternalLoginViewModel> logins = new List<ExternalLoginViewModel>(); string state; if (generateState) { const int strengthInBits = 256; state = RandomOAuthStateGenerator.Generate(strengthInBits); } else { state = null; } foreach (AuthenticationDescription description in descriptions) { ExternalLoginViewModel login = new ExternalLoginViewModel { Name = description.Caption, Url = Url.Route("ExternalLogin", new { provider = description.AuthenticationType, response_type = "token", client_id = Startup.PublicClientId, redirect_uri = new Uri(Request.RequestUri, returnUrl).AbsoluteUri, state = state }), State = state }; logins.Add(login); } return logins; } // GET api/Account/ExternalLogins?returnUrl=%2F&generateState=true [AllowAnonymous] [Route("ExternalLogins")] public IHttpActionResult GetExternalLogins(string returnUrl, string provider, bool generateState = false) { var description = Authentication.GetExternalAuthenticationTypes() .FirstOrDefault(ad => ad.AuthenticationType == provider); if (description == null) { return NotFound(); } string state; if (generateState) { const int strengthInBits = 256; state = RandomOAuthStateGenerator.Generate(strengthInBits); } else { state = null; } ExternalLoginViewModel login = new ExternalLoginViewModel { Name = description.Caption, Url = Url.Route("ExternalLogin", new { provider = description.AuthenticationType, response_type = "token", client_id = Startup.PublicClientId, redirect_uri = new Uri(Request.RequestUri, returnUrl).AbsoluteUri, state = state }), State = state }; return Ok(login); } // POST api/Account/Register [AllowAnonymous] [Route("Register")] public async Task<IHttpActionResult> Register(RegisterBindingModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var user = new ApplicationUser() { UserName = model.UserName, Email = model.Email }; IdentityResult result = await UserManager.CreateAsync(user, model.Password); if (!result.Succeeded) { return GetErrorResult(result); } return Ok(); } [AllowAnonymous] [HttpPost] [Route("checkEmailAvailable")] public async Task<IHttpActionResult> CheckEmailAvailable([FromBody] EmailQueryBindingModel query) { var user = await UserManager.FindByEmailAsync(query.Email); return Ok(new { available = user == null }); } [AllowAnonymous] [HttpPost] [Route("checkUsernameAvailable")] public async Task<IHttpActionResult> CheckUsernameAvailable([FromBody] UsernameQueryBindingModel query) { var user = await UserManager.FindByNameAsync(query.Username); return Ok(new { available = user == null }); } // POST api/Account/RegisterExternal [OverrideAuthentication] [AllowAnonymous] [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)] [Route("RegisterExternal")] public async Task<IHttpActionResult> RegisterExternal(RegisterExternalBindingModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var info = await Authentication.GetExternalLoginInfoAsync(); if (info == null) { return InternalServerError(); } var user = new ApplicationUser() { UserName = model.Email, Email = model.Email }; IdentityResult result = await UserManager.CreateAsync(user); if (!result.Succeeded) { return GetErrorResult(result); } result = await UserManager.AddLoginAsync(user.Id, info.Login); if (!result.Succeeded) { return GetErrorResult(result); } return Ok(); } protected override void Dispose(bool disposing) { if (disposing && _userManager != null) { _userManager.Dispose(); _userManager = null; } base.Dispose(disposing); } #region Helpers private IAuthenticationManager Authentication { get { return Request.GetOwinContext().Authentication; } } private IHttpActionResult GetErrorResult(IdentityResult result) { if (result == null) { return InternalServerError(); } if (!result.Succeeded) { if (result.Errors != null) { foreach (string error in result.Errors) { ModelState.AddModelError("", error); } } if (ModelState.IsValid) { // No ModelState errors are available to send, so just return an empty BadRequest. return BadRequest(); } return BadRequest(ModelState); } return null; } private class ExternalLoginData { public string LoginProvider { get; set; } public string ProviderKey { get; set; } public string UserName { get; set; } public string Email { get; set; } public IList<Claim> GetClaims() { IList<Claim> claims = new List<Claim>(); claims.Add(new Claim(ClaimTypes.NameIdentifier, ProviderKey, null, LoginProvider)); if (UserName != null) { claims.Add(new Claim(ClaimTypes.Name, UserName, null, LoginProvider)); } if (Email != null) { claims.Add(new Claim(ClaimTypes.Email, Email, null, LoginProvider)); } return claims; } public static ExternalLoginData FromIdentity(ClaimsIdentity identity) { if (identity == null) { return null; } Claim providerKeyClaim = identity.FindFirst(ClaimTypes.NameIdentifier); if (providerKeyClaim == null || String.IsNullOrEmpty(providerKeyClaim.Issuer) || String.IsNullOrEmpty(providerKeyClaim.Value)) { return null; } if (providerKeyClaim.Issuer == ClaimsIdentity.DefaultIssuer) { return null; } return new ExternalLoginData { LoginProvider = providerKeyClaim.Issuer, ProviderKey = providerKeyClaim.Value, UserName = identity.FindFirstValue(ClaimTypes.Name), Email = identity.FindFirstValue(ClaimTypes.Email) }; } } private static class RandomOAuthStateGenerator { private static RandomNumberGenerator _random = new RNGCryptoServiceProvider(); public static string Generate(int strengthInBits) { const int bitsPerByte = 8; if (strengthInBits % bitsPerByte != 0) { throw new ArgumentException("strengthInBits must be evenly divisible by 8.", "strengthInBits"); } int strengthInBytes = strengthInBits / bitsPerByte; byte[] data = new byte[strengthInBytes]; _random.GetBytes(data); return HttpServerUtility.UrlTokenEncode(data); } } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; namespace help.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using ServiceStack.ServiceHost; using ServiceStack.ServiceModel.Serialization; using ServiceStack.Text; namespace ServiceStack.Common.Web { public class HttpResponseFilter : IContentTypeFilter { private static readonly UTF8Encoding UTF8EncodingWithoutBom = new UTF8Encoding(false); public static HttpResponseFilter Instance = new HttpResponseFilter(); public Dictionary<string, StreamSerializerDelegate> ContentTypeSerializers = new Dictionary<string, StreamSerializerDelegate>(); public Dictionary<string, ResponseSerializerDelegate> ContentTypeResponseSerializers = new Dictionary<string, ResponseSerializerDelegate>(); public Dictionary<string, StreamDeserializerDelegate> ContentTypeDeserializers = new Dictionary<string, StreamDeserializerDelegate>(); public HttpResponseFilter() { this.ContentTypeFormats = new Dictionary<string, string>(); } public void ClearCustomFilters() { this.ContentTypeFormats = new Dictionary<string, string>(); this.ContentTypeSerializers = new Dictionary<string, StreamSerializerDelegate>(); this.ContentTypeDeserializers = new Dictionary<string, StreamDeserializerDelegate>(); } public Dictionary<string, string> ContentTypeFormats { get; set; } public string GetFormatContentType(string format) { //built-in formats if (format == "json") return ContentType.Json; if (format == "xml") return ContentType.Xml; if (format == "jsv") return ContentType.Jsv; string registeredFormats; ContentTypeFormats.TryGetValue(format, out registeredFormats); return registeredFormats; } public void Register(string contentType, StreamSerializerDelegate streamSerializer, StreamDeserializerDelegate streamDeserializer) { if (contentType.IsNullOrEmpty()) throw new ArgumentNullException("contentType"); var parts = contentType.Split('/'); var format = parts[parts.Length - 1]; this.ContentTypeFormats[format] = contentType; SetContentTypeSerializer(contentType, streamSerializer); SetContentTypeDeserializer(contentType, streamDeserializer); } public void Register(string contentType, ResponseSerializerDelegate responseSerializer, StreamDeserializerDelegate streamDeserializer) { if (contentType.IsNullOrEmpty()) throw new ArgumentNullException("contentType"); var parts = contentType.Split('/'); var format = parts[parts.Length - 1]; this.ContentTypeFormats[format] = contentType; this.ContentTypeResponseSerializers[contentType] = responseSerializer; SetContentTypeDeserializer(contentType, streamDeserializer); } public void SetContentTypeSerializer(string contentType, StreamSerializerDelegate streamSerializer) { this.ContentTypeSerializers[contentType] = streamSerializer; } public void SetContentTypeDeserializer(string contentType, StreamDeserializerDelegate streamDeserializer) { this.ContentTypeDeserializers[contentType] = streamDeserializer; } public byte[] SerializeToBytes(IRequestContext requestContext, object response) { var contentType = requestContext.ResponseContentType; StreamSerializerDelegate responseStreamWriter; if (this.ContentTypeSerializers.TryGetValue(contentType, out responseStreamWriter) || this.ContentTypeSerializers.TryGetValue(ContentType.GetRealContentType(contentType), out responseStreamWriter)) { using (var ms = new MemoryStream()) { responseStreamWriter(requestContext, response, ms); ms.Position = 0; return ms.ToArray(); } } ResponseSerializerDelegate responseWriter; if (this.ContentTypeResponseSerializers.TryGetValue(contentType, out responseWriter) || this.ContentTypeResponseSerializers.TryGetValue(ContentType.GetRealContentType(contentType), out responseWriter)) { using (var ms = new MemoryStream()) { var httpRes = new HttpResponseStreamWrapper(ms); responseWriter(requestContext, response, httpRes); ms.Position = 0; return ms.ToArray(); } } var contentTypeAttr = ContentType.GetEndpointAttributes(contentType); switch (contentTypeAttr) { case EndpointAttributes.Xml: return XmlSerializer.SerializeToString(response).ToUtf8Bytes(); case EndpointAttributes.Json: return JsonDataContractSerializer.Instance.SerializeToString(response).ToUtf8Bytes(); case EndpointAttributes.Jsv: return TypeSerializer.SerializeToString(response).ToUtf8Bytes(); } throw new NotSupportedException("ContentType not supported: " + contentType); } public string SerializeToString(IRequestContext requestContext, object response) { var contentType = requestContext.ResponseContentType; StreamSerializerDelegate responseStreamWriter; if (this.ContentTypeSerializers.TryGetValue(contentType, out responseStreamWriter) || this.ContentTypeSerializers.TryGetValue(ContentType.GetRealContentType(contentType), out responseStreamWriter)) { using (var ms = new MemoryStream()) { responseStreamWriter(requestContext, response, ms); ms.Position = 0; var result = new StreamReader(ms, UTF8EncodingWithoutBom).ReadToEnd(); return result; } } ResponseSerializerDelegate responseWriter; if (this.ContentTypeResponseSerializers.TryGetValue(contentType, out responseWriter) || this.ContentTypeResponseSerializers.TryGetValue(ContentType.GetRealContentType(contentType), out responseWriter)) { using (var ms = new MemoryStream()) { var httpRes = new HttpResponseStreamWrapper(ms) { KeepOpen = true, //Don't let view engines close the OutputStream }; responseWriter(requestContext, response, httpRes); var bytes = ms.ToArray(); var result = bytes.FromUtf8Bytes(); httpRes.ForceClose(); //Manually close the OutputStream return result; } } var contentTypeAttr = ContentType.GetEndpointAttributes(contentType); switch (contentTypeAttr) { case EndpointAttributes.Xml: return XmlSerializer.SerializeToString(response); case EndpointAttributes.Json: return JsonDataContractSerializer.Instance.SerializeToString(response); case EndpointAttributes.Jsv: return TypeSerializer.SerializeToString(response); } throw new NotSupportedException("ContentType not supported: " + contentType); } public void SerializeToStream(IRequestContext requestContext, object response, Stream responseStream) { var contentType = requestContext.ResponseContentType; var serializer = GetResponseSerializer(contentType); if (serializer == null) throw new NotSupportedException("ContentType not supported: " + contentType); var httpRes = new HttpResponseStreamWrapper(responseStream); serializer(requestContext, response, httpRes); } public void SerializeToResponse(IRequestContext requestContext, object response, IHttpResponse httpResponse) { var contentType = requestContext.ResponseContentType; var serializer = GetResponseSerializer(contentType); if (serializer == null) throw new NotSupportedException("ContentType not supported: " + contentType); serializer(requestContext, response, httpResponse); } public ResponseSerializerDelegate GetResponseSerializer(string contentType) { ResponseSerializerDelegate responseWriter; if (this.ContentTypeResponseSerializers.TryGetValue(contentType, out responseWriter) || this.ContentTypeResponseSerializers.TryGetValue(ContentType.GetRealContentType(contentType), out responseWriter)) { return responseWriter; } var serializer = GetStreamSerializer(contentType); if (serializer == null) return null; return (httpReq, dto, httpRes) => serializer(httpReq, dto, httpRes.OutputStream); } public StreamSerializerDelegate GetStreamSerializer(string contentType) { StreamSerializerDelegate responseWriter; if (this.ContentTypeSerializers.TryGetValue(contentType, out responseWriter) || this.ContentTypeSerializers.TryGetValue(ContentType.GetRealContentType(contentType), out responseWriter)) { return responseWriter; } var contentTypeAttr = ContentType.GetEndpointAttributes(contentType); switch (contentTypeAttr) { case EndpointAttributes.Xml: return (r, o, s) => XmlSerializer.SerializeToStream(o, s); case EndpointAttributes.Json: return (r, o, s) => JsonDataContractSerializer.Instance.SerializeToStream(o, s); case EndpointAttributes.Jsv: return (r, o, s) => TypeSerializer.SerializeToStream(o, s); } return null; } public object DeserializeFromString(string contentType, Type type, string request) { var contentTypeAttr = ContentType.GetEndpointAttributes(contentType); switch (contentTypeAttr) { case EndpointAttributes.Xml: return XmlSerializer.DeserializeFromString(request, type); case EndpointAttributes.Json: return JsonDataContractDeserializer.Instance.DeserializeFromString(request, type); case EndpointAttributes.Jsv: return TypeSerializer.DeserializeFromString(request, type); default: throw new NotSupportedException("ContentType not supported: " + contentType); } } public object DeserializeFromStream(string contentType, Type type, Stream fromStream) { var deserializer = GetStreamDeserializer(contentType); if (deserializer == null) throw new NotSupportedException("ContentType not supported: " + contentType); return deserializer(type, fromStream); } public StreamDeserializerDelegate GetStreamDeserializer(string contentType) { StreamDeserializerDelegate streamReader; var realContentType = contentType.Split(';')[0].Trim(); if (this.ContentTypeDeserializers.TryGetValue(realContentType, out streamReader)) { return streamReader; } var contentTypeAttr = ContentType.GetEndpointAttributes(contentType); switch (contentTypeAttr) { case EndpointAttributes.Xml: return XmlSerializer.DeserializeFromStream; case EndpointAttributes.Json: return JsonDataContractDeserializer.Instance.DeserializeFromStream; case EndpointAttributes.Jsv: return TypeSerializer.DeserializeFromStream; } return null; } } }
// // Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !MONO && !NETSTANDARD namespace NLog.Internal.FileAppenders { using System; using System.IO; using System.Security; using System.Threading; using NLog.Common; /// <summary> /// Provides a multi process-safe atomic file append while /// keeping the files open. /// </summary> [SecuritySafeCritical] internal class WindowsMultiProcessFileAppender : BaseMutexFileAppender { public static readonly IFileAppenderFactory TheFactory = new Factory(); private FileStream _fileStream; /// <summary> /// Initializes a new instance of the <see cref="WindowsMultiProcessFileAppender" /> class. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="parameters">The parameters.</param> public WindowsMultiProcessFileAppender(string fileName, ICreateFileParameters parameters) : base(fileName, parameters) { try { CreateAppendOnlyFile(fileName); } catch { if (_fileStream != null) _fileStream.Dispose(); _fileStream = null; throw; } } /// <summary> /// Creates or opens a file in a special mode, so that writes are automatically /// as atomic writes at the file end. /// See also "UnixMultiProcessFileAppender" which does a similar job on *nix platforms. /// </summary> /// <param name="fileName">File to create or open</param> private void CreateAppendOnlyFile(string fileName) { string dir = Path.GetDirectoryName(fileName); if (!Directory.Exists(dir)) { if (!CreateFileParameters.CreateDirs) { throw new DirectoryNotFoundException(dir); } Directory.CreateDirectory(dir); } var fileShare = FileShare.ReadWrite; if (CreateFileParameters.EnableFileDelete) fileShare |= FileShare.Delete; try { bool fileExists = File.Exists(fileName); // https://blogs.msdn.microsoft.com/oldnewthing/20151127-00/?p=92211/ // https://msdn.microsoft.com/en-us/library/ff548289.aspx // If only the FILE_APPEND_DATA and SYNCHRONIZE flags are set, the caller can write only to the end of the file, // and any offset information about writes to the file is ignored. // However, the file will automatically be extended as necessary for this type of write operation. _fileStream = new FileStream( fileName, FileMode.Append, System.Security.AccessControl.FileSystemRights.AppendData | System.Security.AccessControl.FileSystemRights.Synchronize, // <- Atomic append fileShare, 1, // No internal buffer, write directly from user-buffer FileOptions.None); long filePosition = _fileStream.Position; if (fileExists || filePosition > 0) { CreationTimeUtc = File.GetCreationTimeUtc(FileName); if (CreationTimeUtc < DateTime.UtcNow - TimeSpan.FromSeconds(2) && filePosition == 0) { // File wasn't created "almost now". // This could mean creation time has tunneled through from another file (see comment below). Thread.Sleep(50); // Having waited for a short amount of time usually means the file creation process has continued // code execution just enough to the above point where it has fixed up the creation time. CreationTimeUtc = File.GetCreationTimeUtc(FileName); } } else { // We actually created the file and eventually concurrent processes // may have opened the same file in between. // Only the one process creating the file should adjust the file creation time // to avoid being thwarted by Windows' Tunneling capabilities (https://support.microsoft.com/en-us/kb/172190). // Unfortunately we can't use the native SetFileTime() to prevent opening the file 2nd time. // This would require another desiredAccess flag which would disable the atomic append feature. // See also UpdateCreationTime() CreationTimeUtc = DateTime.UtcNow; File.SetCreationTimeUtc(FileName, CreationTimeUtc); } } catch { if (_fileStream != null) _fileStream.Dispose(); _fileStream = null; throw; } } /// <summary> /// Writes the specified bytes. /// </summary> /// <param name="bytes">The bytes array.</param> /// <param name="offset">The bytes array offset.</param> /// <param name="count">The number of bytes.</param> public override void Write(byte[] bytes, int offset, int count) { if (_fileStream != null) { _fileStream.Write(bytes, offset, count); } } /// <summary> /// Closes this instance. /// </summary> public override void Close() { if (_fileStream == null) { return; } InternalLogger.Trace("Closing '{0}'", FileName); try { _fileStream?.Dispose(); } catch (Exception ex) { InternalLogger.Warn(ex, "Failed to close file '{0}'", FileName); Thread.Sleep(1); // Artificial delay to avoid hammering a bad file location } finally { _fileStream = null; } } /// <summary> /// Flushes this instance. /// </summary> public override void Flush() { // do nothing, the file is written directly } public override DateTime? GetFileCreationTimeUtc() { return CreationTimeUtc; // File is kept open, so creation time is static } /// <summary> /// Gets the length in bytes of the file associated with the appender. /// </summary> /// <returns>A long value representing the length of the file in bytes.</returns> public override long? GetFileLength() { return _fileStream?.Length; } /// <summary> /// Factory class. /// </summary> private class Factory : IFileAppenderFactory { /// <summary> /// Opens the appender for given file name and parameters. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="parameters">Creation parameters.</param> /// <returns> /// Instance of <see cref="BaseFileAppender"/> which can be used to write to the file. /// </returns> BaseFileAppender IFileAppenderFactory.Open(string fileName, ICreateFileParameters parameters) { return new WindowsMultiProcessFileAppender(fileName, parameters); } } } } #endif
using System; using System.Runtime.InteropServices; namespace Torshify.Core.Native { internal partial class Spotify { #region Delegates public delegate void DescriptionChangedCallback(IntPtr playlistPtr, IntPtr descPtr, IntPtr userdataPtr); public delegate void ImageChangedCallback(IntPtr playlistPtr, IntPtr imgIdPtr, IntPtr userdataPtr); public delegate void PlaylistMetadataUpdatedCallback(IntPtr playlistPtr, IntPtr userdataPtr); public delegate void PlaylistRenamedCallback(IntPtr playlistPtr, IntPtr userdataPtr); public delegate void PlaylistStateChangedCallback(IntPtr playlistPtr, IntPtr userdataPtr); public delegate void PlaylistUpdateInProgressCallback(IntPtr playlistPtr, bool done, IntPtr userdataPtr); public delegate void SubscribersChangedCallback(IntPtr playlistPtr, IntPtr userdataPtr); public delegate void TrackCreatedChangedCallback(IntPtr playlistPtr, int position, IntPtr userPtr, int when, IntPtr userdataPtr); public delegate void TracksAddedCallback(IntPtr playlistPtr, IntPtr tracksPtr, int numTracks, int position, IntPtr userdataPtr); public delegate void TrackSeenChangedCallback(IntPtr playlistPtr, int position, bool seen, IntPtr userdataPtr); public delegate void TracksMovedCallback(IntPtr playlistPtr, IntPtr trackIndicesPtr, int numTracks, int newPosition, IntPtr userdataPtr); public delegate void TracksRemovedCallback(IntPtr playlistPtr, IntPtr trackIndicesPtr, int numTracks, IntPtr userdataPtr); #endregion Delegates #region Internal Static Methods /// <summary> /// Get load status for the specified playlist. If it's false, you have to wait until playlist_state_changed happens, /// and check again if is_loaded has changed. /// </summary> /// <param name="playlistPtr">Playlist object.</param> /// <returns>True if playlist is loaded, otherwise false.</returns> [DllImport("libspotify")] [return: MarshalAs(UnmanagedType.I1)] internal static extern bool sp_playlist_is_loaded(IntPtr playlistPtr); /// <summary> /// Register interest in the given playlist. /// </summary> /// <param name="playlistPtr">Playlist object.</param> /// <param name="callbacksPtr">Callbacks, see sp_playlist_callbacks.</param> /// <param name="userdataPtr">Userdata to be passed to callbacks.</param> [DllImport("libspotify")] internal static extern Error sp_playlist_add_callbacks(IntPtr playlistPtr, ref PlaylistCallbacks callbacksPtr, IntPtr userdataPtr); /// <summary> /// Unregister interest in the given playlist. /// The combination of (callbacks, userdata) is used to find the entry to be removed. /// </summary> /// <param name="playlistPtr">Playlist object.</param> /// <param name="callbacksPtr">Callbacks, see sp_playlist_callbacks.</param> /// <param name="userdataPtr">Userdata to be passed to callbacks.</param> [DllImport("libspotify")] internal static extern Error sp_playlist_remove_callbacks(IntPtr playlistPtr, ref PlaylistCallbacks callbacksPtr, IntPtr userdataPtr); /// <summary> /// Return number of tracks in the given playlist. /// </summary> /// <param name="playlistPtr">Playlist object.</param> /// <returns>The number of tracks in the playlist.</returns> [DllImport("libspotify")] internal static extern int sp_playlist_num_tracks(IntPtr playlistPtr); /// <summary> /// Return the track at the given index in a playlist. /// </summary> /// <param name="playlistPtr">Playlist object.</param> /// <param name="index">Index into playlist container. Should be in the interval [0, sp_playlist_num_tracks() - 1].</param> /// <returns>The track at the given index.</returns> [DllImport("libspotify")] internal static extern IntPtr sp_playlist_track(IntPtr playlistPtr, int index); /// <summary> /// Return when the given index was added to the playlist. /// </summary> /// <param name="playlistPtr">Playlist object.</param> /// <param name="index">Index into playlist container. Should be in the interval [0, sp_playlist_num_tracks() - 1].</param> /// <returns>Time, Seconds since unix epoch.</returns> [DllImport("libspotify")] internal static extern int sp_playlist_track_create_time(IntPtr playlistPtr, int index); /// <summary> /// Return user that added the given index in the playlist. /// </summary> /// <param name="playlistPtr">Playlist object.</param> /// <param name="index">Index into playlist container. Should be in the interval [0, sp_playlist_num_tracks() - 1].</param> /// <returns>User object.</returns> [DllImport("libspotify")] internal static extern IntPtr sp_playlist_track_creator(IntPtr playlistPtr, int index); /// <summary> /// Return if a playlist entry is marked as seen or not. /// </summary> /// <param name="playlistPtr">Playlist object.</param> /// <param name="index">Index into playlist container. Should be in the interval [0, sp_playlist_num_tracks() - 1].</param> /// <returns>Seen state.</returns> [DllImport("libspotify")] [return: MarshalAs(UnmanagedType.I1)] internal static extern bool sp_playlist_track_seen(IntPtr playlistPtr, int index); /// <summary> /// Return name of given playlist. /// </summary> /// <param name="playlistPtr">Playlist object.</param> /// <returns>The name of the given playlist.</returns> [DllImport("libspotify")] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(MarshalPtrToUtf8))] internal static extern string sp_playlist_name(IntPtr playlistPtr); /// <summary> /// Rename the given playlist The name must not consist of only spaces and it must be shorter than 256 characters. /// </summary> /// <param name="playlistPtr">Playlist object.</param> /// <param name="newName">New name for playlist.</param> /// <returns>Error code.</returns> [DllImport("libspotify")] internal static extern Error sp_playlist_rename(IntPtr playlistPtr, string newName); /// <summary> /// Return a pointer to the user for the given playlist. /// </summary> /// <param name="playlistPtr">Playlist object.</param> /// <returns>User object.</returns> [DllImport("libspotify")] internal static extern IntPtr sp_playlist_owner(IntPtr playlistPtr); /// <summary> /// Return collaborative status for a playlist. /// A playlist in collaborative state can be modifed by all users, not only the user owning the list. /// </summary> /// <param name="playlistPtr">Playlist object.</param> /// <returns>true if playlist is collaborative, otherwise false.</returns> [DllImport("libspotify")] [return: MarshalAs(UnmanagedType.I1)] internal static extern bool sp_playlist_is_collaborative(IntPtr playlistPtr); /// <summary> /// Set collaborative status for a playlist. /// A playlist in collaborative state can be modifed by all users, not only the user owning the list. /// </summary> /// <param name="playlistPtr">Playlist object.</param> /// <param name="collaborative">Wheater or not the playlist should be collaborative.</param> [DllImport("libspotify")] internal static extern Error sp_playlist_set_collaborative(IntPtr playlistPtr, bool collaborative); /// <summary> /// Set autolinking state for a playlist. /// If a playlist is autolinked, unplayable tracks will be made playable by linking them to other Spotify tracks, where possible. /// </summary> /// <param name="playlistPtr">Playlist object.</param> /// <param name="link">The new value.</param> [DllImport("libspotify")] internal static extern Error sp_playlist_set_autolink_tracks(IntPtr playlistPtr, bool link); /// <summary> /// Get description for a playlist. /// </summary> /// <param name="playlistPtr">Playlist object.</param> /// <returns>Description</returns> [DllImport("libspotify")] [return: MarshalAs(UnmanagedType.CustomMarshaler, MarshalTypeRef = typeof(MarshalPtrToUtf8))] internal static extern string sp_playlist_get_description(IntPtr playlistPtr); /// <summary> /// Get image for a playlist. /// </summary> /// <param name="playlistPtr">Playlist object.</param> /// <param name="imageId">[out] 20 byte image id.</param> /// <returns>True if playlist has an image, otherwise false.</returns> [DllImport("libspotify")] [return: MarshalAs(UnmanagedType.I1)] internal static extern bool sp_playlist_get_image(IntPtr playlistPtr, IntPtr imageId); /// <summary> /// Check if a playlist has pending changes. /// Pending changes are local changes that have not yet been acknowledged by the server. /// </summary> /// <param name="playlistPtr">Playlist object.</param> /// <returns>A flag representing if there are pending changes or not.</returns> [DllImport("libspotify")] [return: MarshalAs(UnmanagedType.I1)] internal static extern bool sp_playlist_has_pending_changes(IntPtr playlistPtr); /// <summary> /// Add tracks to a playlist. /// </summary> /// <param name="playlistPtr">Playlist object.</param> /// <param name="trackArrayPtr">Array of pointer to tracks.</param> /// <param name="numTracks">Count of <c>tracks</c> array.</param> /// <param name="position">Start position in playlist where to insert the tracks.</param> /// <param name="sessionPtr">Your session object.</param> /// <returns>Error code.</returns> [DllImport("libspotify")] internal static extern Error sp_playlist_add_tracks(IntPtr playlistPtr, IntPtr trackArrayPtr, int numTracks, int position, IntPtr sessionPtr); /// <summary> /// Remove tracks from a playlist. /// </summary> /// <param name="playlistPtr">Playlist object.</param> /// <param name="trackIndices">Array of pointer to track indices. /// A certain track index should be present at most once, e.g. [0, 1, 2] is valid indata, whereas [0, 1, 1] is invalid.</param> /// <param name="numTracks">Count of <c>trackIndices</c> array.</param> /// <returns>Error code.</returns> [DllImport("libspotify")] internal static extern Error sp_playlist_remove_tracks(IntPtr playlistPtr, int[] trackIndices, int numTracks); /// <summary> /// Move tracks in playlist. /// </summary> /// <param name="playlistPtr">Playlist object.</param> /// <param name="trackIndices">Array of pointer to track indices to be moved. /// A certain track index should be present at most once, e.g. [0, 1, 2] is valid indata, whereas [0, 1, 1] is invalid.</param> /// <param name="numTracks">Count of <c>trackIndices</c> array.</param> /// <param name="newPosition">New position for tracks.</param> /// <returns>Error code.</returns> [DllImport("libspotify")] internal static extern Error sp_playlist_reorder_tracks(IntPtr playlistPtr, int[] trackIndices, int numTracks, int newPosition); /// <summary> /// Return number of subscribers for a given playlist /// </summary> /// <param name="playlistPtr">The playlist object.</param> /// <returns>Number of subscribers</returns> [DllImport("libspotify")] internal static extern int sp_playlist_num_subscribers(IntPtr playlistPtr); /// <summary> /// Return subscribers for a playlist /// </summary> /// <param name="playlistPtr">The playlist object.</param> /// <returns>sp_subscribers struct with array of canonical usernames. This object should be free'd using sp_playlist_subscribers_free()</returns> [DllImport("libspotify")] internal static extern IntPtr sp_playlist_subscribers(IntPtr playlistPtr); /// <summary> /// Free object returned from sp_playlist_subscribers() /// </summary> /// <param name="subscribersPtr">The Subscribers object.</param> [DllImport("libspotify")] internal static extern Error sp_playlist_subscribers_free(IntPtr subscribersPtr); /// <summary> /// Ask library to update the subscription count for a playlist /// /// When the subscription info has been fetched from the Spotify backend /// the playlist subscribers_changed() callback will be invoked. /// In that callback use sp_playlist_num_subscribers() and/or /// sp_playlist_subscribers() to get information about the subscribers. /// You can call those two functions anytime you want but the information /// might not be up to date in such cases /// </summary> /// <param name="sessionPtr">The session object</param> /// <param name="playlistPtr">Playlist object.</param> [DllImport("libspotify")] internal static extern Error sp_playlist_update_subscribers(IntPtr sessionPtr, IntPtr playlistPtr); /// <summary> /// Load an already existing playlist without adding it to a playlistcontainer. /// </summary> /// <param name="sessionPtr">Session object.</param> /// <param name="linkPtr">Link object referring to a playlist.</param> /// <returns>A playlist. The reference is owned by the caller and should be released with sp_playlist_release().</returns> [DllImport("libspotify")] internal static extern IntPtr sp_playlist_create(IntPtr sessionPtr, IntPtr linkPtr); /// <summary> /// Increase the reference count of a playlist. /// </summary> /// <param name="playlistPtr">Playlist object.</param> [DllImport("libspotify")] internal static extern Error sp_playlist_add_ref(IntPtr playlistPtr); /// <summary> /// Decrease the reference count of a playlist. /// </summary> /// <param name="playlistPtr">The playlist object.</param> [DllImport("libspotify")] internal static extern Error sp_playlist_release(IntPtr playlistPtr); /// <summary> /// Mark a playlist to be synchronized for offline playback /// </summary> /// <param name="sessionPtr">Session object</param> /// <param name="playlistPtr">Playlist object</param> /// <param name="offline">True if playlist should be offline, false otherwise</param> [DllImport("libspotify")] internal static extern Error sp_playlist_set_offline_mode(IntPtr sessionPtr, IntPtr playlistPtr, bool offline); /// <summary> /// Get offline status for a playlist /// /// When in SP_PLAYLIST_OFFLINE_STATUS_DOWNLOADING mode the /// sp_playlist_get_offline_download_completed() method can be used to query /// progress of the download /// </summary> /// <param name="sessionPtr">Session object</param> /// <param name="playlistPtr">Playlist object</param> [DllImport("libspotify")] internal static extern PlaylistOfflineStatus sp_playlist_get_offline_status(IntPtr sessionPtr, IntPtr playlistPtr); /// <summary> /// Get download progress for an offline playlist /// </summary> /// <param name="sessionPtr">Session object</param> /// <param name="playlistPtr">Playlist object</param> /// <returns>Value from 0 - 100 that indicates amount of playlist that is downloaded</returns> [DllImport("libspotify")] internal static extern int sp_playlist_get_offline_download_completed(IntPtr sessionPtr, IntPtr playlistPtr); /// <summary> /// Return whether a playlist is loaded in RAM (as opposed to onl stored on disk) /// </summary> /// <param name="sessionPtr"> </param> /// <param name="playlistPtr">Playlist object.</param> [DllImport("libspotify")] [return: MarshalAs(UnmanagedType.I1)] internal static extern bool sp_playlist_is_in_ram(IntPtr sessionPtr, IntPtr playlistPtr); /// <summary> ///Set whether a playlist is loaded in RAM (as opposed to only stored on disk) /// </summary> /// <param name="sessionPtr"> </param> /// <param name="playlistPtr">Playlist object.</param> ///<param name="inRam"> </param> [DllImport("libspotify")] [return: MarshalAs(UnmanagedType.I1)] internal static extern Error sp_playlist_set_in_ram(IntPtr sessionPtr, IntPtr playlistPtr, bool inRam); #endregion Internal Static Methods #region Nested Types [StructLayout(LayoutKind.Sequential)] public struct PlaylistCallbacks { internal IntPtr tracks_added; internal IntPtr tracks_removed; internal IntPtr tracks_moved; internal IntPtr playlist_renamed; internal IntPtr playlist_state_changed; internal IntPtr playlist_update_in_progress; internal IntPtr playlist_metadata_updated; internal IntPtr track_created_changed; internal IntPtr track_seen_changed; internal IntPtr description_changed; internal IntPtr image_changed; internal IntPtr track_message_changed; internal IntPtr subscribers_changed; } #endregion Nested Types } }
// This file was created automatically, do not modify the contents of this file. // ReSharper disable InvalidXmlDocComment // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable MemberCanBePrivate.Global using System; using System.Runtime.InteropServices; // Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\AIModule\Classes\Actions\PawnAction_Sequence.h:11 namespace UnrealEngine { [ManageType("ManagePawnAction_Sequence")] public partial class ManagePawnAction_Sequence : UPawnAction_Sequence, IManageWrapper { public ManagePawnAction_Sequence(IntPtr adress) : base(adress) { } #region DLLInmport [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPawnAction_Sequence_Tick(IntPtr self, float deltaTime); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPawnAction_Sequence_BeginDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPawnAction_Sequence_FinishDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPawnAction_Sequence_MarkAsEditorOnlySubobject(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPawnAction_Sequence_PostCDOContruct(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPawnAction_Sequence_PostEditImport(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPawnAction_Sequence_PostInitProperties(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPawnAction_Sequence_PostLoad(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPawnAction_Sequence_PostNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPawnAction_Sequence_PostRepNotifies(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPawnAction_Sequence_PostSaveRoot(IntPtr self, bool bCleanupIsRequired); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPawnAction_Sequence_PreDestroyFromReplication(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPawnAction_Sequence_PreNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPawnAction_Sequence_ShutdownAfterError(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPawnAction_Sequence_CreateCluster(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E__Supper__UPawnAction_Sequence_OnClusterMarkedAsPendingKill(IntPtr self); #endregion #region Methods protected override void Tick(float deltaTime) => E__Supper__UPawnAction_Sequence_Tick(this, deltaTime); /// <summary> /// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an /// <para>asynchronous cleanup process. </para> /// </summary> public override void BeginDestroy() => E__Supper__UPawnAction_Sequence_BeginDestroy(this); /// <summary> /// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed. /// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para> /// </summary> public override void FinishDestroy() => E__Supper__UPawnAction_Sequence_FinishDestroy(this); /// <summary> /// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds /// </summary> public override void MarkAsEditorOnlySubobject() => E__Supper__UPawnAction_Sequence_MarkAsEditorOnlySubobject(this); /// <summary> /// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion /// <para>in the construction of the default materials </para> /// </summary> public override void PostCDOContruct() => E__Supper__UPawnAction_Sequence_PostCDOContruct(this); /// <summary> /// Called after importing property values for this object (paste, duplicate or .t3d import) /// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para> /// are unsupported by the script serialization /// </summary> public override void PostEditImport() => E__Supper__UPawnAction_Sequence_PostEditImport(this); /// <summary> /// Called after the C++ constructor and after the properties have been initialized, including those loaded from config. /// <para>This is called before any serialization or other setup has happened. </para> /// </summary> public override void PostInitProperties() => E__Supper__UPawnAction_Sequence_PostInitProperties(this); /// <summary> /// Do any object-specific cleanup required immediately after loading an object. /// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para> /// </summary> public override void PostLoad() => E__Supper__UPawnAction_Sequence_PostLoad(this); /// <summary> /// Called right after receiving a bunch /// </summary> public override void PostNetReceive() => E__Supper__UPawnAction_Sequence_PostNetReceive(this); /// <summary> /// Called right after calling all OnRep notifies (called even when there are no notifies) /// </summary> public override void PostRepNotifies() => E__Supper__UPawnAction_Sequence_PostRepNotifies(this); /// <summary> /// Called from within SavePackage on the passed in base/root object. /// <para>This function is called after the package has been saved and can perform cleanup. </para> /// </summary> /// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param> public override void PostSaveRoot(bool bCleanupIsRequired) => E__Supper__UPawnAction_Sequence_PostSaveRoot(this, bCleanupIsRequired); /// <summary> /// Called right before being marked for destruction due to network replication /// </summary> public override void PreDestroyFromReplication() => E__Supper__UPawnAction_Sequence_PreDestroyFromReplication(this); /// <summary> /// Called right before receiving a bunch /// </summary> public override void PreNetReceive() => E__Supper__UPawnAction_Sequence_PreNetReceive(this); /// <summary> /// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources. /// </summary> public override void ShutdownAfterError() => E__Supper__UPawnAction_Sequence_ShutdownAfterError(this); /// <summary> /// Called after PostLoad to create UObject cluster /// </summary> public override void CreateCluster() => E__Supper__UPawnAction_Sequence_CreateCluster(this); /// <summary> /// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it. /// </summary> public override void OnClusterMarkedAsPendingKill() => E__Supper__UPawnAction_Sequence_OnClusterMarkedAsPendingKill(this); #endregion public static implicit operator IntPtr(ManagePawnAction_Sequence self) { return self?.NativePointer ?? IntPtr.Zero; } public static implicit operator ManagePawnAction_Sequence(ObjectPointerDescription PtrDesc) { return NativeManager.GetWrapper<ManagePawnAction_Sequence>(PtrDesc); } } }
/* * UUnit system from UnityCommunity * Heavily modified * 0.4 release by pboechat * http://wiki.unity3d.com/index.php?title=UUnit * http://creativecommons.org/licenses/by-sa/3.0/ */ using System; using System.Collections.Generic; namespace PlayFab.UUnit { public enum UUnitActiveState { PENDING, // Not started ACTIVE, // Currently testing READY, // An answer is sent by the http thread, but the main thread hasn't finalized the test yet COMPLETE, // Test is finalized and recorded ABORTED // todo }; public class UUnitTestContext { public const float DefaultFloatPrecision = 0.0001f; public const double DefaultDoublePrecision = 0.000001; public UUnitActiveState ActiveState; public UUnitFinishState FinishState; public readonly Action<UUnitTestContext> TestDelegate; public readonly UUnitTestCase TestInstance; public DateTime StartTime; public DateTime EndTime; public string TestResultMsg; public readonly string Name; public int retryCount; public UUnitTestContext(UUnitTestCase testInstance, Action<UUnitTestContext> testDelegate, string name) { TestInstance = testInstance; TestDelegate = testDelegate; ActiveState = UUnitActiveState.PENDING; Name = name; } public void AttemptRetry() { ActiveState = UUnitActiveState.PENDING; FinishState = UUnitFinishState.PENDING; TestResultMsg = null; retryCount++; } public void EndTest(UUnitFinishState finishState, string resultMsg) { // When a test is declared finished for the first time, apply it and return if (FinishState == UUnitFinishState.PENDING) { EndTime = DateTime.UtcNow; TestResultMsg = resultMsg; FinishState = finishState; ActiveState = UUnitActiveState.READY; return; } if (finishState != FinishState && resultMsg != TestResultMsg) { // Otherwise describe the additional end-state and fail the test TestResultMsg += "\n" + FinishState + "->" + finishState + " - Cannot declare test finished twice."; if (finishState == UUnitFinishState.FAILED && FinishState == UUnitFinishState.FAILED) TestResultMsg += "\nSecond message: " + resultMsg; FinishState = UUnitFinishState.FAILED; } } public void Skip(string message = "") { EndTime = DateTime.UtcNow; EndTest(UUnitFinishState.SKIPPED, message); throw new UUnitSkipException(message); } public void Fail(string message = null) { if (string.IsNullOrEmpty(message)) message = "fail"; EndTest(UUnitFinishState.FAILED, message); throw new UUnitAssertException(message); } public void True(bool boolean, string message = null) { if (boolean) return; if (string.IsNullOrEmpty(message)) message = "Expected: true, Actual: false"; Fail(message); } public void False(bool boolean, string message = null) { if (!boolean) return; if (string.IsNullOrEmpty(message)) message = "Expected: false, Actual: true"; Fail(message); } public void NotNull(object something, string message = null) { if (something != null) return; // Success if (string.IsNullOrEmpty(message)) message = "Null object"; Fail(message); } public void IsNull(object something, string message = null) { if (something == null) return; if (string.IsNullOrEmpty(message)) message = "Not null object"; Fail(message); } public void StringEquals(string wanted, string got, string message = null) { if (wanted == got) return; if (string.IsNullOrEmpty(message)) message = "Expected: " + wanted + ", Actual: " + got; Fail(message); } public void SbyteEquals(sbyte? wanted, sbyte? got, string message = null) { if (NullableEquals(wanted, got)) return; if (string.IsNullOrEmpty(message)) message = "Expected: " + wanted + ", Actual: " + got; Fail(message); } public void ByteEquals(byte? wanted, byte? got, string message = null) { if (NullableEquals(wanted, got)) return; if (string.IsNullOrEmpty(message)) message = "Expected: " + wanted + ", Actual: " + got; Fail(message); } public void ShortEquals(short? wanted, short? got, string message = null) { if (NullableEquals(wanted, got)) return; if (string.IsNullOrEmpty(message)) message = "Expected: " + wanted + ", Actual: " + got; Fail(message); } public void UshortEquals(ushort? wanted, ushort? got, string message = null) { if (NullableEquals(wanted, got)) return; if (string.IsNullOrEmpty(message)) message = "Expected: " + wanted + ", Actual: " + got; Fail(message); } public void IntEquals(int? wanted, int? got, string message = null) { if (NullableEquals(wanted, got)) return; if (string.IsNullOrEmpty(message)) message = "Expected: " + wanted + ", Actual: " + got; Fail(message); } public void UintEquals(uint? wanted, uint? got, string message = null) { if (NullableEquals(wanted, got)) return; if (string.IsNullOrEmpty(message)) message = "Expected: " + wanted + ", Actual: " + got; Fail(message); } public void LongEquals(long? wanted, long? got, string message = null) { if (NullableEquals(wanted, got)) return; if (string.IsNullOrEmpty(message)) message = "Expected: " + wanted + ", Actual: " + got; Fail(message); } public void ULongEquals(ulong? wanted, ulong? got, string message = null) { if (NullableEquals(wanted, got)) return; if (string.IsNullOrEmpty(message)) message = "Expected: " + wanted + ", Actual: " + got; Fail(message); } public void FloatEquals(float? wanted, float? got, float precision = DefaultFloatPrecision, string message = null) { if (!wanted.HasValue && !got.HasValue) return; if (wanted.HasValue && got.HasValue && Math.Abs(wanted.Value - got.Value) < precision) return; if (string.IsNullOrEmpty(message)) message = "Expected: " + wanted + ", Actual: " + got; Fail(message); } public void DoubleEquals(double? wanted, double? got, double precision = DefaultDoublePrecision, string message = null) { if (!wanted.HasValue && !got.HasValue) return; if (wanted.HasValue && got.HasValue && Math.Abs(wanted.Value - got.Value) < precision) return; if (string.IsNullOrEmpty(message)) message = "Expected: " + wanted + ", Actual: " + got; Fail(message); } public void DateTimeEquals(DateTime? wanted, DateTime? got, TimeSpan precision, string message = null) { if (!wanted.HasValue && !got.HasValue) return; if (wanted.HasValue && got.HasValue && wanted + precision > got && got + precision > wanted) return; if (string.IsNullOrEmpty(message)) message = "Expected: " + wanted + ", Actual: " + got; Fail(message); } public void ObjEquals(object wanted, object got, string message = null) { if (wanted == null && got == null) return; if (wanted != null && got != null && wanted.Equals(got)) return; if (string.IsNullOrEmpty(message)) message = "Expected: " + wanted + ", Actual: " + got; Fail(message); } public void SequenceEquals<T>(IEnumerable<T> wanted, IEnumerable<T> got, string message = null) { var wEnum = wanted.GetEnumerator(); var gEnum = got.GetEnumerator(); bool wNext, gNext; var count = 0; while (true) { wNext = wEnum.MoveNext(); gNext = gEnum.MoveNext(); if (wNext != gNext) Fail(message); if (!wNext) break; count++; ObjEquals(wEnum.Current, gEnum.Current, "Element at " + count + ": " + message); } } private static bool NullableEquals<T>(T? left, T? right) where T : struct { // If both have a value, return whether the values match. if (left.HasValue && right.HasValue) return left.Value.Equals(right.Value); // If neither has a value, return true. If only one does, return false. return !left.HasValue && !right.HasValue; } } }
using System.Collections.Specialized; using System.Linq; using Avalonia.Collections; using Avalonia.Controls.Presenters; using Avalonia.Controls.Templates; using Avalonia.LogicalTree; using Avalonia.VisualTree; using Xunit; using System.Collections.ObjectModel; using Avalonia.UnitTests; using Avalonia.Input; using System.Collections.Generic; namespace Avalonia.Controls.UnitTests { public class ItemsControlTests { [Fact] public void Should_Use_ItemTemplate_To_Create_Control() { var target = new ItemsControl { Template = GetTemplate(), ItemTemplate = new FuncDataTemplate<string>((_, __) => new Canvas()), }; target.Items = new[] { "Foo" }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); var container = (ContentPresenter)target.Presenter.Panel.Children[0]; container.UpdateChild(); Assert.IsType<Canvas>(container.Child); } [Fact] public void Panel_Should_Have_TemplatedParent_Set_To_ItemsControl() { var target = new ItemsControl(); target.Template = GetTemplate(); target.Items = new[] { "Foo" }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); Assert.Equal(target, target.Presenter.Panel.TemplatedParent); } [Fact] public void Container_Should_Have_TemplatedParent_Set_To_Null() { var target = new ItemsControl(); target.Template = GetTemplate(); target.Items = new[] { "Foo" }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); var container = (ContentPresenter)target.Presenter.Panel.Children[0]; Assert.Null(container.TemplatedParent); } [Fact] public void Container_Should_Have_LogicalParent_Set_To_ItemsControl() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var root = new Window(); var target = new ItemsControl(); root.Content = target; var templatedParent = new Button(); target.SetValue(StyledElement.TemplatedParentProperty, templatedParent); target.Template = GetTemplate(); target.Items = new[] { "Foo" }; root.ApplyTemplate(); target.ApplyTemplate(); target.Presenter.ApplyTemplate(); var container = (ContentPresenter)target.Presenter.Panel.Children[0]; Assert.Equal(target, container.Parent); } } [Fact] public void Control_Item_Should_Be_Logical_Child_Before_ApplyTemplate() { var target = new ItemsControl(); var child = new Control(); target.Template = GetTemplate(); target.Items = new[] { child }; Assert.Equal(child.Parent, target); Assert.Equal(child.GetLogicalParent(), target); Assert.Equal(new[] { child }, target.GetLogicalChildren()); } [Fact] public void Added_Container_Should_Have_LogicalParent_Set_To_ItemsControl() { var item = new Border(); var items = new ObservableCollection<Border>(); var target = new ItemsControl { Template = GetTemplate(), Items = items, }; var root = new TestRoot(true, target); root.Measure(new Size(100, 100)); root.Arrange(new Rect(0, 0, 100, 100)); items.Add(item); Assert.Equal(target, item.Parent); } [Fact] public void Control_Item_Should_Be_Removed_From_Logical_Children_Before_ApplyTemplate() { var target = new ItemsControl(); var child = new Control(); var items = new AvaloniaList<Control>(child); target.Template = GetTemplate(); target.Items = items; items.RemoveAt(0); Assert.Null(child.Parent); Assert.Null(child.GetLogicalParent()); Assert.Empty(target.GetLogicalChildren()); } [Fact] public void Clearing_Items_Should_Clear_Child_Controls_Parent_Before_ApplyTemplate() { var target = new ItemsControl(); var child = new Control(); target.Template = GetTemplate(); target.Items = new[] { child }; target.Items = null; Assert.Null(child.Parent); Assert.Null(((ILogical)child).LogicalParent); } [Fact] public void Clearing_Items_Should_Clear_Child_Controls_Parent() { var target = new ItemsControl(); var child = new Control(); target.Template = GetTemplate(); target.Items = new[] { child }; target.ApplyTemplate(); target.Items = null; Assert.Null(child.Parent); Assert.Null(((ILogical)child).LogicalParent); } [Fact] public void Adding_Control_Item_Should_Make_Control_Appear_In_LogicalChildren() { var target = new ItemsControl(); var child = new Control(); target.Template = GetTemplate(); target.Items = new[] { child }; // Should appear both before and after applying template. Assert.Equal(new ILogical[] { child }, target.GetLogicalChildren()); target.ApplyTemplate(); Assert.Equal(new ILogical[] { child }, target.GetLogicalChildren()); } [Fact] public void Adding_String_Item_Should_Make_ContentPresenter_Appear_In_LogicalChildren() { var target = new ItemsControl(); var child = new Control(); target.Template = GetTemplate(); target.Items = new[] { "Foo" }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); var logical = (ILogical)target; Assert.Equal(1, logical.LogicalChildren.Count); Assert.IsType<ContentPresenter>(logical.LogicalChildren[0]); } [Fact] public void Setting_Items_To_Null_Should_Remove_LogicalChildren() { var target = new ItemsControl(); var child = new Control(); target.Template = GetTemplate(); target.Items = new[] { "Foo" }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); Assert.NotEmpty(target.GetLogicalChildren()); target.Items = null; Assert.Equal(new ILogical[0], target.GetLogicalChildren()); } [Fact] public void Setting_Items_Should_Fire_LogicalChildren_CollectionChanged() { var target = new ItemsControl(); var child = new Control(); var called = false; target.Template = GetTemplate(); target.ApplyTemplate(); ((ILogical)target).LogicalChildren.CollectionChanged += (s, e) => called = e.Action == NotifyCollectionChangedAction.Add; target.Items = new[] { child }; Assert.True(called); } [Fact] public void Setting_Items_To_Null_Should_Fire_LogicalChildren_CollectionChanged() { var target = new ItemsControl(); var child = new Control(); var called = false; target.Template = GetTemplate(); target.Items = new[] { child }; target.ApplyTemplate(); ((ILogical)target).LogicalChildren.CollectionChanged += (s, e) => called = e.Action == NotifyCollectionChangedAction.Remove; target.Items = null; Assert.True(called); } [Fact] public void Changing_Items_Should_Fire_LogicalChildren_CollectionChanged() { var target = new ItemsControl(); var child = new Control(); var called = false; target.Template = GetTemplate(); target.Items = new[] { child }; target.ApplyTemplate(); ((ILogical)target).LogicalChildren.CollectionChanged += (s, e) => called = true; target.Items = new[] { "Foo" }; Assert.True(called); } [Fact] public void Adding_Items_Should_Fire_LogicalChildren_CollectionChanged() { var target = new ItemsControl(); var items = new AvaloniaList<string> { "Foo" }; var called = false; target.Template = GetTemplate(); target.Items = items; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); ((ILogical)target).LogicalChildren.CollectionChanged += (s, e) => called = e.Action == NotifyCollectionChangedAction.Add; items.Add("Bar"); Assert.True(called); } [Fact] public void Removing_Items_Should_Fire_LogicalChildren_CollectionChanged() { var target = new ItemsControl(); var items = new AvaloniaList<string> { "Foo", "Bar" }; var called = false; target.Template = GetTemplate(); target.Items = items; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); ((ILogical)target).LogicalChildren.CollectionChanged += (s, e) => called = e.Action == NotifyCollectionChangedAction.Remove; items.Remove("Bar"); Assert.True(called); } [Fact] public void LogicalChildren_Should_Not_Change_Instance_When_Template_Changed() { var target = new ItemsControl() { Template = GetTemplate(), }; var before = ((ILogical)target).LogicalChildren; target.Template = null; target.Template = GetTemplate(); var after = ((ILogical)target).LogicalChildren; Assert.NotNull(before); Assert.NotNull(after); Assert.Same(before, after); } [Fact] public void Should_Clear_Containers_When_ItemsPresenter_Changes() { var target = new ItemsControl { Items = new[] { "foo", "bar" }, Template = GetTemplate(), }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); Assert.Equal(2, target.ItemContainerGenerator.Containers.Count()); target.Template = GetTemplate(); target.ApplyTemplate(); Assert.Empty(target.ItemContainerGenerator.Containers); } [Fact] public void Empty_Class_Should_Initially_Be_Applied() { var target = new ItemsControl() { Template = GetTemplate(), }; Assert.Contains(":empty", target.Classes); } [Fact] public void Empty_Class_Should_Be_Cleared_When_Items_Added() { var target = new ItemsControl() { Template = GetTemplate(), Items = new[] { 1, 2, 3 }, }; Assert.DoesNotContain(":empty", target.Classes); } [Fact] public void Empty_Class_Should_Be_Set_When_Empty_Collection_Set() { var target = new ItemsControl() { Template = GetTemplate(), Items = new[] { 1, 2, 3 }, }; target.Items = new int[0]; Assert.Contains(":empty", target.Classes); } [Fact] public void Setting_Presenter_Explicitly_Should_Set_Item_Parent() { var target = new TestItemsControl(); var child = new Control(); var presenter = new ItemsPresenter { [StyledElement.TemplatedParentProperty] = target, [~ItemsPresenter.ItemsProperty] = target[~ItemsControl.ItemsProperty], }; presenter.ApplyTemplate(); target.Presenter = presenter; target.Items = new[] { child }; target.ApplyTemplate(); Assert.Equal(target, child.Parent); Assert.Equal(target, ((ILogical)child).LogicalParent); } [Fact] public void DataContexts_Should_Be_Correctly_Set() { var items = new object[] { "Foo", new Item("Bar"), new TextBlock { Text = "Baz" }, new ListBoxItem { Content = "Qux" }, }; var target = new ItemsControl { Template = GetTemplate(), DataContext = "Base", DataTemplates = { new FuncDataTemplate<Item>((x, __) => new Button { Content = x }) }, Items = items, }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); var dataContexts = target.Presenter.Panel.Children .Do(x => (x as ContentPresenter)?.UpdateChild()) .Cast<Control>() .Select(x => x.DataContext) .ToList(); Assert.Equal( new object[] { items[0], items[1], "Base", "Base" }, dataContexts); } [Fact] public void Control_Item_Should_Not_Be_NameScope() { var items = new object[] { new TextBlock(), }; var target = new ItemsControl { Template = GetTemplate(), Items = items, }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); var item = target.Presenter.Panel.LogicalChildren[0]; Assert.Null(NameScope.GetNameScope((TextBlock)item)); } [Fact] public void Focuses_Next_Item_On_Key_Down() { using (UnitTestApplication.Start(TestServices.RealFocus)) { var items = new object[] { new Button(), new Button(), }; var target = new ItemsControl { Template = GetTemplate(), Items = items, }; var root = new TestRoot { Child = target }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); target.Presenter.Panel.Children[0].Focus(); target.RaiseEvent(new KeyEventArgs { RoutedEvent = InputElement.KeyDownEvent, Key = Key.Down, }); Assert.Equal( target.Presenter.Panel.Children[1], FocusManager.Instance.Current); } } [Fact] public void Does_Not_Focus_Non_Focusable_Item_On_Key_Down() { using (UnitTestApplication.Start(TestServices.RealFocus)) { var items = new object[] { new Button(), new Button { Focusable = false }, new Button(), }; var target = new ItemsControl { Template = GetTemplate(), Items = items, }; var root = new TestRoot { Child = target }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); target.Presenter.Panel.Children[0].Focus(); target.RaiseEvent(new KeyEventArgs { RoutedEvent = InputElement.KeyDownEvent, Key = Key.Down, }); Assert.Equal( target.Presenter.Panel.Children[2], FocusManager.Instance.Current); } } [Fact] public void Presenter_Items_Should_Be_In_Sync() { var target = new ItemsControl { Template = GetTemplate(), Items = new object[] { new Button(), new Button(), }, }; var root = new TestRoot { Child = target }; var otherPanel = new StackPanel(); target.ApplyTemplate(); target.Presenter.ApplyTemplate(); target.ItemContainerGenerator.Materialized += (s, e) => { Assert.IsType<Canvas>(e.Containers[0].Item); }; target.Items = new[] { new Canvas() }; } [Fact] public void Detaching_Then_Reattaching_To_Logical_Tree_Twice_Does_Not_Throw() { // # Issue 3487 var target = new ItemsControl { Template = GetTemplate(), Items = new[] { "foo", "bar" }, ItemTemplate = new FuncDataTemplate<string>((_, __) => new Canvas()), }; var root = new TestRoot(target); root.Measure(Size.Infinity); root.Arrange(new Rect(root.DesiredSize)); root.Child = null; root.Child = target; target.Measure(Size.Infinity); root.Child = null; root.Child = target; } private class Item { public Item(string value) { Value = value; } public string Value { get; } } private FuncControlTemplate GetTemplate() { return new FuncControlTemplate<ItemsControl>((parent, scope) => { return new Border { Background = new Media.SolidColorBrush(0xffffffff), Child = new ItemsPresenter { Name = "PART_ItemsPresenter", [~ItemsPresenter.ItemsProperty] = parent[~ItemsControl.ItemsProperty], }.RegisterInNameScope(scope) }; }); } private class TestItemsControl : ItemsControl { public new IItemsPresenter Presenter { get { return base.Presenter; } set { base.Presenter = value; } } } } }
/* * ReaderWriterLock.cs - Implementation of the * "System.Threading.ReaderWriterLock" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Threading { #if !ECMA_COMPAT public sealed class ReaderWriterLock { // Lock information for a thread. private sealed class LockInfo { public LockInfo next; public Thread thread; public int numReadLocks; public int numWriteLocks; public LockInfo(Thread thread, LockInfo next) { this.next = next; this.thread = thread; this.numReadLocks = 0; this.numWriteLocks = 0; } }; // class LockInfo // Internal state. private int numReadLocks; private int numWriteLocks; private int seqNum; private int lastWriteSeqNum; private LockInfo lockList; // Constructor. public ReaderWriterLock() { numReadLocks = 0; numWriteLocks = 0; seqNum = 0; lastWriteSeqNum = -1; lockList = null; } // Get the lock information for the current thread. private LockInfo GetLockInfo() { Thread thread = Thread.CurrentThread; LockInfo info = lockList; while(info != null) { if(info.thread == thread) { return info; } info = info.next; } return null; } // Get the lock information for the current thread, creating // a new information object if one doesn't exist yet. private LockInfo GetOrCreateLockInfo() { Thread thread = Thread.CurrentThread; LockInfo info = lockList; while(info != null) { if(info.thread == thread) { return info; } info = info.next; } info = new LockInfo(thread, lockList); lockList = info; return info; } // Acquire the read lock. public void AcquireReaderLock(int millisecondsTimeout) { if(millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException ("millisecondsTimeout", _("ArgRange_NonNegOrNegOne")); } lock(this) { // Get the lock information for this thread. LockInfo info = GetOrCreateLockInfo(); // Block if some other thread has the writer lock. if(millisecondsTimeout == -1) { while(info.numWriteLocks == 0 && numWriteLocks > 0) { if(!Monitor.Wait(this)) { return; } } } else { DateTime expire = DateTime.UtcNow + new TimeSpan(millisecondsTimeout * TimeSpan.TicksPerMillisecond); DateTime now; int ms; while(info.numWriteLocks == 0 && numWriteLocks > 0) { now = DateTime.UtcNow; if(now >= expire) { return; } ms = (int)((expire - now).Ticks / TimeSpan.TicksPerMillisecond); if(!Monitor.Wait(this, ms)) { return; } } } // Update the thread and global read lock counts. ++(info.numReadLocks); ++numReadLocks; } } public void AcquireReaderLock(TimeSpan timeout) { AcquireReaderLock(Monitor.TimeSpanToMS(timeout)); } // Acquire the write lock. public void AcquireWriterLock(int millisecondsTimeout) { if(millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException ("millisecondsTimeout", _("ArgRange_NonNegOrNegOne")); } lock(this) { // Get the lock information for this thread. LockInfo info = GetOrCreateLockInfo(); // Bail out early if we already have the writer lock. if(info.numWriteLocks > 0) { ++(info.numWriteLocks); ++numWriteLocks; lastWriteSeqNum = ++seqNum; return; } // Block while some other thread has the read or write lock. if(millisecondsTimeout == -1) { while(numReadLocks > 0 || numWriteLocks > 0) { if(!Monitor.Wait(this)) { return; } } } else { DateTime expire = DateTime.UtcNow + new TimeSpan(millisecondsTimeout * TimeSpan.TicksPerMillisecond); DateTime now; int ms; while(numReadLocks > 0 || numWriteLocks > 0) { now = DateTime.UtcNow; if(now >= expire) { return; } ms = (int)((expire - now).Ticks / TimeSpan.TicksPerMillisecond); if(!Monitor.Wait(this, ms)) { return; } } } // Update the thread and global write lock counts. ++(info.numWriteLocks); ++numWriteLocks; lastWriteSeqNum = ++seqNum; } } public void AcquireWriterLock(TimeSpan timeout) { AcquireWriterLock(Monitor.TimeSpanToMS(timeout)); } // Determine if there have been any writers since a particular seqnum. public bool AnyWritersSince(int seqNum) { lock(this) { if(seqNum >= 0 && seqNum < lastWriteSeqNum) { return true; } else { return false; } } } // Downgrade the current thread from a writer lock. public void DowngradeFromWriterLock(ref LockCookie lockCookie) { lock(this) { // Get the lock information for this thread. LockInfo info = GetLockInfo(); if(info == null) { return; } // Bail out if the cookie is not "Upgrade". if(lockCookie.type != LockCookie.CookieType.Upgrade || lockCookie.thread != Thread.CurrentThread) { return; } // Restore the thread to its previous lock state. RestoreLockState(info, lockCookie.readCount, lockCookie.writeCount); } } // Release all locks for the current thread and save them. public LockCookie ReleaseLock() { lock(this) { // Get the lock information for this thread. LockInfo info = GetLockInfo(); if(info == null) { return new LockCookie (LockCookie.CookieType.None, Thread.CurrentThread, 0, 0); } // Bail out if the thread doesn't have any locks. if(info.numReadLocks == 0 && info.numWriteLocks == 0) { return new LockCookie (LockCookie.CookieType.None, Thread.CurrentThread, 0, 0); } // Copy the lock infomation into the cookie. LockCookie cookie = new LockCookie (LockCookie.CookieType.Saved, Thread.CurrentThread, info.numReadLocks, info.numWriteLocks); // Release the active locks. numReadLocks -= info.numReadLocks; numWriteLocks -= info.numWriteLocks; info.numReadLocks = 0; info.numWriteLocks = 0; // Determine if we need to wake up a waiting thread. if(numReadLocks == 0 || numWriteLocks == 0) { Monitor.Pulse(this); } // Return the cookie to the caller. return cookie; } } // Release the read lock. public void ReleaseReaderLock() { lock(this) { // Get the lock information for this thread. LockInfo info = GetLockInfo(); if(info == null) { return; } // Save the global write lock count. int saveRead = numReadLocks; int saveWrite = numWriteLocks; // Update the thread and global lock count values. if(info.numReadLocks > 0) { --(info.numReadLocks); --numReadLocks; } // Determine if we need to wake up a waiting thread. if(saveRead > numReadLocks && numReadLocks == 0) { Monitor.Pulse(this); } else if(saveWrite > numWriteLocks && numWriteLocks == 0) { Monitor.Pulse(this); } } } // Release the write lock. public void ReleaseWriterLock() { lock(this) { // Get the lock information for this thread. LockInfo info = GetLockInfo(); if(info == null) { return; } // Bail out with an exception if we have read locks. if(info.numReadLocks > 0) { throw new ApplicationException(_("Invalid_RWLock")); } // Update the thread and global lock count values. if(info.numWriteLocks == 0) { return; } --(info.numWriteLocks); --numWriteLocks; // Determine if we need to wake up a waiting thread. if(numWriteLocks == 0) { Monitor.Pulse(this); } } } // Restore the lock state for the current thread. private void RestoreLockState(LockInfo info, int readCount, int writeCount) { // Save the current global lock state. int saveRead = numReadLocks; int saveWrite = numWriteLocks; // Remove the locks that are currently held by the thread. numReadLocks -= info.numReadLocks; numWriteLocks -= info.numWriteLocks; info.numReadLocks = 0; info.numWriteLocks = 0; // Wake up any waiting threads. if(saveRead > numReadLocks && numReadLocks == 0) { Monitor.Pulse(this); } else if(saveWrite > numWriteLocks && numWriteLocks == 0) { Monitor.Pulse(this); } // Re-acquire the locks based upon the type required. if(readCount > 0 && writeCount == 0) { // Re-acquire read locks only. while(numWriteLocks > 0) { Monitor.Wait(this); } info.numReadLocks += readCount; numReadLocks += readCount; } else if(readCount == 0 && writeCount > 0) { // Re-acquire write locks only. while(numReadLocks > 0 && numWriteLocks > 0) { Monitor.Wait(this); } info.numWriteLocks += writeCount; numWriteLocks += writeCount; } else if(readCount > 0 && writeCount > 0) { // Re-acquire both read and write locks. while(numWriteLocks > 0) { Monitor.Wait(this); } info.numReadLocks += readCount; numReadLocks += readCount; info.numWriteLocks += writeCount; numWriteLocks += writeCount; } } // Restore all locks for the curent thread to a previous "Release" value. public void RestoreLock(ref LockCookie lockCookie) { lock(this) { // Get the lock information for this thread. LockInfo info = GetLockInfo(); if(info == null) { return; } // Bail out if the cookie is not "Saved" or if // we have prevailing locks at the moment. if(lockCookie.type != LockCookie.CookieType.Saved || lockCookie.thread != Thread.CurrentThread || info.numReadLocks > 0 || info.numWriteLocks > 0) { return; } // Restore the thread to its previous lock state. RestoreLockState(info, lockCookie.readCount, lockCookie.writeCount); } } // Update the current thread to a writer lock. public LockCookie UpgradeToWriterLock(int millisecondsTimeout) { LockCookie cookie; if(millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException ("millisecondsTimeout", _("ArgRange_NonNegOrNegOne")); } lock(this) { // Get the lock information for this thread. LockInfo info = GetOrCreateLockInfo(); // Bail out early if we already have the writer lock. if(info.numWriteLocks > 0) { cookie = new LockCookie (LockCookie.CookieType.Upgrade, Thread.CurrentThread, info.numReadLocks, info.numWriteLocks); ++(info.numWriteLocks); ++numWriteLocks; lastWriteSeqNum = ++seqNum; return cookie; } // If we have the read lock, then upgrade it. if(info.numReadLocks > 0) { cookie = new LockCookie (LockCookie.CookieType.Upgrade, Thread.CurrentThread, info.numReadLocks, info.numWriteLocks); info.numWriteLocks += info.numReadLocks; numReadLocks -= info.numReadLocks; numWriteLocks -= info.numReadLocks; info.numReadLocks = 0; lastWriteSeqNum = ++seqNum; return cookie; } // Block while some other thread has the read or write lock. if(millisecondsTimeout == -1) { while(numReadLocks > 0 || numWriteLocks > 0) { if(!Monitor.Wait(this)) { return new LockCookie (LockCookie.CookieType.None, Thread.CurrentThread, 0, 0); } } } else { DateTime expire = DateTime.UtcNow + new TimeSpan(millisecondsTimeout * TimeSpan.TicksPerMillisecond); DateTime now; int ms; while(numReadLocks > 0 || numWriteLocks > 0) { now = DateTime.UtcNow; if(now >= expire) { return new LockCookie (LockCookie.CookieType.None, Thread.CurrentThread, 0, 0); } ms = (int)((expire - now).Ticks / TimeSpan.TicksPerMillisecond); if(!Monitor.Wait(this, ms)) { return new LockCookie (LockCookie.CookieType.None, Thread.CurrentThread, 0, 0); } } } // Update the thread and global write lock counts. cookie = new LockCookie (LockCookie.CookieType.Upgrade, Thread.CurrentThread, info.numReadLocks, info.numWriteLocks); ++(info.numWriteLocks); ++numWriteLocks; lastWriteSeqNum = ++seqNum; return cookie; } } public LockCookie UpgradeToWriterLock(TimeSpan timeout) { return UpgradeToWriterLock(Monitor.TimeSpanToMS(timeout)); } // Determine if the read lock is held by the current thread. public bool IsReaderLockHeld { get { lock(this) { LockInfo info = GetLockInfo(); if(info != null) { return (info.numReadLocks > 0); } else { return false; } } } } // Determine if the write lock is held by the current thread. public bool IsWriterLockHeld { get { lock(this) { LockInfo info = GetLockInfo(); if(info != null) { return (info.numWriteLocks > 0); } else { return false; } } } } // Get the writer sequence number. public int WriterSeqNum { get { lock(this) { return seqNum; } } } }; // class ReaderWriterLock #endif // !ECMA_COMPAT }; // namespace System.Threading
using Microsoft.IdentityModel.S2S.Protocols.OAuth2; using Microsoft.IdentityModel.Tokens; using Microsoft.SharePoint.Client; using System; using System.Net; using System.Security.Principal; using System.Web; using System.Web.Configuration; namespace MyFirstS2SAppWeb { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted add-in. /// This method is deprecated because the autohosted option is no longer available. /// </summary> [ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)] public string GetDatabaseConnectionString() { throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available."); } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; bool contextTokenExpired = false; try { if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } } catch (SecurityTokenExpiredException) { contextTokenExpired = true; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
// Copyright (c) 2014-2015 Robert Rouhani <robert.rouhani@gmail.com> and other contributors (see CONTRIBUTORS file). // Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE using System; using SharpNav.Geometry; using SharpNav.Pathfinding; #if MONOGAME using Vector3 = Microsoft.Xna.Framework.Vector3; #elif OPENTK using Vector3 = OpenTK.Vector3; #elif SHARPDX using Vector3 = SharpDX.Vector3; #endif namespace SharpNav.Crowds { /// <summary> /// A crowd agent is a unit that moves across the navigation mesh /// </summary> public class Agent : IEquatable<Agent> { #region Fields /// <summary> /// The maximum number of corners a crowd agent will look ahead in the path /// </summary> private const int AgentMaxCorners = 4; public const int AgentMaxNeighbors = 6; private bool active; private AgentState state; private bool partial; private PathCorridor corridor; private LocalBoundary boundary; public float topologyOptTime; private CrowdNeighbor[] neighbors; //size = CROWDAGENT_MAX_NEIGHBORS private int numNeis; public float DesiredSpeed; private Vector3 currentPos; public Vector3 Disp; public Vector3 DesiredVel; public Vector3 NVel; public Vector3 Vel; public AgentParams Parameters; public StraightPath Corners; private TargetState targetState; public NavPolyId TargetRef; private Vector3 targetPos; public int TargetPathQueryIndex; public bool TargetReplan; public float TargetReplanTime; #endregion #region Constructors public Agent() { active = false; corridor = new PathCorridor(); boundary = new LocalBoundary(); neighbors = new CrowdNeighbor[AgentMaxNeighbors]; Corners = new StraightPath(); } #endregion #region Properties public bool IsActive { get { return active; } set { active = value; } } public bool IsPartial { get { return partial; } set { partial = value; } } public AgentState State { get { return state; } set { state = value; } } public Vector3 Position { get { return currentPos; } set { currentPos = value; } } public LocalBoundary Boundary { get { return boundary; } } public PathCorridor Corridor { get { return corridor; } } public CrowdNeighbor[] Neighbors { get { return neighbors; } } public int NeighborCount { get { return numNeis; } set { numNeis = value; } } public TargetState TargetState { get { return targetState; } set { targetState = value; } } public Vector3 TargetPosition { get { return targetPos; } set { targetPos = value; } } #endregion #region Methods /// <summary> /// Update the position after a certain time 'dt' /// </summary> /// <param name="dt">Time that passed</param> public void Integrate(float dt) { //fake dyanmic constraint float maxDelta = Parameters.MaxAcceleration * dt; Vector3 dv = NVel - Vel; float ds = dv.Length(); if (ds > maxDelta) dv = dv * (maxDelta / ds); Vel = Vel + dv; //integrate if (Vel.Length() > 0.0001f) currentPos = currentPos + Vel * dt; else Vel = new Vector3(0, 0, 0); } public void Reset(NavPolyId reference, Vector3 nearest) { this.corridor.Reset(reference, nearest); this.boundary.Reset(); this.partial = false; this.topologyOptTime = 0; this.TargetReplanTime = 0; this.numNeis = 0; this.DesiredVel = new Vector3(0.0f, 0.0f, 0.0f); this.NVel = new Vector3(0.0f, 0.0f, 0.0f); this.Vel = new Vector3(0.0f, 0.0f, 0.0f); this.currentPos = nearest; this.DesiredSpeed = 0; if (reference != NavPolyId.Null) this.state = AgentState.Walking; else this.state = AgentState.Invalid; this.TargetState = TargetState.None; } /// <summary> /// Change the move target /// </summary> /// <param name="reference">The polygon reference</param> /// <param name="pos">The target's coordinates</param> public void RequestMoveTargetReplan(NavPolyId reference, Vector3 pos) { //initialize request this.TargetRef = reference; this.targetPos = pos; this.TargetPathQueryIndex = PathQueue.Invalid; this.TargetReplan = true; if (this.TargetRef != NavPolyId.Null) this.TargetState = TargetState.Requesting; else this.TargetState = TargetState.Failed; } /// <summary> /// Request a new move target /// </summary> /// <param name="reference">The polygon reference</param> /// <param name="pos">The target's coordinates</param> /// <returns>True if request met, false if not</returns> public bool RequestMoveTarget(NavPolyId reference, Vector3 pos) { if (reference == NavPolyId.Null) return false; //initialize request this.TargetRef = reference; this.targetPos = pos; this.TargetPathQueryIndex = PathQueue.Invalid; this.TargetReplan = false; if (this.TargetRef != NavPolyId.Null) this.targetState = TargetState.Requesting; else this.targetState = TargetState.Failed; return true; } /// <summary> /// Request a new move velocity /// </summary> /// <param name="vel">The agent's velocity</param> public void RequestMoveVelocity(Vector3 vel) { //initialize request this.TargetRef = NavPolyId.Null; this.targetPos = vel; this.TargetPathQueryIndex = PathQueue.Invalid; this.TargetReplan = false; this.targetState = TargetState.Velocity; } /// <summary> /// Reset the move target of an agent /// </summary> public void ResetMoveTarget() { //initialize request this.TargetRef = NavPolyId.Null; this.targetPos = new Vector3(0.0f, 0.0f, 0.0f); this.TargetPathQueryIndex = PathQueue.Invalid; this.TargetReplan = false; this.targetState = TargetState.None; } /// <summary> /// Modify the agent parameters /// </summary> /// <param name="parameters">The new parameters</param> public void UpdateAgentParameters(AgentParams parameters) { this.Parameters = parameters; } public static bool operator ==(Agent left, Agent right) { return left.Equals(right); } public static bool operator !=(Agent left, Agent right) { return !(left == right); } public bool Equals(Agent other) { //TODO find a way to actually compare for equality. return object.ReferenceEquals(this, other); } public override bool Equals(object obj) { var other = obj as Agent; if (other != null) return this.Equals(other); return false; } public override string ToString() { //TODO write an actual ToString. return base.ToString(); } #endregion } }
using System; using System.Net; using HttpMock.Verify.NUnit; using NUnit.Framework; namespace HttpMock.Integration.Tests { [TestFixture] public class HttpExpectationTests { private string _hostUrl; [SetUp] public void SetUp() { _hostUrl = HostHelper.GenerateAHostUrlForAStubServer(); } [Test] public void Should_assert_a_request_was_made() { var stubHttp = HttpMockRepository.At(_hostUrl); stubHttp.Stub(x => x.Get("/api/status")).Return("OK").OK(); new WebClient().DownloadString(string.Format("{0}/api/status", _hostUrl)); stubHttp.AssertWasCalled(x => x.Get("/api/status")); } [Test] public void Should_assert_that_a_request_was_not_made() { var stubHttp = HttpMockRepository.At(_hostUrl); stubHttp.Stub(x => x.Get("/api/status")).Return("OK").OK(); stubHttp.Stub(x => x.Get("/api/echo")).Return("OK").OK(); new WebClient().DownloadString(string.Format("{0}/api/status", _hostUrl)); stubHttp.AssertWasNotCalled(x => x.Get("/api/echo")); } [Test] public void Should_assert_when_stub_is_missing() { var stubHttp = HttpMockRepository.At(_hostUrl); Assert.Throws<AssertionException>(() => stubHttp.AssertWasCalled(x => x.Get("/api/echo"))); } [Test] public void Should_match_a_POST_request_was_made_with_the_expected_body() { var stubHttp = HttpMockRepository.At(_hostUrl); stubHttp.Stub(x => x.Post("/endpoint/handler")).Return("OK").OK(); string expectedData = "postdata"; new WebClient().UploadString(string.Format("{0}/endpoint/handler", _hostUrl), expectedData); stubHttp.AssertWasCalled(x => x.Post("/endpoint/handler")).WithBody(expectedData); } [Test] public void Should_match_a_POST_request_was_made_with_a_body_that_matches_a_constraint() { var stubHttp = HttpMockRepository.At(_hostUrl); stubHttp.Stub(x => x.Post("/endpoint/handler")).Return("OK").OK(); string expectedData = "postdata" + DateTime.Now; new WebClient().UploadString(string.Format("{0}/endpoint/handler", _hostUrl), expectedData); stubHttp.AssertWasCalled(x => x.Post("/endpoint/handler")).WithBody(Does.StartWith("postdata")); } [Test] public void Should_not_match_a_POST_request_was_made_with_a_body_that_doesnt_match_a_constraint() { var stubHttp = HttpMockRepository.At(_hostUrl); stubHttp.Stub(x => x.Post("/endpoint/handler")).Return("OK").OK(); string expectedData = "DUMMYPREFIX-postdata" + DateTime.Now; new WebClient().UploadString(string.Format("{0}/endpoint/handler", _hostUrl), expectedData); Assert.Throws<AssertionException>(() => stubHttp.AssertWasCalled(x => x.Post("/endpoint/handler")) .WithBody(Does.StartWith("postdata"))); } [Test] public void Should_fail_assertion_if_request_header_is_missing() { const string endPoint = "/put/no/header"; var stubHttp = HttpMockRepository.At(_hostUrl); stubHttp.Stub(x => x.Put(endPoint)).Return("OK").OK(); var request = (HttpWebRequest) WebRequest.Create(_hostUrl + endPoint); request.Method = "PUT"; using (request.GetResponse()) { Assert.Throws<AssertionException>(() => stubHttp.AssertWasCalled(x => x.Put(endPoint)) .WithHeader("X-Wibble", Is.EqualTo("Wobble"))); } } [Test] public void Should_fail_assertion_if_request_header_differs_from_expectation() { const string endPoint = "/put/no/header"; var stubHttp = HttpMockRepository.At(_hostUrl); stubHttp.Stub(x => x.Put(endPoint)).Return("OK").OK(); var request = (HttpWebRequest) WebRequest.Create(_hostUrl + endPoint); request.Method = "PUT"; request.Headers.Add("Waffle", "Pancake"); using (request.GetResponse()) { Assert.Throws<AssertionException>(() => stubHttp.AssertWasCalled(x => x.Put(endPoint)) .WithHeader("Waffle", Is.EqualTo("Wobble"))); } } [Test] public void Should_pass_assertion_if_request_header_satisfies_expectation() { const string endPoint = "/put/no/header"; var stubHttp = HttpMockRepository.At(_hostUrl); stubHttp.Stub(x => x.Put(endPoint)).Return("OK").OK(); var request = (HttpWebRequest) WebRequest.Create(_hostUrl + endPoint); request.Method = "PUT"; const string pancake = "Pancake"; request.Headers.Add("Waffle", pancake); using (request.GetResponse()) stubHttp.AssertWasCalled(x => x.Put(endPoint)).WithHeader("Waffle", Is.EqualTo(pancake)); } [Test] public void Should_match_many_POST_requests_which_were_made_with_expected_body() { var stubHttp = HttpMockRepository.At(_hostUrl); stubHttp.Stub(x => x.Post("/endpoint/handler")).Return("OK").OK(); const string expectedData = "postdata"; new WebClient().UploadString(string.Format("{0}/endpoint/handler", _hostUrl), expectedData); new WebClient().UploadString(string.Format("{0}/endpoint/handler", _hostUrl), expectedData); stubHttp.AssertWasCalled(x => x.Post("/endpoint/handler")).Times(2); } [Test] public void Should_not_match_if_times_value_doesnt_match_requestCount() { var stubHttp = HttpMockRepository.At(_hostUrl); stubHttp.Stub(x => x.Post("/endpoint/handler")).Return("OK").OK(); const string expectedData = "postdata"; new WebClient().UploadString(string.Format("{0}/endpoint/handler", _hostUrl), expectedData); new WebClient().UploadString(string.Format("{0}/endpoint/handler", _hostUrl), expectedData); Assert.Throws<AssertionException>(() => stubHttp.AssertWasCalled(x => x.Post("/endpoint/handler")).Times(3)); } [Test] public void Should_assert_a_request_was_not_made_when_multiple_requests_are_made() { var stubHttp = HttpMockRepository.At(_hostUrl); stubHttp.Stub(x => x.Get("/api/status")).Return("OK").OK(); stubHttp.Stub(x => x.Get("/api/echo")).Return("OK").OK(); new WebClient().DownloadString(string.Format("{0}/api/status", _hostUrl)); stubHttp.AssertWasNotCalled(x => x.Get("/api/echo")); Assert.Throws<AssertionException>(() => stubHttp.AssertWasNotCalled(x => x.Get("/api/status"))); } [Test] public void Should_assert_a_request_was_called_when_multiple_requests_are_made() { var stubHttp = HttpMockRepository.At(_hostUrl); stubHttp.Stub(x => x.Get("/api/status")).Return("OK").OK(); stubHttp.Stub(x => x.Get("/api/echo")).Return("OK").OK(); new WebClient().DownloadString(string.Format("{0}/api/status", _hostUrl)); stubHttp.AssertWasCalled(x => x.Get("/api/status")); Assert.Throws<AssertionException>(() => stubHttp.AssertWasCalled(x => x.Get("/api/echo"))); } [Test] public void Should_not_depend_on_the_order_the_stubs_were_created() { var expectedResponse = "PATH/ONE"; var stubHttp = HttpMockRepository.At(_hostUrl); stubHttp.Stub(x => x.Get("/api/path")).Return("PATH").OK(); stubHttp.Stub(x => x.Get("/api/path/one")).Return(expectedResponse).OK(); var result = new WebClient().DownloadString(string.Format("{0}/api/path/one", _hostUrl)); Assert.That(result, Is.EqualTo(expectedResponse)); } } }
//----------------------------------------------------------------------- // <copyright file="Stages.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Threading.Tasks; using Akka.Event; using Akka.Streams.Stage; using Akka.Streams.Supervision; namespace Akka.Streams.Implementation.Stages { public static class DefaultAttributes { public static readonly Attributes IODispatcher = ActorAttributes.CreateDispatcher("akka.stream.default-blocking-io-dispatcher"); public static readonly Attributes Fused = Attributes.CreateName("fused"); public static readonly Attributes Select = Attributes.CreateName("select"); public static readonly Attributes Log = Attributes.CreateName("log"); public static readonly Attributes Where = Attributes.CreateName("where"); public static readonly Attributes Collect = Attributes.CreateName("collect"); public static readonly Attributes Sum = Attributes.CreateName("sum"); public static readonly Attributes Recover = Attributes.CreateName("recover"); public static readonly Attributes RecoverWith = Attributes.CreateName("recoverWith"); public static readonly Attributes MapAsync = Attributes.CreateName("mapAsync"); public static readonly Attributes MapAsyncUnordered = Attributes.CreateName("mapAsyncUnordered"); public static readonly Attributes Grouped = Attributes.CreateName("grouped"); public static readonly Attributes Limit = Attributes.CreateName("limit"); public static readonly Attributes LimitWeighted = Attributes.CreateName("limitWeighted"); public static readonly Attributes Sliding = Attributes.CreateName("sliding"); public static readonly Attributes Take = Attributes.CreateName("take"); public static readonly Attributes Drop = Attributes.CreateName("drop"); public static readonly Attributes Skip = Attributes.CreateName("skip"); public static readonly Attributes TakeWhile = Attributes.CreateName("takeWhile"); public static readonly Attributes SkipWhile = Attributes.CreateName("skipWhile"); public static readonly Attributes Scan = Attributes.CreateName("scan"); public static readonly Attributes Aggregate = Attributes.CreateName("aggregate"); public static readonly Attributes AggregateAsync = Attributes.CreateName("aggregateAsync"); public static readonly Attributes Buffer = Attributes.CreateName("buffer"); public static readonly Attributes Batch = Attributes.CreateName("batch"); public static readonly Attributes BatchWeighted = Attributes.CreateName("batchWeighted"); public static readonly Attributes Conflate = Attributes.CreateName("conflate"); public static readonly Attributes Expand = Attributes.CreateName("expand"); public static readonly Attributes StatefulSelectMany = Attributes.CreateName("statefulSelectMany"); public static readonly Attributes GroupBy = Attributes.CreateName("groupBy"); public static readonly Attributes PrefixAndTail = Attributes.CreateName("prefixAndTail"); public static readonly Attributes Split = Attributes.CreateName("split"); public static readonly Attributes ConcatAll = Attributes.CreateName("concatAll"); public static readonly Attributes Processor = Attributes.CreateName("processor"); public static readonly Attributes ProcessorWithKey = Attributes.CreateName("processorWithKey"); public static readonly Attributes IdentityOp = Attributes.CreateName("identityOp"); public static readonly Attributes DelimiterFraming = Attributes.CreateName("delimiterFraming"); public static readonly Attributes Initial = Attributes.CreateName("initial"); public static readonly Attributes Completion = Attributes.CreateName("completion"); public static readonly Attributes Idle = Attributes.CreateName("idle"); public static readonly Attributes IdleTimeoutBidi = Attributes.CreateName("idleTimeoutBidi"); public static readonly Attributes DelayInitial = Attributes.CreateName("delayInitial"); public static readonly Attributes IdleInject = Attributes.CreateName("idleInject"); public static readonly Attributes BackpressureTimeout = Attributes.CreateName("backpressureTimeout"); public static readonly Attributes Merge = Attributes.CreateName("merge"); public static readonly Attributes MergePreferred = Attributes.CreateName("mergePreferred"); public static readonly Attributes FlattenMerge = Attributes.CreateName("flattenMerge"); public static readonly Attributes Broadcast = Attributes.CreateName("broadcast"); public static readonly Attributes Balance = Attributes.CreateName("balance"); public static readonly Attributes Zip = Attributes.CreateName("zip"); public static readonly Attributes Unzip = Attributes.CreateName("unzip"); public static readonly Attributes Concat = Attributes.CreateName("concat"); public static readonly Attributes OrElse = Attributes.CreateName("orElse"); public static readonly Attributes Repeat = Attributes.CreateName("repeat"); public static readonly Attributes Unfold = Attributes.CreateName("unfold"); public static readonly Attributes UnfoldAsync = Attributes.CreateName("unfoldAsync"); public static readonly Attributes UnfoldInf = Attributes.CreateName("unfoldInf"); public static readonly Attributes UnfoldResourceSource = Attributes.CreateName("unfoldResourceSource").And(IODispatcher); public static readonly Attributes UnfoldResourceSourceAsync = Attributes.CreateName("unfoldResourceSourceAsync").And(IODispatcher); public static readonly Attributes TerminationWatcher = Attributes.CreateName("terminationWatcher"); public static readonly Attributes Delay = Attributes.CreateName("delay"); public static readonly Attributes ZipN = Attributes.CreateName("zipN"); public static readonly Attributes ZipWithN = Attributes.CreateName("zipWithN"); public static readonly Attributes PublisherSource = Attributes.CreateName("publisherSource"); public static readonly Attributes EnumerableSource = Attributes.CreateName("enumerableSource"); public static readonly Attributes CycledSource = Attributes.CreateName("cycledSource"); public static readonly Attributes TaskSource = Attributes.CreateName("taskSource"); public static readonly Attributes TickSource = Attributes.CreateName("tickSource"); public static readonly Attributes SingleSource = Attributes.CreateName("singleSource"); public static readonly Attributes EmptySource = Attributes.CreateName("emptySource"); public static readonly Attributes MaybeSource = Attributes.CreateName("maybeSource"); public static readonly Attributes FailedSource = Attributes.CreateName("failedSource"); public static readonly Attributes ConcatSource = Attributes.CreateName("concatSource"); public static readonly Attributes ConcatMaterializedSource = Attributes.CreateName("concatMaterializedSource"); public static readonly Attributes SubscriberSource = Attributes.CreateName("subscriberSource"); public static readonly Attributes ActorPublisherSource = Attributes.CreateName("actorPublisherSource"); public static readonly Attributes ActorRefSource = Attributes.CreateName("actorRefSource"); public static readonly Attributes QueueSource = Attributes.CreateName("queueSource"); public static readonly Attributes InputStreamSource = Attributes.CreateName("inputStreamSource").And(IODispatcher); public static readonly Attributes OutputStreamSource = Attributes.CreateName("outputStreamSource").And(IODispatcher); public static readonly Attributes FileSource = Attributes.CreateName("fileSource").And(IODispatcher); public static readonly Attributes SubscriberSink = Attributes.CreateName("subscriberSink"); public static readonly Attributes CancelledSink = Attributes.CreateName("cancelledSink"); public static readonly Attributes FirstSink = Attributes.CreateName("firstSink").And(Attributes.CreateInputBuffer(initial: 1, max: 1)); public static readonly Attributes FirstOrDefaultSink = Attributes.CreateName("firstOrDefaultSink").And(Attributes.CreateInputBuffer(initial: 1, max: 1)); public static readonly Attributes LastSink = Attributes.CreateName("lastSink"); public static readonly Attributes LastOrDefaultSink = Attributes.CreateName("lastOrDefaultSink"); public static readonly Attributes PublisherSink = Attributes.CreateName("publisherSink"); public static readonly Attributes FanoutPublisherSink = Attributes.CreateName("fanoutPublisherSink"); public static readonly Attributes IgnoreSink = Attributes.CreateName("ignoreSink"); public static readonly Attributes ActorRefSink = Attributes.CreateName("actorRefSink"); public static readonly Attributes ActorRefWithAck = Attributes.CreateName("actorRefWithAckSink"); public static readonly Attributes ActorSubscriberSink = Attributes.CreateName("actorSubscriberSink"); public static readonly Attributes QueueSink = Attributes.CreateName("queueSink"); public static readonly Attributes LazySink = Attributes.CreateName("lazySink"); public static readonly Attributes InputStreamSink = Attributes.CreateName("inputStreamSink").And(IODispatcher); public static readonly Attributes OutputStreamSink = Attributes.CreateName("outputStreamSink").And(IODispatcher); public static readonly Attributes FileSink = Attributes.CreateName("fileSink").And(IODispatcher); public static readonly Attributes SeqSink = Attributes.CreateName("seqSink"); } /// <summary> /// Stage that is backed by a GraphStage but can be symbolically introspected /// </summary> public sealed class SymbolicGraphStage<TIn, TOut> : PushPullGraphStage<TIn, TOut> { public SymbolicGraphStage(ISymbolicStage<TIn, TOut> symbolicStage) : base(symbolicStage.Create, symbolicStage.Attributes) { } } public interface ISymbolicStage<in TIn, out TOut> : IStage<TIn, TOut> { Attributes Attributes { get; } IStage<TIn, TOut> Create(Attributes effectiveAttributes); } public abstract class SymbolicStage<TIn, TOut> : ISymbolicStage<TIn, TOut> { protected SymbolicStage(Attributes attributes) { Attributes = attributes; } public Attributes Attributes { get; } public abstract IStage<TIn, TOut> Create(Attributes effectiveAttributes); protected Decider Supervision(Attributes attributes) => attributes.GetAttribute(new ActorAttributes.SupervisionStrategy(Deciders.StoppingDecider)).Decider; } public sealed class Buffer<T> : SymbolicStage<T, T> { private readonly int _size; private readonly OverflowStrategy _overflowStrategy; public Buffer(int size, OverflowStrategy overflowStrategy, Attributes attributes = null) : base(attributes ?? DefaultAttributes.Buffer) { _size = size; _overflowStrategy = overflowStrategy; } public override IStage<T, T> Create(Attributes effectiveAttributes) => new Fusing.Buffer<T>(_size, _overflowStrategy); } public sealed class FirstOrDefault<TIn> : GraphStageWithMaterializedValue<SinkShape<TIn>, Task<TIn>> { #region internal classes private sealed class Logic : InGraphStageLogic { private readonly FirstOrDefault<TIn> _stage; private readonly TaskCompletionSource<TIn> _promise = new TaskCompletionSource<TIn>(); public Task<TIn> Task => _promise.Task; public Logic(FirstOrDefault<TIn> stage) : base(stage.Shape) { _stage = stage; SetHandler(stage._in, this); } public override void OnPush() { _promise.TrySetResult(Grab(_stage._in)); CompleteStage(); } public override void OnUpstreamFinish() { if (_stage._throwOnDefault) _promise.TrySetException(new NoSuchElementException("First of empty stream")); else _promise.TrySetResult(default(TIn)); CompleteStage(); } public override void OnUpstreamFailure(Exception e) { _promise.TrySetException(e); FailStage(e); } public override void PreStart() => Pull(_stage._in); } #endregion private readonly bool _throwOnDefault; private readonly Inlet<TIn> _in = new Inlet<TIn>("firstOrDefault.in"); public FirstOrDefault(bool throwOnDefault = false) { _throwOnDefault = throwOnDefault; } public override SinkShape<TIn> Shape => new SinkShape<TIn>(_in); public override ILogicAndMaterializedValue<Task<TIn>> CreateLogicAndMaterializedValue(Attributes inheritedAttributes) { var logic = new Logic(this); return new LogicAndMaterializedValue<Task<TIn>>(logic, logic.Task); } public override string ToString() => "FirstOrDefaultStage"; } public sealed class LastOrDefault<TIn> : GraphStageWithMaterializedValue<SinkShape<TIn>, Task<TIn>> { #region internal classes private sealed class Logic : InGraphStageLogic { private readonly LastOrDefault<TIn> _stage; private readonly TaskCompletionSource<TIn> _promise = new TaskCompletionSource<TIn>(); private TIn _prev; private bool _foundAtLeastOne; public Task<TIn> Task => _promise.Task; public Logic(LastOrDefault<TIn> stage) : base(stage.Shape) { _stage = stage; SetHandler(stage._in, this); } public override void OnPush() { _prev = Grab(_stage._in); _foundAtLeastOne = true; Pull(_stage._in); } public override void OnUpstreamFinish() { if (_stage._throwOnDefault && !_foundAtLeastOne) _promise.TrySetException(new NoSuchElementException("Last of empty stream")); else _promise.TrySetResult(_prev); CompleteStage(); } public override void OnUpstreamFailure(Exception e) { _promise.TrySetException(e); FailStage(e); } public override void PreStart() => Pull(_stage._in); } #endregion private readonly bool _throwOnDefault; private readonly Inlet<TIn> _in = new Inlet<TIn>("lastOrDefault.in"); public LastOrDefault(bool throwOnDefault = false) { _throwOnDefault = throwOnDefault; } public override SinkShape<TIn> Shape => new SinkShape<TIn>(_in); public override ILogicAndMaterializedValue<Task<TIn>> CreateLogicAndMaterializedValue(Attributes inheritedAttributes) { var logic = new Logic(this); return new LogicAndMaterializedValue<Task<TIn>>(logic, logic.Task); } public override string ToString() => "LastOrDefaultStage"; } }
using System; using System.ComponentModel; using System.IO; using System.Text; using Thinktecture.Text; // ReSharper disable AssignNullToNotNullAttribute namespace Thinktecture.IO.Adapters { /// <summary> /// Adapter for <see cref="StreamWriter"/>. /// </summary> public class StreamWriterAdapter : TextWriterAdapter, IStreamWriter { /// <summary>Provides a StreamWriter with no backing store that can be written to, but not read from.</summary> public new static readonly IStreamWriter Null = new StreamWriterAdapter(StreamWriter.Null); /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] public new StreamWriter UnsafeConvert() { return Implementation; } /// <summary> /// Implementation used by the adapter. /// </summary> protected new StreamWriter Implementation { get; } /// <summary>Initializes a new instance of the <see cref="StreamWriterAdapter" /> class for the specified stream by using UTF-8 encoding and the default buffer size.</summary> /// <param name="stream">The stream to write to. </param> /// <exception cref="T:System.ArgumentException"> /// <paramref name="stream" /> is not writable. </exception> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="stream" /> is null. </exception> public StreamWriterAdapter(IStream stream) : this(stream.ToImplementation()) { } /// <summary>Initializes a new instance of the <see cref="StreamWriterAdapter" /> class for the specified stream by using UTF-8 encoding and the default buffer size.</summary> /// <param name="stream">The stream to write to. </param> /// <exception cref="T:System.ArgumentException"> /// <paramref name="stream" /> is not writable. </exception> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="stream" /> is null. </exception> public StreamWriterAdapter(Stream stream) : this(new StreamWriter(stream)) { } /// <summary>Initializes a new instance of the <see cref="StreamWriterAdapter" /> class for the specified stream by using the specified encoding and the default buffer size.</summary> /// <param name="stream">The stream to write to. </param> /// <param name="encoding">The character encoding to use. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="stream" /> or <paramref name="encoding" /> is null. </exception> /// <exception cref="T:System.ArgumentException"> /// <paramref name="stream" /> is not writable. </exception> public StreamWriterAdapter(IStream stream, IEncoding encoding) : this(stream.ToImplementation(), encoding.ToImplementation()) { } /// <summary>Initializes a new instance of the <see cref="StreamWriterAdapter" /> class for the specified stream by using the specified encoding and the default buffer size.</summary> /// <param name="stream">The stream to write to. </param> /// <param name="encoding">The character encoding to use. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="stream" /> or <paramref name="encoding" /> is null. </exception> /// <exception cref="T:System.ArgumentException"> /// <paramref name="stream" /> is not writable. </exception> public StreamWriterAdapter(Stream stream, IEncoding encoding) : this(stream, encoding.ToImplementation()) { } /// <summary>Initializes a new instance of the <see cref="StreamWriterAdapter" /> class for the specified stream by using the specified encoding and the default buffer size.</summary> /// <param name="stream">The stream to write to. </param> /// <param name="encoding">The character encoding to use. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="stream" /> or <paramref name="encoding" /> is null. </exception> /// <exception cref="T:System.ArgumentException"> /// <paramref name="stream" /> is not writable. </exception> public StreamWriterAdapter(IStream stream, Encoding encoding) : this(stream.ToImplementation(), encoding) { } /// <summary>Initializes a new instance of the <see cref="StreamWriterAdapter" /> class for the specified stream by using the specified encoding and the default buffer size.</summary> /// <param name="stream">The stream to write to. </param> /// <param name="encoding">The character encoding to use. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="stream" /> or <paramref name="encoding" /> is null. </exception> /// <exception cref="T:System.ArgumentException"> /// <paramref name="stream" /> is not writable. </exception> public StreamWriterAdapter(Stream stream, Encoding encoding) : this(new StreamWriter(stream, encoding)) { } /// <summary>Initializes a new instance of the <see cref="StreamWriterAdapter" /> class for the specified stream by using the specified encoding and buffer size.</summary> /// <param name="stream">The stream to write to. </param> /// <param name="encoding">The character encoding to use. </param> /// <param name="bufferSize">The buffer size, in bytes. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="stream" /> or <paramref name="encoding" /> is null. </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="bufferSize" /> is negative. </exception> /// <exception cref="T:System.ArgumentException"> /// <paramref name="stream" /> is not writable. </exception> public StreamWriterAdapter(IStream stream, IEncoding encoding, int bufferSize) : this(stream.ToImplementation(), encoding.ToImplementation(), bufferSize) { } /// <summary>Initializes a new instance of the <see cref="StreamWriterAdapter" /> class for the specified stream by using the specified encoding and buffer size.</summary> /// <param name="stream">The stream to write to. </param> /// <param name="encoding">The character encoding to use. </param> /// <param name="bufferSize">The buffer size, in bytes. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="stream" /> or <paramref name="encoding" /> is null. </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="bufferSize" /> is negative. </exception> /// <exception cref="T:System.ArgumentException"> /// <paramref name="stream" /> is not writable. </exception> public StreamWriterAdapter(Stream stream, IEncoding encoding, int bufferSize) : this(stream, encoding.ToImplementation(), bufferSize) { } /// <summary>Initializes a new instance of the <see cref="StreamWriterAdapter" /> class for the specified stream by using the specified encoding and buffer size.</summary> /// <param name="stream">The stream to write to. </param> /// <param name="encoding">The character encoding to use. </param> /// <param name="bufferSize">The buffer size, in bytes. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="stream" /> or <paramref name="encoding" /> is null. </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="bufferSize" /> is negative. </exception> /// <exception cref="T:System.ArgumentException"> /// <paramref name="stream" /> is not writable. </exception> public StreamWriterAdapter(IStream stream, Encoding encoding, int bufferSize) : this(stream.ToImplementation(), encoding, bufferSize) { } /// <summary>Initializes a new instance of the <see cref="StreamWriterAdapter" /> class for the specified stream by using the specified encoding and buffer size.</summary> /// <param name="stream">The stream to write to. </param> /// <param name="encoding">The character encoding to use. </param> /// <param name="bufferSize">The buffer size, in bytes. </param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="stream" /> or <paramref name="encoding" /> is null. </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="bufferSize" /> is negative. </exception> /// <exception cref="T:System.ArgumentException"> /// <paramref name="stream" /> is not writable. </exception> public StreamWriterAdapter(Stream stream, Encoding encoding, int bufferSize) : this(new StreamWriter(stream, encoding, bufferSize)) { } /// <summary>Initializes a new instance of the <see cref="StreamWriterAdapter" /> class for the specified stream by using the specified encoding and buffer size, and optionally leaves the stream open.</summary> /// <param name="stream">The stream to write to.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="bufferSize">The buffer size, in bytes.</param> /// <param name="leaveOpen">true to leave the stream open after the <see cref="T:System.IO.StreamWriter" /> object is disposed; otherwise, false.</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="stream" /> or <paramref name="encoding" /> is null. </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="bufferSize" /> is negative. </exception> /// <exception cref="T:System.ArgumentException"> /// <paramref name="stream" /> is not writable. </exception> public StreamWriterAdapter(IStream stream, IEncoding encoding, int bufferSize, bool leaveOpen) : this(stream.ToImplementation(), encoding.ToImplementation(), bufferSize, leaveOpen) { } /// <summary>Initializes a new instance of the <see cref="StreamWriterAdapter" /> class for the specified stream by using the specified encoding and buffer size, and optionally leaves the stream open.</summary> /// <param name="stream">The stream to write to.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="bufferSize">The buffer size, in bytes.</param> /// <param name="leaveOpen">true to leave the stream open after the <see cref="T:System.IO.StreamWriter" /> object is disposed; otherwise, false.</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="stream" /> or <paramref name="encoding" /> is null. </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="bufferSize" /> is negative. </exception> /// <exception cref="T:System.ArgumentException"> /// <paramref name="stream" /> is not writable. </exception> public StreamWriterAdapter(Stream stream, IEncoding encoding, int bufferSize, bool leaveOpen) : this(stream, encoding.ToImplementation(), bufferSize, leaveOpen) { } /// <summary>Initializes a new instance of the <see cref="StreamWriterAdapter" /> class for the specified stream by using the specified encoding and buffer size, and optionally leaves the stream open.</summary> /// <param name="stream">The stream to write to.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="bufferSize">The buffer size, in bytes.</param> /// <param name="leaveOpen">true to leave the stream open after the <see cref="T:System.IO.StreamWriter" /> object is disposed; otherwise, false.</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="stream" /> or <paramref name="encoding" /> is null. </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="bufferSize" /> is negative. </exception> /// <exception cref="T:System.ArgumentException"> /// <paramref name="stream" /> is not writable. </exception> public StreamWriterAdapter(IStream stream, Encoding encoding, int bufferSize, bool leaveOpen) : this(stream.ToImplementation(), encoding, bufferSize, leaveOpen) { } /// <summary>Initializes a new instance of the <see cref="StreamWriterAdapter" /> class for the specified stream by using the specified encoding and buffer size, and optionally leaves the stream open.</summary> /// <param name="path">The file path to write to.</param> /// <exception cref="T:System.ArgumentNullException"> <paramref name="path" /> is null. </exception> public StreamWriterAdapter(string path) : this(new StreamWriter(path)) { } /// <summary>Initializes a new instance of the <see cref="StreamWriterAdapter" /> class for the specified stream by using the specified encoding and buffer size, and optionally leaves the stream open.</summary> /// <param name="path">The file path to write to.</param> /// <param name="append">Indication whether the content should be appended to file.</param> /// <exception cref="T:System.ArgumentNullException"> <paramref name="path" /> is null. </exception> public StreamWriterAdapter(string path, bool append) : this(new StreamWriter(path, append)) { } /// <summary>Initializes a new instance of the <see cref="StreamWriterAdapter" /> class for the specified stream by using the specified encoding and buffer size, and optionally leaves the stream open.</summary> /// <param name="path">The file path to write to.</param> /// <param name="append">Indication whether the content should be appended to file.</param> /// <param name="encoding">The character encoding to use.</param> /// <exception cref="T:System.ArgumentNullException"> <paramref name="path" /> is null. </exception> public StreamWriterAdapter(string path, bool append, Encoding encoding) : this(new StreamWriter(path, append, encoding)) { } /// <summary>Initializes a new instance of the <see cref="StreamWriterAdapter" /> class for the specified stream by using the specified encoding and buffer size, and optionally leaves the stream open.</summary> /// <param name="path">The file path to write to.</param> /// <param name="append">Indication whether the content should be appended to file.</param> /// <param name="encoding">The character encoding to use.</param> /// <exception cref="T:System.ArgumentNullException"> <paramref name="path" /> is null. </exception> public StreamWriterAdapter(string path, bool append, IEncoding encoding) : this(new StreamWriter(path, append, encoding.ToImplementation())) { } /// <summary>Initializes a new instance of the <see cref="StreamWriterAdapter" /> class for the specified stream by using the specified encoding and buffer size, and optionally leaves the stream open.</summary> /// <param name="path">The file path to write to.</param> /// <param name="append">Indication whether the content should be appended to file.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="bufferSize">The buffer size, in bytes.</param> /// <exception cref="T:System.ArgumentNullException"> <paramref name="path" /> is null. </exception> public StreamWriterAdapter(string path, bool append, Encoding encoding, int bufferSize) : this(new StreamWriter(path, append, encoding, bufferSize)) { } /// <summary>Initializes a new instance of the <see cref="StreamWriterAdapter" /> class for the specified stream by using the specified encoding and buffer size, and optionally leaves the stream open.</summary> /// <param name="path">The file path to write to.</param> /// <param name="append">Indication whether the content should be appended to file.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="bufferSize">The buffer size, in bytes.</param> /// <exception cref="T:System.ArgumentNullException"> <paramref name="path" /> is null. </exception> public StreamWriterAdapter(string path, bool append, IEncoding encoding, int bufferSize) : this(new StreamWriter(path, append, encoding.ToImplementation(), bufferSize)) { } /// <summary>Initializes a new instance of the <see cref="StreamWriterAdapter" /> class for the specified stream by using the specified encoding and buffer size, and optionally leaves the stream open.</summary> /// <param name="stream">The stream to write to.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="bufferSize">The buffer size, in bytes.</param> /// <param name="leaveOpen">true to leave the stream open after the <see cref="T:System.IO.StreamWriter" /> object is disposed; otherwise, false.</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="stream" /> or <paramref name="encoding" /> is null. </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="bufferSize" /> is negative. </exception> /// <exception cref="T:System.ArgumentException"> /// <paramref name="stream" /> is not writable. </exception> public StreamWriterAdapter(Stream stream, Encoding encoding, int bufferSize, bool leaveOpen) : this(new StreamWriter(stream, encoding, bufferSize, leaveOpen)) { } /// <summary> /// Initializes a new instance of the <see cref="StreamWriterAdapter" /> class. /// </summary> /// <param name="writer">Writer to be used by the adapter.</param> public StreamWriterAdapter(StreamWriter writer) : base(writer) { Implementation = writer ?? throw new ArgumentNullException(nameof(writer)); } /// <inheritdoc /> public bool AutoFlush { get => Implementation.AutoFlush; set => Implementation.AutoFlush = value; } /// <inheritdoc /> public IStream BaseStream => Implementation.BaseStream.ToInterface(); } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // // <OWNER>[....]</OWNER> namespace System.Threading { using System; using System.Security.Permissions; using System.Runtime.CompilerServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Runtime; // After much discussion, we decided the Interlocked class doesn't need // any HPA's for synchronization or external threading. They hurt C#'s // codegen for the yield keyword, and arguably they didn't protect much. // Instead, they penalized people (and compilers) for writing threadsafe // code. public static class Interlocked { /****************************** * Increment * Implemented: int * long *****************************/ [ResourceExposure(ResourceScope.None)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static int Increment(ref int location) { return Add(ref location, 1); } [ResourceExposure(ResourceScope.None)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static long Increment(ref long location) { return Add(ref location, 1); } /****************************** * Decrement * Implemented: int * long *****************************/ [ResourceExposure(ResourceScope.None)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static int Decrement(ref int location) { return Add(ref location, -1); } [ResourceExposure(ResourceScope.None)] public static long Decrement(ref long location) { return Add(ref location, -1); } /****************************** * Exchange * Implemented: int * long * float * double * Object * IntPtr *****************************/ [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Security.SecuritySafeCritical] public static extern int Exchange(ref int location1, int value); [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] [System.Security.SecuritySafeCritical] public static extern long Exchange(ref long location1, long value); [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] [System.Security.SecuritySafeCritical] public static extern float Exchange(ref float location1, float value); [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] [System.Security.SecuritySafeCritical] public static extern double Exchange(ref double location1, double value); [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Security.SecuritySafeCritical] public static extern Object Exchange(ref Object location1, Object value); [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Security.SecuritySafeCritical] public static extern IntPtr Exchange(ref IntPtr location1, IntPtr value); [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.InteropServices.ComVisible(false)] [System.Security.SecuritySafeCritical] public static T Exchange<T>(ref T location1, T value) where T : class { _Exchange(__makeref(location1), __makeref(value)); //Since value is a local we use trash its data on return // The Exchange replaces the data with new data // so after the return "value" contains the original location1 //See ExchangeGeneric for more details return value; } [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Security.SecuritySafeCritical] private static extern void _Exchange(TypedReference location1, TypedReference value); /****************************** * CompareExchange * Implemented: int * long * float * double * Object * IntPtr *****************************/ [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Security.SecuritySafeCritical] public static extern int CompareExchange(ref int location1, int value, int comparand); [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] [System.Security.SecuritySafeCritical] public static extern long CompareExchange(ref long location1, long value, long comparand); [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] [System.Security.SecuritySafeCritical] public static extern float CompareExchange(ref float location1, float value, float comparand); [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] [System.Security.SecuritySafeCritical] public static extern double CompareExchange(ref double location1, double value, double comparand); [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Security.SecuritySafeCritical] public static extern Object CompareExchange(ref Object location1, Object value, Object comparand); [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Security.SecuritySafeCritical] public static extern IntPtr CompareExchange(ref IntPtr location1, IntPtr value, IntPtr comparand); /***************************************************************** * CompareExchange<T> * * Notice how CompareExchange<T>() uses the __makeref keyword * to create two TypedReferences before calling _CompareExchange(). * This is horribly slow. Ideally we would like CompareExchange<T>() * to simply call CompareExchange(ref Object, Object, Object); * however, this would require casting a "ref T" into a "ref Object", * which is not legal in C#. * * Thus we opted to cheat, and hacked to JIT so that when it reads * the method body for CompareExchange<T>() it gets back the * following IL: * * ldarg.0 * ldarg.1 * ldarg.2 * call System.Threading.Interlocked::CompareExchange(ref Object, Object, Object) * ret * * See getILIntrinsicImplementationForInterlocked() in VM\JitInterface.cpp * for details. *****************************************************************/ [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Runtime.InteropServices.ComVisible(false)] [System.Security.SecuritySafeCritical] public static T CompareExchange<T>(ref T location1, T value, T comparand) where T : class { // _CompareExchange() passes back the value read from location1 via local named 'value' _CompareExchange(__makeref(location1), __makeref(value), comparand); return value; } [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Security.SecuritySafeCritical] private static extern void _CompareExchange(TypedReference location1, TypedReference value, Object comparand); // BCL-internal overload that returns success via a ref bool param, useful for reliable spin locks. [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] [System.Security.SecuritySafeCritical] internal static extern int CompareExchange(ref int location1, int value, int comparand, ref bool succeeded); /****************************** * Add * Implemented: int * long *****************************/ [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal static extern int ExchangeAdd(ref int location1, int value); [ResourceExposure(ResourceScope.None)] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern long ExchangeAdd(ref long location1, long value); [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static int Add(ref int location1, int value) { return ExchangeAdd(ref location1, value) + value; } [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static long Add(ref long location1, long value) { return ExchangeAdd(ref location1, value) + value; } /****************************** * Read *****************************/ public static long Read(ref long location) { return Interlocked.CompareExchange(ref location,0,0); } public static void MemoryBarrier() { Thread.MemoryBarrier(); } } }
using System; using System.Threading; using System.Net.Sockets; using System.Net; using System.IO; namespace PubNubMessaging.Core { #region "Network Status -- code split required" internal abstract class ClientNetworkStatus { private static bool _status = true; private static bool _failClientNetworkForTesting = false; private static bool _machineSuspendMode = false; private static IJsonPluggableLibrary _jsonPluggableLibrary; internal static IJsonPluggableLibrary JsonPluggableLibrary { get { return _jsonPluggableLibrary; } set { _jsonPluggableLibrary = value; } } #if (SILVERLIGHT || WINDOWS_PHONE) private static ManualResetEvent mres = new ManualResetEvent(false); private static ManualResetEvent mreSocketAsync = new ManualResetEvent(false); #elif(!UNITY_IOS && !UNITY_ANDROID) private static ManualResetEventSlim mres = new ManualResetEventSlim (false); #endif internal static bool SimulateNetworkFailForTesting { get { return _failClientNetworkForTesting; } set { _failClientNetworkForTesting = value; } } internal static bool MachineSuspendMode { get { return _machineSuspendMode; } set { _machineSuspendMode = value; } } /*#if(__MonoCS__ && !UNITY_IOS && !UNITY_ANDROID) static UdpClient udp; #endif*/ #if(UNITY_IOS || UNITY_ANDROID || __MonoCS__) static HttpWebRequest request; static WebResponse response; internal static int HeartbeatInterval { get; set; } internal static bool CheckInternetStatusUnity<T> (bool systemActive, Action<PubnubClientError> errorCallback, string[] channels, int heartBeatInterval) { HeartbeatInterval = heartBeatInterval; if (_failClientNetworkForTesting) { //Only to simulate network fail return false; } else { CheckClientNetworkAvailability<T> (CallbackClientNetworkStatus, errorCallback, channels); return _status; } } #endif internal static bool CheckInternetStatus<T> (bool systemActive, Action<PubnubClientError> errorCallback, string[] channels) { if (_failClientNetworkForTesting || _machineSuspendMode) { //Only to simulate network fail return false; } else { CheckClientNetworkAvailability<T> (CallbackClientNetworkStatus, errorCallback, channels); return _status; } } //#endif public static bool GetInternetStatus () { return _status; } private static void CallbackClientNetworkStatus (bool status) { _status = status; } private static void CheckClientNetworkAvailability<T> (Action<bool> callback, Action<PubnubClientError> errorCallback, string[] channels) { InternetState<T> state = new InternetState<T> (); state.Callback = callback; state.ErrorCallback = errorCallback; state.Channels = channels; #if (UNITY_ANDROID || UNITY_IOS) CheckSocketConnect<T>(state); #elif(__MonoCS__) CheckSocketConnect<T> (state); #else ThreadPool.QueueUserWorkItem(CheckSocketConnect<T>, state); #endif #if (SILVERLIGHT || WINDOWS_PHONE) mres.WaitOne(); #elif(!UNITY_ANDROID && !UNITY_IOS) mres.Wait (); #endif } private static void CheckSocketConnect<T> (object internetState) { InternetState<T> state = internetState as InternetState<T>; Action<bool> callback = state.Callback; Action<PubnubClientError> errorCallback = state.ErrorCallback; string[] channels = state.Channels; try { #if (SILVERLIGHT || WINDOWS_PHONE) using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { SocketAsyncEventArgs sae = new SocketAsyncEventArgs(); sae.UserToken = state; sae.RemoteEndPoint = new DnsEndPoint("pubsub.pubnub.com", 80); sae.Completed += new EventHandler<SocketAsyncEventArgs>(socketAsync_Completed<T>); bool test = socket.ConnectAsync(sae); mreSocketAsync.WaitOne(1000); sae.Completed -= new EventHandler<SocketAsyncEventArgs>(socketAsync_Completed<T>); socket.Close(); } #elif (UNITY_IOS || UNITY_ANDROID) if(request!=null){ request.Abort(); request = null; } request = (HttpWebRequest)WebRequest.Create("http://pubsub.pubnub.com"); if(request!= null){ request.Timeout = HeartbeatInterval * 1000; request.ContentType = "application/json"; if(response!=null){ response.Close(); response = null; } response = request.GetResponse (); if(response != null){ if(((HttpWebResponse)response).ContentLength <= 0){ _status = false; throw new Exception("Failed to connect"); } else { using(Stream dataStream = response.GetResponseStream ()){ using(StreamReader reader = new StreamReader (dataStream)){ string responseFromServer = reader.ReadToEnd (); LoggingMethod.WriteToLog(string.Format("DateTime {0}, Response:{1}", DateTime.Now.ToString(), responseFromServer), LoggingMethod.LevelInfo); _status = true; callback(true); reader.Close(); } dataStream.Close(); } } } } #elif(__MonoCS__) using (UdpClient udp = new UdpClient ("pubsub.pubnub.com", 80)) { IPAddress localAddress = ((IPEndPoint)udp.Client.LocalEndPoint).Address; if (udp != null && udp.Client != null && udp.Client.RemoteEndPoint != null) { udp.Client.SendTimeout = HeartbeatInterval * 1000; EndPoint remotepoint = udp.Client.RemoteEndPoint; string remoteAddress = (remotepoint != null) ? remotepoint.ToString () : ""; LoggingMethod.WriteToLog (string.Format ("DateTime {0} checkInternetStatus LocalIP: {1}, RemoteEndPoint:{2}", DateTime.Now.ToString (), localAddress.ToString (), remoteAddress), LoggingMethod.LevelVerbose); _status = true; callback (true); } } #else using (UdpClient udp = new UdpClient("pubsub.pubnub.com", 80)) { IPAddress localAddress = ((IPEndPoint)udp.Client.LocalEndPoint).Address; EndPoint remotepoint = udp.Client.RemoteEndPoint; string remoteAddress = (remotepoint != null) ? remotepoint.ToString() : ""; udp.Close(); LoggingMethod.WriteToLog(string.Format("DateTime {0} checkInternetStatus LocalIP: {1}, RemoteEndPoint:{2}", DateTime.Now.ToString(), localAddress.ToString(), remoteAddress), LoggingMethod.LevelVerbose); callback(true); } #endif } #if (UNITY_IOS || UNITY_ANDROID) catch (WebException webEx){ if(webEx.Message.Contains("404")){ _status =true; callback(true); } else { _status =false; ParseCheckSocketConnectException<T>(webEx, channels, errorCallback, callback); } } #endif catch (Exception ex) { #if(__MonoCS__) _status = false; #endif ParseCheckSocketConnectException<T> (ex, channels, errorCallback, callback); } finally { #if (UNITY_IOS || UNITY_ANDROID) if(response!=null){ response.Close(); response = null; } if(request!=null){ request = null; } #elif(__MonoCS__) #endif #if(UNITY_IOS) GC.Collect(); #endif } #if (!UNITY_ANDROID && !UNITY_IOS) mres.Set (); #endif } static void ParseCheckSocketConnectException<T> (Exception ex, string[] channels, Action<PubnubClientError> errorCallback, Action<bool> callback) { PubnubErrorCode errorType = PubnubErrorCodeHelper.GetErrorType (ex); int statusCode = (int)errorType; string errorDescription = PubnubErrorCodeDescription.GetStatusCodeDescription (errorType); PubnubClientError error = new PubnubClientError (statusCode, PubnubErrorSeverity.Warn, true, ex.ToString (), ex, PubnubMessageSource.Client, null, null, errorDescription, string.Join (",", channels)); GoToCallback (error, errorCallback); LoggingMethod.WriteToLog (string.Format ("DateTime {0} checkInternetStatus Error. {1}", DateTime.Now.ToString (), ex.ToString ()), LoggingMethod.LevelError); callback (false); } private static void GoToCallback<T> (object result, Action<T> Callback) { if (Callback != null) { if (typeof(T) == typeof(string)) { JsonResponseToCallback (result, Callback); } else { Callback ((T)(object)result); } } } private static void GoToCallback<T> (PubnubClientError result, Action<PubnubClientError> Callback) { if (Callback != null) { //TODO: //Include custom message related to error/status code for developer //error.AdditionalMessage = MyCustomErrorMessageRetrieverBasedOnStatusCode(error.StatusCode); Callback (result); } } private static void JsonResponseToCallback<T> (object result, Action<T> callback) { string callbackJson = ""; if (typeof(T) == typeof(string)) { callbackJson = _jsonPluggableLibrary.SerializeToJsonString (result); Action<string> castCallback = callback as Action<string>; castCallback (callbackJson); } } #if (SILVERLIGHT || WINDOWS_PHONE) static void socketAsync_Completed<T>(object sender, SocketAsyncEventArgs e) { if (e.LastOperation == SocketAsyncOperation.Connect) { Socket skt = sender as Socket; InternetState<T> state = e.UserToken as InternetState<T>; if (state != null) { LoggingMethod.WriteToLog(string.Format("DateTime {0} socketAsync_Completed.", DateTime.Now.ToString()), LoggingMethod.LevelInfo); state.Callback(true); } mreSocketAsync.Set(); } } #endif } #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; namespace System { public static class AppContext { [Flags] private enum SwitchValueState { HasFalseValue = 0x1, HasTrueValue = 0x2, HasLookedForOverride = 0x4, UnknownValue = 0x8 // Has no default and could not find an override } private static readonly Dictionary<string, SwitchValueState> s_switchMap = new Dictionary<string, SwitchValueState>(); public static string BaseDirectory { #if FEATURE_CORECLR [System.Security.SecuritySafeCritical] #endif get { // The value of APP_CONTEXT_BASE_DIRECTORY key has to be a string and it is not allowed to be any other type. // Otherwise the caller will get invalid cast exception return (string) AppDomain.CurrentDomain.GetData("APP_CONTEXT_BASE_DIRECTORY") ?? AppDomain.CurrentDomain.BaseDirectory; } } public static string TargetFrameworkName { get { // Forward the value that is set on the current domain. return AppDomain.CurrentDomain.SetupInformation.TargetFrameworkName; } } #if FEATURE_CORECLR [System.Security.SecuritySafeCritical] #endif public static object GetData(string name) { return AppDomain.CurrentDomain.GetData(name); } [System.Security.SecuritySafeCritical] public static void SetData(string name, object data) { AppDomain.CurrentDomain.SetData(name, data); } public static event UnhandledExceptionEventHandler UnhandledException { [System.Security.SecurityCritical] add { AppDomain.CurrentDomain.UnhandledException += value; } [System.Security.SecurityCritical] remove { AppDomain.CurrentDomain.UnhandledException -= value; } } public static event System.EventHandler<System.Runtime.ExceptionServices.FirstChanceExceptionEventArgs> FirstChanceException { [System.Security.SecurityCritical] add { AppDomain.CurrentDomain.FirstChanceException += value; } [System.Security.SecurityCritical] remove { AppDomain.CurrentDomain.FirstChanceException -= value; } } public static event System.EventHandler ProcessExit { [System.Security.SecurityCritical] add { AppDomain.CurrentDomain.ProcessExit += value; } [System.Security.SecurityCritical] remove { AppDomain.CurrentDomain.ProcessExit -= value; } } #region Switch APIs static AppContext() { // populate the AppContext with the default set of values AppContextDefaultValues.PopulateDefaultValues(); } /// <summary> /// Try to get the value of the switch. /// </summary> /// <param name="switchName">The name of the switch</param> /// <param name="isEnabled">A variable where to place the value of the switch</param> /// <returns>A return value of true represents that the switch was set and <paramref name="isEnabled"/> contains the value of the switch</returns> public static bool TryGetSwitch(string switchName, out bool isEnabled) { if (switchName == null) throw new ArgumentNullException("switchName"); if (switchName.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "switchName"); // By default, the switch is not enabled. isEnabled = false; SwitchValueState switchValue; lock (s_switchMap) { if (s_switchMap.TryGetValue(switchName, out switchValue)) { // The value is in the dictionary. // There are 3 cases here: // 1. The value of the switch is 'unknown'. This means that the switch name is not known to the system (either via defaults or checking overrides). // Example: This is the case when, during a servicing event, a switch is added to System.Xml which ships before mscorlib. The value of the switch // Will be unknown to mscorlib.dll and we want to prevent checking the overrides every time we check this switch // 2. The switch has a valid value AND we have read the overrides for it // Example: TryGetSwitch is called for a switch set via SetSwitch // 3. The switch has the default value and we need to check for overrides // Example: TryGetSwitch is called for the first time for a switch that has a default value // 1. The value is unknown if (switchValue == SwitchValueState.UnknownValue) { isEnabled = false; return false; } // We get the value of isEnabled from the value that we stored in the dictionary isEnabled = (switchValue & SwitchValueState.HasTrueValue) == SwitchValueState.HasTrueValue; // 2. The switch has a valid value AND we have checked for overrides if ((switchValue & SwitchValueState.HasLookedForOverride) == SwitchValueState.HasLookedForOverride) { return true; } // 3. The switch has a valid value, but we need to check for overrides. // Regardless of whether or not the switch has an override, we need to update the value to reflect // the fact that we checked for overrides. bool overrideValue; if (AppContextDefaultValues.TryGetSwitchOverride(switchName, out overrideValue)) { // we found an override! isEnabled = overrideValue; } // Update the switch in the dictionary to mark it as 'checked for override' s_switchMap[switchName] = (isEnabled ? SwitchValueState.HasTrueValue : SwitchValueState.HasFalseValue) | SwitchValueState.HasLookedForOverride; return true; } else { // The value is NOT in the dictionary // In this case we need to see if we have an override defined for the value. // There are 2 cases: // 1. The value has an override specified. In this case we need to add the value to the dictionary // and mark it as checked for overrides // Example: In a servicing event, System.Xml introduces a switch and an override is specified. // The value is not found in mscorlib (as System.Xml ships independent of mscorlib) // 2. The value does not have an override specified // In this case, we want to capture the fact that we looked for a value and found nothing by adding // an entry in the dictionary with the 'sentinel' value of 'SwitchValueState.UnknownValue'. // Example: This will prevent us from trying to find overrides for values that we don't have in the dictionary // 1. The value has an override specified. bool overrideValue; if (AppContextDefaultValues.TryGetSwitchOverride(switchName, out overrideValue)) { isEnabled = overrideValue; // Update the switch in the dictionary to mark it as 'checked for override' s_switchMap[switchName] = (isEnabled ? SwitchValueState.HasTrueValue : SwitchValueState.HasFalseValue) | SwitchValueState.HasLookedForOverride; return true; } // 2. The value does not have an override. s_switchMap[switchName] = SwitchValueState.UnknownValue; } } return false; // we did not find a value for the switch } /// <summary> /// Assign a switch a value /// </summary> /// <param name="switchName">The name of the switch</param> /// <param name="isEnabled">The value to assign</param> public static void SetSwitch(string switchName, bool isEnabled) { if (switchName == null) throw new ArgumentNullException("switchName"); if (switchName.Length == 0) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyName"), "switchName"); SwitchValueState switchValue = (isEnabled ? SwitchValueState.HasTrueValue : SwitchValueState.HasFalseValue) | SwitchValueState.HasLookedForOverride; lock (s_switchMap) { // Store the new value and the fact that we checked in the dictionary s_switchMap[switchName] = switchValue; } } /// <summary> /// This method is going to be called from the AppContextDefaultValues class when setting up the /// default values for the switches. !!!! This method is called during the static constructor so it does not /// take a lock !!!! If you are planning to use this outside of that, please ensure proper locking. /// </summary> internal static void DefineSwitchDefault(string switchName, bool isEnabled) { s_switchMap[switchName] = isEnabled ? SwitchValueState.HasTrueValue : SwitchValueState.HasFalseValue; } #endregion } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // <OWNER>[....]</OWNER> // // // StrongName.cs // // StrongName is an IIdentity representing strong names. // namespace System.Security.Policy { using System.IO; using System.Reflection; using System.Security.Util; using System.Security.Permissions; using System.Diagnostics.Contracts; using CultureInfo = System.Globalization.CultureInfo; [Serializable] [System.Runtime.InteropServices.ComVisible(true)] public sealed class StrongName : EvidenceBase, IIdentityPermissionFactory, IDelayEvaluatedEvidence { private StrongNamePublicKeyBlob m_publicKeyBlob; private String m_name; private Version m_version; // Delay evaluated evidence is for policy resolution only, so it doesn't make sense to save that // state away and then try to evaluate the strong name later. [NonSerialized] private RuntimeAssembly m_assembly = null; [NonSerialized] private bool m_wasUsed = false; internal StrongName() {} public StrongName( StrongNamePublicKeyBlob blob, String name, Version version ) : this(blob, name, version, null) { } internal StrongName(StrongNamePublicKeyBlob blob, String name, Version version, Assembly assembly) { if (name == null) throw new ArgumentNullException("name"); if (String.IsNullOrEmpty(name)) throw new ArgumentException(Environment.GetResourceString("Argument_EmptyStrongName")); if (blob == null) throw new ArgumentNullException("blob"); if (version == null) throw new ArgumentNullException("version"); Contract.EndContractBlock(); RuntimeAssembly rtAssembly = assembly as RuntimeAssembly; if (assembly != null && rtAssembly == null) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeAssembly"), "assembly"); m_publicKeyBlob = blob; m_name = name; m_version = version; m_assembly = rtAssembly; } public StrongNamePublicKeyBlob PublicKey { get { return m_publicKeyBlob; } } public String Name { get { return m_name; } } public Version Version { get { return m_version; } } bool IDelayEvaluatedEvidence.IsVerified { [System.Security.SecurityCritical] // auto-generated get { #if FEATURE_CAS_POLICY return m_assembly != null ? m_assembly.IsStrongNameVerified : true; #else // !FEATURE_CAS_POLICY return true; #endif // FEATURE_CAS_POLICY } } bool IDelayEvaluatedEvidence.WasUsed { get { return m_wasUsed; } } void IDelayEvaluatedEvidence.MarkUsed() { m_wasUsed = true; } internal static bool CompareNames( String asmName, String mcName ) { if (mcName.Length > 0 && mcName[mcName.Length-1] == '*' && mcName.Length - 1 <= asmName.Length) return String.Compare( mcName, 0, asmName, 0, mcName.Length - 1, StringComparison.OrdinalIgnoreCase) == 0; else return String.Compare( mcName, asmName, StringComparison.OrdinalIgnoreCase) == 0; } public IPermission CreateIdentityPermission( Evidence evidence ) { return new StrongNameIdentityPermission( m_publicKeyBlob, m_name, m_version ); } public override EvidenceBase Clone() { return new StrongName(m_publicKeyBlob, m_name, m_version); } public Object Copy() { return Clone(); } #if FEATURE_CAS_POLICY internal SecurityElement ToXml() { SecurityElement root = new SecurityElement( "StrongName" ); root.AddAttribute( "version", "1" ); if (m_publicKeyBlob != null) root.AddAttribute( "Key", System.Security.Util.Hex.EncodeHexString( m_publicKeyBlob.PublicKey ) ); if (m_name != null) root.AddAttribute( "Name", m_name ); if (m_version != null) root.AddAttribute( "Version", m_version.ToString() ); return root; } internal void FromXml (SecurityElement element) { if (element == null) throw new ArgumentNullException("element"); if (String.Compare(element.Tag, "StrongName", StringComparison.Ordinal) != 0) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidXML")); Contract.EndContractBlock(); m_publicKeyBlob = null; m_version = null; string key = element.Attribute("Key"); if (key != null) m_publicKeyBlob = new StrongNamePublicKeyBlob(System.Security.Util.Hex.DecodeHexString(key)); m_name = element.Attribute("Name"); string version = element.Attribute("Version"); if (version != null) m_version = new Version(version); } public override String ToString() { return ToXml().ToString(); } #endif // FEATURE_CAS_POLICY public override bool Equals( Object o ) { StrongName that = (o as StrongName); return (that != null) && Equals( this.m_publicKeyBlob, that.m_publicKeyBlob ) && Equals( this.m_name, that.m_name ) && Equals( this.m_version, that.m_version ); } public override int GetHashCode() { if (m_publicKeyBlob != null) { return m_publicKeyBlob.GetHashCode(); } else if (m_name != null || m_version != null) { return (m_name == null ? 0 : m_name.GetHashCode()) + (m_version == null ? 0 : m_version.GetHashCode()); } else { return typeof( StrongName ).GetHashCode(); } } // INormalizeForIsolatedStorage is not implemented for startup perf // equivalent to INormalizeForIsolatedStorage.Normalize() internal Object Normalize() { MemoryStream ms = new MemoryStream(); BinaryWriter bw = new BinaryWriter(ms); bw.Write(m_publicKeyBlob.PublicKey); bw.Write(m_version.Major); bw.Write(m_name); ms.Position = 0; return ms; } } }
/* * 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 autoscaling-2011-01-01.normal.json service model. */ using System; using System.IO; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using Amazon.AutoScaling; using Amazon.AutoScaling.Model; using Amazon.AutoScaling.Model.Internal.MarshallTransformations; using Amazon.Runtime.Internal.Transform; using ServiceClientGenerator; using AWSSDK_DotNet35.UnitTests.TestTools; namespace AWSSDK_DotNet35.UnitTests.Marshalling { [TestClass] public class AutoScalingMarshallingTests { static readonly ServiceModel service_model = Utils.LoadServiceModel("autoscaling-2011-01-01.normal.json", "autoscaling.customizations.json"); [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void AttachInstancesMarshallTest() { var operation = service_model.FindOperation("AttachInstances"); var request = InstantiateClassGenerator.Execute<AttachInstancesRequest>(); var marshaller = new AttachInstancesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void AttachLoadBalancersMarshallTest() { var operation = service_model.FindOperation("AttachLoadBalancers"); var request = InstantiateClassGenerator.Execute<AttachLoadBalancersRequest>(); var marshaller = new AttachLoadBalancersRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = AttachLoadBalancersResponseUnmarshaller.Instance.Unmarshall(context) as AttachLoadBalancersResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void CompleteLifecycleActionMarshallTest() { var operation = service_model.FindOperation("CompleteLifecycleAction"); var request = InstantiateClassGenerator.Execute<CompleteLifecycleActionRequest>(); var marshaller = new CompleteLifecycleActionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = CompleteLifecycleActionResponseUnmarshaller.Instance.Unmarshall(context) as CompleteLifecycleActionResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void CreateAutoScalingGroupMarshallTest() { var operation = service_model.FindOperation("CreateAutoScalingGroup"); var request = InstantiateClassGenerator.Execute<CreateAutoScalingGroupRequest>(); var marshaller = new CreateAutoScalingGroupRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void CreateLaunchConfigurationMarshallTest() { var operation = service_model.FindOperation("CreateLaunchConfiguration"); var request = InstantiateClassGenerator.Execute<CreateLaunchConfigurationRequest>(); var marshaller = new CreateLaunchConfigurationRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void CreateOrUpdateTagsMarshallTest() { var operation = service_model.FindOperation("CreateOrUpdateTags"); var request = InstantiateClassGenerator.Execute<CreateOrUpdateTagsRequest>(); var marshaller = new CreateOrUpdateTagsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void DeleteAutoScalingGroupMarshallTest() { var operation = service_model.FindOperation("DeleteAutoScalingGroup"); var request = InstantiateClassGenerator.Execute<DeleteAutoScalingGroupRequest>(); var marshaller = new DeleteAutoScalingGroupRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void DeleteLaunchConfigurationMarshallTest() { var operation = service_model.FindOperation("DeleteLaunchConfiguration"); var request = InstantiateClassGenerator.Execute<DeleteLaunchConfigurationRequest>(); var marshaller = new DeleteLaunchConfigurationRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void DeleteLifecycleHookMarshallTest() { var operation = service_model.FindOperation("DeleteLifecycleHook"); var request = InstantiateClassGenerator.Execute<DeleteLifecycleHookRequest>(); var marshaller = new DeleteLifecycleHookRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DeleteLifecycleHookResponseUnmarshaller.Instance.Unmarshall(context) as DeleteLifecycleHookResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void DeleteNotificationConfigurationMarshallTest() { var operation = service_model.FindOperation("DeleteNotificationConfiguration"); var request = InstantiateClassGenerator.Execute<DeleteNotificationConfigurationRequest>(); var marshaller = new DeleteNotificationConfigurationRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void DeletePolicyMarshallTest() { var operation = service_model.FindOperation("DeletePolicy"); var request = InstantiateClassGenerator.Execute<DeletePolicyRequest>(); var marshaller = new DeletePolicyRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void DeleteScheduledActionMarshallTest() { var operation = service_model.FindOperation("DeleteScheduledAction"); var request = InstantiateClassGenerator.Execute<DeleteScheduledActionRequest>(); var marshaller = new DeleteScheduledActionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void DeleteTagsMarshallTest() { var operation = service_model.FindOperation("DeleteTags"); var request = InstantiateClassGenerator.Execute<DeleteTagsRequest>(); var marshaller = new DeleteTagsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void DescribeAccountLimitsMarshallTest() { var operation = service_model.FindOperation("DescribeAccountLimits"); var request = InstantiateClassGenerator.Execute<DescribeAccountLimitsRequest>(); var marshaller = new DescribeAccountLimitsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DescribeAccountLimitsResponseUnmarshaller.Instance.Unmarshall(context) as DescribeAccountLimitsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void DescribeAdjustmentTypesMarshallTest() { var operation = service_model.FindOperation("DescribeAdjustmentTypes"); var request = InstantiateClassGenerator.Execute<DescribeAdjustmentTypesRequest>(); var marshaller = new DescribeAdjustmentTypesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DescribeAdjustmentTypesResponseUnmarshaller.Instance.Unmarshall(context) as DescribeAdjustmentTypesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void DescribeAutoScalingGroupsMarshallTest() { var operation = service_model.FindOperation("DescribeAutoScalingGroups"); var request = InstantiateClassGenerator.Execute<DescribeAutoScalingGroupsRequest>(); var marshaller = new DescribeAutoScalingGroupsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DescribeAutoScalingGroupsResponseUnmarshaller.Instance.Unmarshall(context) as DescribeAutoScalingGroupsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void DescribeAutoScalingInstancesMarshallTest() { var operation = service_model.FindOperation("DescribeAutoScalingInstances"); var request = InstantiateClassGenerator.Execute<DescribeAutoScalingInstancesRequest>(); var marshaller = new DescribeAutoScalingInstancesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DescribeAutoScalingInstancesResponseUnmarshaller.Instance.Unmarshall(context) as DescribeAutoScalingInstancesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void DescribeAutoScalingNotificationTypesMarshallTest() { var operation = service_model.FindOperation("DescribeAutoScalingNotificationTypes"); var request = InstantiateClassGenerator.Execute<DescribeAutoScalingNotificationTypesRequest>(); var marshaller = new DescribeAutoScalingNotificationTypesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DescribeAutoScalingNotificationTypesResponseUnmarshaller.Instance.Unmarshall(context) as DescribeAutoScalingNotificationTypesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void DescribeLaunchConfigurationsMarshallTest() { var operation = service_model.FindOperation("DescribeLaunchConfigurations"); var request = InstantiateClassGenerator.Execute<DescribeLaunchConfigurationsRequest>(); var marshaller = new DescribeLaunchConfigurationsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DescribeLaunchConfigurationsResponseUnmarshaller.Instance.Unmarshall(context) as DescribeLaunchConfigurationsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void DescribeLifecycleHooksMarshallTest() { var operation = service_model.FindOperation("DescribeLifecycleHooks"); var request = InstantiateClassGenerator.Execute<DescribeLifecycleHooksRequest>(); var marshaller = new DescribeLifecycleHooksRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DescribeLifecycleHooksResponseUnmarshaller.Instance.Unmarshall(context) as DescribeLifecycleHooksResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void DescribeLifecycleHookTypesMarshallTest() { var operation = service_model.FindOperation("DescribeLifecycleHookTypes"); var request = InstantiateClassGenerator.Execute<DescribeLifecycleHookTypesRequest>(); var marshaller = new DescribeLifecycleHookTypesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DescribeLifecycleHookTypesResponseUnmarshaller.Instance.Unmarshall(context) as DescribeLifecycleHookTypesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void DescribeLoadBalancersMarshallTest() { var operation = service_model.FindOperation("DescribeLoadBalancers"); var request = InstantiateClassGenerator.Execute<DescribeLoadBalancersRequest>(); var marshaller = new DescribeLoadBalancersRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DescribeLoadBalancersResponseUnmarshaller.Instance.Unmarshall(context) as DescribeLoadBalancersResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void DescribeMetricCollectionTypesMarshallTest() { var operation = service_model.FindOperation("DescribeMetricCollectionTypes"); var request = InstantiateClassGenerator.Execute<DescribeMetricCollectionTypesRequest>(); var marshaller = new DescribeMetricCollectionTypesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DescribeMetricCollectionTypesResponseUnmarshaller.Instance.Unmarshall(context) as DescribeMetricCollectionTypesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void DescribeNotificationConfigurationsMarshallTest() { var operation = service_model.FindOperation("DescribeNotificationConfigurations"); var request = InstantiateClassGenerator.Execute<DescribeNotificationConfigurationsRequest>(); var marshaller = new DescribeNotificationConfigurationsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DescribeNotificationConfigurationsResponseUnmarshaller.Instance.Unmarshall(context) as DescribeNotificationConfigurationsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void DescribePoliciesMarshallTest() { var operation = service_model.FindOperation("DescribePolicies"); var request = InstantiateClassGenerator.Execute<DescribePoliciesRequest>(); var marshaller = new DescribePoliciesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DescribePoliciesResponseUnmarshaller.Instance.Unmarshall(context) as DescribePoliciesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void DescribeScalingActivitiesMarshallTest() { var operation = service_model.FindOperation("DescribeScalingActivities"); var request = InstantiateClassGenerator.Execute<DescribeScalingActivitiesRequest>(); var marshaller = new DescribeScalingActivitiesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DescribeScalingActivitiesResponseUnmarshaller.Instance.Unmarshall(context) as DescribeScalingActivitiesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void DescribeScalingProcessTypesMarshallTest() { var operation = service_model.FindOperation("DescribeScalingProcessTypes"); var request = InstantiateClassGenerator.Execute<DescribeScalingProcessTypesRequest>(); var marshaller = new DescribeScalingProcessTypesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DescribeScalingProcessTypesResponseUnmarshaller.Instance.Unmarshall(context) as DescribeScalingProcessTypesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void DescribeScheduledActionsMarshallTest() { var operation = service_model.FindOperation("DescribeScheduledActions"); var request = InstantiateClassGenerator.Execute<DescribeScheduledActionsRequest>(); var marshaller = new DescribeScheduledActionsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DescribeScheduledActionsResponseUnmarshaller.Instance.Unmarshall(context) as DescribeScheduledActionsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void DescribeTagsMarshallTest() { var operation = service_model.FindOperation("DescribeTags"); var request = InstantiateClassGenerator.Execute<DescribeTagsRequest>(); var marshaller = new DescribeTagsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DescribeTagsResponseUnmarshaller.Instance.Unmarshall(context) as DescribeTagsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void DescribeTerminationPolicyTypesMarshallTest() { var operation = service_model.FindOperation("DescribeTerminationPolicyTypes"); var request = InstantiateClassGenerator.Execute<DescribeTerminationPolicyTypesRequest>(); var marshaller = new DescribeTerminationPolicyTypesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DescribeTerminationPolicyTypesResponseUnmarshaller.Instance.Unmarshall(context) as DescribeTerminationPolicyTypesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void DetachInstancesMarshallTest() { var operation = service_model.FindOperation("DetachInstances"); var request = InstantiateClassGenerator.Execute<DetachInstancesRequest>(); var marshaller = new DetachInstancesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DetachInstancesResponseUnmarshaller.Instance.Unmarshall(context) as DetachInstancesResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void DetachLoadBalancersMarshallTest() { var operation = service_model.FindOperation("DetachLoadBalancers"); var request = InstantiateClassGenerator.Execute<DetachLoadBalancersRequest>(); var marshaller = new DetachLoadBalancersRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = DetachLoadBalancersResponseUnmarshaller.Instance.Unmarshall(context) as DetachLoadBalancersResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void DisableMetricsCollectionMarshallTest() { var operation = service_model.FindOperation("DisableMetricsCollection"); var request = InstantiateClassGenerator.Execute<DisableMetricsCollectionRequest>(); var marshaller = new DisableMetricsCollectionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void EnableMetricsCollectionMarshallTest() { var operation = service_model.FindOperation("EnableMetricsCollection"); var request = InstantiateClassGenerator.Execute<EnableMetricsCollectionRequest>(); var marshaller = new EnableMetricsCollectionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void EnterStandbyMarshallTest() { var operation = service_model.FindOperation("EnterStandby"); var request = InstantiateClassGenerator.Execute<EnterStandbyRequest>(); var marshaller = new EnterStandbyRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = EnterStandbyResponseUnmarshaller.Instance.Unmarshall(context) as EnterStandbyResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void ExecutePolicyMarshallTest() { var operation = service_model.FindOperation("ExecutePolicy"); var request = InstantiateClassGenerator.Execute<ExecutePolicyRequest>(); var marshaller = new ExecutePolicyRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void ExitStandbyMarshallTest() { var operation = service_model.FindOperation("ExitStandby"); var request = InstantiateClassGenerator.Execute<ExitStandbyRequest>(); var marshaller = new ExitStandbyRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = ExitStandbyResponseUnmarshaller.Instance.Unmarshall(context) as ExitStandbyResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void PutLifecycleHookMarshallTest() { var operation = service_model.FindOperation("PutLifecycleHook"); var request = InstantiateClassGenerator.Execute<PutLifecycleHookRequest>(); var marshaller = new PutLifecycleHookRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = PutLifecycleHookResponseUnmarshaller.Instance.Unmarshall(context) as PutLifecycleHookResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void PutNotificationConfigurationMarshallTest() { var operation = service_model.FindOperation("PutNotificationConfiguration"); var request = InstantiateClassGenerator.Execute<PutNotificationConfigurationRequest>(); var marshaller = new PutNotificationConfigurationRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void PutScalingPolicyMarshallTest() { var operation = service_model.FindOperation("PutScalingPolicy"); var request = InstantiateClassGenerator.Execute<PutScalingPolicyRequest>(); var marshaller = new PutScalingPolicyRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = PutScalingPolicyResponseUnmarshaller.Instance.Unmarshall(context) as PutScalingPolicyResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void PutScheduledUpdateGroupActionMarshallTest() { var operation = service_model.FindOperation("PutScheduledUpdateGroupAction"); var request = InstantiateClassGenerator.Execute<PutScheduledUpdateGroupActionRequest>(); var marshaller = new PutScheduledUpdateGroupActionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void RecordLifecycleActionHeartbeatMarshallTest() { var operation = service_model.FindOperation("RecordLifecycleActionHeartbeat"); var request = InstantiateClassGenerator.Execute<RecordLifecycleActionHeartbeatRequest>(); var marshaller = new RecordLifecycleActionHeartbeatRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = RecordLifecycleActionHeartbeatResponseUnmarshaller.Instance.Unmarshall(context) as RecordLifecycleActionHeartbeatResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void ResumeProcessesMarshallTest() { var operation = service_model.FindOperation("ResumeProcesses"); var request = InstantiateClassGenerator.Execute<ResumeProcessesRequest>(); var marshaller = new ResumeProcessesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void SetDesiredCapacityMarshallTest() { var operation = service_model.FindOperation("SetDesiredCapacity"); var request = InstantiateClassGenerator.Execute<SetDesiredCapacityRequest>(); var marshaller = new SetDesiredCapacityRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void SetInstanceHealthMarshallTest() { var operation = service_model.FindOperation("SetInstanceHealth"); var request = InstantiateClassGenerator.Execute<SetInstanceHealthRequest>(); var marshaller = new SetInstanceHealthRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void SuspendProcessesMarshallTest() { var operation = service_model.FindOperation("SuspendProcesses"); var request = InstantiateClassGenerator.Execute<SuspendProcessesRequest>(); var marshaller = new SuspendProcessesRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void TerminateInstanceInAutoScalingGroupMarshallTest() { var operation = service_model.FindOperation("TerminateInstanceInAutoScalingGroup"); var request = InstantiateClassGenerator.Execute<TerminateInstanceInAutoScalingGroupRequest>(); var marshaller = new TerminateInstanceInAutoScalingGroupRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); var payloadResponse = new XmlSampleGenerator(service_model, operation).Execute(); var context = new XmlUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, null); var response = TerminateInstanceInAutoScalingGroupResponseUnmarshaller.Instance.Unmarshall(context) as TerminateInstanceInAutoScalingGroupResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Query")] [TestCategory("AutoScaling")] public void UpdateAutoScalingGroupMarshallTest() { var operation = service_model.FindOperation("UpdateAutoScalingGroup"); var request = InstantiateClassGenerator.Execute<UpdateAutoScalingGroupRequest>(); var marshaller = new UpdateAutoScalingGroupRequestMarshaller(); var internalRequest = marshaller.Marshall(request); var validator = new AWSQueryValidator(internalRequest.Parameters, request, service_model, operation); validator.Validate(); } } }
#region License /* The MIT License Copyright (c) 2008 Sky Morey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion namespace System.Text.Html { /// <summary> /// HtmlStringReader /// </summary> public class HtmlStringReader : IDisposable { private string _text; private int _textLength; private StringBuilder _b; private int _startIndex = 0; private int _valueStartIndex; private int _valueEndIndex; private int _openIndex = -1; private int _closeIndex; private string _lastParseElementName; /// <summary> /// Initializes a new instance of the <see cref="HtmlStringReader"/> class. /// </summary> /// <param name="text">The text.</param> public HtmlStringReader(string text) : this(text, new StringBuilder()) { } /// <summary> /// Initializes a new instance of the <see cref="HtmlStringReader"/> class. /// </summary> /// <param name="text">The text.</param> /// <param name="b">The b.</param> public HtmlStringReader(string text, StringBuilder b) { _text = text; _textLength = text.Length; _b = b; } /// <summary> /// Appends the specified value. /// </summary> /// <param name="value">The value.</param> public void Append(string value) { _b.Append(value); } /// <summary> /// Gets the found element. /// </summary> /// <returns></returns> public string GetFoundElement() { if (_openIndex == -1) throw new InvalidOperationException(); // find matching > to the open anchor tag int openCloseBraceIndex = _text.IndexOf(">", _openIndex); if (openCloseBraceIndex == -1) openCloseBraceIndex = _textLength; // extract tag return _text.Substring(_openIndex, openCloseBraceIndex - _openIndex) + ">"; } /// <summary> /// Determines whether [is attribute in element] [the specified element]. /// </summary> /// <param name="element">The element.</param> /// <param name="attribute">The attribute.</param> /// <returns> /// <c>true</c> if [is attribute in element] [the specified element]; otherwise, <c>false</c>. /// </returns> public bool IsAttributeInElement(string element, string attribute) { int attributeLength = attribute.Length; int targetStartKey = 0; // if the tag contains the text "attribute" int targetAttribIndex; while ((targetAttribIndex = element.IndexOf(attribute, targetStartKey, StringComparison.OrdinalIgnoreCase)) > -1) // determine whether "attribute" is inside of a string if (((element.Substring(0, targetAttribIndex).Length - element.Substring(0, targetAttribIndex).Replace("\"", string.Empty).Length) % 2) == 0) // "attribute" is not inside of a string -- attribute exists return true; else // skip "attribute" text and look for next match targetStartKey = targetAttribIndex + attributeLength; return false; } /// <summary> /// Indexes the of. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> public int IndexOf(string value) { return _text.IndexOf(value, _startIndex, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Sets the search value. /// </summary> /// <param name="valueStartIndex">Start index of the value.</param> /// <param name="valueEndIndex">End index of the value.</param> public void SetSearchValue(int valueStartIndex, int valueEndIndex) { _valueStartIndex = valueStartIndex; _valueEndIndex = valueEndIndex; } /// <summary> /// Searches for any element. /// </summary> /// <returns></returns> public bool SearchIfInElement() { _lastParseElementName = null; // look for the closest open tag (<) to the left of the url _openIndex = _text.LastIndexOf("<", _valueStartIndex, _valueStartIndex - _startIndex + 1, StringComparison.OrdinalIgnoreCase); // open tag found if (_openIndex > -1) { // find the corresponding close tag ([</][/>]) to the left of the url _closeIndex = _text.LastIndexOf("</", _valueStartIndex, _valueStartIndex - _openIndex + 1, StringComparison.OrdinalIgnoreCase); int close2Index = _text.LastIndexOf("/>", _valueStartIndex, _valueStartIndex - _openIndex + 1, StringComparison.OrdinalIgnoreCase); if ((close2Index > -1) && (close2Index < _closeIndex)) _closeIndex = close2Index; // false:close tag found -- url is not enclosed in an anchor tag // true:close tag not found -- url is already linked (enclosed in an anchor tag) return (_closeIndex == -1); } // open tag not found else return false; } /// <summary> /// Searches for element. /// </summary> /// <param name="elementName">Name of the element.</param> /// <returns></returns> public bool SearchIfInElement(string elementName) { _lastParseElementName = elementName.ToLowerInvariant(); // look for the closest open element tag (<a>) to the left of the url _openIndex = _text.LastIndexOf("<" + elementName + " ", _valueStartIndex, _valueStartIndex - _startIndex + 1, StringComparison.OrdinalIgnoreCase); // open tag found if (_openIndex > -1) { // find the corresponding close tag (</a>) to the left of the url _closeIndex = _text.LastIndexOf("</" + elementName + ">", _valueStartIndex, _valueStartIndex - _openIndex + 1, StringComparison.OrdinalIgnoreCase); // false:close tag found -- value is not enclosed in an element tag // true:close tag not found -- value is already elemented (enclosed in an anchor tag) return (_closeIndex == -1); } // open tag not found else return false; } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { } #region Stream /// <summary> /// Streams to end of first element. /// </summary> public void StreamToEndOfFirstElement() { // find the close tag (>) to the left of the url int closeIndex = _text.IndexOf(">", _valueEndIndex, StringComparison.OrdinalIgnoreCase); if (closeIndex > -1) { _b.Append(_text.Substring(_startIndex, closeIndex - _startIndex + 1)); Advance(closeIndex + 1); } else { _b.Append(_text.Substring(_startIndex)); Advance(_textLength); } } /// <summary> /// Streams the found element fragment. /// </summary> /// <param name="elementBuilder">The element builder.</param> public void StreamFoundElementFragment(Func<string, string> elementBuilder) { if (_openIndex == -1) throw new InvalidOperationException(); int elementOffset = _lastParseElementName.Length + 2; // look for closing anchor tag int closeIndex = _text.IndexOf("</" + _lastParseElementName + ">", _valueEndIndex, StringComparison.OrdinalIgnoreCase); // close anchor tag found if (closeIndex > -1) { closeIndex += elementOffset; _b.Append(elementBuilder("<" + _lastParseElementName + " " + _text.Substring(_openIndex + elementOffset, closeIndex - _openIndex - elementOffset - 1))); Advance(closeIndex + 1); } // close anchor tag not found else { Advance(_textLength); _b.Append(elementBuilder("<" + _lastParseElementName + " " + _text.Substring(_openIndex + elementOffset, _startIndex - _openIndex - elementOffset))); } } /// <summary> /// Streams to end of value. /// </summary> public void StreamToEndOfValue() { _b.Append(_text.Substring(_startIndex, _valueStartIndex - _startIndex)); Advance(_valueEndIndex + 1); } /// <summary> /// Advances the specified index. /// </summary> /// <param name="index">The index.</param> protected void Advance(int index) { _startIndex = index; _openIndex = -1; } /// <summary> /// Streams to begin element. /// </summary> public void StreamToBeginElement() { if (_openIndex == -1) throw new InvalidOperationException(); // stream text to left of url _b.Append(_text.Substring(_startIndex, _openIndex - _startIndex)); } /// <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() { // append trailing text, if any if (_startIndex < _textLength) { _b.Append(_text.Substring(_startIndex)); Advance(_textLength); } return _b.ToString(); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.IO.Tests { public class BufferedStream_StreamAsync : StreamAsync { protected override Stream CreateStream() { return new BufferedStream(new MemoryStream()); } [Fact] public async Task ConcurrentOperationsAreSerialized() { byte[] data = Enumerable.Range(0, 1000).Select(i => unchecked((byte)i)).ToArray(); var mcaos = new ManuallyReleaseAsyncOperationsStream(); var stream = new BufferedStream(mcaos, 1); var tasks = new Task[4]; for (int i = 0; i < 4; i++) { tasks[i] = stream.WriteAsync(data, 250 * i, 250); } Assert.All(tasks, t => Assert.Equal(TaskStatus.WaitingForActivation, t.Status)); mcaos.Release(); await Task.WhenAll(tasks); stream.Position = 0; for (int i = 0; i < tasks.Length; i++) { Assert.Equal(i, stream.ReadByte()); } } [Fact] public void UnderlyingStreamThrowsExceptions() { var stream = new BufferedStream(new ThrowsExceptionFromAsyncOperationsStream()); Assert.Equal(TaskStatus.Faulted, stream.ReadAsync(new byte[1], 0, 1).Status); Assert.Equal(TaskStatus.Faulted, stream.WriteAsync(new byte[10000], 0, 10000).Status); stream.WriteByte(1); Assert.Equal(TaskStatus.Faulted, stream.FlushAsync().Status); } [Theory] [InlineData(false)] [InlineData(true)] public async Task CopyToTest_RequiresFlushingOfWrites(bool copyAsynchronously) { byte[] data = Enumerable.Range(0, 1000).Select(i => (byte)(i % 256)).ToArray(); var manualReleaseStream = new ManuallyReleaseAsyncOperationsStream(); var src = new BufferedStream(manualReleaseStream); src.Write(data, 0, data.Length); src.Position = 0; var dst = new MemoryStream(); data[0] = 42; src.WriteByte(42); dst.WriteByte(42); if (copyAsynchronously) { Task copyTask = src.CopyToAsync(dst); manualReleaseStream.Release(); await copyTask; } else { manualReleaseStream.Release(); src.CopyTo(dst); } Assert.Equal(data, dst.ToArray()); } [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] [InlineData(true, true)] public async Task CopyToTest_ReadBeforeCopy_CopiesAllData(bool copyAsynchronously, bool wrappedStreamCanSeek) { byte[] data = Enumerable.Range(0, 1000).Select(i => (byte)(i % 256)).ToArray(); var wrapped = new ManuallyReleaseAsyncOperationsStream(); wrapped.Release(); wrapped.Write(data, 0, data.Length); wrapped.Position = 0; wrapped.SetCanSeek(wrappedStreamCanSeek); var src = new BufferedStream(wrapped, 100); src.ReadByte(); var dst = new MemoryStream(); if (copyAsynchronously) { await src.CopyToAsync(dst); } else { src.CopyTo(dst); } var expected = new byte[data.Length - 1]; Array.Copy(data, 1, expected, 0, expected.Length); Assert.Equal(expected, dst.ToArray()); } } public class BufferedStream_StreamMethods : StreamMethods { protected override Stream CreateStream() { return new BufferedStream(new MemoryStream()); } protected override Stream CreateStream(int bufferSize) { return new BufferedStream(new MemoryStream(), bufferSize); } [Fact] public void ReadByte_ThenRead_EndOfStreamCorrectlyFound() { using (var s = new BufferedStream(new MemoryStream(new byte[] { 1, 2 }), 2)) { Assert.Equal(1, s.ReadByte()); Assert.Equal(2, s.ReadByte()); Assert.Equal(-1, s.ReadByte()); Assert.Equal(0, s.Read(new byte[1], 0, 1)); Assert.Equal(0, s.Read(new byte[1], 0, 1)); } } } public class BufferedStream_TestLeaveOpen : TestLeaveOpen { protected override Stream CreateStream() { return new BufferedStream(new MemoryStream()); } } public class StreamWriterWithBufferedStream_CloseTests : CloseTests { protected override Stream CreateStream() { return new BufferedStream(new MemoryStream()); } } public class StreamWriterWithBufferedStream_FlushTests : FlushTests { protected override Stream CreateStream() { return new BufferedStream(new MemoryStream()); } [Fact] public void WriteAfterRead_NonSeekableStream_Throws() { var wrapped = new WrappedMemoryStream(canRead: true, canWrite: true, canSeek: false, data: new byte[] { 1, 2, 3, 4, 5 }); var s = new BufferedStream(wrapped); s.Read(new byte[3], 0, 3); Assert.Throws<NotSupportedException>(() => s.Write(new byte[10], 0, 10)); } } public class StreamWriterWithBufferedStream_WriteTests : WriteTests { protected override Stream CreateStream() { return new BufferedStream(new MemoryStream()); } } public class StreamReaderWithBufferedStream_Tests : StreamReaderTests { protected override Stream CreateStream() { return new BufferedStream(new MemoryStream()); } protected override Stream GetSmallStream() { byte[] testData = new byte[] { 72, 69, 76, 76, 79 }; return new BufferedStream(new MemoryStream(testData)); } protected override Stream GetLargeStream() { byte[] testData = new byte[] { 72, 69, 76, 76, 79 }; List<byte> data = new List<byte>(); for (int i = 0; i < 1000; i++) { data.AddRange(testData); } return new BufferedStream(new MemoryStream(data.ToArray())); } } public class BinaryWriterWithBufferedStream_Tests : BinaryWriterTests { protected override Stream CreateStream() { return new BufferedStream(new MemoryStream()); } [Fact] public override void BinaryWriter_FlushTests() { // [] Check that flush updates the underlying stream using (Stream memstr2 = CreateStream()) using (BinaryWriter bw2 = new BinaryWriter(memstr2)) { string str = "HelloWorld"; int expectedLength = str.Length + 1; // 1 for 7-bit encoded length bw2.Write(str); Assert.Equal(expectedLength, memstr2.Length); bw2.Flush(); Assert.Equal(expectedLength, memstr2.Length); } // [] Flushing a closed writer may throw an exception depending on the underlying stream using (Stream memstr2 = CreateStream()) { BinaryWriter bw2 = new BinaryWriter(memstr2); bw2.Dispose(); Assert.Throws<ObjectDisposedException>(() => bw2.Flush()); } } } public class BinaryWriterWithBufferedStream_WriteByteCharTests : BinaryWriter_WriteByteCharTests { protected override Stream CreateStream() { return new BufferedStream(new MemoryStream()); } } public class BinaryWriterWithBufferedStream_WriteTests : BinaryWriter_WriteTests { protected override Stream CreateStream() { return new BufferedStream(new MemoryStream()); } } internal sealed class ManuallyReleaseAsyncOperationsStream : Stream { private readonly MemoryStream _stream = new MemoryStream(); private readonly TaskCompletionSource<bool> _tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); private bool _canSeek = true; public override bool CanSeek => _canSeek; public override bool CanRead => _stream.CanRead; public override bool CanWrite => _stream.CanWrite; public override long Length => _stream.Length; public override long Position { get => _stream.Position; set => _stream.Position = value; } public void SetCanSeek(bool canSeek) => _canSeek = canSeek; public void Release() { _tcs.SetResult(true); } public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { await _tcs.Task; return await _stream.ReadAsync(buffer, offset, count, cancellationToken); } public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { await _tcs.Task; await _stream.WriteAsync(buffer, offset, count, cancellationToken); } public override async Task FlushAsync(CancellationToken cancellationToken) { await _tcs.Task; await _stream.FlushAsync(cancellationToken); } public override void Flush() => _stream.Flush(); public override int Read(byte[] buffer, int offset, int count) => _stream.Read(buffer, offset, count); public override long Seek(long offset, SeekOrigin origin) => _stream.Seek(offset, origin); public override void SetLength(long value) => _stream.SetLength(value); public override void Write(byte[] buffer, int offset, int count) => _stream.Write(buffer, offset, count); } internal sealed class ThrowsExceptionFromAsyncOperationsStream : MemoryStream { public override int Read(byte[] buffer, int offset, int count) => throw new InvalidOperationException("Exception from ReadAsync"); public override void Write(byte[] buffer, int offset, int count) => throw new InvalidOperationException("Exception from ReadAsync"); public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => throw new InvalidOperationException("Exception from ReadAsync"); public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => throw new InvalidOperationException("Exception from WriteAsync"); public override Task FlushAsync(CancellationToken cancellationToken) => throw new InvalidOperationException("Exception from FlushAsync"); } public class BufferedStream_NS17 { protected Stream CreateStream() { return new BufferedStream(new MemoryStream()); } private void EndCallback(IAsyncResult ar) { } [Fact] public void BeginEndReadTest() { Stream stream = CreateStream(); IAsyncResult result = stream.BeginRead(new byte[1], 0, 1, new AsyncCallback(EndCallback), new object()); stream.EndRead(result); } [Fact] public void BeginEndWriteTest() { Stream stream = CreateStream(); IAsyncResult result = stream.BeginWrite(new byte[1], 0, 1, new AsyncCallback(EndCallback), new object()); stream.EndWrite(result); } } }
namespace XenAdmin.TabPages { partial class VMStoragePage { /// <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) { // Deregister listeners. VM = null; 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(VMStoragePage)); this.AddButton = new System.Windows.Forms.Button(); this.EditButton = new System.Windows.Forms.Button(); this.AttachButton = new System.Windows.Forms.Button(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this.DeactivateButtonContainer = new XenAdmin.Controls.ToolTipContainer(); this.DeactivateButton = new System.Windows.Forms.Button(); this.MoveButtonContainer = new XenAdmin.Controls.ToolTipContainer(); this.MoveButton = new System.Windows.Forms.Button(); this.DeleteButtonContainer = new XenAdmin.Controls.ToolTipContainer(); this.DeleteButton = new System.Windows.Forms.Button(); this.DetachButtonContainer = new XenAdmin.Controls.ToolTipContainer(); this.DetachButton = new System.Windows.Forms.Button(); this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components); this.toolStripMenuItemAdd = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemAttach = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemDeactivate = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemMove = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemDelete = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripMenuItemDetach = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.toolStripMenuItemProperties = new System.Windows.Forms.ToolStripMenuItem(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.dataGridViewStorage = new XenAdmin.Controls.DataGridViewEx.DataGridViewEx(); this.ColumnDevicePosition = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnName = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnDesc = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnSR = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnSRVolume = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnSize = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnReadOnly = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnPriority = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnActive = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.ColumnDevicePath = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.multipleDvdIsoList1 = new XenAdmin.Controls.MultipleDvdIsoList(); this.gradientPanel1 = new XenAdmin.Controls.GradientPanel.GradientPanel(); this.TitleLabel = new System.Windows.Forms.Label(); this.dataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn2 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn3 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn4 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn5 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn6 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn7 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn8 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn9 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn10 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.flowLayoutPanel1.SuspendLayout(); this.DeactivateButtonContainer.SuspendLayout(); this.MoveButtonContainer.SuspendLayout(); this.DeleteButtonContainer.SuspendLayout(); this.DetachButtonContainer.SuspendLayout(); this.contextMenuStrip1.SuspendLayout(); this.tableLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridViewStorage)).BeginInit(); this.gradientPanel1.SuspendLayout(); this.SuspendLayout(); // // AddButton // resources.ApplyResources(this.AddButton, "AddButton"); this.AddButton.Name = "AddButton"; this.AddButton.UseVisualStyleBackColor = true; this.AddButton.Click += new System.EventHandler(this.AddButton_Click); // // EditButton // resources.ApplyResources(this.EditButton, "EditButton"); this.EditButton.Name = "EditButton"; this.EditButton.UseVisualStyleBackColor = true; this.EditButton.Click += new System.EventHandler(this.EditButton_Click); // // AttachButton // resources.ApplyResources(this.AttachButton, "AttachButton"); this.AttachButton.Name = "AttachButton"; this.AttachButton.UseVisualStyleBackColor = true; this.AttachButton.Click += new System.EventHandler(this.AttachButton_Click); // // flowLayoutPanel1 // this.flowLayoutPanel1.Controls.Add(this.AddButton); this.flowLayoutPanel1.Controls.Add(this.AttachButton); this.flowLayoutPanel1.Controls.Add(this.DeactivateButtonContainer); this.flowLayoutPanel1.Controls.Add(this.MoveButtonContainer); this.flowLayoutPanel1.Controls.Add(this.EditButton); this.flowLayoutPanel1.Controls.Add(this.DeleteButtonContainer); this.flowLayoutPanel1.Controls.Add(this.DetachButtonContainer); resources.ApplyResources(this.flowLayoutPanel1, "flowLayoutPanel1"); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; // // DeactivateButtonContainer // this.DeactivateButtonContainer.Controls.Add(this.DeactivateButton); resources.ApplyResources(this.DeactivateButtonContainer, "DeactivateButtonContainer"); this.DeactivateButtonContainer.Name = "DeactivateButtonContainer"; // // DeactivateButton // resources.ApplyResources(this.DeactivateButton, "DeactivateButton"); this.DeactivateButton.Name = "DeactivateButton"; this.DeactivateButton.UseVisualStyleBackColor = true; this.DeactivateButton.Click += new System.EventHandler(this.DeactivateButton_Click); // // MoveButtonContainer // this.MoveButtonContainer.Controls.Add(this.MoveButton); resources.ApplyResources(this.MoveButtonContainer, "MoveButtonContainer"); this.MoveButtonContainer.Name = "MoveButtonContainer"; // // MoveButton // resources.ApplyResources(this.MoveButton, "MoveButton"); this.MoveButton.Name = "MoveButton"; this.MoveButton.UseVisualStyleBackColor = true; this.MoveButton.Click += new System.EventHandler(this.MoveButton_Click); // // DeleteButtonContainer // this.DeleteButtonContainer.Controls.Add(this.DeleteButton); resources.ApplyResources(this.DeleteButtonContainer, "DeleteButtonContainer"); this.DeleteButtonContainer.Name = "DeleteButtonContainer"; // // DeleteButton // resources.ApplyResources(this.DeleteButton, "DeleteButton"); this.DeleteButton.Name = "DeleteButton"; this.DeleteButton.UseVisualStyleBackColor = true; this.DeleteButton.Click += new System.EventHandler(this.DeleteDriveButton_Click); // // DetachButtonContainer // this.DetachButtonContainer.Controls.Add(this.DetachButton); resources.ApplyResources(this.DetachButtonContainer, "DetachButtonContainer"); this.DetachButtonContainer.Name = "DetachButtonContainer"; // // DetachButton // resources.ApplyResources(this.DetachButton, "DetachButton"); this.DetachButton.Name = "DetachButton"; this.DetachButton.UseVisualStyleBackColor = true; this.DetachButton.Click += new System.EventHandler(this.DetachButton_Click); // // contextMenuStrip1 // this.contextMenuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20); this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.toolStripMenuItemAdd, this.toolStripMenuItemAttach, this.toolStripMenuItemDeactivate, this.toolStripMenuItemMove, this.toolStripMenuItemDelete, this.toolStripMenuItemDetach, this.toolStripSeparator1, this.toolStripMenuItemProperties}); this.contextMenuStrip1.Name = "contextMenuStrip1"; resources.ApplyResources(this.contextMenuStrip1, "contextMenuStrip1"); this.contextMenuStrip1.Opening += new System.ComponentModel.CancelEventHandler(this.contextMenuStrip1_Opening); // // toolStripMenuItemAdd // this.toolStripMenuItemAdd.Name = "toolStripMenuItemAdd"; resources.ApplyResources(this.toolStripMenuItemAdd, "toolStripMenuItemAdd"); this.toolStripMenuItemAdd.Click += new System.EventHandler(this.toolStripMenuItemAdd_Click); // // toolStripMenuItemAttach // this.toolStripMenuItemAttach.Name = "toolStripMenuItemAttach"; resources.ApplyResources(this.toolStripMenuItemAttach, "toolStripMenuItemAttach"); this.toolStripMenuItemAttach.Click += new System.EventHandler(this.toolStripMenuItemAttach_Click); // // toolStripMenuItemDeactivate // this.toolStripMenuItemDeactivate.Name = "toolStripMenuItemDeactivate"; resources.ApplyResources(this.toolStripMenuItemDeactivate, "toolStripMenuItemDeactivate"); this.toolStripMenuItemDeactivate.Click += new System.EventHandler(this.toolStripMenuItemDeactivate_Click); // // toolStripMenuItemMove // this.toolStripMenuItemMove.Name = "toolStripMenuItemMove"; resources.ApplyResources(this.toolStripMenuItemMove, "toolStripMenuItemMove"); this.toolStripMenuItemMove.Click += new System.EventHandler(this.toolStripMenuItemMove_Click); // // toolStripMenuItemDelete // this.toolStripMenuItemDelete.Name = "toolStripMenuItemDelete"; resources.ApplyResources(this.toolStripMenuItemDelete, "toolStripMenuItemDelete"); this.toolStripMenuItemDelete.Click += new System.EventHandler(this.toolStripMenuItemDelete_Click); // // toolStripMenuItemDetach // this.toolStripMenuItemDetach.Name = "toolStripMenuItemDetach"; resources.ApplyResources(this.toolStripMenuItemDetach, "toolStripMenuItemDetach"); this.toolStripMenuItemDetach.Click += new System.EventHandler(this.toolStripMenuItemDetach_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1"); // // toolStripMenuItemProperties // this.toolStripMenuItemProperties.Image = global::XenAdmin.Properties.Resources.edit_16; resources.ApplyResources(this.toolStripMenuItemProperties, "toolStripMenuItemProperties"); this.toolStripMenuItemProperties.Name = "toolStripMenuItemProperties"; this.toolStripMenuItemProperties.Click += new System.EventHandler(this.toolStripMenuItemProperties_Click); // // tableLayoutPanel1 // resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1"); this.tableLayoutPanel1.Controls.Add(this.flowLayoutPanel1, 0, 2); this.tableLayoutPanel1.Controls.Add(this.dataGridViewStorage, 0, 1); this.tableLayoutPanel1.Controls.Add(this.multipleDvdIsoList1, 0, 0); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; // // dataGridViewStorage // this.dataGridViewStorage.BackgroundColor = System.Drawing.SystemColors.Window; this.dataGridViewStorage.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; this.dataGridViewStorage.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing; this.dataGridViewStorage.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.ColumnDevicePosition, this.ColumnName, this.ColumnDesc, this.ColumnSR, this.ColumnSRVolume, this.ColumnSize, this.ColumnReadOnly, this.ColumnPriority, this.ColumnActive, this.ColumnDevicePath}); resources.ApplyResources(this.dataGridViewStorage, "dataGridViewStorage"); this.dataGridViewStorage.MultiSelect = true; this.dataGridViewStorage.Name = "dataGridViewStorage"; this.dataGridViewStorage.ReadOnly = true; this.dataGridViewStorage.CellMouseDoubleClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.dataGridViewStorage_CellMouseDoubleClick); this.dataGridViewStorage.SelectionChanged += new System.EventHandler(this.dataGridViewStorage_SelectedIndexChanged); this.dataGridViewStorage.SortCompare += new System.Windows.Forms.DataGridViewSortCompareEventHandler(this.dataGridViewStorage_SortCompare); this.dataGridViewStorage.KeyUp += new System.Windows.Forms.KeyEventHandler(this.dataGridViewStorage_KeyUp); this.dataGridViewStorage.MouseUp += new System.Windows.Forms.MouseEventHandler(this.dataGridViewStorage_MouseUp); // // ColumnDevicePosition // this.ColumnDevicePosition.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; resources.ApplyResources(this.ColumnDevicePosition, "ColumnDevicePosition"); this.ColumnDevicePosition.Name = "ColumnDevicePosition"; this.ColumnDevicePosition.ReadOnly = true; // // ColumnName // this.ColumnName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; resources.ApplyResources(this.ColumnName, "ColumnName"); this.ColumnName.Name = "ColumnName"; this.ColumnName.ReadOnly = true; // // ColumnDesc // this.ColumnDesc.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; resources.ApplyResources(this.ColumnDesc, "ColumnDesc"); this.ColumnDesc.Name = "ColumnDesc"; this.ColumnDesc.ReadOnly = true; // // ColumnSR // this.ColumnSR.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; resources.ApplyResources(this.ColumnSR, "ColumnSR"); this.ColumnSR.Name = "ColumnSR"; this.ColumnSR.ReadOnly = true; // // ColumnSRVolume // this.ColumnSRVolume.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; resources.ApplyResources(this.ColumnSRVolume, "ColumnSRVolume"); this.ColumnSRVolume.Name = "ColumnSRVolume"; this.ColumnSRVolume.ReadOnly = true; // // ColumnSize // this.ColumnSize.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; resources.ApplyResources(this.ColumnSize, "ColumnSize"); this.ColumnSize.Name = "ColumnSize"; this.ColumnSize.ReadOnly = true; // // ColumnReadOnly // this.ColumnReadOnly.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; resources.ApplyResources(this.ColumnReadOnly, "ColumnReadOnly"); this.ColumnReadOnly.Name = "ColumnReadOnly"; this.ColumnReadOnly.ReadOnly = true; // // ColumnPriority // this.ColumnPriority.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; resources.ApplyResources(this.ColumnPriority, "ColumnPriority"); this.ColumnPriority.Name = "ColumnPriority"; this.ColumnPriority.ReadOnly = true; // // ColumnActive // this.ColumnActive.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; resources.ApplyResources(this.ColumnActive, "ColumnActive"); this.ColumnActive.Name = "ColumnActive"; this.ColumnActive.ReadOnly = true; // // ColumnDevicePath // this.ColumnDevicePath.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.ColumnDevicePath, "ColumnDevicePath"); this.ColumnDevicePath.Name = "ColumnDevicePath"; this.ColumnDevicePath.ReadOnly = true; // // multipleDvdIsoList1 // resources.ApplyResources(this.multipleDvdIsoList1, "multipleDvdIsoList1"); this.multipleDvdIsoList1.LabelNewCdForeColor = System.Drawing.SystemColors.HotTrack; this.multipleDvdIsoList1.LabelSingleDvdForeColor = System.Drawing.SystemColors.ControlText; this.multipleDvdIsoList1.LinkLabelLinkColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(255))))); this.multipleDvdIsoList1.Name = "multipleDvdIsoList1"; this.multipleDvdIsoList1.VM = null; // // gradientPanel1 // this.gradientPanel1.Controls.Add(this.TitleLabel); resources.ApplyResources(this.gradientPanel1, "gradientPanel1"); this.gradientPanel1.Name = "gradientPanel1"; this.gradientPanel1.Scheme = XenAdmin.Controls.GradientPanel.GradientPanel.Schemes.Tab; // // TitleLabel // resources.ApplyResources(this.TitleLabel, "TitleLabel"); this.TitleLabel.AutoEllipsis = true; this.TitleLabel.ForeColor = System.Drawing.Color.White; this.TitleLabel.Name = "TitleLabel"; // // dataGridViewTextBoxColumn1 // this.dataGridViewTextBoxColumn1.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.dataGridViewTextBoxColumn1, "dataGridViewTextBoxColumn1"); this.dataGridViewTextBoxColumn1.Name = "dataGridViewTextBoxColumn1"; this.dataGridViewTextBoxColumn1.ReadOnly = true; // // dataGridViewTextBoxColumn2 // this.dataGridViewTextBoxColumn2.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.dataGridViewTextBoxColumn2, "dataGridViewTextBoxColumn2"); this.dataGridViewTextBoxColumn2.Name = "dataGridViewTextBoxColumn2"; this.dataGridViewTextBoxColumn2.ReadOnly = true; // // dataGridViewTextBoxColumn3 // this.dataGridViewTextBoxColumn3.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.dataGridViewTextBoxColumn3, "dataGridViewTextBoxColumn3"); this.dataGridViewTextBoxColumn3.Name = "dataGridViewTextBoxColumn3"; this.dataGridViewTextBoxColumn3.ReadOnly = true; // // dataGridViewTextBoxColumn4 // this.dataGridViewTextBoxColumn4.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; resources.ApplyResources(this.dataGridViewTextBoxColumn4, "dataGridViewTextBoxColumn4"); this.dataGridViewTextBoxColumn4.Name = "dataGridViewTextBoxColumn4"; this.dataGridViewTextBoxColumn4.ReadOnly = true; // // dataGridViewTextBoxColumn5 // this.dataGridViewTextBoxColumn5.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.dataGridViewTextBoxColumn5, "dataGridViewTextBoxColumn5"); this.dataGridViewTextBoxColumn5.Name = "dataGridViewTextBoxColumn5"; this.dataGridViewTextBoxColumn5.ReadOnly = true; // // dataGridViewTextBoxColumn6 // this.dataGridViewTextBoxColumn6.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.dataGridViewTextBoxColumn6, "dataGridViewTextBoxColumn6"); this.dataGridViewTextBoxColumn6.Name = "dataGridViewTextBoxColumn6"; this.dataGridViewTextBoxColumn6.ReadOnly = true; // // dataGridViewTextBoxColumn7 // this.dataGridViewTextBoxColumn7.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.dataGridViewTextBoxColumn7, "dataGridViewTextBoxColumn7"); this.dataGridViewTextBoxColumn7.Name = "dataGridViewTextBoxColumn7"; this.dataGridViewTextBoxColumn7.ReadOnly = true; // // dataGridViewTextBoxColumn8 // this.dataGridViewTextBoxColumn8.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.dataGridViewTextBoxColumn8, "dataGridViewTextBoxColumn8"); this.dataGridViewTextBoxColumn8.Name = "dataGridViewTextBoxColumn8"; this.dataGridViewTextBoxColumn8.ReadOnly = true; // // dataGridViewTextBoxColumn9 // this.dataGridViewTextBoxColumn9.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.dataGridViewTextBoxColumn9, "dataGridViewTextBoxColumn9"); this.dataGridViewTextBoxColumn9.Name = "dataGridViewTextBoxColumn9"; this.dataGridViewTextBoxColumn9.ReadOnly = true; // // dataGridViewTextBoxColumn10 // this.dataGridViewTextBoxColumn10.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; resources.ApplyResources(this.dataGridViewTextBoxColumn10, "dataGridViewTextBoxColumn10"); this.dataGridViewTextBoxColumn10.Name = "dataGridViewTextBoxColumn10"; this.dataGridViewTextBoxColumn10.ReadOnly = true; // // VMStoragePage // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.BackColor = System.Drawing.Color.Transparent; this.Controls.Add(this.tableLayoutPanel1); this.Controls.Add(this.gradientPanel1); this.DoubleBuffered = true; this.Name = "VMStoragePage"; this.flowLayoutPanel1.ResumeLayout(false); this.DeactivateButtonContainer.ResumeLayout(false); this.MoveButtonContainer.ResumeLayout(false); this.DeleteButtonContainer.ResumeLayout(false); this.DetachButtonContainer.ResumeLayout(false); this.contextMenuStrip1.ResumeLayout(false); this.tableLayoutPanel1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dataGridViewStorage)).EndInit(); this.gradientPanel1.ResumeLayout(false); this.ResumeLayout(false); } #endregion public System.Windows.Forms.Button AttachButton; public System.Windows.Forms.Button AddButton; private System.Windows.Forms.Button EditButton; public System.Windows.Forms.Button DetachButton; public System.Windows.Forms.Button DeleteButton; private System.Windows.Forms.Label TitleLabel; private XenAdmin.Controls.ToolTipContainer DetachButtonContainer; private XenAdmin.Controls.ToolTipContainer DeleteButtonContainer; private XenAdmin.Controls.ToolTipContainer DeactivateButtonContainer; private XenAdmin.Controls.GradientPanel.GradientPanel gradientPanel1; public System.Windows.Forms.Button DeactivateButton; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; private XenAdmin.Controls.MultipleDvdIsoList multipleDvdIsoList1; private XenAdmin.Controls.DataGridViewEx.DataGridViewEx dataGridViewStorage; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn1; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn3; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn4; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn5; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn6; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn7; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn8; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn9; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn10; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnDevicePosition; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnName; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnDesc; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnSR; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnSRVolume; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnSize; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnReadOnly; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnPriority; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnActive; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnDevicePath; private XenAdmin.Controls.ToolTipContainer MoveButtonContainer; private System.Windows.Forms.Button MoveButton; private System.Windows.Forms.ContextMenuStrip contextMenuStrip1; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemAdd; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemAttach; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemDeactivate; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemMove; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemProperties; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemDelete; private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemDetach; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Security.Claims; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Umbraco.Extensions; namespace Umbraco.Cms.Core.Security { public abstract class UmbracoUserStore<TUser, TRole> : UserStoreBase<TUser, TRole, string, IdentityUserClaim<string>, IdentityUserRole<string>, IdentityUserLogin<string>, IdentityUserToken<string>, IdentityRoleClaim<string>> where TUser : UmbracoIdentityUser where TRole : IdentityRole<string> { protected UmbracoUserStore(IdentityErrorDescriber describer) : base(describer) { } /// <summary> /// Not supported in Umbraco /// </summary> /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] public override IQueryable<TUser> Users => throw new NotImplementedException(); protected static int UserIdToInt(string userId) { if(int.TryParse(userId, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { return result; } if(Guid.TryParse(userId, out var key)) { // Reverse the IntExtensions.ToGuid return BitConverter.ToInt32(key.ToByteArray(), 0); } throw new InvalidOperationException($"Unable to convert user ID ({userId})to int using InvariantCulture"); } protected static string UserIdToString(int userId) => string.Intern(userId.ToString(CultureInfo.InvariantCulture)); /// <summary> /// Not supported in Umbraco /// </summary> /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] public override Task AddClaimsAsync(TUser user, IEnumerable<Claim> claims, CancellationToken cancellationToken = default) => throw new NotImplementedException(); /// <summary> /// Adds a user to a role (user group) /// </summary> public override Task AddToRoleAsync(TUser user, string normalizedRoleName, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } if (normalizedRoleName == null) { throw new ArgumentNullException(nameof(normalizedRoleName)); } if (string.IsNullOrWhiteSpace(normalizedRoleName)) { throw new ArgumentException("Value can't be empty or consist only of white-space characters.", nameof(normalizedRoleName)); } IdentityUserRole<string> userRole = user.Roles.SingleOrDefault(r => r.RoleId == normalizedRoleName); if (userRole == null) { user.AddRole(normalizedRoleName); } return Task.CompletedTask; } /// <inheritdoc /> public override Task<TUser> FindByIdAsync(string userId, CancellationToken cancellationToken = default) => FindUserAsync(userId, cancellationToken); /// <summary> /// Not supported in Umbraco /// </summary> /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] public override Task<IList<Claim>> GetClaimsAsync(TUser user, CancellationToken cancellationToken = default) => throw new NotImplementedException(); /// <inheritdoc /> public override Task<string> GetNormalizedEmailAsync(TUser user, CancellationToken cancellationToken) => GetEmailAsync(user, cancellationToken); /// <inheritdoc /> public override Task<string> GetNormalizedUserNameAsync(TUser user, CancellationToken cancellationToken = default) => GetUserNameAsync(user, cancellationToken); /// <summary> /// Gets a list of role names the specified user belongs to. /// </summary> public override Task<IList<string>> GetRolesAsync(TUser user, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } return Task.FromResult((IList<string>)user.Roles.Select(x => x.RoleId).ToList()); } /// <inheritdoc /> public override Task<string> GetSecurityStampAsync(TUser user, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } // the stamp cannot be null, so if it is currently null then we'll just return a hash of the password return Task.FromResult(user.SecurityStamp.IsNullOrWhiteSpace() ? user.PasswordHash.GenerateHash() : user.SecurityStamp); } /// <summary> /// Not supported in Umbraco /// </summary> /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] public override Task<IList<TUser>> GetUsersForClaimAsync(Claim claim, CancellationToken cancellationToken = default) => throw new NotImplementedException(); /// <inheritdoc /> public override async Task<bool> HasPasswordAsync(TUser user, CancellationToken cancellationToken = default) { // This checks if it's null bool result = await base.HasPasswordAsync(user, cancellationToken); if (result) { // we also want to check empty return string.IsNullOrEmpty(user.PasswordHash) == false; } return false; } /// <summary> /// Returns true if a user is in the role /// </summary> public override Task<bool> IsInRoleAsync(TUser user, string normalizedRoleName, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (user == null) { throw new ArgumentNullException(nameof(user)); } return Task.FromResult(user.Roles.Select(x => x.RoleId).InvariantContains(normalizedRoleName)); } /// <summary> /// Not supported in Umbraco /// </summary> /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] public override Task RemoveClaimsAsync(TUser user, IEnumerable<Claim> claims, CancellationToken cancellationToken = default) => throw new NotImplementedException(); /// <summary> /// Removes the role (user group) for the user /// </summary> public override Task RemoveFromRoleAsync(TUser user, string normalizedRoleName, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); if (user == null) { throw new ArgumentNullException(nameof(user)); } if (normalizedRoleName == null) { throw new ArgumentNullException(nameof(normalizedRoleName)); } if (string.IsNullOrWhiteSpace(normalizedRoleName)) { throw new ArgumentException("Value can't be empty or consist only of white-space characters.", nameof(normalizedRoleName)); } IdentityUserRole<string> userRole = user.Roles.SingleOrDefault(r => r.RoleId == normalizedRoleName); if (userRole != null) { user.Roles.Remove(userRole); } return Task.CompletedTask; } /// <summary> /// Not supported in Umbraco /// </summary> /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] public override Task ReplaceClaimAsync(TUser user, Claim claim, Claim newClaim, CancellationToken cancellationToken = default) => throw new NotImplementedException(); /// <inheritdoc /> public override Task SetNormalizedEmailAsync(TUser user, string normalizedEmail, CancellationToken cancellationToken) => SetEmailAsync(user, normalizedEmail, cancellationToken); /// <inheritdoc /> public override Task SetNormalizedUserNameAsync(TUser user, string normalizedName, CancellationToken cancellationToken = default) => SetUserNameAsync(user, normalizedName, cancellationToken); /// <inheritdoc /> public override async Task SetPasswordHashAsync(TUser user, string passwordHash, CancellationToken cancellationToken = default) { await base.SetPasswordHashAsync(user, passwordHash, cancellationToken); user.LastPasswordChangeDateUtc = DateTime.UtcNow; } /// <summary> /// Not supported in Umbraco, see comments above on GetTokenAsync, RemoveTokenAsync, SetTokenAsync /// </summary> /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] protected override Task AddUserTokenAsync(IdentityUserToken<string> token) => throw new NotImplementedException(); /// <summary> /// Not supported in Umbraco, see comments above on GetTokenAsync, RemoveTokenAsync, SetTokenAsync /// </summary> /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] protected override Task<IdentityUserToken<string>> FindTokenAsync(TUser user, string loginProvider, string name, CancellationToken cancellationToken) => throw new NotImplementedException(); /// <summary> /// Not supported in Umbraco, see comments above on GetTokenAsync, RemoveTokenAsync, SetTokenAsync /// </summary> /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] protected override Task RemoveUserTokenAsync(IdentityUserToken<string> token) => throw new NotImplementedException(); } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.Controls.StickyNoteControl.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows.Controls { sealed public partial class StickyNoteControl : Control, MS.Internal.Annotations.Component.IAnnotationComponent { #region Methods and constructors void MS.Internal.Annotations.Component.IAnnotationComponent.AddAttachedAnnotation(MS.Internal.Annotations.IAttachedAnnotation attachedAnnotation) { } System.Windows.Media.GeneralTransform MS.Internal.Annotations.Component.IAnnotationComponent.GetDesiredTransform(System.Windows.Media.GeneralTransform transform) { return default(System.Windows.Media.GeneralTransform); } void MS.Internal.Annotations.Component.IAnnotationComponent.RemoveAttachedAnnotation(MS.Internal.Annotations.IAttachedAnnotation attachedAnnotation) { } public override void OnApplyTemplate() { } protected override void OnGotKeyboardFocus(System.Windows.Input.KeyboardFocusChangedEventArgs args) { } protected override void OnIsKeyboardFocusWithinChanged(System.Windows.DependencyPropertyChangedEventArgs args) { } protected override void OnTemplateChanged(ControlTemplate oldTemplate, ControlTemplate newTemplate) { } private StickyNoteControl() { } #endregion #region Properties and indexers public System.Windows.Annotations.IAnchorInfo AnchorInfo { get { return default(System.Windows.Annotations.IAnchorInfo); } } public string Author { get { return default(string); } } public System.Windows.Media.FontFamily CaptionFontFamily { get { return default(System.Windows.Media.FontFamily); } set { } } public double CaptionFontSize { get { return default(double); } set { } } public System.Windows.FontStretch CaptionFontStretch { get { return default(System.Windows.FontStretch); } set { } } public System.Windows.FontStyle CaptionFontStyle { get { return default(System.Windows.FontStyle); } set { } } public System.Windows.FontWeight CaptionFontWeight { get { return default(System.Windows.FontWeight); } set { } } public bool IsActive { get { return default(bool); } } public bool IsExpanded { get { return default(bool); } set { } } public bool IsMouseOverAnchor { get { return default(bool); } } System.Windows.UIElement MS.Internal.Annotations.Component.IAnnotationComponent.AnnotatedElement { get { return default(System.Windows.UIElement); } } System.Collections.IList MS.Internal.Annotations.Component.IAnnotationComponent.AttachedAnnotations { get { return default(System.Collections.IList); } } bool MS.Internal.Annotations.Component.IAnnotationComponent.IsDirty { get { return default(bool); } set { } } int MS.Internal.Annotations.Component.IAnnotationComponent.ZOrder { get { return default(int); } set { } } public double PenWidth { get { return default(double); } set { } } public StickyNoteType StickyNoteType { get { return default(StickyNoteType); } } #endregion #region Fields public readonly static System.Windows.DependencyProperty AuthorProperty; public readonly static System.Windows.DependencyProperty CaptionFontFamilyProperty; public readonly static System.Windows.DependencyProperty CaptionFontSizeProperty; public readonly static System.Windows.DependencyProperty CaptionFontStretchProperty; public readonly static System.Windows.DependencyProperty CaptionFontStyleProperty; public readonly static System.Windows.DependencyProperty CaptionFontWeightProperty; public readonly static System.Windows.Input.RoutedCommand DeleteNoteCommand; public readonly static System.Windows.Input.RoutedCommand InkCommand; public readonly static System.Xml.XmlQualifiedName InkSchemaName; public readonly static System.Windows.DependencyProperty IsActiveProperty; public readonly static System.Windows.DependencyProperty IsExpandedProperty; public readonly static System.Windows.DependencyProperty IsMouseOverAnchorProperty; public readonly static System.Windows.DependencyProperty PenWidthProperty; public readonly static System.Windows.DependencyProperty StickyNoteTypeProperty; public readonly static System.Xml.XmlQualifiedName TextSchemaName; #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Threading; namespace OpenSim.Region.CoreModules.Scripting.ScriptModuleComms { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "ScriptModuleCommsModule")] public class ScriptModuleCommsModule : INonSharedRegionModule, IScriptModuleComms { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private static string LogHeader = "[MODULE COMMS]"; private Dictionary<string, object> m_constants = new Dictionary<string, object>(); private ReaderWriterLock m_ConstantsRwLock = new ReaderWriterLock(); #region ScriptInvocation private Dictionary<string, ScriptInvocationData> m_scriptInvocation = new Dictionary<string, ScriptInvocationData>(); private ReaderWriterLock m_ScriptInvocationRwLock = new ReaderWriterLock(); protected class ScriptInvocationData { public ScriptInvocationData(string fname, Delegate fn, Type[] callsig, Type returnsig) { FunctionName = fname; ScriptInvocationDelegate = fn; TypeSignature = callsig; ReturnType = returnsig; } public string FunctionName { get; private set; } public Type ReturnType { get; private set; } public Delegate ScriptInvocationDelegate { get; private set; } public Type[] TypeSignature { get; private set; } } #endregion ScriptInvocation private IScriptModule m_scriptModule = null; public event ScriptCommand OnScriptCommand; #region RegionModuleInterface public string Name { get { return "ScriptModuleCommsModule"; } } public Type ReplaceableInterface { get { return null; } } public void AddRegion(Scene scene) { scene.RegisterModuleInterface<IScriptModuleComms>(this); } public void Close() { } public void Initialise(IConfigSource config) { } public void RegionLoaded(Scene scene) { m_scriptModule = scene.RequestModuleInterface<IScriptModule>(); if (m_scriptModule != null) m_log.Info("[MODULE COMMANDS]: Script engine found, module active"); } public void RemoveRegion(Scene scene) { } #endregion RegionModuleInterface #region ScriptModuleComms public void DispatchReply(UUID script, int code, string text, string k) { if (m_scriptModule == null) return; Object[] args = new Object[] { -1, code, text, k }; m_scriptModule.PostScriptEvent(script, "link_message", args); } /// <summary> /// Get all registered constants /// </summary> public Dictionary<string, object> GetConstants() { Dictionary<string, object> ret = new Dictionary<string, object>(); m_ConstantsRwLock.AcquireReaderLock(-1); try { foreach (KeyValuePair<string, object> kvp in m_constants) ret[kvp.Key] = kvp.Value; } finally { m_ConstantsRwLock.ReleaseReaderLock(); } return ret; } public Delegate[] GetScriptInvocationList() { List<Delegate> ret = new List<Delegate>(); m_ScriptInvocationRwLock.AcquireReaderLock(-1); try { foreach (ScriptInvocationData d in m_scriptInvocation.Values) ret.Add(d.ScriptInvocationDelegate); } finally { m_ScriptInvocationRwLock.ReleaseReaderLock(); } return ret.ToArray(); } public object InvokeOperation(UUID hostid, UUID scriptid, string fname, params object[] parms) { List<object> olist = new List<object>(); olist.Add(hostid); olist.Add(scriptid); foreach (object o in parms) olist.Add(o); Delegate fn = LookupScriptInvocation(fname); return fn.DynamicInvoke(olist.ToArray()); } /// <summary> /// Operation to check for a registered constant /// </summary> public object LookupModConstant(string cname) { // m_log.DebugFormat("[MODULE COMMANDS] lookup constant <{0}>",cname); m_ConstantsRwLock.AcquireReaderLock(-1); try { object value = null; if (m_constants.TryGetValue(cname, out value)) return value; } finally { m_ConstantsRwLock.ReleaseReaderLock(); } return null; } public string LookupModInvocation(string fname) { m_ScriptInvocationRwLock.AcquireReaderLock(-1); try { ScriptInvocationData sid; if (m_scriptInvocation.TryGetValue(fname, out sid)) { if (sid.ReturnType == typeof(string)) return "modInvokeS"; else if (sid.ReturnType == typeof(int)) return "modInvokeI"; else if (sid.ReturnType == typeof(float)) return "modInvokeF"; else if (sid.ReturnType == typeof(UUID)) return "modInvokeK"; else if (sid.ReturnType == typeof(OpenMetaverse.Vector3)) return "modInvokeV"; else if (sid.ReturnType == typeof(OpenMetaverse.Quaternion)) return "modInvokeR"; else if (sid.ReturnType == typeof(object[])) return "modInvokeL"; m_log.WarnFormat("[MODULE COMMANDS] failed to find match for {0} with return type {1}", fname, sid.ReturnType.Name); } } finally { m_ScriptInvocationRwLock.ReleaseReaderLock(); } return null; } public Type LookupReturnType(string fname) { m_ScriptInvocationRwLock.AcquireReaderLock(-1); try { ScriptInvocationData sid; if (m_scriptInvocation.TryGetValue(fname, out sid)) return sid.ReturnType; } finally { m_ScriptInvocationRwLock.ReleaseReaderLock(); } return null; } public Delegate LookupScriptInvocation(string fname) { m_ScriptInvocationRwLock.AcquireReaderLock(-1); try { ScriptInvocationData sid; if (m_scriptInvocation.TryGetValue(fname, out sid)) return sid.ScriptInvocationDelegate; } finally { m_ScriptInvocationRwLock.ReleaseReaderLock(); } return null; } public Type[] LookupTypeSignature(string fname) { m_ScriptInvocationRwLock.AcquireReaderLock(-1); try { ScriptInvocationData sid; if (m_scriptInvocation.TryGetValue(fname, out sid)) return sid.TypeSignature; } finally { m_ScriptInvocationRwLock.ReleaseReaderLock(); } return null; } public void RaiseEvent(UUID script, string id, string module, string command, string k) { ScriptCommand c = OnScriptCommand; if (c == null) return; c(script, id, module, command, k); } /// <summary> /// Operation to for a region module to register a constant to be used /// by the script engine /// </summary> public void RegisterConstant(string cname, object value) { m_ConstantsRwLock.AcquireWriterLock(-1); try { m_constants.Add(cname, value); } finally { m_ConstantsRwLock.ReleaseWriterLock(); } } public void RegisterConstants(IRegionModuleBase target) { foreach (FieldInfo field in target.GetType().GetFields( BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance)) { if (field.GetCustomAttributes( typeof(ScriptConstantAttribute), true).Any()) { RegisterConstant(field.Name, field.GetValue(target)); } } } public void RegisterScriptInvocation(object target, string meth) { MethodInfo mi = GetMethodInfoFromType(target.GetType(), meth, true); if (mi == null) { m_log.WarnFormat("{0} Failed to register method {1}", LogHeader, meth); return; } RegisterScriptInvocation(target, mi); } public void RegisterScriptInvocation(object target, string[] meth) { foreach (string m in meth) RegisterScriptInvocation(target, m); } public void RegisterScriptInvocation(object target, MethodInfo mi) { // m_log.DebugFormat("[MODULE COMMANDS] Register method {0} from type {1}", mi.Name, (target is Type) ? ((Type)target).Name : target.GetType().Name); Type delegateType = typeof(void); List<Type> typeArgs = mi.GetParameters() .Select(p => p.ParameterType) .ToList(); if (mi.ReturnType == typeof(void)) { delegateType = Expression.GetActionType(typeArgs.ToArray()); } else { try { typeArgs.Add(mi.ReturnType); delegateType = Expression.GetFuncType(typeArgs.ToArray()); } catch (Exception e) { m_log.ErrorFormat("{0} Failed to create function signature. Most likely more than 5 parameters. Method={1}. Error={2}", LogHeader, mi.Name, e); } } Delegate fcall; if (!(target is Type)) fcall = Delegate.CreateDelegate(delegateType, target, mi); else fcall = Delegate.CreateDelegate(delegateType, (Type)target, mi.Name); m_ScriptInvocationRwLock.AcquireReaderLock(-1); try { ParameterInfo[] parameters = fcall.Method.GetParameters(); if (parameters.Length < 2) // Must have two UUID params return; // Hide the first two parameters Type[] parmTypes = new Type[parameters.Length - 2]; for (int i = 2; i < parameters.Length; i++) parmTypes[i - 2] = parameters[i].ParameterType; LockCookie lc = m_ScriptInvocationRwLock.UpgradeToWriterLock(-1); try { m_scriptInvocation[fcall.Method.Name] = new ScriptInvocationData(fcall.Method.Name, fcall, parmTypes, fcall.Method.ReturnType); } finally { m_ScriptInvocationRwLock.DowngradeFromWriterLock(ref lc); } } finally { m_ScriptInvocationRwLock.ReleaseReaderLock(); } } public void RegisterScriptInvocation(Type target, string[] methods) { foreach (string method in methods) { MethodInfo mi = GetMethodInfoFromType(target, method, false); if (mi == null) m_log.WarnFormat("[MODULE COMMANDS] Failed to register method {0}", method); else RegisterScriptInvocation(target, mi); } } public void RegisterScriptInvocations(IRegionModuleBase target) { foreach (MethodInfo method in target.GetType().GetMethods( BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) { if (method.GetCustomAttributes( typeof(ScriptInvocationAttribute), true).Any()) { if (method.IsStatic) RegisterScriptInvocation(target.GetType(), method); else RegisterScriptInvocation(target, method); } } } private static MethodInfo GetMethodInfoFromType(Type target, string meth, bool searchInstanceMethods) { BindingFlags getMethodFlags = BindingFlags.NonPublic | BindingFlags.Public; if (searchInstanceMethods) getMethodFlags |= BindingFlags.Instance; else getMethodFlags |= BindingFlags.Static; return target.GetMethod(meth, getMethodFlags); } #endregion ScriptModuleComms } }
using System; using NUnit.Framework; using Whois.Parsers; namespace Whois.Parsing.Whois.Ua.Ua { [TestFixture] public class UaParsingTests : ParsingTests { private WhoisParser parser; [SetUp] public void SetUp() { SerilogConfig.Init(); parser = new WhoisParser(); } [Test] public void Test_other_status_clienthold() { var sample = SampleReader.Read("whois.ua", "ua", "other_status_clienthold.txt"); var response = parser.Parse("whois.ua", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.ua/ua/Found01", response.TemplateName); Assert.AreEqual("oogle.com.ua", response.DomainName.ToString()); // Registrar Details Assert.AreEqual("ua.imena", response.Registrar.Name); Assert.AreEqual("http://www.imena.ua", response.Registrar.Url); Assert.AreEqual(new DateTime(2013, 07, 19, 01, 23, 16, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(2010, 07, 18, 12, 15, 39, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2013, 07, 18, 12, 15, 38, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("pl-imena-1", response.Registrant.RegistryId); Assert.AreEqual(@"""Internet Invest"" Ltd", response.Registrant.Name); Assert.AreEqual(@"""Internet Invest"" Ltd", response.Registrant.Organization); Assert.AreEqual("+380.442010102", response.Registrant.TelephoneNumber); Assert.AreEqual("+380.442010100", response.Registrant.FaxNumber); Assert.AreEqual("hostmaster@imena.ua", response.Registrant.Email); // Registrant Address Assert.AreEqual(4, response.Registrant.Address.Count); Assert.AreEqual("Gaidara st. 50", response.Registrant.Address[0]); Assert.AreEqual("KYIV", response.Registrant.Address[1]); Assert.AreEqual("UA", response.Registrant.Address[2]); Assert.AreEqual("UA", response.Registrant.Address[3]); // AdminContact Details Assert.AreEqual("pl-imena-1", response.AdminContact.RegistryId); Assert.AreEqual(@"""Internet Invest"" Ltd", response.AdminContact.Name); Assert.AreEqual(@"""Internet Invest"" Ltd", response.AdminContact.Organization); Assert.AreEqual("+380.442010102", response.AdminContact.TelephoneNumber); Assert.AreEqual("+380.442010100", response.AdminContact.FaxNumber); Assert.AreEqual("hostmaster@imena.ua", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(4, response.AdminContact.Address.Count); Assert.AreEqual("Gaidara st. 50", response.AdminContact.Address[0]); Assert.AreEqual("KYIV", response.AdminContact.Address[1]); Assert.AreEqual("UA", response.AdminContact.Address[2]); Assert.AreEqual("UA", response.AdminContact.Address[3]); // TechnicalContact Details Assert.AreEqual("pl-imena-1", response.TechnicalContact.RegistryId); Assert.AreEqual(@"""Internet Invest"" Ltd", response.TechnicalContact.Name); Assert.AreEqual(@"""Internet Invest"" Ltd", response.TechnicalContact.Organization); Assert.AreEqual("+380.442010102", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("+380.442010100", response.TechnicalContact.FaxNumber); Assert.AreEqual("hostmaster@imena.ua", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(4, response.TechnicalContact.Address.Count); Assert.AreEqual("Gaidara st. 50", response.TechnicalContact.Address[0]); Assert.AreEqual("KYIV", response.TechnicalContact.Address[1]); Assert.AreEqual("UA", response.TechnicalContact.Address[2]); Assert.AreEqual("UA", response.TechnicalContact.Address[3]); // Nameservers Assert.AreEqual(3, response.NameServers.Count); Assert.AreEqual("ns3.imena.com.ua", response.NameServers[0]); Assert.AreEqual("ns2.imena.com.ua", response.NameServers[1]); Assert.AreEqual("ns1.imena.com.ua", response.NameServers[2]); // Domain Status Assert.AreEqual(1, response.DomainStatus.Count); Assert.AreEqual("clientHold", response.DomainStatus[0]); Assert.AreEqual(46, response.FieldsParsed); } [Test] public void Test_other_status_clienttransferprohibited() { var sample = SampleReader.Read("whois.ua", "ua", "other_status_clienttransferprohibited.txt"); var response = parser.Parse("whois.ua", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.ua/ua/Found01", response.TemplateName); Assert.AreEqual("fcbank.com.ua", response.DomainName.ToString()); // Registrar Details Assert.AreEqual("ua.register", response.Registrar.Name); Assert.AreEqual("http://register.ua", response.Registrar.Url); Assert.AreEqual(new DateTime(2013, 06, 14, 11, 09, 54, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(2004, 08, 06, 10, 17, 36, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2014, 08, 06, 10, 17, 36, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("com-fac5-1", response.Registrant.RegistryId); Assert.AreEqual(@"JSC ""Finance and Credit"" Bank", response.Registrant.Name); Assert.AreEqual(@"JSC ""Finance and Credit"" Bank", response.Registrant.Organization); Assert.AreEqual("+380.443642909", response.Registrant.TelephoneNumber); Assert.AreEqual("hostmaster@fcbank.com.ua", response.Registrant.Email); // Registrant Address Assert.AreEqual(4, response.Registrant.Address.Count); Assert.AreEqual("Artema str 60", response.Registrant.Address[0]); Assert.AreEqual("KIEV", response.Registrant.Address[1]); Assert.AreEqual("UA", response.Registrant.Address[2]); Assert.AreEqual("UA", response.Registrant.Address[3]); // AdminContact Details Assert.AreEqual("com-fac5-1", response.AdminContact.RegistryId); Assert.AreEqual(@"JSC ""Finance and Credit"" Bank", response.AdminContact.Name); Assert.AreEqual(@"JSC ""Finance and Credit"" Bank", response.AdminContact.Organization); Assert.AreEqual("+380.443642909", response.AdminContact.TelephoneNumber); Assert.AreEqual("hostmaster@fcbank.com.ua", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(4, response.AdminContact.Address.Count); Assert.AreEqual("Artema str 60", response.AdminContact.Address[0]); Assert.AreEqual("KIEV", response.AdminContact.Address[1]); Assert.AreEqual("UA", response.AdminContact.Address[2]); Assert.AreEqual("UA", response.AdminContact.Address[3]); // TechnicalContact Details Assert.AreEqual("com-fac5-1", response.TechnicalContact.RegistryId); Assert.AreEqual(@"JSC ""Finance and Credit"" Bank", response.TechnicalContact.Name); Assert.AreEqual(@"JSC ""Finance and Credit"" Bank", response.TechnicalContact.Organization); Assert.AreEqual("+380.443642909", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("hostmaster@fcbank.com.ua", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(4, response.TechnicalContact.Address.Count); Assert.AreEqual("Artema str 60", response.TechnicalContact.Address[0]); Assert.AreEqual("KIEV", response.TechnicalContact.Address[1]); Assert.AreEqual("UA", response.TechnicalContact.Address[2]); Assert.AreEqual("UA", response.TechnicalContact.Address[3]); // Nameservers Assert.AreEqual(5, response.NameServers.Count); Assert.AreEqual("ns2.fcbank.com.ua", response.NameServers[0]); Assert.AreEqual("ns1.fcbank.com.ua", response.NameServers[1]); Assert.AreEqual("ns.secondary.net.ua", response.NameServers[2]); Assert.AreEqual("ns1.fcbank.com.ua", response.NameServers[3]); Assert.AreEqual("ns2.fcbank.com.ua", response.NameServers[4]); // Domain Status Assert.AreEqual(1, response.DomainStatus.Count); Assert.AreEqual("clientTransferProhibited", response.DomainStatus[0]); Assert.AreEqual(45, response.FieldsParsed); } [Test] public void Test_other_status_graceperiod() { var sample = SampleReader.Read("whois.ua", "ua", "other_status_graceperiod.txt"); var response = parser.Parse("whois.ua", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Other, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.ua/ua/Found01", response.TemplateName); Assert.AreEqual("oogle.com.ua", response.DomainName.ToString()); // Registrar Details Assert.AreEqual("ua.imena", response.Registrar.Name); Assert.AreEqual("http://www.imena.ua", response.Registrar.Url); Assert.AreEqual(new DateTime(2013, 07, 19, 01, 23, 16, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(2010, 07, 18, 12, 15, 39, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2013, 07, 18, 12, 15, 38, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("pl-imena-1", response.Registrant.RegistryId); Assert.AreEqual(@"""Internet Invest"" Ltd", response.Registrant.Name); Assert.AreEqual(@"""Internet Invest"" Ltd", response.Registrant.Organization); Assert.AreEqual("+380.442010102", response.Registrant.TelephoneNumber); Assert.AreEqual("+380.442010100", response.Registrant.FaxNumber); Assert.AreEqual("hostmaster@imena.ua", response.Registrant.Email); // Registrant Address Assert.AreEqual(4, response.Registrant.Address.Count); Assert.AreEqual("Gaidara st. 50", response.Registrant.Address[0]); Assert.AreEqual("KYIV", response.Registrant.Address[1]); Assert.AreEqual("UA", response.Registrant.Address[2]); Assert.AreEqual("UA", response.Registrant.Address[3]); // AdminContact Details Assert.AreEqual("pl-imena-1", response.AdminContact.RegistryId); Assert.AreEqual(@"""Internet Invest"" Ltd", response.AdminContact.Name); Assert.AreEqual(@"""Internet Invest"" Ltd", response.AdminContact.Organization); Assert.AreEqual("+380.442010102", response.AdminContact.TelephoneNumber); Assert.AreEqual("+380.442010100", response.AdminContact.FaxNumber); Assert.AreEqual("hostmaster@imena.ua", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(4, response.AdminContact.Address.Count); Assert.AreEqual("Gaidara st. 50", response.AdminContact.Address[0]); Assert.AreEqual("KYIV", response.AdminContact.Address[1]); Assert.AreEqual("UA", response.AdminContact.Address[2]); Assert.AreEqual("UA", response.AdminContact.Address[3]); // TechnicalContact Details Assert.AreEqual("pl-imena-1", response.TechnicalContact.RegistryId); Assert.AreEqual(@"""Internet Invest"" Ltd", response.TechnicalContact.Name); Assert.AreEqual(@"""Internet Invest"" Ltd", response.TechnicalContact.Organization); Assert.AreEqual("+380.442010102", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("+380.442010100", response.TechnicalContact.FaxNumber); Assert.AreEqual("hostmaster@imena.ua", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(4, response.TechnicalContact.Address.Count); Assert.AreEqual("Gaidara st. 50", response.TechnicalContact.Address[0]); Assert.AreEqual("KYIV", response.TechnicalContact.Address[1]); Assert.AreEqual("UA", response.TechnicalContact.Address[2]); Assert.AreEqual("UA", response.TechnicalContact.Address[3]); // Nameservers Assert.AreEqual(3, response.NameServers.Count); Assert.AreEqual("ns3.imena.com.ua", response.NameServers[0]); Assert.AreEqual("ns2.imena.com.ua", response.NameServers[1]); Assert.AreEqual("ns1.imena.com.ua", response.NameServers[2]); // Domain Status Assert.AreEqual(1, response.DomainStatus.Count); Assert.AreEqual("AutoRenewGracePeriod", response.DomainStatus[0]); Assert.AreEqual(46, response.FieldsParsed); } [Test] public void Test_found() { var sample = SampleReader.Read("whois.ua", "ua", "found.txt"); var response = parser.Parse("whois.ua", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.ua/ua/Found01", response.TemplateName); Assert.AreEqual("google.com.ua", response.DomainName.ToString()); // Registrar Details Assert.AreEqual("ua.imena", response.Registrar.Name); Assert.AreEqual("http://www.imena.ua", response.Registrar.Url); Assert.AreEqual(new DateTime(2013, 04, 15, 17, 00, 10, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(2002, 12, 03, 22, 00, 00, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2013, 12, 03, 22, 00, 00, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("com-gi8-1", response.Registrant.RegistryId); Assert.AreEqual("Google Inc.", response.Registrant.Name); Assert.AreEqual("Google Inc.", response.Registrant.Organization); Assert.AreEqual("+16503300100", response.Registrant.TelephoneNumber); Assert.AreEqual("+16506188571", response.Registrant.FaxNumber); Assert.AreEqual("dns-admin@google.com", response.Registrant.Email); // Registrant Address Assert.AreEqual(4, response.Registrant.Address.Count); Assert.AreEqual("1600 Amphitheatre Parkway Mountain View CA 94043 US", response.Registrant.Address[0]); Assert.AreEqual("n/a", response.Registrant.Address[1]); Assert.AreEqual("UA", response.Registrant.Address[2]); Assert.AreEqual("UA", response.Registrant.Address[3]); // AdminContact Details Assert.AreEqual("com-gi8-1", response.AdminContact.RegistryId); Assert.AreEqual("Google Inc.", response.AdminContact.Name); Assert.AreEqual("Google Inc.", response.AdminContact.Organization); Assert.AreEqual("+16503300100", response.AdminContact.TelephoneNumber); Assert.AreEqual("+16506188571", response.AdminContact.FaxNumber); Assert.AreEqual("dns-admin@google.com", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(4, response.AdminContact.Address.Count); Assert.AreEqual("1600 Amphitheatre Parkway Mountain View CA 94043 US", response.AdminContact.Address[0]); Assert.AreEqual("n/a", response.AdminContact.Address[1]); Assert.AreEqual("UA", response.AdminContact.Address[2]); Assert.AreEqual("UA", response.AdminContact.Address[3]); // TechnicalContact Details Assert.AreEqual("com-gi8-1", response.TechnicalContact.RegistryId); Assert.AreEqual("Google Inc.", response.TechnicalContact.Name); Assert.AreEqual("Google Inc.", response.TechnicalContact.Organization); Assert.AreEqual("+16503300100", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("+16506188571", response.TechnicalContact.FaxNumber); Assert.AreEqual("dns-admin@google.com", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(4, response.TechnicalContact.Address.Count); Assert.AreEqual("1600 Amphitheatre Parkway Mountain View CA 94043 US", response.TechnicalContact.Address[0]); Assert.AreEqual("n/a", response.TechnicalContact.Address[1]); Assert.AreEqual("UA", response.TechnicalContact.Address[2]); Assert.AreEqual("UA", response.TechnicalContact.Address[3]); // Nameservers Assert.AreEqual(4, response.NameServers.Count); Assert.AreEqual("ns3.google.com", response.NameServers[0]); Assert.AreEqual("ns1.google.com", response.NameServers[1]); Assert.AreEqual("ns4.google.com", response.NameServers[2]); Assert.AreEqual("ns2.google.com", response.NameServers[3]); // Domain Status Assert.AreEqual(1, response.DomainStatus.Count); Assert.AreEqual("ok", response.DomainStatus[0]); Assert.AreEqual(47, response.FieldsParsed); } [Test] public void Test_pending_delete() { var sample = SampleReader.Read("whois.ua", "ua", "pending_delete.txt"); var response = parser.Parse("whois.ua", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.PendingDelete, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.ua/ua/Found01", response.TemplateName); Assert.AreEqual("googke.com.ua", response.DomainName.ToString()); // Registrar Details Assert.AreEqual("ua.imena", response.Registrar.Name); Assert.AreEqual("http://www.imena.ua", response.Registrar.Url); Assert.AreEqual(new DateTime(2013, 06, 03, 20, 33, 01, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(2011, 04, 05, 14, 53, 25, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2013, 04, 05, 14, 53, 25, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("pl-imena-1", response.Registrant.RegistryId); Assert.AreEqual(@"""Internet Invest"" Ltd", response.Registrant.Name); Assert.AreEqual(@"""Internet Invest"" Ltd", response.Registrant.Organization); Assert.AreEqual("+380.442010102", response.Registrant.TelephoneNumber); Assert.AreEqual("+380.442010100", response.Registrant.FaxNumber); Assert.AreEqual("hostmaster@imena.ua", response.Registrant.Email); // Registrant Address Assert.AreEqual(4, response.Registrant.Address.Count); Assert.AreEqual("Gaidara st. 50", response.Registrant.Address[0]); Assert.AreEqual("KYIV", response.Registrant.Address[1]); Assert.AreEqual("UA", response.Registrant.Address[2]); Assert.AreEqual("UA", response.Registrant.Address[3]); // AdminContact Details Assert.AreEqual("pl-imena-1", response.AdminContact.RegistryId); Assert.AreEqual(@"""Internet Invest"" Ltd", response.AdminContact.Name); Assert.AreEqual(@"""Internet Invest"" Ltd", response.AdminContact.Organization); Assert.AreEqual("+380.442010102", response.AdminContact.TelephoneNumber); Assert.AreEqual("+380.442010100", response.AdminContact.FaxNumber); Assert.AreEqual("hostmaster@imena.ua", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(4, response.AdminContact.Address.Count); Assert.AreEqual("Gaidara st. 50", response.AdminContact.Address[0]); Assert.AreEqual("KYIV", response.AdminContact.Address[1]); Assert.AreEqual("UA", response.AdminContact.Address[2]); Assert.AreEqual("UA", response.AdminContact.Address[3]); // TechnicalContact Details Assert.AreEqual("pl-imena-1", response.TechnicalContact.RegistryId); Assert.AreEqual(@"""Internet Invest"" Ltd", response.TechnicalContact.Name); Assert.AreEqual(@"""Internet Invest"" Ltd", response.TechnicalContact.Organization); Assert.AreEqual("+380.442010102", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("+380.442010100", response.TechnicalContact.FaxNumber); Assert.AreEqual("hostmaster@imena.ua", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(4, response.TechnicalContact.Address.Count); Assert.AreEqual("Gaidara st. 50", response.TechnicalContact.Address[0]); Assert.AreEqual("KYIV", response.TechnicalContact.Address[1]); Assert.AreEqual("UA", response.TechnicalContact.Address[2]); Assert.AreEqual("UA", response.TechnicalContact.Address[3]); // Nameservers Assert.AreEqual(3, response.NameServers.Count); Assert.AreEqual("ns3.imena.com.ua", response.NameServers[0]); Assert.AreEqual("ns2.imena.com.ua", response.NameServers[1]); Assert.AreEqual("ns1.imena.com.ua", response.NameServers[2]); // Domain Status Assert.AreEqual(1, response.DomainStatus.Count); Assert.AreEqual("pendingDelete", response.DomainStatus[0]); Assert.AreEqual(46, response.FieldsParsed); } [Test] public void Test_other_status_redemptionperiod() { var sample = SampleReader.Read("whois.ua", "ua", "other_status_redemptionperiod.txt"); var response = parser.Parse("whois.ua", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Redemption, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.ua/ua/Found01", response.TemplateName); Assert.AreEqual("googlw.com.ua", response.DomainName.ToString()); // Registrar Details Assert.AreEqual("ua.freehost", response.Registrar.Name); Assert.AreEqual("http://www.freehost.ua", response.Registrar.Url); Assert.AreEqual(new DateTime(2013, 07, 18, 21, 01, 45, 000, DateTimeKind.Utc), response.Updated); Assert.AreEqual(new DateTime(2012, 06, 19, 07, 13, 30, 000, DateTimeKind.Utc), response.Registered); Assert.AreEqual(new DateTime(2013, 06, 19, 07, 13, 30, 000, DateTimeKind.Utc), response.Expiration); // Registrant Details Assert.AreEqual("frh-qrlkjdef1llb", response.Registrant.RegistryId); Assert.AreEqual("not published", response.Registrant.Name); Assert.AreEqual("KOT-studiya", response.Registrant.Organization); // Registrant Address Assert.AreEqual(1, response.Registrant.Address.Count); Assert.AreEqual("n/a", response.Registrant.Address[0]); // AdminContact Details Assert.AreEqual("frh-clwxo1st7ewr", response.AdminContact.RegistryId); Assert.AreEqual("not published", response.AdminContact.Name); Assert.AreEqual("KOT-studiya", response.AdminContact.Organization); // AdminContact Address Assert.AreEqual(1, response.AdminContact.Address.Count); Assert.AreEqual("n/a", response.AdminContact.Address[0]); // TechnicalContact Details Assert.AreEqual("frh-hsa3zl8hqqso", response.TechnicalContact.RegistryId); Assert.AreEqual("not published", response.TechnicalContact.Name); Assert.AreEqual("KOT-studiya", response.TechnicalContact.Organization); // TechnicalContact Address Assert.AreEqual(1, response.TechnicalContact.Address.Count); Assert.AreEqual("n/a", response.TechnicalContact.Address[0]); // Nameservers Assert.AreEqual(2, response.NameServers.Count); Assert.AreEqual("ns2.notpaid.com.ua", response.NameServers[0]); Assert.AreEqual("ns1.notpaid.com.ua", response.NameServers[1]); // Domain Status Assert.AreEqual(1, response.DomainStatus.Count); Assert.AreEqual("RedemptionPeriod", response.DomainStatus[0]); Assert.AreEqual(27, response.FieldsParsed); } [Test] public void Test_not_found() { var sample = SampleReader.Read("whois.ua", "ua", "not_found.txt"); var response = parser.Parse("whois.ua", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.NotFound, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.ua/ua/NotFound", response.TemplateName); Assert.AreEqual("u34jedzcq.com.ua", response.DomainName.ToString()); Assert.AreEqual(2, response.FieldsParsed); } [Test] public void Test_found_status_registered() { var sample = SampleReader.Read("whois.ua", "ua", "found_status_registered.txt"); var response = parser.Parse("whois.ua", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.ua/ua/Found02", response.TemplateName); Assert.AreEqual("kyivstar.ua", response.DomainName.ToString()); // AdminContact Details Assert.AreEqual("KG780-UANIC", response.AdminContact.RegistryId); Assert.AreEqual("Kyivstar GSM", response.AdminContact.Organization); Assert.AreEqual("+380 (44) 2473939", response.AdminContact.TelephoneNumber); Assert.AreEqual("+380 (44) 2473954", response.AdminContact.FaxNumber); Assert.AreEqual("dnsmaster@kyivstar.net", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(3, response.AdminContact.Address.Count); Assert.AreEqual("Chervonozoryanyi Av., 51", response.AdminContact.Address[0]); Assert.AreEqual("03110 KYIV", response.AdminContact.Address[1]); Assert.AreEqual("UA", response.AdminContact.Address[2]); // TechnicalContact Details Assert.AreEqual("KG780-UANIC", response.TechnicalContact.RegistryId); Assert.AreEqual("Kyivstar GSM", response.TechnicalContact.Organization); Assert.AreEqual("+380 (44) 2473939", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("+380 (44) 2473954", response.TechnicalContact.FaxNumber); Assert.AreEqual("dnsmaster@kyivstar.net", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(3, response.TechnicalContact.Address.Count); Assert.AreEqual("Chervonozoryanyi Av., 51", response.TechnicalContact.Address[0]); Assert.AreEqual("03110 KYIV", response.TechnicalContact.Address[1]); Assert.AreEqual("UA", response.TechnicalContact.Address[2]); // Nameservers Assert.AreEqual(2, response.NameServers.Count); Assert.AreEqual("ns2.elvisti.kiev.ua", response.NameServers[0]); Assert.AreEqual("ns.kyivstar.net", response.NameServers[1]); // Domain Status Assert.AreEqual(1, response.DomainStatus.Count); Assert.AreEqual("OK-UNTIL 20140903121852", response.DomainStatus[0]); Assert.AreEqual(35, response.FieldsParsed); } [Test] public void Test_found_contacts_multiple() { var sample = SampleReader.Read("whois.ua", "ua", "found_contacts_multiple.txt"); var response = parser.Parse("whois.ua", sample); Assert.Greater(sample.Length, 0); Assert.AreEqual(WhoisStatus.Found, response.Status); Assert.AreEqual(0, response.ParsingErrors); Assert.AreEqual("whois.ua/ua/Found02", response.TemplateName); Assert.AreEqual("kyivstar.ua", response.DomainName.ToString()); // AdminContact Details Assert.AreEqual("KG780-UANIC", response.AdminContact.RegistryId); Assert.AreEqual("Kyivstar GSM", response.AdminContact.Organization); Assert.AreEqual("+380 (44) 2473939", response.AdminContact.TelephoneNumber); Assert.AreEqual("+380 (44) 2473954", response.AdminContact.FaxNumber); Assert.AreEqual("dnsmaster@kyivstar.net", response.AdminContact.Email); // AdminContact Address Assert.AreEqual(3, response.AdminContact.Address.Count); Assert.AreEqual("Chervonozoryanyi Av., 51", response.AdminContact.Address[0]); Assert.AreEqual("03110 KYIV", response.AdminContact.Address[1]); Assert.AreEqual("UA", response.AdminContact.Address[2]); // TechnicalContact Details Assert.AreEqual("KG780-UANIC", response.TechnicalContact.RegistryId); Assert.AreEqual("Kyivstar GSM", response.TechnicalContact.Organization); Assert.AreEqual("+380 (44) 2473939", response.TechnicalContact.TelephoneNumber); Assert.AreEqual("+380 (44) 2473954", response.TechnicalContact.FaxNumber); Assert.AreEqual("dnsmaster@kyivstar.net", response.TechnicalContact.Email); // TechnicalContact Address Assert.AreEqual(3, response.TechnicalContact.Address.Count); Assert.AreEqual("Chervonozoryanyi Av., 51", response.TechnicalContact.Address[0]); Assert.AreEqual("03110 KYIV", response.TechnicalContact.Address[1]); Assert.AreEqual("UA", response.TechnicalContact.Address[2]); // Nameservers Assert.AreEqual(2, response.NameServers.Count); Assert.AreEqual("ns2.elvisti.kiev.ua", response.NameServers[0]); Assert.AreEqual("ns.kyivstar.net", response.NameServers[1]); // Domain Status Assert.AreEqual(1, response.DomainStatus.Count); Assert.AreEqual("OK-UNTIL 20140903121852", response.DomainStatus[0]); Assert.AreEqual(35, response.FieldsParsed); } } }
using System; using System.Data; using System.Data.OleDb; using System.Collections; using System.Configuration; using PCSComUtils.Common; using PCSComUtils.DataAccess; using PCSComUtils.PCSExc; namespace PCSComMaterials.Inventory.DS { public class IV_BalanceMasterLocationDS { public IV_BalanceMasterLocationDS() { } private const string THIS = "PCSComMaterials.Inventory.DS.DS.IV_BalanceMasterLocationDS"; //************************************************************************** /// <Description> /// This method uses to add data to IV_BalanceMasterLocation /// </Description> /// <Inputs> /// IV_BalanceMasterLocationVO /// </Inputs> /// <Outputs> /// newly inserted primarkey value /// </Outputs> /// <Returns> /// void /// </Returns> /// <Authors> /// Code generate /// </Authors> /// <History> /// Thursday, October 05, 2006 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Add(object pobjObjectVO) { const string METHOD_NAME = THIS + ".Add()"; OleDbConnection oconPCS =null; OleDbCommand ocmdPCS =null; try { IV_BalanceMasterLocationVO objObject = (IV_BalanceMasterLocationVO) pobjObjectVO; string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand("", oconPCS); strSql= "INSERT INTO IV_BalanceMasterLocation(" + IV_BalanceMasterLocationTable.EFFECTDATE_FLD + "," + IV_BalanceMasterLocationTable.OHQUANTITY_FLD + "," + IV_BalanceMasterLocationTable.COMMITQUANTITY_FLD + "," + IV_BalanceMasterLocationTable.PRODUCTID_FLD + "," + IV_BalanceMasterLocationTable.MASTERLOCATIONID_FLD + "," + IV_BalanceMasterLocationTable.STOCKUMID_FLD + ")" + "VALUES(?,?,?,?,?,?)"; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceMasterLocationTable.EFFECTDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[IV_BalanceMasterLocationTable.EFFECTDATE_FLD].Value = objObject.EffectDate; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceMasterLocationTable.OHQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[IV_BalanceMasterLocationTable.OHQUANTITY_FLD].Value = objObject.OHQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceMasterLocationTable.COMMITQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[IV_BalanceMasterLocationTable.COMMITQUANTITY_FLD].Value = objObject.CommitQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceMasterLocationTable.PRODUCTID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceMasterLocationTable.PRODUCTID_FLD].Value = objObject.ProductID; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceMasterLocationTable.MASTERLOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceMasterLocationTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceMasterLocationTable.STOCKUMID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceMasterLocationTable.STOCKUMID_FLD].Value = objObject.StockUMID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to delete data from IV_BalanceMasterLocation /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// void /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// Code generate /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Delete(int pintID) { const string METHOD_NAME = THIS + ".Delete()"; string strSql = String.Empty; strSql= "DELETE " + IV_BalanceMasterLocationTable.TABLE_NAME + " WHERE " + "BalanceMasterLocationID" + "=" + pintID.ToString(); OleDbConnection oconPCS=null; OleDbCommand ocmdPCS =null; try { Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); ocmdPCS = null; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get data from IV_BalanceMasterLocation /// </Description> /// <Inputs> /// ID /// </Inputs> /// <Outputs> /// IV_BalanceMasterLocationVO /// </Outputs> /// <Returns> /// IV_BalanceMasterLocationVO /// </Returns> /// <Authors> /// Code Generate /// </Authors> /// <History> /// Thursday, October 05, 2006 /// </History> /// <Notes> /// </Notes> //************************************************************************** public object GetObjectVO(int pintID) { const string METHOD_NAME = THIS + ".GetObjectVO()"; DataSet dstPCS = new DataSet(); OleDbDataReader odrPCS = null; OleDbConnection oconPCS = null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + IV_BalanceMasterLocationTable.BALANCEMASTERLOCATIONID_FLD + "," + IV_BalanceMasterLocationTable.EFFECTDATE_FLD + "," + IV_BalanceMasterLocationTable.OHQUANTITY_FLD + "," + IV_BalanceMasterLocationTable.COMMITQUANTITY_FLD + "," + IV_BalanceMasterLocationTable.PRODUCTID_FLD + "," + IV_BalanceMasterLocationTable.MASTERLOCATIONID_FLD + "," + IV_BalanceMasterLocationTable.STOCKUMID_FLD + " FROM " + IV_BalanceMasterLocationTable.TABLE_NAME +" WHERE " + IV_BalanceMasterLocationTable.BALANCEMASTERLOCATIONID_FLD + "=" + pintID; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); odrPCS = ocmdPCS.ExecuteReader(); IV_BalanceMasterLocationVO objObject = new IV_BalanceMasterLocationVO(); while (odrPCS.Read()) { objObject.BalanceMasterLocationID = int.Parse(odrPCS[IV_BalanceMasterLocationTable.BALANCEMASTERLOCATIONID_FLD].ToString()); objObject.EffectDate = DateTime.Parse(odrPCS[IV_BalanceMasterLocationTable.EFFECTDATE_FLD].ToString()); objObject.OHQuantity = Decimal.Parse(odrPCS[IV_BalanceMasterLocationTable.OHQUANTITY_FLD].ToString()); objObject.CommitQuantity = Decimal.Parse(odrPCS[IV_BalanceMasterLocationTable.COMMITQUANTITY_FLD].ToString()); objObject.ProductID = int.Parse(odrPCS[IV_BalanceMasterLocationTable.PRODUCTID_FLD].ToString()); objObject.MasterLocationID = int.Parse(odrPCS[IV_BalanceMasterLocationTable.MASTERLOCATIONID_FLD].ToString()); objObject.StockUMID = int.Parse(odrPCS[IV_BalanceMasterLocationTable.STOCKUMID_FLD].ToString()); } return objObject; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update data to IV_BalanceMasterLocation /// </Description> /// <Inputs> /// IV_BalanceMasterLocationVO /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// Code Generate /// </Authors> /// <History> /// 09-Dec-2004 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void Update(object pobjObjecVO) { const string METHOD_NAME = THIS + ".Update()"; IV_BalanceMasterLocationVO objObject = (IV_BalanceMasterLocationVO) pobjObjecVO; //prepare value for parameters OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); strSql= "UPDATE IV_BalanceMasterLocation SET " + IV_BalanceMasterLocationTable.EFFECTDATE_FLD + "= ?" + "," + IV_BalanceMasterLocationTable.OHQUANTITY_FLD + "= ?" + "," + IV_BalanceMasterLocationTable.COMMITQUANTITY_FLD + "= ?" + "," + IV_BalanceMasterLocationTable.PRODUCTID_FLD + "= ?" + "," + IV_BalanceMasterLocationTable.MASTERLOCATIONID_FLD + "= ?" + "," + IV_BalanceMasterLocationTable.STOCKUMID_FLD + "= ?" +" WHERE " + IV_BalanceMasterLocationTable.BALANCEMASTERLOCATIONID_FLD + "= ?"; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceMasterLocationTable.EFFECTDATE_FLD, OleDbType.Date)); ocmdPCS.Parameters[IV_BalanceMasterLocationTable.EFFECTDATE_FLD].Value = objObject.EffectDate; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceMasterLocationTable.OHQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[IV_BalanceMasterLocationTable.OHQUANTITY_FLD].Value = objObject.OHQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceMasterLocationTable.COMMITQUANTITY_FLD, OleDbType.Decimal)); ocmdPCS.Parameters[IV_BalanceMasterLocationTable.COMMITQUANTITY_FLD].Value = objObject.CommitQuantity; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceMasterLocationTable.PRODUCTID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceMasterLocationTable.PRODUCTID_FLD].Value = objObject.ProductID; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceMasterLocationTable.MASTERLOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceMasterLocationTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceMasterLocationTable.STOCKUMID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceMasterLocationTable.STOCKUMID_FLD].Value = objObject.StockUMID; ocmdPCS.Parameters.Add(new OleDbParameter(IV_BalanceMasterLocationTable.BALANCEMASTERLOCATIONID_FLD, OleDbType.Integer)); ocmdPCS.Parameters[IV_BalanceMasterLocationTable.BALANCEMASTERLOCATIONID_FLD].Value = objObject.BalanceMasterLocationID; ocmdPCS.CommandText = strSql; ocmdPCS.Connection.Open(); ocmdPCS.ExecuteNonQuery(); } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } /// <summary> /// Get all record in two period, this period and previous period /// </summary> /// <param name="pdtmEffectDate"></param> /// <returns></returns> /// <author>Trada</author> /// <date>Tuesday, October 17 2006</date> public DataSet GetAllBalanceMasterLocationInTwoPeriod(DateTime pdtmEffectDate) { const string METHOD_NAME = THIS + ".GetAllBalanceMasterLocationInTwoPeriod()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + IV_BalanceMasterLocationTable.BALANCEMASTERLOCATIONID_FLD + "," + IV_BalanceMasterLocationTable.EFFECTDATE_FLD + "," + IV_BalanceMasterLocationTable.OHQUANTITY_FLD + "," + IV_BalanceMasterLocationTable.COMMITQUANTITY_FLD + "," + IV_BalanceMasterLocationTable.PRODUCTID_FLD + "," + IV_BalanceMasterLocationTable.MASTERLOCATIONID_FLD + "," + IV_BalanceMasterLocationTable.STOCKUMID_FLD + " FROM " + IV_BalanceMasterLocationTable.TABLE_NAME + " WHERE " + IV_BalanceMasterLocationTable.EFFECTDATE_FLD + " = '" + pdtmEffectDate.ToShortDateString() + "' OR " + IV_BalanceMasterLocationTable.EFFECTDATE_FLD + " = '" + pdtmEffectDate.AddMonths(-1).ToShortDateString() + "'"; PCSComUtils.DataAccess.Utils utils = new PCSComUtils.DataAccess.Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS,IV_BalanceMasterLocationTable.TABLE_NAME); return dstPCS; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to get all data from IV_BalanceMasterLocation /// </Description> /// <Inputs> /// /// </Inputs> /// <Outputs> /// DataSet /// </Outputs> /// <Returns> /// DataSet /// </Returns> /// <Authors> /// Code Generate /// </Authors> /// <History> /// Thursday, October 05, 2006 /// </History> /// <Notes> /// </Notes> //************************************************************************** public DataSet List() { const string METHOD_NAME = THIS + ".List()"; DataSet dstPCS = new DataSet(); OleDbConnection oconPCS =null; OleDbCommand ocmdPCS = null; try { string strSql = String.Empty; strSql= "SELECT " + IV_BalanceMasterLocationTable.BALANCEMASTERLOCATIONID_FLD + "," + IV_BalanceMasterLocationTable.EFFECTDATE_FLD + "," + IV_BalanceMasterLocationTable.OHQUANTITY_FLD + "," + IV_BalanceMasterLocationTable.COMMITQUANTITY_FLD + "," + IV_BalanceMasterLocationTable.PRODUCTID_FLD + "," + IV_BalanceMasterLocationTable.MASTERLOCATIONID_FLD + "," + IV_BalanceMasterLocationTable.STOCKUMID_FLD + " FROM " + IV_BalanceMasterLocationTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); ocmdPCS = new OleDbCommand(strSql, oconPCS); ocmdPCS.Connection.Open(); OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS); odadPCS.Fill(dstPCS,IV_BalanceMasterLocationTable.TABLE_NAME); return dstPCS; } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } //************************************************************************** /// <Description> /// This method uses to update a DataSet /// </Description> /// <Inputs> /// DataSet /// </Inputs> /// <Outputs> /// /// </Outputs> /// <Returns> /// /// </Returns> /// <Authors> /// Code Generate /// </Authors> /// <History> /// Thursday, October 05, 2006 /// </History> /// <Notes> /// </Notes> //************************************************************************** public void UpdateDataSet(DataSet pData) { const string METHOD_NAME = THIS + ".UpdateDataSet()"; string strSql; OleDbConnection oconPCS =null; OleDbCommandBuilder odcbPCS ; OleDbDataAdapter odadPCS = new OleDbDataAdapter(); try { strSql= "SELECT " + IV_BalanceMasterLocationTable.BALANCEMASTERLOCATIONID_FLD + "," + IV_BalanceMasterLocationTable.EFFECTDATE_FLD + "," + IV_BalanceMasterLocationTable.OHQUANTITY_FLD + "," + IV_BalanceMasterLocationTable.COMMITQUANTITY_FLD + "," + IV_BalanceMasterLocationTable.PRODUCTID_FLD + "," + IV_BalanceMasterLocationTable.MASTERLOCATIONID_FLD + "," + IV_BalanceMasterLocationTable.STOCKUMID_FLD + " FROM " + IV_BalanceMasterLocationTable.TABLE_NAME; Utils utils = new Utils(); oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString); odadPCS.SelectCommand = new OleDbCommand(strSql, oconPCS); odcbPCS = new OleDbCommandBuilder(odadPCS); pData.EnforceConstraints = false; odadPCS.Update(pData,IV_BalanceMasterLocationTable.TABLE_NAME); } catch(OleDbException ex) { throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME,ex); } catch(InvalidOperationException ex) { throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex); } catch (Exception ex) { throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex); } finally { if (oconPCS!=null) { if (oconPCS.State != ConnectionState.Closed) { oconPCS.Close(); } } } } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SqlMapperExtensionsAsync.cs" company="Dapper"> // License: http://www.apache.org/licenses/LICENSE-2.0 // Home page: http://code.google.com/p/dapper-dot-net/ // </copyright> // <auto-generated> // Generated from Dapper source. // </auto-generated> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Dapper; #pragma warning disable 1573, 1591 // xml comments namespace Dapper.Contrib.Extensions { internal static partial class SqlMapperExtensions { /// <summary> /// Returns a single entity by a single id from table "Ts" asynchronously using .NET 4.5 Task. T must be of interface type. /// Id must be marked with [Key] attribute. /// Created entity is tracked/intercepted for changes and used by the Update() extension. /// </summary> /// <typeparam name="T">Interface type to create and populate</typeparam> /// <param name="connection">Open SqlConnection</param> /// <param name="id">Id of the entity to get, must be marked with [Key] attribute</param> /// <returns>Entity of T</returns> public static async Task<T> GetAsync<T>(this IDbConnection connection, dynamic id, IDbTransaction transaction = null, int? commandTimeout = null) where T : class { var type = typeof(T); string sql; if (!GetQueries.TryGetValue(type.TypeHandle, out sql)) { var keys = KeyPropertiesCache(type); if (keys.Count() > 1) throw new DataException("Get<T> only supports an entity with a single [Key] property"); if (!keys.Any()) throw new DataException("Get<T> only supports en entity with a [Key] property"); var onlyKey = keys.First(); var name = GetTableName(type); // TODO: pluralizer // TODO: query information schema and only select fields that are both in information schema and underlying class / interface sql = "select * from " + name + " where " + onlyKey.Name + " = @id"; GetQueries[type.TypeHandle] = sql; } var dynParms = new DynamicParameters(); dynParms.Add("@id", id); T obj; if (type.IsInterface) { var res = (await connection.QueryAsync<dynamic>(sql, dynParms).ConfigureAwait(false)).FirstOrDefault() as IDictionary<string, object>; if (res == null) return null; obj = ProxyGenerator.GetInterfaceProxy<T>(); foreach (var property in TypePropertiesCache(type)) { var val = res[property.Name]; property.SetValue(obj, val, null); } ((IProxy)obj).IsDirty = false; //reset change tracking and return } else { obj = (await connection.QueryAsync<T>(sql, dynParms, transaction, commandTimeout).ConfigureAwait(false)).FirstOrDefault(); } return obj; } /// <summary> /// Inserts an entity into table "Ts" asynchronously using .NET 4.5 Task and returns identity id. /// </summary> /// <param name="connection">Open SqlConnection</param> /// <param name="entityToInsert">Entity to insert</param> /// <returns>Identity of inserted entity</returns> public static Task<int> InsertAsync<T>(this IDbConnection connection, T entityToInsert, IDbTransaction transaction = null, int? commandTimeout = null) where T : class { var type = typeof(T); var name = GetTableName(type); var sbColumnList = new StringBuilder(null); var allProperties = TypePropertiesCache(type); var keyProperties = KeyPropertiesCache(type); var computedProperties = ComputedPropertiesCache(type); var allPropertiesExceptKeyAndComputed = allProperties.Except(keyProperties.Union(computedProperties)).ToList(); for (var i = 0; i < allPropertiesExceptKeyAndComputed.Count(); i++) { var property = allPropertiesExceptKeyAndComputed.ElementAt(i); sbColumnList.AppendFormat("[{0}]", property.Name); if (i < allPropertiesExceptKeyAndComputed.Count() - 1) sbColumnList.Append(", "); } var sbParameterList = new StringBuilder(null); for (var i = 0; i < allPropertiesExceptKeyAndComputed.Count(); i++) { var property = allPropertiesExceptKeyAndComputed.ElementAt(i); sbParameterList.AppendFormat("@{0}", property.Name); if (i < allPropertiesExceptKeyAndComputed.Count() - 1) sbParameterList.Append(", "); } var adapter = GetFormatter(connection); return adapter.InsertAsync(connection, transaction, commandTimeout, name, sbColumnList.ToString(), sbParameterList.ToString(), keyProperties, entityToInsert); } /// <summary> /// Updates entity in table "Ts" asynchronously using .NET 4.5 Task, checks if the entity is modified if the entity is tracked by the Get() extension. /// </summary> /// <typeparam name="T">Type to be updated</typeparam> /// <param name="connection">Open SqlConnection</param> /// <param name="entityToUpdate">Entity to be updated</param> /// <returns>true if updated, false if not found or not modified (tracked entities)</returns> public static async Task<bool> UpdateAsync<T>(this IDbConnection connection, T entityToUpdate, IDbTransaction transaction = null, int? commandTimeout = null) where T : class { var proxy = entityToUpdate as IProxy; if (proxy != null) { if (!proxy.IsDirty) return false; } var type = typeof(T); var keyProperties = KeyPropertiesCache(type); if (!keyProperties.Any()) throw new ArgumentException("Entity must have at least one [Key] property"); var name = GetTableName(type); var sb = new StringBuilder(); sb.AppendFormat("update {0} set ", name); var allProperties = TypePropertiesCache(type); var computedProperties = ComputedPropertiesCache(type); var nonIdProps = allProperties.Except(keyProperties.Union(computedProperties)).ToList(); for (var i = 0; i < nonIdProps.Count(); i++) { var property = nonIdProps.ElementAt(i); sb.AppendFormat("{0} = @{1}", property.Name, property.Name); if (i < nonIdProps.Count() - 1) sb.AppendFormat(", "); } sb.Append(" where "); for (var i = 0; i < keyProperties.Count(); i++) { var property = keyProperties.ElementAt(i); sb.AppendFormat("{0} = @{1}", property.Name, property.Name); if (i < keyProperties.Count() - 1) sb.AppendFormat(" and "); } var updated = await connection.ExecuteAsync(sb.ToString(), entityToUpdate, commandTimeout: commandTimeout, transaction: transaction).ConfigureAwait(false); return updated > 0; } /// <summary> /// Delete entity in table "Ts" asynchronously using .NET 4.5 Task. /// </summary> /// <typeparam name="T">Type of entity</typeparam> /// <param name="connection">Open SqlConnection</param> /// <param name="entityToDelete">Entity to delete</param> /// <returns>true if deleted, false if not found</returns> public static async Task<bool> DeleteAsync<T>(this IDbConnection connection, T entityToDelete, IDbTransaction transaction = null, int? commandTimeout = null) where T : class { if (entityToDelete == null) throw new ArgumentException("Cannot Delete null Object", "entityToDelete"); var type = typeof(T); var keyProperties = KeyPropertiesCache(type); if (!keyProperties.Any()) throw new ArgumentException("Entity must have at least one [Key] property"); var name = GetTableName(type); var sb = new StringBuilder(); sb.AppendFormat("delete from {0} where ", name); for (var i = 0; i < keyProperties.Count(); i++) { var property = keyProperties.ElementAt(i); sb.AppendFormat("{0} = @{1}", property.Name, property.Name); if (i < keyProperties.Count() - 1) sb.AppendFormat(" and "); } var deleted = await connection.ExecuteAsync(sb.ToString(), entityToDelete, transaction, commandTimeout).ConfigureAwait(false); return deleted > 0; } /// <summary> /// Delete all entities in the table related to the type T asynchronously using .NET 4.5 Task. /// </summary> /// <typeparam name="T">Type of entity</typeparam> /// <param name="connection">Open SqlConnection</param> /// <returns>true if deleted, false if none found</returns> public static async Task<bool> DeleteAllAsync<T>(this IDbConnection connection, IDbTransaction transaction = null, int? commandTimeout = null) where T : class { var type = typeof(T); var name = GetTableName(type); var statement = String.Format("delete from {0}", name); var deleted = await connection.ExecuteAsync(statement, null, transaction, commandTimeout).ConfigureAwait(false); return deleted > 0; } } } internal partial interface ISqlAdapter { Task<int> InsertAsync(IDbConnection connection, IDbTransaction transaction, int? commandTimeout, String tableName, string columnList, string parameterList, IEnumerable<PropertyInfo> keyProperties, object entityToInsert); } internal partial class SqlServerAdapter { public async Task<int> InsertAsync(IDbConnection connection, IDbTransaction transaction, int? commandTimeout, String tableName, string columnList, string parameterList, IEnumerable<PropertyInfo> keyProperties, object entityToInsert) { var cmd = String.Format("insert into {0} ({1}) values ({2})", tableName, columnList, parameterList); await connection.ExecuteAsync(cmd, entityToInsert, transaction, commandTimeout).ConfigureAwait(false); //NOTE: would prefer to use IDENT_CURRENT('tablename') or IDENT_SCOPE but these are not available on SQLCE var r = await connection.QueryAsync<dynamic>("select @@IDENTITY id", transaction: transaction, commandTimeout: commandTimeout).ConfigureAwait(false); var id = (int)r.First().id; var propertyInfos = keyProperties as PropertyInfo[] ?? keyProperties.ToArray(); if (propertyInfos.Any()) propertyInfos.First().SetValue(entityToInsert, id, null); return id; } } internal partial class PostgresAdapter { public async Task<int> InsertAsync(IDbConnection connection, IDbTransaction transaction, int? commandTimeout, String tableName, string columnList, string parameterList, IEnumerable<PropertyInfo> keyProperties, object entityToInsert) { var sb = new StringBuilder(); sb.AppendFormat("insert into {0} ({1}) values ({2})", tableName, columnList, parameterList); // If no primary key then safe to assume a join table with not too much data to return var propertyInfos = keyProperties as PropertyInfo[] ?? keyProperties.ToArray(); if (!propertyInfos.Any()) sb.Append(" RETURNING *"); else { sb.Append(" RETURNING "); bool first = true; foreach (var property in propertyInfos) { if (!first) sb.Append(", "); first = false; sb.Append(property.Name); } } var results = await connection.QueryAsync<dynamic>(sb.ToString(), entityToInsert, transaction, commandTimeout).ConfigureAwait(false); // Return the key by assinging the corresponding property in the object - by product is that it supports compound primary keys var id = 0; foreach (var p in propertyInfos) { var value = ((IDictionary<string, object>)results.First())[p.Name.ToLower()]; p.SetValue(entityToInsert, value, null); if (id == 0) id = Convert.ToInt32(value); } return id; } } internal partial class SQLiteAdapter { public async Task<int> InsertAsync(IDbConnection connection, IDbTransaction transaction, int? commandTimeout, String tableName, string columnList, string parameterList, IEnumerable<PropertyInfo> keyProperties, object entityToInsert) { var cmd = String.Format("insert into {0} ({1}) values ({2})", tableName, columnList, parameterList); await connection.ExecuteAsync(cmd, entityToInsert, transaction: transaction, commandTimeout: commandTimeout).ConfigureAwait(false); var r = await connection.QueryAsync<dynamic>("select last_insert_rowid() id", transaction: transaction, commandTimeout: commandTimeout).ConfigureAwait(false); var id = (int)r.First().id; var propertyInfos = keyProperties as PropertyInfo[] ?? keyProperties.ToArray(); if (propertyInfos.Any()) propertyInfos.First().SetValue(entityToInsert, id, null); return id; } }
//------------------------------------------------------------------------------ // <copyright file="DMLibTestBase.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation // </copyright> //------------------------------------------------------------------------------ namespace DMLibTest { using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using DMLibTestCodeGen; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.DataMovement; using MS.Test.Common.MsTestLib; public class DMLibTestBase : MultiDirectionTestBase<DMLibDataInfo, DMLibDataType> { private static Dictionary<string, string> sourceConnectionStrings = new Dictionary<string, string>(); private static Dictionary<string, string> destConnectionStrings = new Dictionary<string, string>(); public const string FolderName = "folder"; public const string FileName = "testfile"; public const string DirName = "testdir"; public static int FileSizeInKB { get; set; } public static void SetSourceConnectionString(string value, DMLibDataType dataType) { string key = DMLibTestBase.GetLocationKey(dataType); sourceConnectionStrings[key] = value; } public static void SetDestConnectionString(string value, DMLibDataType dataType) { string key = DMLibTestBase.GetLocationKey(dataType); destConnectionStrings[key] = value; } public static string GetSourceConnectionString(DMLibDataType dataType) { return GetConnectionString(SourceOrDest.Source, dataType); } public static string GetDestConnectionString(DMLibDataType dataType) { return GetConnectionString(SourceOrDest.Dest, dataType); } private static string GetConnectionString(SourceOrDest sourceOrDest, DMLibDataType dataType) { IDictionary<string, string> connectionStrings = SourceOrDest.Source == sourceOrDest ? sourceConnectionStrings : destConnectionStrings; string key = DMLibTestBase.GetLocationKey(dataType); string connectionString; if (connectionStrings.TryGetValue(key, out connectionString)) { return connectionString; } if (SourceOrDest.Dest == sourceOrDest) { return TestAccounts.Secondary.ConnectionString; } else { return TestAccounts.Primary.ConnectionString; } } public static new void BaseClassInitialize(TestContext testContext) { MultiDirectionTestBase<DMLibDataInfo, DMLibDataType>.BaseClassInitialize(testContext); FileSizeInKB = int.Parse(Test.Data.Get("FileSize")); DMLibTestBase.InitializeDataAdaptor(); } private static void InitializeDataAdaptor() { var srcBlobTestAccount = new TestAccount(GetSourceConnectionString(DMLibDataType.CloudBlob)); var destBlobTestAccount = new TestAccount(GetDestConnectionString(DMLibDataType.CloudBlob)); var srcFileTestAccount = new TestAccount(GetSourceConnectionString(DMLibDataType.CloudFile)); var destFileTestAccount = new TestAccount(GetDestConnectionString(DMLibDataType.CloudFile)); // Initialize data adaptor for normal location SetSourceAdaptor(DMLibDataType.Local, new LocalDataAdaptor(DMLibTestBase.SourceRoot + DMLibTestHelper.RandomNameSuffix(), SourceOrDest.Source)); SetSourceAdaptor(DMLibDataType.Stream, new LocalDataAdaptor(DMLibTestBase.SourceRoot + DMLibTestHelper.RandomNameSuffix(), SourceOrDest.Source, useStream: true)); SetSourceAdaptor(DMLibDataType.URI, new URIBlobDataAdaptor(srcBlobTestAccount, DMLibTestBase.SourceRoot + DMLibTestHelper.RandomNameSuffix())); SetSourceAdaptor(DMLibDataType.BlockBlob, new CloudBlobDataAdaptor(srcBlobTestAccount, DMLibTestBase.SourceRoot + DMLibTestHelper.RandomNameSuffix(), BlobType.Block, SourceOrDest.Source)); SetSourceAdaptor(DMLibDataType.PageBlob, new CloudBlobDataAdaptor(srcBlobTestAccount, DMLibTestBase.SourceRoot + DMLibTestHelper.RandomNameSuffix(), BlobType.Page, SourceOrDest.Source)); SetSourceAdaptor(DMLibDataType.AppendBlob, new CloudBlobDataAdaptor(srcBlobTestAccount, DMLibTestBase.SourceRoot + DMLibTestHelper.RandomNameSuffix(), BlobType.Append, SourceOrDest.Source)); SetSourceAdaptor(DMLibDataType.CloudFile, new CloudFileDataAdaptor(srcFileTestAccount, DMLibTestBase.SourceRoot + DMLibTestHelper.RandomNameSuffix(), SourceOrDest.Source)); SetDestAdaptor(DMLibDataType.Local, new LocalDataAdaptor(DMLibTestBase.DestRoot + DMLibTestHelper.RandomNameSuffix(), SourceOrDest.Dest)); SetDestAdaptor(DMLibDataType.Stream, new LocalDataAdaptor(DMLibTestBase.DestRoot + DMLibTestHelper.RandomNameSuffix(), SourceOrDest.Dest, useStream: true)); SetDestAdaptor(DMLibDataType.BlockBlob, new CloudBlobDataAdaptor(destBlobTestAccount, DMLibTestBase.DestRoot + DMLibTestHelper.RandomNameSuffix(), BlobType.Block, SourceOrDest.Dest)); SetDestAdaptor(DMLibDataType.PageBlob, new CloudBlobDataAdaptor(destBlobTestAccount, DMLibTestBase.DestRoot + DMLibTestHelper.RandomNameSuffix(), BlobType.Page, SourceOrDest.Dest)); SetDestAdaptor(DMLibDataType.AppendBlob, new CloudBlobDataAdaptor(destBlobTestAccount, DMLibTestBase.DestRoot + DMLibTestHelper.RandomNameSuffix(), BlobType.Append, SourceOrDest.Dest)); SetDestAdaptor(DMLibDataType.CloudFile, new CloudFileDataAdaptor(destFileTestAccount, DMLibTestBase.DestRoot + DMLibTestHelper.RandomNameSuffix(), SourceOrDest.Dest)); } public TestResult<DMLibDataInfo> ExecuteTestCase(DMLibDataInfo sourceDataInfo, TestExecutionOptions<DMLibDataInfo> options) { this.CleanupData(); SourceAdaptor.CreateIfNotExists(); DestAdaptor.CreateIfNotExists(); if (sourceDataInfo != null) { SourceAdaptor.GenerateData(sourceDataInfo); } if (options.DestTransferDataInfo != null) { DestAdaptor.GenerateData(options.DestTransferDataInfo); } if (options.AfterDataPrepared != null) { options.AfterDataPrepared(); } List<TransferItem> allItems = new List<TransferItem>(); foreach(var fileNode in sourceDataInfo.EnumerateFileNodes()) { TransferItem item = new TransferItem() { SourceObject = SourceAdaptor.GetTransferObject(fileNode), DestObject = DestAdaptor.GetTransferObject(fileNode), SourceType = DMLibTestContext.SourceType, DestType = DMLibTestContext.DestType, IsServiceCopy = DMLibTestContext.IsAsync, }; if (options.TransferItemModifier != null) { options.TransferItemModifier(fileNode, item); } allItems.Add(item); } return this.RunTransferItems(allItems, options); } public TestResult<DMLibDataInfo> RunTransferItems(IEnumerable<TransferItem> items, TestExecutionOptions<DMLibDataInfo> options) { List<Task> allTasks = new List<Task>(); var testResult = new TestResult<DMLibDataInfo>(); try { foreach (TransferItem item in items) { DMLibWrapper wrapper = GetDMLibWrapper(item.SourceType, item.DestType, DMLibTestContext.IsAsync); if (item.BeforeStarted != null) { item.BeforeStarted(); } try { if (options.LimitSpeed) { OperationContext.GlobalSendingRequest += this.LimitSpeed; TransferManager.Configurations.ParallelOperations = DMLibTestConstants.LimitedSpeedNC; } allTasks.Add(wrapper.DoTransfer(item)); } catch (Exception e) { testResult.AddException(e); } if (item.AfterStarted != null) { item.AfterStarted(); } } if (options.AfterAllItemAdded != null) { options.AfterAllItemAdded(); } try { Task.WaitAll(allTasks.ToArray(), options.TimeoutInMs); } catch (Exception e) { AggregateException ae = e as AggregateException; if (ae != null) { ae = ae.Flatten(); foreach (var innerE in ae.InnerExceptions) { testResult.AddException(innerE); } } else { testResult.AddException(e); } } } finally { if (options.LimitSpeed) { OperationContext.GlobalSendingRequest -= this.LimitSpeed; TransferManager.Configurations.ParallelOperations = DMLibTestConstants.DefaultNC; } } Parallel.ForEach(items, currentItem => currentItem.CloseStreamIfNecessary()); if (!options.DisableDestinationFetch) { testResult.DataInfo = DestAdaptor.GetTransferDataInfo(string.Empty); } foreach (var exception in testResult.Exceptions) { Test.Info("Exception from DMLib: {0}", exception.ToString()); } return testResult; } public DMLibWrapper GetDMLibWrapper(DMLibDataType sourceType, DMLibDataType destType, bool isServiceCopy) { if (DMLibTestBase.IsLocal(sourceType)) { return new UploadWrapper(); } else if (DMLibTestBase.IsLocal(destType)) { return new DownloadWrapper(); } else { return new CopyWrapper(); } } public static object DefaultTransferOptions { get { return DMLibTestBase.GetDefaultTransferOptions(DMLibTestContext.SourceType, DMLibTestContext.DestType); } } public static object GetDefaultTransferOptions(DMLibDataType sourceType, DMLibDataType destType) { if (DMLibTestBase.IsLocal(sourceType)) { return new UploadOptions(); } else if (DMLibTestBase.IsLocal(destType)) { return new DownloadOptions(); } else { return new CopyOptions(); } } public static string MapBlobDataTypeToBlobType(DMLibDataType blobDataType) { switch (blobDataType) { case DMLibDataType.BlockBlob: return BlobType.Block; case DMLibDataType.PageBlob: return BlobType.Page; case DMLibDataType.AppendBlob: return BlobType.Append; default: throw new ArgumentException("blobDataType"); } } private void LimitSpeed(object sender, RequestEventArgs e) { Thread.Sleep(100); } public DMLibDataInfo GenerateSourceDataInfo(FileNumOption fileNumOption, string folderName = "") { return this.GenerateSourceDataInfo(fileNumOption, DMLibTestBase.FileSizeInKB, folderName); } public DMLibDataInfo GenerateSourceDataInfo(FileNumOption fileNumOption, int totalSizeInKB, string folderName = "") { DMLibDataInfo sourceDataInfo = new DMLibDataInfo(folderName); if (fileNumOption == FileNumOption.FileTree) { DMLibDataHelper.AddTreeTotalSize( sourceDataInfo.RootNode, DMLibTestBase.DirName, DMLibTestBase.FileName, DMLibTestConstants.RecursiveFolderWidth, DMLibTestConstants.RecursiveFolderDepth, totalSizeInKB); } else if (fileNumOption == FileNumOption.FlatFolder) { DMLibDataHelper.AddMultipleFilesTotalSize( sourceDataInfo.RootNode, DMLibTestBase.FileName, DMLibTestConstants.FlatFileCount, totalSizeInKB); } else if (fileNumOption == FileNumOption.OneFile) { DMLibDataHelper.AddOneFile(sourceDataInfo.RootNode, DMLibTestBase.FileName, totalSizeInKB); } return sourceDataInfo; } public enum FileNumOption { OneFile, FlatFolder, FileTree, } public override bool IsCloudService(DMLibDataType dataType) { return DMLibDataType.Cloud.HasFlag(dataType); } public static bool IsLocal(DMLibDataType dataType) { return dataType == DMLibDataType.Stream || dataType == DMLibDataType.Local; } public static bool IsCloudBlob(DMLibDataType dataType) { return DMLibDataType.CloudBlob.HasFlag(dataType); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.CoreModules.World.Land; namespace OpenSim.Region.RegionCombinerModule { public class RegionCombinerLargeLandChannel : ILandChannel { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private RegionData RegData; private ILandChannel RootRegionLandChannel; private readonly List<RegionData> RegionConnections; #region ILandChannel Members public RegionCombinerLargeLandChannel(RegionData regData, ILandChannel rootRegionLandChannel, List<RegionData> regionConnections) { RegData = regData; RootRegionLandChannel = rootRegionLandChannel; RegionConnections = regionConnections; } public List<ILandObject> ParcelsNearPoint(Vector3 position) { //m_log.DebugFormat("[LANDPARCELNEARPOINT]: {0}>", position); return RootRegionLandChannel.ParcelsNearPoint(position - RegData.Offset); } public List<ILandObject> AllParcels() { return RootRegionLandChannel.AllParcels(); } public void Clear(bool setupDefaultParcel) { RootRegionLandChannel.Clear(setupDefaultParcel); } public ILandObject GetLandObject(Vector3 position) { return GetLandObject(position.X, position.Y); } public ILandObject GetLandObject(int x, int y) { return GetLandObject((float)x, (float)y); // m_log.DebugFormat("[BIGLANDTESTINT]: <{0},{1}>", x, y); // // if (x > 0 && x <= (int)Constants.RegionSize && y > 0 && y <= (int)Constants.RegionSize) // { // return RootRegionLandChannel.GetLandObject(x, y); // } // else // { // int offsetX = (x / (int)Constants.RegionSize); // int offsetY = (y / (int)Constants.RegionSize); // offsetX *= (int)Constants.RegionSize; // offsetY *= (int)Constants.RegionSize; // // foreach (RegionData regionData in RegionConnections) // { // if (regionData.Offset.X == offsetX && regionData.Offset.Y == offsetY) // { // m_log.DebugFormat( // "[REGION COMBINER LARGE LAND CHANNEL]: Found region {0} at offset {1},{2}", // regionData.RegionScene.Name, offsetX, offsetY); // // return regionData.RegionScene.LandChannel.GetLandObject(x - offsetX, y - offsetY); // } // } // //ILandObject obj = new LandObject(UUID.Zero, false, RegData.RegionScene); // //obj.LandData.Name = "NO LAND"; // //return obj; // } // // m_log.DebugFormat("[REGION COMBINER LARGE LAND CHANNEL]: No region found at {0},{1}, returning null", x, y); // // return null; } public ILandObject GetLandObject(int localID) { // XXX: Possibly should be looking in every land channel, not just the root. return RootRegionLandChannel.GetLandObject(localID); } public ILandObject GetLandObject(float x, float y) { // m_log.DebugFormat("[BIGLANDTESTFLOAT]: <{0},{1}>", x, y); if (x > 0 && x <= (int)Constants.RegionSize && y > 0 && y <= (int)Constants.RegionSize) { return RootRegionLandChannel.GetLandObject(x, y); } else { int offsetX = (int)(x/(int) Constants.RegionSize); int offsetY = (int)(y/(int) Constants.RegionSize); offsetX *= (int) Constants.RegionSize; offsetY *= (int) Constants.RegionSize; foreach (RegionData regionData in RegionConnections) { if (regionData.Offset.X == offsetX && regionData.Offset.Y == offsetY) { // m_log.DebugFormat( // "[REGION COMBINER LARGE LAND CHANNEL]: Found region {0} at offset {1},{2}", // regionData.RegionScene.Name, offsetX, offsetY); return regionData.RegionScene.LandChannel.GetLandObject(x - offsetX, y - offsetY); } } // ILandObject obj = new LandObject(UUID.Zero, false, RegData.RegionScene); // obj.LandData.Name = "NO LAND"; // return obj; } // m_log.DebugFormat("[REGION COMBINER LARGE LAND CHANNEL]: No region found at {0},{1}, returning null", x, y); return null; } public bool IsForcefulBansAllowed() { return RootRegionLandChannel.IsForcefulBansAllowed(); } public void UpdateLandObject(int localID, LandData data) { RootRegionLandChannel.UpdateLandObject(localID, data); } public void Join(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id) { RootRegionLandChannel.Join(start_x, start_y, end_x, end_y, attempting_user_id); } public void Subdivide(int start_x, int start_y, int end_x, int end_y, UUID attempting_user_id) { RootRegionLandChannel.Subdivide(start_x, start_y, end_x, end_y, attempting_user_id); } public void ReturnObjectsInParcel(int localID, uint returnType, UUID[] agentIDs, UUID[] taskIDs, IClientAPI remoteClient) { RootRegionLandChannel.ReturnObjectsInParcel(localID, returnType, agentIDs, taskIDs, remoteClient); } public void setParcelObjectMaxOverride(overrideParcelMaxPrimCountDelegate overrideDel) { RootRegionLandChannel.setParcelObjectMaxOverride(overrideDel); } public void setSimulatorObjectMaxOverride(overrideSimulatorMaxPrimCountDelegate overrideDel) { RootRegionLandChannel.setSimulatorObjectMaxOverride(overrideDel); } public void SetParcelOtherCleanTime(IClientAPI remoteClient, int localID, int otherCleanTime) { RootRegionLandChannel.SetParcelOtherCleanTime(remoteClient, localID, otherCleanTime); } public void sendClientInitialLandInfo(IClientAPI remoteClient) { } #endregion } }
// // Authors: // Alan McGovern alan.mcgovern@gmail.com // Ben Motmans <ben.motmans@gmail.com> // Lucas Ontivero lucasontivero@gmail.com // // Copyright (C) 2006 Alan McGovern // Copyright (C) 2007 Ben Motmans // Copyright (C) 2014 Lucas Ontivero // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; namespace Open.Nat { internal sealed class UpnpNatDevice : NatDevice { internal readonly UpnpNatDeviceInfo DeviceInfo; private readonly SoapClient _soapClient; internal UpnpNatDevice(UpnpNatDeviceInfo deviceInfo) { Touch(); DeviceInfo = deviceInfo; _soapClient = new SoapClient(DeviceInfo.ServiceControlUri, DeviceInfo.ServiceType); } #if NET35 public override Task<IPAddress> GetExternalIPAsync() { NatDiscoverer.TraceSource.LogInfo("GetExternalIPAsync - Getting external IP address"); var message = new GetExternalIPAddressRequestMessage(); return _soapClient .InvokeAsync("GetExternalIPAddress", message.ToXml()) .TimeoutAfter(TimeSpan.FromSeconds(4)) .ContinueWith(task => { var responseData = task.Result; var response = new GetExternalIPAddressResponseMessage(responseData, DeviceInfo.ServiceType); return response.ExternalIPAddress; }); } #else public override async Task<IPAddress> GetExternalIPAsync() { NatDiscoverer.TraceSource.LogInfo("GetExternalIPAsync - Getting external IP address"); var message = new GetExternalIPAddressRequestMessage(); var responseData = await _soapClient .InvokeAsync("GetExternalIPAddress", message.ToXml()) .TimeoutAfter(TimeSpan.FromSeconds(4)); var response = new GetExternalIPAddressResponseMessage(responseData, DeviceInfo.ServiceType); return response.ExternalIPAddress; } #endif #if NET35 public override Task CreatePortMapAsync(Mapping mapping) { Guard.IsNotNull(mapping, "mapping"); if (mapping.PrivateIP.Equals(IPAddress.None)) mapping.PrivateIP = DeviceInfo.LocalAddress; NatDiscoverer.TraceSource.LogInfo("CreatePortMapAsync - Creating port mapping {0}", mapping); var message = new CreatePortMappingRequestMessage(mapping); return _soapClient .InvokeAsync("AddPortMapping", message.ToXml()) .TimeoutAfter(TimeSpan.FromSeconds(4)) .ContinueWith(task => { if (!task.IsFaulted) { RegisterMapping(mapping); } else { MappingException me = task.Exception.InnerException as MappingException; if (me == null) { throw task.Exception.InnerException; } switch (me.ErrorCode) { case UpnpConstants.OnlyPermanentLeasesSupported: NatDiscoverer.TraceSource.LogWarn( "Only Permanent Leases Supported - There is no warranty it will be closed"); mapping.Lifetime = 0; // We create the mapping anyway. It must be released on shutdown. mapping.LifetimeType = MappingLifetime.ForcedSession; CreatePortMapAsync(mapping); break; case UpnpConstants.SamePortValuesRequired: NatDiscoverer.TraceSource.LogWarn( "Same Port Values Required - Using internal port {0}", mapping.PrivatePort); mapping.PublicPort = mapping.PrivatePort; CreatePortMapAsync(mapping); break; case UpnpConstants.RemoteHostOnlySupportsWildcard: NatDiscoverer.TraceSource.LogWarn("Remote Host Only Supports Wildcard"); mapping.PublicIP = IPAddress.None; CreatePortMapAsync(mapping); break; case UpnpConstants.ExternalPortOnlySupportsWildcard: NatDiscoverer.TraceSource.LogWarn("External Port Only Supports Wildcard"); throw me; case UpnpConstants.ConflictInMappingEntry: NatDiscoverer.TraceSource.LogWarn("Conflict with an already existing mapping"); throw me; default: throw me; } } }); } #else public override async Task CreatePortMapAsync(Mapping mapping) { Guard.IsNotNull(mapping, "mapping"); if(mapping.PrivateIP.Equals(IPAddress.None)) mapping.PrivateIP = DeviceInfo.LocalAddress; NatDiscoverer.TraceSource.LogInfo("CreatePortMapAsync - Creating port mapping {0}", mapping); try { var message = new CreatePortMappingRequestMessage(mapping); await _soapClient .InvokeAsync("AddPortMapping", message.ToXml()) .TimeoutAfter(TimeSpan.FromSeconds(4)); RegisterMapping(mapping); } catch(MappingException me) { switch (me.ErrorCode) { case UpnpConstants.OnlyPermanentLeasesSupported: NatDiscoverer.TraceSource.LogWarn("Only Permanent Leases Supported - There is no warranty it will be closed"); mapping.Lifetime = 0; // We create the mapping anyway. It must be released on shutdown. mapping.LifetimeType = MappingLifetime.ForcedSession; CreatePortMapAsync(mapping); break; case UpnpConstants.SamePortValuesRequired: NatDiscoverer.TraceSource.LogWarn("Same Port Values Required - Using internal port {0}", mapping.PrivatePort); mapping.PublicPort = mapping.PrivatePort; CreatePortMapAsync(mapping); break; case UpnpConstants.RemoteHostOnlySupportsWildcard: NatDiscoverer.TraceSource.LogWarn("Remote Host Only Supports Wildcard"); mapping.PublicIP = IPAddress.None; CreatePortMapAsync(mapping); break; case UpnpConstants.ExternalPortOnlySupportsWildcard: NatDiscoverer.TraceSource.LogWarn("External Port Only Supports Wildcard"); throw; case UpnpConstants.ConflictInMappingEntry: NatDiscoverer.TraceSource.LogWarn("Conflict with an already existing mapping"); throw; default: throw; } } } #endif #if NET35 public override Task DeletePortMapAsync(Mapping mapping) { Guard.IsNotNull(mapping, "mapping"); if (mapping.PrivateIP.Equals(IPAddress.None)) mapping.PrivateIP = DeviceInfo.LocalAddress; NatDiscoverer.TraceSource.LogInfo("DeletePortMapAsync - Deleteing port mapping {0}", mapping); var message = new DeletePortMappingRequestMessage(mapping); return _soapClient .InvokeAsync("DeletePortMapping", message.ToXml()) .TimeoutAfter(TimeSpan.FromSeconds(4)) .ContinueWith(task => { if (!task.IsFaulted) { UnregisterMapping(mapping); } else { MappingException e = task.Exception.InnerException as MappingException; if (e != null && e.ErrorCode != UpnpConstants.NoSuchEntryInArray) throw e; } }); } #else public override async Task DeletePortMapAsync(Mapping mapping) { Guard.IsNotNull(mapping, "mapping"); if (mapping.PrivateIP.Equals(IPAddress.None)) mapping.PrivateIP = DeviceInfo.LocalAddress; NatDiscoverer.TraceSource.LogInfo("DeletePortMapAsync - Deleteing port mapping {0}", mapping); try { var message = new DeletePortMappingRequestMessage(mapping); await _soapClient .InvokeAsync("DeletePortMapping", message.ToXml()) .TimeoutAfter(TimeSpan.FromSeconds(4)); UnregisterMapping(mapping); } catch (MappingException e) { if(e.ErrorCode != UpnpConstants.NoSuchEntryInArray) throw; } } #endif #if NET35 public void GetGenericMappingAsync(int index, List<Mapping> mappings, TaskCompletionSource<IEnumerable<Mapping>> taskCompletionSource) { var message = new GetGenericPortMappingEntry(index); _soapClient .InvokeAsync("GetGenericPortMappingEntry", message.ToXml()) .TimeoutAfter(TimeSpan.FromSeconds(4)) .ContinueWith(task => { if (!task.IsFaulted) { var responseData = task.Result; var responseMessage = new GetPortMappingEntryResponseMessage(responseData, DeviceInfo.ServiceType, true); IPAddress internalClientIp; if (!IPAddress.TryParse(responseMessage.InternalClient, out internalClientIp)) { NatDiscoverer.TraceSource.LogWarn("InternalClient is not an IP address. Mapping ignored!"); } else { var mapping = new Mapping(responseMessage.Protocol , internalClientIp , responseMessage.InternalPort , responseMessage.ExternalPort , responseMessage.LeaseDuration , responseMessage.PortMappingDescription); mappings.Add(mapping); } GetGenericMappingAsync(index + 1, mappings, taskCompletionSource); } else { MappingException e = task.Exception.InnerException as MappingException; if (e == null) { throw task.Exception.InnerException; } if (e.ErrorCode == UpnpConstants.SpecifiedArrayIndexInvalid || e.ErrorCode == UpnpConstants.NoSuchEntryInArray) { // there are no more mappings taskCompletionSource.SetResult(mappings); return; } // DD-WRT Linux base router (and others probably) fails with 402-InvalidArgument when index is out of range if (e.ErrorCode == UpnpConstants.InvalidArguments) { NatDiscoverer.TraceSource.LogWarn("Router failed with 402-InvalidArgument. No more mappings is assumed."); taskCompletionSource.SetResult(mappings); return; } throw task.Exception.InnerException; } }); } public override Task<IEnumerable<Mapping>> GetAllMappingsAsync() { var taskCompletionSource = new TaskCompletionSource<IEnumerable<Mapping>>(); NatDiscoverer.TraceSource.LogInfo("GetAllMappingsAsync - Getting all mappings"); GetGenericMappingAsync(0, new List<Mapping>(), taskCompletionSource); return taskCompletionSource.Task; } #else public override async Task<IEnumerable<Mapping>> GetAllMappingsAsync() { var index = 0; var mappings = new List<Mapping>(); NatDiscoverer.TraceSource.LogInfo("GetAllMappingsAsync - Getting all mappings"); while (true) { try { var message = new GetGenericPortMappingEntry(index++); var responseData = await _soapClient .InvokeAsync("GetGenericPortMappingEntry", message.ToXml()) .TimeoutAfter(TimeSpan.FromSeconds(4)); var responseMessage = new GetPortMappingEntryResponseMessage(responseData, DeviceInfo.ServiceType, true); IPAddress internalClientIp; if(!IPAddress.TryParse(responseMessage.InternalClient, out internalClientIp)) { NatDiscoverer.TraceSource.LogWarn("InternalClient is not an IP address. Mapping ignored!"); continue; } var mapping = new Mapping(responseMessage.Protocol , internalClientIp , responseMessage.InternalPort , responseMessage.ExternalPort , responseMessage.LeaseDuration , responseMessage.PortMappingDescription); mappings.Add(mapping); } catch (MappingException e) { if (e.ErrorCode == UpnpConstants.SpecifiedArrayIndexInvalid || e.ErrorCode == UpnpConstants.NoSuchEntryInArray) break; // there are no more mappings // DD-WRT Linux base router (and others probably) fails with 402-InvalidArgument when index is out of range if (e.ErrorCode == UpnpConstants.InvalidArguments) { NatDiscoverer.TraceSource.LogWarn("Router failed with 402-InvalidArgument. No more mappings is assumed."); break; } throw; } } return mappings.ToArray(); } #endif #if NET35 public override Task<Mapping> GetSpecificMappingAsync(Protocol protocol, int port) { Guard.IsTrue(protocol == Protocol.Tcp || protocol == Protocol.Udp, "protocol"); Guard.IsInRange(port, 0, ushort.MaxValue, "port"); NatDiscoverer.TraceSource.LogInfo("GetSpecificMappingAsync - Getting mapping for protocol: {0} port: {1}", Enum.GetName(typeof(Protocol), protocol), port); var message = new GetSpecificPortMappingEntryRequestMessage(protocol, port); return _soapClient .InvokeAsync("GetSpecificPortMappingEntry", message.ToXml()) .TimeoutAfter(TimeSpan.FromSeconds(4)) .ContinueWith(task => { if (!task.IsFaulted) { var responseData = task.Result; var messageResponse = new GetPortMappingEntryResponseMessage(responseData, DeviceInfo.ServiceType, false); return new Mapping(messageResponse.Protocol , IPAddress.Parse(messageResponse.InternalClient) , messageResponse.InternalPort , messageResponse.ExternalPort , messageResponse.LeaseDuration , messageResponse.PortMappingDescription); } else { MappingException e = task.Exception.InnerException as MappingException; if (e != null && e.ErrorCode == UpnpConstants.NoSuchEntryInArray) return null; // DD-WRT Linux base router (and others probably) fails with 402-InvalidArgument // when no mapping is found in the mappings table if (e != null && e.ErrorCode == UpnpConstants.InvalidArguments) { NatDiscoverer.TraceSource.LogWarn("Router failed with 402-InvalidArgument. Mapping not found is assumed."); return null; } throw task.Exception.InnerException; } }); } #else public override async Task<Mapping> GetSpecificMappingAsync (Protocol protocol, int port) { Guard.IsTrue(protocol == Protocol.Tcp || protocol == Protocol.Udp, "protocol"); Guard.IsInRange(port, 0, ushort.MaxValue, "port"); NatDiscoverer.TraceSource.LogInfo("GetSpecificMappingAsync - Getting mapping for protocol: {0} port: {1}", Enum.GetName(typeof(Protocol), protocol), port); try { var message = new GetSpecificPortMappingEntryRequestMessage(protocol, port); var responseData = await _soapClient .InvokeAsync("GetSpecificPortMappingEntry", message.ToXml()) .TimeoutAfter(TimeSpan.FromSeconds(4)); var messageResponse = new GetPortMappingEntryResponseMessage(responseData, DeviceInfo.ServiceType, false); return new Mapping(messageResponse.Protocol , IPAddress.Parse(messageResponse.InternalClient) , messageResponse.InternalPort , messageResponse.ExternalPort , messageResponse.LeaseDuration , messageResponse.PortMappingDescription); } catch (MappingException e) { if (e.ErrorCode == UpnpConstants.NoSuchEntryInArray ) return null; // DD-WRT Linux base router (and others probably) fails with 402-InvalidArgument // when no mapping is found in the mappings table if (e.ErrorCode == UpnpConstants.InvalidArguments) { NatDiscoverer.TraceSource.LogWarn("Router failed with 402-InvalidArgument. Mapping not found is assumed."); return null; } throw; } } #endif public override string ToString() { //GetExternalIP is blocking and can throw exceptions, can't use it here. return String.Format( "EndPoint: {0}\nControl Url: {1}\nService Type: {2}\nLast Seen: {3}", DeviceInfo.HostEndPoint, DeviceInfo.ServiceControlUri, DeviceInfo.ServiceType, LastSeen); } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Web.Script.Serialization; using Microsoft.PythonTools.Analysis; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Parsing.Ast; using Microsoft.PythonTools.Projects; namespace Microsoft.PythonTools.Django.Analysis { [AnalysisExtensionName(Name)] partial class DjangoAnalyzer : IDisposable, IAnalysisExtension { internal const string Name = "django"; internal readonly Dictionary<string, TagInfo> _tags = new Dictionary<string, TagInfo>(); internal readonly Dictionary<string, TagInfo> _filters = new Dictionary<string, TagInfo>(); internal readonly IList<DjangoUrl> _urls = new List<DjangoUrl>(); private readonly HashSet<IPythonProjectEntry> _hookedEntries = new HashSet<IPythonProjectEntry>(); internal readonly Dictionary<string, TemplateVariables> _templateFiles = new Dictionary<string, TemplateVariables>(StringComparer.OrdinalIgnoreCase); private ConditionalWeakTable<Node, ContextMarker> _contextTable = new ConditionalWeakTable<Node, ContextMarker>(); private ConditionalWeakTable<Node, DeferredDecorator> _decoratorTable = new ConditionalWeakTable<Node, DeferredDecorator>(); private readonly Dictionary<string, GetTemplateAnalysisValue> _templateAnalysis = new Dictionary<string, GetTemplateAnalysisValue>(); private PythonAnalyzer _analyzer; internal static readonly Dictionary<string, string> _knownTags = MakeKnownTagsTable(); internal static readonly Dictionary<string, string> _knownFilters = MakeKnownFiltersTable(); public DjangoAnalyzer() { foreach (var tagName in _nestedEndTags) { _tags[tagName] = new TagInfo("", null); } } internal static readonly Dictionary<string, string> _nestedTags = new Dictionary<string, string>() { { "for", "endfor" }, { "if", "endif" }, { "ifequal", "endifequal" }, { "ifnotequal", "endifnotequal" }, { "ifchanged", "endifchanged" }, { "autoescape", "endautoescape" }, { "comment", "endcomment" }, { "filter", "endfilter" }, { "spaceless", "endspaceless" }, { "with", "endwith" }, { "empty", "endfor" }, { "else", "endif" }, }; internal static readonly HashSet<string> _nestedEndTags = MakeNestedEndTags(); internal static readonly HashSet<string> _nestedStartTags = MakeNestedStartTags(); internal static class Commands { public const string GetTags = "getTags"; public const string GetVariables = "getVariables"; public const string GetFilters = "getFilters"; public const string GetUrls = "getUrls"; public const string GetMembers = "getMembers"; } public string HandleCommand(string commandId, string body) { var serializer = new JavaScriptSerializer(); Dictionary<string, HashSet<AnalysisValue>> variables; switch (commandId) { case Commands.GetTags: return serializer.Serialize(_tags.Keys.ToArray()); case Commands.GetVariables: variables = GetVariablesForTemplateFile(body); if (variables != null) { return serializer.Serialize(variables.Keys.ToArray()); } return "[]"; case Commands.GetFilters: Dictionary<string, string> res = new Dictionary<string, string>(); foreach (var filter in _filters) { res[filter.Key] = filter.Value.Documentation; } return serializer.Serialize(res); case Commands.GetUrls: // GroupBy + Select have the same effect as Distinct with a long EqualityComparer return serializer.Serialize(_urls.GroupBy(url => url.FullName).Select(urlGroup => urlGroup.First())); case Commands.GetMembers: string[] args = serializer.Deserialize<string[]>(body); var file = args[0]; var varName = args[1]; variables = GetVariablesForTemplateFile(file); HashSet<AnalysisValue> values; IProjectEntry projEntry; if (_analyzer.TryGetProjectEntryByPath(file, out projEntry)) { var context = projEntry.AnalysisContext; if (variables != null && variables.TryGetValue(varName, out values)) { var newTags = new Dictionary<string, PythonMemberType>(); foreach (var member in values.SelectMany(item => item.GetAllMembers(context))) { string name = member.Key; PythonMemberType type, newType = GetMemberType(member.Value); if (!newTags.TryGetValue(name, out type)) { newTags[name] = newType; } else if (type != newType && type != PythonMemberType.Unknown && newType != PythonMemberType.Unknown) { newTags[name] = PythonMemberType.Multiple; } } var dict = newTags.ToDictionary(x => x.Key, x => x.Value.ToString().ToLowerInvariant()); return serializer.Serialize(dict); } } return "{}"; default: return String.Empty; } } private static PythonMemberType GetMemberType(IAnalysisSet values) { PythonMemberType newType = PythonMemberType.Unknown; foreach (var value in values) { if (value.MemberType == newType) { continue; } else if (newType == PythonMemberType.Unknown) { newType = value.MemberType; } else { newType = PythonMemberType.Multiple; break; } } return newType; } public void Register(PythonAnalyzer analyzer) { if (analyzer == null) { throw new ArgumentNullException("analyzer"); } _tags.Clear(); _filters.Clear(); _urls.Clear(); foreach (var entry in _hookedEntries) { entry.NewParseTree -= OnNewParseTree; } _hookedEntries.Clear(); _templateAnalysis.Clear(); _templateFiles.Clear(); _contextTable = new ConditionalWeakTable<Node, ContextMarker>(); _decoratorTable = new ConditionalWeakTable<Node, DeferredDecorator>(); foreach (var keyValue in _knownTags) { _tags[keyValue.Key] = new TagInfo(keyValue.Value, null); } foreach (var keyValue in _knownFilters) { _filters[keyValue.Key] = new TagInfo(keyValue.Value, null); } HookAnalysis(analyzer); _analyzer = analyzer; } private void OnNewParseTree(object sender, EventArgs e) { var entry = sender as IPythonProjectEntry; if (entry != null && _hookedEntries.Remove(entry)) { var removeTags = _tags.Where(kv => kv.Value.Entry == entry).Select(kv => kv.Key).ToList(); var removeFilters = _filters.Where(kv => kv.Value.Entry == entry).Select(kv => kv.Key).ToList(); foreach (var key in removeTags) { _tags.Remove(key); } foreach (var key in removeFilters) { _filters.Remove(key); } } } private void HookAnalysis(PythonAnalyzer analyzer) { analyzer.SpecializeFunction("django.template.loader", "render_to_string", RenderToStringProcessor, true); analyzer.SpecializeFunction("django.shortcuts", "render_to_response", RenderToStringProcessor, true); analyzer.SpecializeFunction("django.shortcuts", "render", RenderProcessor, true); analyzer.SpecializeFunction("django.contrib.gis.shortcuts", "render_to_kml", RenderToStringProcessor, true); analyzer.SpecializeFunction("django.contrib.gis.shortcuts", "render_to_kmz", RenderToStringProcessor, true); analyzer.SpecializeFunction("django.contrib.gis.shortcuts", "render_to_text", RenderToStringProcessor, true); analyzer.SpecializeFunction("django.template.Library", "filter", FilterProcessor, true); analyzer.SpecializeFunction("django.template.Library", "filter_function", FilterProcessor, true); analyzer.SpecializeFunction("django.template.Library", "tag", TagProcessor, true); analyzer.SpecializeFunction("django.template.Library", "tag_function", TagProcessor, true); analyzer.SpecializeFunction("django.template.Library", "assignment_tag", TagProcessor, true); analyzer.SpecializeFunction("django.template.Library", "simple_tag", TagProcessor, true); // Django >= 1.9 analyzer.SpecializeFunction("django.template.library", "import_library", "django.template.library.Library", true); // Django < 1.9 analyzer.SpecializeFunction("django.template.base", "import_library", "django.template.base.Library", true); analyzer.SpecializeFunction("django.template.base.Parser", "parse", ParseProcessor, true); analyzer.SpecializeFunction("django.template.loader", "get_template", GetTemplateProcessor, true); analyzer.SpecializeFunction("django.template.context", "Context", ContextClassProcessor, true); analyzer.SpecializeFunction("django.template", "RequestContext", RequestContextClassProcessor, true); analyzer.SpecializeFunction("django.template.context", "RequestContext", RequestContextClassProcessor, true); analyzer.SpecializeFunction("django.template.base.Template", "render", TemplateRenderProcessor, true); // View specializers analyzer.SpecializeFunction("django.views.generic.detail.DetailView", "as_view", DetailViewProcessor, true); analyzer.SpecializeFunction("django.views.generic.DetailView", "as_view", DetailViewProcessor, true); analyzer.SpecializeFunction("django.views.generic.list.ListView", "as_view", ListViewProcessor, true); analyzer.SpecializeFunction("django.views.generic.ListView", "as_view", ListViewProcessor, true); // Urls specializers analyzer.SpecializeFunction("django.conf.urls", "url", UrlProcessor, true); analyzer.SpecializeFunction("django.urls", "url", UrlProcessor, true); analyzer.SpecializeFunction("django.urls", "path", UrlProcessor, true); } private IAnalysisSet ParseProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) { // def parse(self, parse_until=None): // We want to find closing tags here passed to parse_until... if (args.Length >= 2) { foreach (var tuple in args[1]) { foreach (var indexValue in tuple.GetItems()) { var values = indexValue.Value; foreach (var value in values) { var str = value.GetConstantValueAsString(); if (str != null) { RegisterTag(unit.ProjectEntry, _tags, str); } } } } } return AnalysisSet.Empty; } #region IDisposable Members public void Dispose() { _filters.Clear(); _tags.Clear(); foreach (var entry in _hookedEntries) { entry.NewParseTree -= OnNewParseTree; } _hookedEntries.Clear(); _templateAnalysis.Clear(); _templateFiles.Clear(); } #endregion /// <summary> /// Specializes "DetailView.as_view" /// </summary> private IAnalysisSet DetailViewProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) { return ViewProcessor(node, unit, args, keywordArgNames, "_details.html"); } /// <summary> /// Specializes "ListView.as_view" /// </summary> private IAnalysisSet ListViewProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) { return ViewProcessor(node, unit, args, keywordArgNames, "_list.html"); } private IAnalysisSet ViewProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames, string defaultTemplateNameSuffix) { var templateNames = GetArg(args, keywordArgNames, "template_name", -1, AnalysisSet.Empty) .Select(v => v.GetConstantValueAsString()) .Where(s => !string.IsNullOrEmpty(s)) .ToList(); var templateNameSuffix = GetArg(args, keywordArgNames, "template_name_suffix", -1, AnalysisSet.Empty) .Select(v => v.GetConstantValueAsString()) .Where(s => !string.IsNullOrEmpty(s)) .ToList(); var contextObjName = GetArg(args, keywordArgNames, "context_object_name", -1, AnalysisSet.Empty) .Select(v => v.GetConstantValueAsString()) .Where(s => !string.IsNullOrEmpty(s)) .ToList(); var model = GetArg(args, keywordArgNames, "model", -1); // TODO: Support this (this requires some analyis improvements as currently we // typically don't get useful values for queryset // Right now, queryset only flows into the template if template_name // is also specified. var querySet = GetArg(args, keywordArgNames, "queryset", -1); if (templateNames.Any()) { foreach (var templateName in templateNames) { AddViewTemplate(unit, model, querySet, contextObjName, templateName); } } else if (model != null) { // template name is [app]/[modelname]_[template_name_suffix] string appName; int firstDot = unit.ProjectEntry.ModuleName.IndexOf('.'); if (firstDot != -1) { appName = unit.ProjectEntry.ModuleName.Substring(0, firstDot); } else { appName = unit.ProjectEntry.ModuleName; } foreach (var modelInst in model) { string baseName = appName + "/" + modelInst.Name.ToLowerInvariant(); foreach (var suffix in templateNameSuffix.DefaultIfEmpty(defaultTemplateNameSuffix)) { AddViewTemplate(unit, model, querySet, contextObjName, baseName + suffix); } } } return AnalysisSet.Empty; } private void AddViewTemplate( AnalysisUnit unit, IAnalysisSet model, IAnalysisSet querySet, IEnumerable<string> contextObjName, string templateName ) { TemplateVariables tags; if (!_templateFiles.TryGetValue(templateName, out tags)) { _templateFiles[templateName] = tags = new TemplateVariables(); } if (querySet != null) { foreach (var name in contextObjName) { tags.UpdateVariable(name, unit, AnalysisSet.Empty); } } else if (model != null) { foreach (var modelInst in model) { foreach (var name in contextObjName.DefaultIfEmpty(modelInst.Name.ToLowerInvariant())) { tags.UpdateVariable(name, unit, modelInst.GetInstanceType()); } } } } private IAnalysisSet UrlProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) { // No completion if the url has no name (reverse matching not possible) if (keywordArgNames.Length == 0) { return AnalysisSet.Empty; } IAnalysisSet urlNames = GetArg(args, keywordArgNames, "name", -1); if (urlNames == null) { // The kwargs do not contain a name arg return AnalysisSet.Empty; } string urlName = urlNames.First().GetConstantValueAsString(); string urlRegex = args.First().First().GetConstantValueAsString(); if (urlName != null && urlRegex != null) { _urls.Add(new DjangoUrl(urlName, urlRegex)); } return AnalysisSet.Empty; } private static void GetStringArguments(HashSet<string> arguments, IAnalysisSet arg) { foreach (var value in arg) { string templateName = value.GetConstantValueAsString(); if (templateName != null) { arguments.Add(templateName); } } } private IAnalysisSet FilterProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) { return ProcessTags(node, unit, args, keywordArgNames, _filters); } private IAnalysisSet TagProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) { return ProcessTags(node, unit, args, keywordArgNames, _tags); } class DeferredDecorator : AnalysisValue { private readonly DjangoAnalyzer _analyzer; private readonly IAnalysisSet _name; private readonly Dictionary<string, TagInfo> _tags; public DeferredDecorator(DjangoAnalyzer analyzer, IAnalysisSet name, Dictionary<string, TagInfo> tags) { _analyzer = analyzer; _name = name; _tags = tags; } public override IAnalysisSet Call(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) { _analyzer.ProcessTags(node, unit, new[] { AnalysisSet.Empty, _name, args[0] }, NameExpression.EmptyArray, _tags); return AnalysisSet.Empty; } } private IAnalysisSet ProcessTags(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames, Dictionary<string, TagInfo> tags) { if (args.Length >= 3) { // library.filter(name, value) foreach (var name in args[1]) { var constName = name.GetConstantValue(); if (constName == Type.Missing) { if (name.Name != null) { RegisterTag(unit.ProjectEntry, tags, name.Name, name.Documentation); } } else { var strName = name.GetConstantValueAsString(); if (strName != null) { RegisterTag(unit.ProjectEntry, tags, strName); } } } foreach (var func in args[2]) { // TODO: Find a better node var parser = unit.FindAnalysisValueByName(node, "django.template.base.Parser"); if (parser != null) { func.Call(node, unit, new[] { parser, AnalysisSet.Empty }, NameExpression.EmptyArray); } } } else if (args.Length >= 2) { // library.filter(value) foreach (var name in args[1]) { string tagName = name.Name ?? name.GetConstantValueAsString(); if (tagName != null) { RegisterTag(unit.ProjectEntry, tags, tagName, name.Documentation); } if (name.MemberType != PythonMemberType.Constant) { var parser = unit.FindAnalysisValueByName(node, "django.template.base.Parser"); if (parser != null) { name.Call(node, unit, new[] { parser, AnalysisSet.Empty }, NameExpression.EmptyArray); } } } } else if (args.Length == 1) { foreach (var name in args[0]) { if (name.MemberType == PythonMemberType.Constant) { // library.filter('name') DeferredDecorator dec; if (!_decoratorTable.TryGetValue(node, out dec)) { dec = new DeferredDecorator(this, name, tags); _decoratorTable.Add(node, dec); } return dec; } else if (name.Name != null) { // library.filter RegisterTag(unit.ProjectEntry, tags, name.Name, name.Documentation); } } } return AnalysisSet.Empty; } private void RegisterTag(IPythonProjectEntry entry, Dictionary<string, TagInfo> tags, string name, string documentation = null) { TagInfo tag; if (!tags.TryGetValue(name, out tag) || (String.IsNullOrWhiteSpace(tag.Documentation) && !String.IsNullOrEmpty(documentation))) { tags[name] = tag = new TagInfo(documentation, entry); if (entry != null && _hookedEntries.Add(entry)) { entry.NewParseTree += OnNewParseTree; } } } private IAnalysisSet RenderToStringProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) { var names = GetArg(args, keywordArgNames, "template_name", 0); var context = GetArg(args, keywordArgNames, "context_instance", 2); var dictArgs = context == null ? GetArg(args, keywordArgNames, "dictionary", 1) : null; if (dictArgs != null || context != null) { foreach (var name in names.Select(n => n.GetConstantValueAsString()).Where(n => !string.IsNullOrEmpty(n))) { AddTemplateMapping(unit, name, dictArgs, context); } } return AnalysisSet.Empty; } private IAnalysisSet RenderProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) { var names = GetArg(args, keywordArgNames, "template_name", 1); var context = GetArg(args, keywordArgNames, "context_instance", 3); var dictArgs = context == null ? GetArg(args, keywordArgNames, "dictionary", 2) : null; if (dictArgs != null || context != null) { foreach (var name in names.Select(n => n.GetConstantValueAsString()).Where(n => !string.IsNullOrEmpty(n))) { AddTemplateMapping(unit, name, dictArgs, context); } } return AnalysisSet.Empty; } private void AddTemplateMapping( AnalysisUnit unit, string filename, IEnumerable<AnalysisValue> dictArgs, IEnumerable<AnalysisValue> context ) { TemplateVariables tags; if (!_templateFiles.TryGetValue(filename, out tags)) { _templateFiles[filename] = tags = new TemplateVariables(); } IEnumerable<KeyValuePair<IAnalysisSet, IAnalysisSet>> items = null; if (context != null) { items = context.OfType<ContextMarker>() .SelectMany(ctxt => ctxt.Arguments.SelectMany(v => v.GetItems())); } else if (dictArgs != null) { items = dictArgs.SelectMany(v => v.GetItems()); } if (items != null) { foreach (var keyValue in items) { foreach (var key in keyValue.Key) { var keyName = key.GetConstantValueAsString(); if (keyName != null) { tags.UpdateVariable(keyName, unit, keyValue.Value); } } } } } class GetTemplateAnalysisValue : AnalysisValue { public readonly string Filename; public readonly TemplateRenderMethod RenderMethod; public readonly DjangoAnalyzer Analyzer; public GetTemplateAnalysisValue(DjangoAnalyzer analyzer, string name) { Analyzer = analyzer; Filename = name; RenderMethod = new TemplateRenderMethod(this); } public override IAnalysisSet GetMember(Node node, AnalysisUnit unit, string name) { if (name == "render") { return RenderMethod; } return base.GetMember(node, unit, name); } } class TemplateRenderMethod : AnalysisValue { public readonly GetTemplateAnalysisValue GetTemplateValue; public TemplateRenderMethod(GetTemplateAnalysisValue getTemplateAnalysisValue) { this.GetTemplateValue = getTemplateAnalysisValue; } public override IAnalysisSet Call(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) { if (args.Length == 1) { string filename = GetTemplateValue.Filename; GetTemplateValue.Analyzer.AddTemplateMapping(unit, filename, null, args[0]); } return base.Call(node, unit, args, keywordArgNames); } } private IAnalysisSet GetTemplateProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) { var res = AnalysisSet.Empty; if (args.Length >= 1) { foreach (var filename in args[0]) { var file = filename.GetConstantValueAsString(); if (file != null) { GetTemplateAnalysisValue value; if (!_templateAnalysis.TryGetValue(file, out value)) { _templateAnalysis[file] = value = new GetTemplateAnalysisValue(this, file); } res = res.Add(value); } } } return res; } class ContextMarker : AnalysisValue { public readonly HashSet<AnalysisValue> Arguments; public ContextMarker() { Arguments = new HashSet<AnalysisValue>(); } public override IEnumerable<KeyValuePair<IAnalysisSet, IAnalysisSet>> GetItems() { return Arguments.SelectMany(av => av.GetItems()); } } private IAnalysisSet ContextClassProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) { var dict = GetArg(args, keywordArgNames, "dict_", 0); if (dict != null && dict.Any()) { ContextMarker contextValue; if (!_contextTable.TryGetValue(node, out contextValue)) { contextValue = new ContextMarker(); _contextTable.Add(node, contextValue); } contextValue.Arguments.UnionWith(dict); return contextValue; } return AnalysisSet.Empty; } private IAnalysisSet RequestContextClassProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) { var dict = GetArg(args, keywordArgNames, "dict_", 1); if (dict != null) { return ContextClassProcessor(node, unit, new[] { dict }, NameExpression.EmptyArray); } return AnalysisSet.Empty; } private IAnalysisSet TemplateRenderProcessor(Node node, AnalysisUnit unit, IAnalysisSet[] args, NameExpression[] keywordArgNames) { if (args.Length == 2) { foreach (var templateValue in args[0].OfType<GetTemplateAnalysisValue>()) { AddTemplateMapping(unit, templateValue.Filename, null, args[1]); } } return AnalysisSet.Empty; } private static IAnalysisSet GetArg( IAnalysisSet[] args, NameExpression[] keywordArgNames, string name, int index, IAnalysisSet defaultValue = null ) { for (int i = 0, j = args.Length - keywordArgNames.Length; i < keywordArgNames.Length && j < args.Length; ++i, ++j) { var kwArg = keywordArgNames[i]; if (kwArg == null) { Debug.Fail("Null keyword argument"); } else if (kwArg.Name == name) { return args[j]; } } if (0 <= index && index < args.Length) { return args[index]; } return defaultValue; } public Dictionary<string, HashSet<AnalysisValue>> GetVariablesForTemplateFile(string filename) { string curLevel = filename; // is C:\Fob\Oar\Baz\fob.html string curPath = filename = Path.GetFileName(filename); // is fob.html for (; ; ) { string curFilename = filename.Replace('\\', '/'); TemplateVariables res; if (_templateFiles.TryGetValue(curFilename, out res)) { return res.GetAllValues(); } curLevel = Path.GetDirectoryName(curLevel); // C:\Fob\Oar\Baz\fob.html gets us C:\Fob\Oar\Baz var fn2 = Path.GetFileName(curLevel); // Gets us Baz if (String.IsNullOrEmpty(fn2)) { break; } curPath = Path.Combine(fn2, curPath); // Get us Baz\fob.html filename = curPath; } return null; } private static HashSet<string> MakeNestedEndTags() { HashSet<string> res = new HashSet<string>(); foreach (var value in _nestedTags.Values) { res.Add(value); } return res; } private static HashSet<string> MakeNestedStartTags() { HashSet<string> res = new HashSet<string>(); foreach (var key in _nestedTags.Keys) { res.Add(key); } return res; } } }
//----------------------------------------------------------------------- // <copyright file="FlowBufferSpec.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using Akka.Streams.Dsl; using Akka.Streams.TestKit; using Akka.Streams.TestKit.Tests; using Akka.Util.Internal; using FluentAssertions; using Xunit; using Xunit.Abstractions; namespace Akka.Streams.Tests.Dsl { public class FlowBufferSpec : AkkaSpec { private ActorMaterializer Materializer { get; } public FlowBufferSpec(ITestOutputHelper helper) : base(helper) { var settings = ActorMaterializerSettings.Create(Sys).WithInputBuffer(1, 1); Materializer = ActorMaterializer.Create(Sys, settings); } [Fact] public void Buffer_must_pass_elements_through_normally_in_backpressured_mode() { var future = Source.From(Enumerable.Range(1, 1000)) .Buffer(100, OverflowStrategy.Backpressure) .Grouped(1001) .RunWith(Sink.First<IEnumerable<int>>(), Materializer); future.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); future.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1,1000)); } [Fact] public void Buffer_must_pass_elements_through_normally_in_backpressured_mode_with_buffer_size_one() { var future = Source.From(Enumerable.Range(1, 1000)) .Buffer(1, OverflowStrategy.Backpressure) .Grouped(1001) .RunWith(Sink.First<IEnumerable<int>>(), Materializer); future.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); future.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 1000)); } [Fact] public void Buffer_must_pass_elements_through_a_chain_of_backpressured_buffers_of_different_size() { this.AssertAllStagesStopped(() => { var future = Source.From(Enumerable.Range(1, 1000)) .Buffer(1, OverflowStrategy.Backpressure) .Buffer(10, OverflowStrategy.Backpressure) .Buffer(256, OverflowStrategy.Backpressure) .Buffer(1, OverflowStrategy.Backpressure) .Buffer(5, OverflowStrategy.Backpressure) .Buffer(128, OverflowStrategy.Backpressure) .Grouped(1001) .RunWith(Sink.First<IEnumerable<int>>(), Materializer); future.Wait(TimeSpan.FromSeconds(3)).Should().BeTrue(); future.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 1000)); }, Materializer); } [Fact] public void Buffer_must_accept_elements_that_fit_in_the_buffer_while_downstream_is_silent() { var publisher = TestPublisher.CreateProbe<int>(this); var subscriber = TestSubscriber.CreateManualProbe<int>(this); Source.FromPublisher(publisher) .Buffer(100, OverflowStrategy.Backpressure) .To(Sink.FromSubscriber(subscriber)) .Run(Materializer); var sub = subscriber.ExpectSubscription(); // Fill up buffer Enumerable.Range(1, 100).ForEach(i => publisher.SendNext(i)); // drain Enumerable.Range(1, 100).ForEach(i => { sub.Request(1); subscriber.ExpectNext(i); }); sub.Cancel(); } [Fact] public void Buffer_must_drop_head_elements_if_buffer_is_full_and_configured_so() { var publisher = TestPublisher.CreateProbe<int>(this); var subscriber = TestSubscriber.CreateManualProbe<int>(this); Source.FromPublisher(publisher) .Buffer(100, OverflowStrategy.DropHead) .To(Sink.FromSubscriber(subscriber)) .Run(Materializer); var sub = subscriber.ExpectSubscription(); // Fill up buffer Enumerable.Range(1, 200).ForEach(i => publisher.SendNext(i)); // The next request would be otherwise in race with the last onNext in the above loop subscriber.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); // drain for (var i = 101; i <= 200; i++) { sub.Request(1); subscriber.ExpectNext(i); } sub.Request(1); subscriber.ExpectNoMsg(TimeSpan.FromSeconds(1)); publisher.SendNext(-1); sub.Request(1); subscriber.ExpectNext(-1); sub.Cancel(); } [Fact] public void Buffer_must_drop_tail_elements_if_buffer_is_full_and_configured_so() { var publisher = TestPublisher.CreateProbe<int>(this); var subscriber = TestSubscriber.CreateManualProbe<int>(this); Source.FromPublisher(publisher) .Buffer(100, OverflowStrategy.DropTail) .To(Sink.FromSubscriber(subscriber)) .Run(Materializer); var sub = subscriber.ExpectSubscription(); // Fill up buffer Enumerable.Range(1, 200).ForEach(i => publisher.SendNext(i)); // The next request would be otherwise in race with the last onNext in the above loop subscriber.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); // drain for (var i = 1; i <= 99; i++) { sub.Request(1); subscriber.ExpectNext(i); } sub.Request(1); subscriber.ExpectNext(200); sub.Request(1); subscriber.ExpectNoMsg(TimeSpan.FromSeconds(1)); publisher.SendNext(-1); sub.Request(1); subscriber.ExpectNext(-1); sub.Cancel(); } [Fact] public void Buffer_must_drop_all_elements_if_buffer_is_full_and_configured_so() { var publisher = TestPublisher.CreateProbe<int>(this); var subscriber = TestSubscriber.CreateManualProbe<int>(this); Source.FromPublisher(publisher) .Buffer(100, OverflowStrategy.DropBuffer) .To(Sink.FromSubscriber(subscriber)) .Run(Materializer); var sub = subscriber.ExpectSubscription(); // Fill up buffer Enumerable.Range(1, 150).ForEach(i => publisher.SendNext(i)); // The next request would be otherwise in race with the last onNext in the above loop subscriber.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); // drain for (var i = 101; i <= 150; i++) { sub.Request(1); subscriber.ExpectNext(i); } sub.Request(1); subscriber.ExpectNoMsg(TimeSpan.FromSeconds(1)); publisher.SendNext(-1); sub.Request(1); subscriber.ExpectNext(-1); sub.Cancel(); } [Fact] public void Buffer_must_drop_new_elements_if_buffer_is_full_and_configured_so() { var t = this.SourceProbe<int>() .Buffer(100, OverflowStrategy.DropNew) .ToMaterialized(this.SinkProbe<int>(), Keep.Both) .Run(Materializer); var publisher = t.Item1; var subscriber = t.Item2; subscriber.EnsureSubscription(); // Fill up buffer Enumerable.Range(1, 150).ForEach(i => publisher.SendNext(i)); // The next request would be otherwise in race with the last onNext in the above loop subscriber.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); // drain for (var i = 1; i <= 100; i++) subscriber.RequestNext(i); subscriber.Request(1); subscriber.ExpectNoMsg(TimeSpan.FromSeconds(1)); publisher.SendNext(-1); subscriber.RequestNext(-1); subscriber.Cancel(); } [Fact] public void Buffer_must_fail_upstream_if_buffer_is_full_and_configured_so() { this.AssertAllStagesStopped(() => { var publisher = TestPublisher.CreateProbe<int>(this); var subscriber = TestSubscriber.CreateManualProbe<int>(this); Source.FromPublisher(publisher) .Buffer(100, OverflowStrategy.Fail) .To(Sink.FromSubscriber(subscriber)) .Run(Materializer); var sub = subscriber.ExpectSubscription(); // Fill up buffer Enumerable.Range(1, 100).ForEach(i => publisher.SendNext(i)); // drain for (var i = 1; i <= 10; i++) { sub.Request(1); subscriber.ExpectNext(i); } // overflow the buffer for (var i = 101; i <= 111; i++) publisher.SendNext(i); publisher.ExpectCancellation(); var actualError = subscriber.ExpectError(); actualError.Should().BeOfType<BufferOverflowException>(); actualError.Message.Should().Be("Buffer overflow (max capacity was 100)"); }, Materializer); } [Theory] [InlineData(OverflowStrategy.DropHead)] [InlineData(OverflowStrategy.DropTail)] [InlineData(OverflowStrategy.DropBuffer)] public void Buffer_must_work_with_strategy_if_bugger_size_of_one(OverflowStrategy strategy) { var publisher = TestPublisher.CreateProbe<int>(this); var subscriber = TestSubscriber.CreateManualProbe<int>(this); Source.FromPublisher(publisher) .Buffer(1, strategy) .To(Sink.FromSubscriber(subscriber)) .Run(Materializer); var sub = subscriber.ExpectSubscription(); // Fill up buffer Enumerable.Range(1, 200).ForEach(i => publisher.SendNext(i)); // The request below is in race otherwise with the onNext(200) above subscriber.ExpectNoMsg(TimeSpan.FromMilliseconds(500)); sub.Request(1); subscriber.ExpectNext(200); publisher.SendNext(-1); sub.Request(1); subscriber.ExpectNext(-1); sub.Cancel(); } } }
using NBitcoin; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; using WalletWasabi.CoinJoin.Common.Models; using WalletWasabi.Logging; using WalletWasabi.Tor.Http; using WalletWasabi.Tor.Http.Extensions; using WalletWasabi.Tor.Socks5.Exceptions; using WalletWasabi.WebClients.Wasabi; using static WalletWasabi.Crypto.SchnorrBlinding; using UnblindedSignature = WalletWasabi.Crypto.UnblindedSignature; namespace WalletWasabi.CoinJoin.Client.Clients { public abstract class AliceClientBase : IDisposable { private volatile bool _disposedValue = false; // To detect redundant calls protected AliceClientBase( long roundId, IEnumerable<BitcoinAddress> registeredAddresses, IEnumerable<Requester> requesters, Network network, IHttpClient httpClient) { TorClient = httpClient; RoundId = roundId; RegisteredAddresses = registeredAddresses.ToArray(); Requesters = requesters.ToArray(); Network = network; } public Guid UniqueId { get; private set; } public long RoundId { get; } public Network Network { get; } public BitcoinAddress[] RegisteredAddresses { get; } public Requester[] Requesters { get; } public IHttpClient TorClient { get; } public static async Task<AliceClient4> CreateNewAsync( long roundId, IEnumerable<BitcoinAddress> registeredAddresses, IEnumerable<PubKey> signerPubKeys, IEnumerable<Requester> requesters, Network network, BitcoinAddress changeOutput, IEnumerable<BlindedOutputWithNonceIndex> blindedOutputScriptHashes, IEnumerable<InputProofModel> inputs, IHttpClient httpClient) { var request = new InputsRequest4 { RoundId = roundId, BlindedOutputScripts = blindedOutputScriptHashes, ChangeOutputAddress = changeOutput, Inputs = inputs }; var client = new AliceClient4(roundId, registeredAddresses, signerPubKeys, requesters, network, httpClient); try { // Correct it if forgot to set. if (request.RoundId != roundId) { if (request.RoundId == 0) { request.RoundId = roundId; } else { throw new NotSupportedException($"InputRequest {nameof(roundId)} does not match to the provided {nameof(roundId)}: {request.RoundId} != {roundId}."); } } using HttpResponseMessage response = await client.TorClient.SendAsync(HttpMethod.Post, $"/api/v{WasabiClient.ApiVersion}/btc/chaumiancoinjoin/inputs/", request.ToHttpStringContent()).ConfigureAwait(false); if (response.StatusCode != HttpStatusCode.OK) { await response.ThrowRequestExceptionFromContentAsync().ConfigureAwait(false); } var inputsResponse = await response.Content.ReadAsJsonAsync<InputsResponse>().ConfigureAwait(false); if (inputsResponse.RoundId != roundId) // This should never happen. If it does, that's a bug in the coordinator. { throw new NotSupportedException($"Coordinator assigned us to the wrong round: {inputsResponse.RoundId}. Requested round: {roundId}."); } client.UniqueId = inputsResponse.UniqueId; Logger.LogInfo($"Round ({client.RoundId}), Alice ({client.UniqueId}): Registered {request.Inputs.Count()} inputs."); return client; } catch { client?.Dispose(); throw; } } public async Task<(RoundPhase currentPhase, IEnumerable<ActiveOutput> activeOutputs)> PostConfirmationAsync() { using HttpResponseMessage response = await TorClient.SendAsync(HttpMethod.Post, $"/api/v{WasabiClient.ApiVersion}/btc/chaumiancoinjoin/confirmation?uniqueId={UniqueId}&roundId={RoundId}").ConfigureAwait(false); if (response.StatusCode != HttpStatusCode.OK) { await response.ThrowRequestExceptionFromContentAsync().ConfigureAwait(false); } ConnectionConfirmationResponse resp = await response.Content.ReadAsJsonAsync<ConnectionConfirmationResponse>().ConfigureAwait(false); Logger.LogInfo($"Round ({RoundId}), Alice ({UniqueId}): Confirmed connection. Phase: {resp.CurrentPhase}."); var activeOutputs = new List<ActiveOutput>(); if (resp.BlindedOutputSignatures is { } && resp.BlindedOutputSignatures.Any()) { var unblindedSignatures = new List<UnblindedSignature>(); var blindedSignatures = resp.BlindedOutputSignatures.ToArray(); for (int i = 0; i < blindedSignatures.Length; i++) { uint256 blindedSignature = blindedSignatures[i]; Requester requester = Requesters[i]; UnblindedSignature unblindedSignature = requester.UnblindSignature(blindedSignature); var address = RegisteredAddresses[i]; uint256 outputScriptHash = new uint256(NBitcoin.Crypto.Hashes.SHA256(address.ScriptPubKey.ToBytes())); PubKey signerPubKey = GetSignerPubKey(i); if (!VerifySignature(outputScriptHash, unblindedSignature, signerPubKey)) { throw new NotSupportedException($"Coordinator did not sign the blinded output properly for level: {i}."); } unblindedSignatures.Add(unblindedSignature); } for (int i = 0; i < Math.Min(unblindedSignatures.Count, RegisteredAddresses.Length); i++) { var sig = unblindedSignatures[i]; var addr = RegisteredAddresses[i]; var lvl = i; var actOut = new ActiveOutput(addr, sig, lvl); activeOutputs.Add(actOut); } } return (resp.CurrentPhase, activeOutputs); } protected abstract PubKey GetSignerPubKey(int i); public async Task PostUnConfirmationAsync() { using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(3))) { try { using HttpResponseMessage response = await TorClient.SendAsync(HttpMethod.Post, $"/api/v{WasabiClient.ApiVersion}/btc/chaumiancoinjoin/unconfirmation?uniqueId={UniqueId}&roundId={RoundId}", cancel: cts.Token).ConfigureAwait(false); if (response.StatusCode is HttpStatusCode.BadRequest or HttpStatusCode.Gone) // Otherwise maybe some internet connection issue there's. Let's consider that as timed out. { await response.ThrowRequestExceptionFromContentAsync().ConfigureAwait(false); } } catch (Exception ex) when (ex is OperationCanceledException or TimeoutException) // If could not do it within 3 seconds then it'll likely time out and take it as unconfirmed. { return; } catch (HttpRequestException ex) when (ex.InnerException is TorException) // If some Tor connection issue then it'll likely time out and take it as unconfirmed. { return; } } Logger.LogInfo($"Round ({RoundId}), Alice ({UniqueId}): Unconfirmed connection."); } public async Task<Transaction> GetUnsignedCoinJoinAsync() { using HttpResponseMessage response = await TorClient.SendAsync(HttpMethod.Get, $"/api/v{WasabiClient.ApiVersion}/btc/chaumiancoinjoin/coinjoin?uniqueId={UniqueId}&roundId={RoundId}").ConfigureAwait(false); if (response.StatusCode != HttpStatusCode.OK) { await response.ThrowRequestExceptionFromContentAsync().ConfigureAwait(false); } var coinjoinHex = await response.Content.ReadAsJsonAsync<string>().ConfigureAwait(false); Transaction coinJoin = Transaction.Parse(coinjoinHex, Network.Main); Logger.LogInfo($"Round ({RoundId}), Alice ({UniqueId}): Acquired unsigned CoinJoin: {coinJoin.GetHash()}."); return coinJoin; } public async Task PostSignaturesAsync(IDictionary<int, WitScript> signatures) { var myDic = signatures.ToDictionary(signature => signature.Key, signature => signature.Value.ToString()); var jsonSignatures = JsonConvert.SerializeObject(myDic, Formatting.None); var signatureRequestContent = new StringContent(jsonSignatures, Encoding.UTF8, "application/json"); using HttpResponseMessage response = await TorClient.SendAsync(HttpMethod.Post, $"/api/v{WasabiClient.ApiVersion}/btc/chaumiancoinjoin/signatures?uniqueId={UniqueId}&roundId={RoundId}", signatureRequestContent).ConfigureAwait(false); if (response.StatusCode != HttpStatusCode.NoContent) { await response.ThrowRequestExceptionFromContentAsync().ConfigureAwait(false); } Logger.LogInfo($"Round ({RoundId}), Alice ({UniqueId}): Posted {signatures.Count} signatures."); } protected virtual void Dispose(bool disposing) { if (!_disposedValue) { if (disposing) { (TorClient as IDisposable)?.Dispose(); } _disposedValue = true; } } // This code added to correctly implement the disposable pattern. public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.Network; namespace Microsoft.WindowsAzure.Management.Network { /// <summary> /// The Network Management API includes operations for managing the Virtual /// IPs for your deployment. /// </summary> internal partial class VirtualIPOperations : IServiceOperations<NetworkManagementClient>, IVirtualIPOperations { /// <summary> /// Initializes a new instance of the VirtualIPOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal VirtualIPOperations(NetworkManagementClient client) { this._client = client; } private NetworkManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Network.NetworkManagementClient. /// </summary> public NetworkManagementClient Client { get { return this._client; } } /// <summary> /// The Add Virtual IP operation adds a logical Virtual IP to the /// deployment. /// </summary> /// <param name='serviceName'> /// Required. The name of the hosted service that contains the given /// deployment. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment where the logical Virtual IP /// is to be added. /// </param> /// <param name='virtualIPName'> /// Required. The name of the logical Virtual IP to be added. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task<OperationStatusResponse> AddAsync(string serviceName, string deploymentName, string virtualIPName, CancellationToken cancellationToken) { NetworkManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("deploymentName", deploymentName); tracingParameters.Add("virtualIPName", virtualIPName); TracingAdapter.Enter(invocationId, this, "AddAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse response = await client.VirtualIPs.BeginAddingAsync(serviceName, deploymentName, virtualIPName, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == OperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.Status != OperationStatus.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } return result; } /// <summary> /// The Begin Adding Virtual IP operation adds a logical Virtual IP to /// the deployment. /// </summary> /// <param name='serviceName'> /// Required. The name of the hosted service that contains the given /// deployment. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment where the logical Virtual IP /// is to be added. /// </param> /// <param name='virtualIPName'> /// Required. The name of the logical Virtual IP to be added. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task<OperationStatusResponse> BeginAddingAsync(string serviceName, string deploymentName, string virtualIPName, CancellationToken cancellationToken) { // Validate if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (deploymentName == null) { throw new ArgumentNullException("deploymentName"); } if (virtualIPName == null) { throw new ArgumentNullException("virtualIPName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("deploymentName", deploymentName); tracingParameters.Add("virtualIPName", virtualIPName); TracingAdapter.Enter(invocationId, this, "BeginAddingAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/hostedservices/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/deployments/"; url = url + Uri.EscapeDataString(deploymentName); url = url + "/"; url = url + Uri.EscapeDataString(virtualIPName); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Post; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2016-07-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result OperationStatusResponse result = null; // Deserialize Response result = new OperationStatusResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Begin Removing Virtual IP operation removes a logical Virtual /// IP from the deployment. /// </summary> /// <param name='serviceName'> /// Required. The name of the hosted service that contains the given /// deployment. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment whose logical Virtual IP is to /// be removed. /// </param> /// <param name='virtualIPName'> /// Required. The name of the logical Virtual IP to be added. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task<OperationStatusResponse> BeginRemovingAsync(string serviceName, string deploymentName, string virtualIPName, CancellationToken cancellationToken) { // Validate if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (deploymentName == null) { throw new ArgumentNullException("deploymentName"); } if (virtualIPName == null) { throw new ArgumentNullException("virtualIPName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("deploymentName", deploymentName); tracingParameters.Add("virtualIPName", virtualIPName); TracingAdapter.Enter(invocationId, this, "BeginRemovingAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/services/hostedservices/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/deployments/"; url = url + Uri.EscapeDataString(deploymentName); url = url + "/virtualIPs/"; url = url + Uri.EscapeDataString(virtualIPName); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2016-07-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result OperationStatusResponse result = null; // Deserialize Response result = new OperationStatusResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// The Remove Virtual IP operation removes a logical Virtual IP from /// the deployment. /// </summary> /// <param name='serviceName'> /// Required. The name of the hosted service that contains the given /// deployment. /// </param> /// <param name='deploymentName'> /// Required. The name of the deployment whose logical Virtual IP is to /// be removed. /// </param> /// <param name='virtualIPName'> /// Required. The name of the logical Virtual IP to be removed. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task<OperationStatusResponse> RemoveAsync(string serviceName, string deploymentName, string virtualIPName, CancellationToken cancellationToken) { NetworkManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("deploymentName", deploymentName); tracingParameters.Add("virtualIPName", virtualIPName); TracingAdapter.Enter(invocationId, this, "RemoveAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse response = await client.VirtualIPs.BeginRemovingAsync(serviceName, deploymentName, virtualIPName, cancellationToken).ConfigureAwait(false); if (response.Status == OperationStatus.Succeeded) { return response; } cancellationToken.ThrowIfCancellationRequested(); OperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 30; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while (result.Status == OperationStatus.InProgress) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 30; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.Status != OperationStatus.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } return result; } } }
using System; using System.IO; using System.Net; using System.Threading.Tasks; using NUnit.Framework; using RestFiles.ServiceModel; using ServiceStack; /* For syntax highlighting and better readability of this file, view it on GitHub: * https://github.com/ServiceStack/ServiceStack.Examples/blob/master/src/RestFiles/RestFiles.Tests/AsyncRestClientTests.cs */ namespace RestFiles.Tests { /// <summary> /// These test show how you can call ServiceStack REST web services asynchronously using an IRestClientAsync. /// /// Async service calls are a great for GUI apps as they can be called without blocking the UI thread. /// They are also great for performance as no time is spent on blocking IO calls. /// </summary> [TestFixture] public class AsyncRestClientTests { public const string WebServiceHostUrl = "http://localhost:8080/"; private const string ReadmeFileContents = "THIS IS A README FILE"; private const string ReplacedFileContents = "THIS README FILE HAS BEEN REPLACED"; private const string TestUploadFileContents = "THIS FILE IS USED FOR UPLOADING IN TESTS"; public string FilesRootDir; RestFilesHttpListener appHost; [TestFixtureSetUp] public void TextFixtureSetUp() { appHost = new RestFilesHttpListener(); appHost.Init(); } [TestFixtureTearDown] public void TestFixtureTearDown() { if (appHost != null) appHost.Dispose(); appHost = null; } [SetUp] public void OnBeforeEachTest() { FilesRootDir = appHost.Config.RootDirectory; if (Directory.Exists(FilesRootDir)) { Directory.Delete(FilesRootDir, true); } Directory.CreateDirectory(FilesRootDir + "SubFolder"); Directory.CreateDirectory(FilesRootDir + "SubFolder2"); File.WriteAllText(Path.Combine(FilesRootDir, "README.txt"), ReadmeFileContents); File.WriteAllText(Path.Combine(FilesRootDir, "TESTUPLOAD.txt"), TestUploadFileContents); } public IRestClientAsync CreateAsyncRestClient() { return new JsonServiceClient(WebServiceHostUrl); //Best choice for Ajax web apps, faster than XML //return new XmlServiceClient(WebServiceHostUrl); //Ubiquitous structured data format best for supporting non .NET clients //return new JsvServiceClient(WebServiceHostUrl); //Fastest, most compact and resilient format great for .NET to .NET client / server } private static void FailOnAsyncError<T>(T response, Exception ex) { Assert.Fail(ex.Message); } [Test] public async Task Can_GetAsync_to_retrieve_existing_file() { var restClient = CreateAsyncRestClient(); var response = await restClient.GetAsync<FilesResponse>("files/README.txt"); Assert.That(response.File.Contents, Is.EqualTo("THIS IS A README FILE")); } [Test] public async Task Can_GetAsync_to_retrieve_existing_folder_listing() { var restClient = CreateAsyncRestClient(); var response = await restClient.GetAsync<FilesResponse>("files/"); Assert.That(response.Directory.Folders.Count, Is.EqualTo(2)); Assert.That(response.Directory.Files.Count, Is.EqualTo(2)); } [Test] public async Task Can_PostAsync_to_path_without_uploaded_files_to_create_a_new_Directory() { var restClient = CreateAsyncRestClient(); FilesResponse response = await restClient.PostAsync<FilesResponse>("files/SubFolder/NewFolder", new Files()); Assert.That(Directory.Exists(FilesRootDir + "SubFolder/NewFolder")); } [Test] public void Can_WebRequest_POST_upload_file_to_save_new_file_and_create_new_Directory() { var webRequest = WebRequest.Create(WebServiceHostUrl + "files/UploadedFiles/"); var fileToUpload = new FileInfo(FilesRootDir + "TESTUPLOAD.txt"); webRequest.UploadFile(fileToUpload, MimeTypes.GetMimeType(fileToUpload.Name)); Assert.That(Directory.Exists(FilesRootDir + "UploadedFiles")); Assert.That(File.ReadAllText(FilesRootDir + "UploadedFiles/TESTUPLOAD.txt"), Is.EqualTo(TestUploadFileContents)); } [Test] public void Can_RestClient_POST_upload_file_to_save_new_file_and_create_new_Directory() { var restClient = (IRestClient)CreateAsyncRestClient(); var fileToUpload = new FileInfo(FilesRootDir + "TESTUPLOAD.txt"); restClient.PostFile<FilesResponse>("files/UploadedFiles/", fileToUpload, MimeTypes.GetMimeType(fileToUpload.Name)); Assert.That(Directory.Exists(FilesRootDir + "UploadedFiles")); Assert.That(File.ReadAllText(FilesRootDir + "UploadedFiles/TESTUPLOAD.txt"), Is.EqualTo(TestUploadFileContents)); } [Test] public async Task Can_PutAsync_to_replace_text_content_of_an_existing_file() { var restClient = CreateAsyncRestClient(); var response = await restClient.PutAsync<FilesResponse>("files/README.txt", new Files { TextContents = ReplacedFileContents }); Assert.That(File.ReadAllText(FilesRootDir + "README.txt"), Is.EqualTo(ReplacedFileContents)); } [Test] public async Task Can_DeleteAsync_to_replace_text_content_of_an_existing_file() { var restClient = CreateAsyncRestClient(); var response = await restClient.DeleteAsync<FilesResponse>("files/README.txt"); Assert.That(!File.Exists(FilesRootDir + "README.txt")); } /* * Error Handling Tests */ [Test] public async Task GET_a_file_that_doesnt_exist_throws_a_404_FileNotFoundException() { var restClient = CreateAsyncRestClient(); try { await restClient.GetAsync<FilesResponse>("files/UnknownFolder"); } catch (WebServiceException webEx) { var response = (FilesResponse)webEx.ResponseDto; Assert.That(webEx.StatusCode, Is.EqualTo(404)); Assert.That(response.ResponseStatus.ErrorCode, Is.EqualTo(typeof(FileNotFoundException).Name)); Assert.That(response.ResponseStatus.Message, Is.EqualTo("Could not find: UnknownFolder")); } } [Test] public async Task POST_to_an_existing_file_throws_a_500_NotSupportedException() { var restClient = (IRestClient)CreateAsyncRestClient(); var fileToUpload = new FileInfo(FilesRootDir + "TESTUPLOAD.txt"); try { var response = restClient.PostFile<FilesResponse>("files/README.txt", fileToUpload, MimeTypes.GetMimeType(fileToUpload.Name)); Assert.Fail("Should fail with NotSupportedException"); } catch (WebServiceException webEx) { Assert.That(webEx.StatusCode, Is.EqualTo(405)); var response = (FilesResponse)webEx.ResponseDto; Assert.That(response.ResponseStatus.ErrorCode, Is.EqualTo(typeof(NotSupportedException).Name)); Assert.That(response.ResponseStatus.Message, Is.EqualTo("POST only supports uploading new files. Use PUT to replace contents of an existing file")); } } [Test] public async Task PUT_to_replace_a_non_existing_file_throws_404() { var restClient = CreateAsyncRestClient(); try { await restClient.PutAsync<FilesResponse>("files/non-existing-file.txt", new Files { TextContents = ReplacedFileContents }); } catch (WebServiceException webEx) { var response = (FilesResponse)webEx.ResponseDto; Assert.That(webEx.StatusCode, Is.EqualTo(404)); Assert.That(response.ResponseStatus.ErrorCode, Is.EqualTo(typeof(FileNotFoundException).Name)); Assert.That(response.ResponseStatus.Message, Is.EqualTo("Could not find: non-existing-file.txt")); } } [Test] public async Task DELETE_a_non_existing_file_throws_404() { var restClient = CreateAsyncRestClient(); try { await restClient.DeleteAsync<FilesResponse>("files/non-existing-file.txt"); } catch (WebServiceException webEx) { var response = (FilesResponse)webEx.ResponseDto; Assert.That(webEx.StatusCode, Is.EqualTo(404)); Assert.That(response.ResponseStatus.ErrorCode, Is.EqualTo(typeof(FileNotFoundException).Name)); Assert.That(response.ResponseStatus.Message, Is.EqualTo("Could not find: non-existing-file.txt")); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace HelloWebAPI.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information. using Microsoft.VisualStudio.Shell.Interop; using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Security; using System.Windows; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using System.Drawing; using System.IO; using System.Windows.Forms; using System.Collections; using System.Text; using System.Linq; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; using IServiceProvider = System.IServiceProvider; using ShellConstants = Microsoft.VisualStudio.Shell.Interop.Constants; using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants; namespace Microsoft.VisualStudio.FSharp.ProjectSystem { internal class SolutionListenerForProjectReferenceUpdate : SolutionListener { public SolutionListenerForProjectReferenceUpdate(IServiceProvider serviceProvider) : base(serviceProvider) { } /// <summary> /// Notifies listening clients that the project has been opened. /// This method is called when on opening solution and when project is reloaded. /// If project was modified before opening (i.e. target framework moniker was changed) then it can: /// 1) have bad references - new version of target framework is lower than version of target framework in one of project references /// 2) be the cause of bad references - current project A was referenced by project B and new version of target framework in A is higher than in B /// To deal with this situation we renew state of error in: /// - project references of current project (solve 1) /// - project references of all project that point to current project (solve 2) /// </summary> public override int OnAfterOpenProject(IVsHierarchy hierarchy, int added) { var projectReferences = GetProjectReferencesContainingThisProject(hierarchy); foreach (var projRef in projectReferences) { // refresh all references to specified project projRef.RefreshProjectReferenceErrorState(); } var refContainerProvider = hierarchy as IReferenceContainerProvider; if (refContainerProvider != null) { var refContainer = refContainerProvider.GetReferenceContainer(); foreach (var projRef in refContainer.EnumReferences().OfType<ProjectReferenceNode>()) { projRef.RefreshProjectReferenceErrorState(); } } return VSConstants.S_OK; } /// <summary> /// Delete this project from the references of projects of this type, if it is found. /// </summary> /// <param name="hierarchy"></param> /// <param name="removed"></param> /// <returns></returns> public override int OnBeforeCloseProject(IVsHierarchy hierarchy, int removed) { if (removed != 0) { List<ProjectReferenceNode> projectReferences = this.GetProjectReferencesContainingThisProject(hierarchy); foreach (ProjectReferenceNode projectReference in projectReferences) { // Remove will delete error associated with reference projectReference.Remove(false); // Set back the remove state on the project refererence. The reason why we are doing this is that the OnBeforeUnloadProject immedaitely calls // OnBeforeCloseProject, thus we would be deleting references when we should not. Unload should not remove references. projectReference.CanRemoveReference = true; } } return VSConstants.S_OK; } /// <summary> /// Needs to update the dangling reference on projects that contain this hierarchy as project reference. /// </summary> /// <param name="stubHierarchy"></param> /// <param name="realHierarchy"></param> /// <returns></returns> public override int OnAfterLoadProject(IVsHierarchy stubHierarchy, IVsHierarchy realHierarchy) { List<ProjectReferenceNode> projectReferences = this.GetProjectReferencesContainingThisProject(realHierarchy); // Refersh the project reference node. That should trigger the drawing of the normal project reference icon. foreach (ProjectReferenceNode projectReference in projectReferences) { projectReference.CanRemoveReference = true; projectReference.OnInvalidateItems(projectReference.Parent); } return VSConstants.S_OK; } public override int OnAfterRenameProject(IVsHierarchy hierarchy) { if (hierarchy == null) { return VSConstants.E_INVALIDARG; } try { List<ProjectReferenceNode> projectReferences = this.GetProjectReferencesContainingThisProject(hierarchy); // Collect data that is needed to initialize the new project reference node. string projectRef; ErrorHandler.ThrowOnFailure(this.Solution.GetProjrefOfProject(hierarchy, out projectRef)); object nameAsObject; ErrorHandler.ThrowOnFailure(hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_Name, out nameAsObject)); string projectName = (string)nameAsObject; string projectPath = String.Empty; if (hierarchy is IVsProject3) { IVsProject3 project = (IVsProject3)hierarchy; ErrorHandler.ThrowOnFailure(project.GetMkDocument(VSConstants.VSITEMID_ROOT, out projectPath)); } // Remove and re add the node. foreach (ProjectReferenceNode projectReference in projectReferences) { ProjectNode projectMgr = projectReference.ProjectMgr; IReferenceContainer refContainer = projectMgr.GetReferenceContainer(); projectReference.Remove(false); VSCOMPONENTSELECTORDATA selectorData = new VSCOMPONENTSELECTORDATA(); selectorData.type = VSCOMPONENTTYPE.VSCOMPONENTTYPE_Project; selectorData.bstrTitle = projectName; selectorData.bstrFile = projectPath; selectorData.bstrProjRef = projectRef; refContainer.AddReferenceFromSelectorData(selectorData); } } catch (COMException e) { Trace.WriteLine("Exception :" + e.Message); return e.ErrorCode; } return VSConstants.S_OK; } public override int OnBeforeUnloadProject(IVsHierarchy realHierarchy, IVsHierarchy stubHierarchy) { List<ProjectReferenceNode> projectReferences = this.GetProjectReferencesContainingThisProject(realHierarchy); // Refresh the project reference node. That should trigger the drawing of the dangling project reference icon. foreach (ProjectReferenceNode projectReference in projectReferences) { projectReference.IsNodeValid = true; projectReference.OnInvalidateItems(projectReference.Parent); projectReference.CanRemoveReference = false; projectReference.IsNodeValid = false; projectReference.DropReferencedProjectCache(); // delete any 'reference' related errors that were induced by this project projectReference.CleanProjectReferenceErrorState(); } return VSConstants.S_OK; } private List<ProjectReferenceNode> GetProjectReferencesContainingThisProject(IVsHierarchy inputHierarchy) { List<ProjectReferenceNode> projectReferences = new List<ProjectReferenceNode>(); if (this.Solution == null || inputHierarchy == null) { return projectReferences; } uint flags = (uint)(__VSENUMPROJFLAGS.EPF_ALLPROJECTS | __VSENUMPROJFLAGS.EPF_LOADEDINSOLUTION); Guid enumOnlyThisType = Guid.Empty; IEnumHierarchies enumHierarchies = null; ErrorHandler.ThrowOnFailure(this.Solution.GetProjectEnum(flags, ref enumOnlyThisType, out enumHierarchies)); Debug.Assert(enumHierarchies != null, "Could not get list of hierarchies in solution"); IVsHierarchy[] hierarchies = new IVsHierarchy[1]; uint fetched; int returnValue = VSConstants.S_OK; do { returnValue = enumHierarchies.Next(1, hierarchies, out fetched); Debug.Assert(fetched <= 1, "We asked one project to be fetched VSCore gave more than one. We cannot handle that"); if (returnValue == VSConstants.S_OK && fetched == 1) { IVsHierarchy hierarchy = hierarchies[0]; Debug.Assert(hierarchy != null, "Could not retrieve a hierarchy"); IReferenceContainerProvider provider = hierarchy as IReferenceContainerProvider; if (provider != null) { IReferenceContainer referenceContainer = provider.GetReferenceContainer(); Debug.Assert(referenceContainer != null, "Could not found the References virtual node"); ProjectReferenceNode projectReferenceNode = this.GetProjectReferenceOnNodeForHierarchy(referenceContainer.EnumReferences(), inputHierarchy); if (projectReferenceNode != null) { projectReferences.Add(projectReferenceNode); } } } } while (returnValue == VSConstants.S_OK && fetched == 1); return projectReferences; } private ProjectReferenceNode GetProjectReferenceOnNodeForHierarchy(IList<ReferenceNode> references, IVsHierarchy inputHierarchy) { if (references == null) { return null; } Guid projectGuid; inputHierarchy.GetGuidProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ProjectIDGuid, out projectGuid); string canonicalName; inputHierarchy.GetCanonicalName(VSConstants.VSITEMID_ROOT, out canonicalName); foreach (ReferenceNode refNode in references) { ProjectReferenceNode projRefNode = refNode as ProjectReferenceNode; if (projRefNode != null) { if (projRefNode.ReferencedProjectGuid == projectGuid) { return projRefNode; } // Try with canonical names, if the project that is removed is an unloaded project than the above criteria will not pass. if (!String.IsNullOrEmpty(projRefNode.Url) && NativeMethods.IsSamePath(projRefNode.Url, canonicalName)) { return projRefNode; } } } return null; } } }
using System; using System.Collections.Generic; using System.Threading; using Moq; using NRules.Diagnostics; using NRules.Extensibility; using NRules.Rete; using Xunit; namespace NRules.Tests { public class SessionTest { private readonly Mock<IAgendaInternal> _agenda; private readonly Mock<INetwork> _network; private readonly Mock<IWorkingMemory> _workingMemory; private readonly Mock<IEventAggregator> _eventAggregator; private readonly Mock<IMetricsAggregator> _metricsAggregator; private readonly Mock<IActionExecutor> _actionExecutor; private readonly Mock<IIdGenerator> _idGenerator; private readonly Mock<IDependencyResolver> _dependencyResolver; private readonly Mock<IActionInterceptor> _actionInterceptor; public SessionTest() { _agenda = new Mock<IAgendaInternal>(); _network = new Mock<INetwork>(); _workingMemory = new Mock<IWorkingMemory>(); _eventAggregator = new Mock<IEventAggregator>(); _metricsAggregator = new Mock<IMetricsAggregator>(); _actionExecutor = new Mock<IActionExecutor>(); _idGenerator = new Mock<IIdGenerator>(); _dependencyResolver = new Mock<IDependencyResolver>(); _actionInterceptor = new Mock<IActionInterceptor>(); } [Fact] public void Insert_FactDoesNotExist_PropagatesAssert() { // Arrange var fact = new object(); var target = CreateTarget(); _workingMemory.Setup(x => x.GetFact(fact)).Returns(() => null); // Act target.Insert(fact); // Assert _network.Verify(x => x.PropagateAssert( It.Is<IExecutionContext>(p => p.WorkingMemory == _workingMemory.Object), It.Is<List<Fact>>(p => p.Count == 1 && p[0].Object == fact)), Times.Exactly(1)); } [Fact] public void InsertAll_FactsDoNotExist_PropagatesAssert() { // Arrange var facts = new[] { new object(), new object() }; var target = CreateTarget(); _workingMemory.Setup(x => x.GetFact(It.IsAny<object>())).Returns(() => null); // Act target.InsertAll(facts); // Assert _network.Verify(x => x.PropagateAssert( It.Is<IExecutionContext>(p => p.WorkingMemory == _workingMemory.Object), It.Is<List<Fact>>(p => p.Count == 2 && p[0].Object == facts[0] && p[1].Object == facts[1])), Times.Exactly(1)); } [Fact] public void InsertAll_SomeFactsExist_Throws() { // Arrange var facts = new[] { new object(), new object() }; var factWrappers = new Dictionary<object, Fact> { {facts[0], new Fact(facts[0])}, {facts[1], null} }; var target = CreateTarget(); _workingMemory.Setup(x => x.GetFact(It.IsAny<object>())).Returns<object>(x => factWrappers[x]); // Act - Assert Assert.Throws<ArgumentException>(() => target.InsertAll(facts)); } [Fact] public void TryInsertAll_SomeFactsExistOptionsAllOrNothing_DoesNotPropagateAssert() { // Arrange var facts = new[] { new object(), new object() }; var factWrappers = new Dictionary<object, Fact> { {facts[0], new Fact(facts[0])}, {facts[1], null} }; var target = CreateTarget(); _workingMemory.Setup(x => x.GetFact(It.IsAny<object>())).Returns<object>(x => factWrappers[x]); // Act var result = target.TryInsertAll(facts, BatchOptions.AllOrNothing); // Assert Assert.Equal(1, result.FailedCount); _network.Verify(x => x.PropagateAssert( It.Is<IExecutionContext>(p => p.WorkingMemory == _workingMemory.Object), It.IsAny<List<Fact>>()), Times.Never()); } [Fact] public void TryInsertAll_SomeFactsExistOptionsSkipFailed_PropagatesAssertForNonFailed() { // Arrange var facts = new[] { new object(), new object() }; var factWrappers = new Dictionary<object, Fact> { {facts[0], new Fact(facts[0])}, {facts[1], null} }; var target = CreateTarget(); _workingMemory.Setup(x => x.GetFact(It.IsAny<object>())).Returns<object>(x => factWrappers[x]); // Act var result = target.TryInsertAll(facts, BatchOptions.SkipFailed); // Assert Assert.Equal(1, result.FailedCount); _network.Verify(x => x.PropagateAssert( It.Is<IExecutionContext>(p => p.WorkingMemory == _workingMemory.Object), It.Is<List<Fact>>(p => p.Count == 1 && p[0].Object == facts[1])), Times.Exactly(1)); } [Fact] public void Update_FactExists_PropagatesUpdate() { // Arrange var fact = new object(); var factWrapper = new Fact(fact); var target = CreateTarget(); _workingMemory.Setup(x => x.GetFact(fact)).Returns(factWrapper); // Act target.Update(fact); // Assert _network.Verify(x => x.PropagateUpdate( It.Is<IExecutionContext>(p => p.WorkingMemory == _workingMemory.Object), It.Is<List<Fact>>(p => p.Count == 1 && p[0].Object == fact)), Times.Exactly(1)); } [Fact] public void UpdateAll_FactsExist_PropagatesUpdate() { // Arrange var facts = new[] { new object(), new object() }; var factWrappers = new Dictionary<object, Fact> { {facts[0], new Fact(facts[0])}, {facts[1], new Fact(facts[1])} }; var target = CreateTarget(); _workingMemory.Setup(x => x.GetFact(It.IsAny<object>())).Returns<object>(x => factWrappers[x]); // Act target.UpdateAll(facts); // Assert _network.Verify(x => x.PropagateUpdate( It.Is<IExecutionContext>(p => p.WorkingMemory == _workingMemory.Object), It.Is<List<Fact>>(p => p.Count == 2 && p[0].Object == facts[0] && p[1].Object == facts[1])), Times.Exactly(1)); } [Fact] public void UpdateAll_SomeFactsDoNotExist_Throws() { // Arrange var facts = new[] {new object(), new object()}; var factWrappers = new Dictionary<object, Fact> { {facts[0], new Fact(facts[0])}, {facts[1], null} }; var target = CreateTarget(); _workingMemory.Setup(x => x.GetFact(It.IsAny<object>())).Returns<object>(x => factWrappers[x]); // Act - Assert Assert.Throws<ArgumentException>(() => target.UpdateAll(facts)); } [Fact] public void TryUpdateAll_SomeFactsDoNotExistOptionsAllOrNothing_DoesNotPropagateUpdate() { // Arrange var facts = new[] { new object(), new object() }; var factWrappers = new Dictionary<object, Fact> { {facts[0], new Fact(facts[0])}, {facts[1], null} }; var target = CreateTarget(); _workingMemory.Setup(x => x.GetFact(It.IsAny<object>())).Returns<object>(x => factWrappers[x]); // Act var result = target.TryUpdateAll(facts, BatchOptions.AllOrNothing); // Assert Assert.Equal(1, result.FailedCount); _network.Verify(x => x.PropagateUpdate( It.Is<IExecutionContext>(p => p.WorkingMemory == _workingMemory.Object), It.IsAny<List<Fact>>()), Times.Never()); } [Fact] public void TryUpdateAll_SomeFactsDoNotExistOptionsSkipFailed_PropagateUpdateNonFailed() { // Arrange var facts = new[] { new object(), new object() }; var factWrappers = new Dictionary<object, Fact> { {facts[0], new Fact(facts[0])}, {facts[1], null} }; var target = CreateTarget(); _workingMemory.Setup(x => x.GetFact(It.IsAny<object>())).Returns<object>(x => factWrappers[x]); // Act var result = target.TryUpdateAll(facts, BatchOptions.SkipFailed); // Assert Assert.Equal(1, result.FailedCount); _network.Verify(x => x.PropagateUpdate( It.Is<IExecutionContext>(p => p.WorkingMemory == _workingMemory.Object), It.Is<List<Fact>>(p => p.Count == 1 && p[0].Object == facts[0])), Times.Exactly(1)); } [Fact] public void Retract_FactExists_PropagatesRetract() { // Arrange var fact = new object(); var factWrapper = new Fact(fact); var target = CreateTarget(); _workingMemory.Setup(x => x.GetFact(fact)).Returns(factWrapper); // Act target.Retract(fact); // Assert _network.Verify(x => x.PropagateRetract( It.Is<IExecutionContext>(p => p.WorkingMemory == _workingMemory.Object), It.Is<List<Fact>>(p => p.Count == 1 && p[0] == factWrapper)), Times.Exactly(1)); } [Fact] public void RetractAll_FactsExist_PropagatesRetract() { // Arrange var facts = new[] { new object(), new object() }; var factWrappers = new Dictionary<object, Fact> { {facts[0], new Fact(facts[0])}, {facts[1], new Fact(facts[1])} }; var target = CreateTarget(); _workingMemory.Setup(x => x.GetFact(It.IsAny<object>())).Returns<object>(x => factWrappers[x]); // Act target.RetractAll(facts); // Assert _network.Verify(x => x.PropagateRetract( It.Is<IExecutionContext>(p => p.WorkingMemory == _workingMemory.Object), It.Is<List<Fact>>(p => p.Count == 2 && p[0].Object == facts[0] && p[1].Object == facts[1])), Times.Exactly(1)); } [Fact] public void RetractAll_SomeFactsDoNotExist_Throws() { // Arrange var facts = new[] { new object(), new object() }; var factWrappers = new Dictionary<object, Fact> { {facts[0], new Fact(facts[0])}, {facts[1], null} }; var target = CreateTarget(); _workingMemory.Setup(x => x.GetFact(It.IsAny<object>())).Returns<object>(x => factWrappers[x]); // Act - Assert Assert.Throws<ArgumentException>(() => target.RetractAll(facts)); } [Fact] public void TryRetractAll_SomeFactsDoNotExistOptionsAllOrNothing_DoesNotPropagateRetract() { // Arrange var facts = new[] { new object(), new object() }; var factWrappers = new Dictionary<object, Fact> { {facts[0], new Fact(facts[0])}, {facts[1], null} }; var target = CreateTarget(); _workingMemory.Setup(x => x.GetFact(It.IsAny<object>())).Returns<object>(x => factWrappers[x]); // Act var result = target.TryRetractAll(facts, BatchOptions.AllOrNothing); // Assert Assert.Equal(1, result.FailedCount); _network.Verify(x => x.PropagateRetract( It.Is<IExecutionContext>(p => p.WorkingMemory == _workingMemory.Object), It.IsAny<List<Fact>>()), Times.Never()); } [Fact] public void TryRetractAll_SomeFactsDoNotExistOptionsSkipFailed_PropagateRetractNonFailed() { // Arrange var facts = new[] { new object(), new object() }; var factWrappers = new Dictionary<object, Fact> { {facts[0], new Fact(facts[0])}, {facts[1], null} }; var target = CreateTarget(); _workingMemory.Setup(x => x.GetFact(It.IsAny<object>())).Returns<object>(x => factWrappers[x]); // Act var result = target.TryRetractAll(facts, BatchOptions.SkipFailed); // Assert Assert.Equal(1, result.FailedCount); _network.Verify(x => x.PropagateRetract( It.Is<IExecutionContext>(p => p.WorkingMemory == _workingMemory.Object), It.Is<List<Fact>>(p => p.Count == 1 && p[0].Object == facts[0])), Times.Exactly(1)); } [Fact] public void Fire_NoActiveRules_ReturnsZero() { // Arrange var target = CreateTarget(); _agenda.Setup(x => x.IsEmpty).Returns(true); // Act var actual = target.Fire(); // Assert Assert.Equal(0, actual); } [Fact] public void Fire_ActiveRules_ReturnsNumberOfRulesFired() { // Arrange var target = CreateTarget(); _agenda.Setup(x => x.Pop()).Returns(StubActivation()); _agenda.SetupSequence(x => x.IsEmpty) .Returns(false).Returns(false).Returns(true); // Act var actual = target.Fire(); // Assert Assert.Equal(2, actual); } [Fact] public void Fire_ActiveRulesMoreThanMax_FiresMaxRules() { // Arrange var target = CreateTarget(); _agenda.Setup(x => x.Pop()).Returns(StubActivation()); _agenda.SetupSequence(x => x.IsEmpty) .Returns(false).Returns(false).Returns(true); // Act var actual = target.Fire(1); // Assert Assert.Equal(1, actual); } [Fact] public void Fire_CancellationRequested() { using (var cancellationSource = new CancellationTokenSource()) { // Arrange var hitCount = 0; var target = CreateTarget(); _agenda.Setup(x => x.Pop()).Returns(StubActivation()); _agenda .Setup(x => x.IsEmpty) .Returns(() => { if (++hitCount == 2) { cancellationSource.Cancel(); } return hitCount >= 5; }); // Act var actual = target.Fire(cancellationSource.Token); // Assert Assert.Equal(2, actual); _actionExecutor.Verify(ae => ae.Execute(It.IsAny<IExecutionContext>(), It.Is<IActionContext>(ac => ac.CancellationToken == cancellationSource.Token))); } } [Fact] public void Fire_CancellationRequested_WithMaxRules() { using (var cancellationSource = new CancellationTokenSource()) { // Arrange var hitCount = 0; var target = CreateTarget(); _agenda.Setup(x => x.Pop()).Returns(StubActivation()); _agenda .Setup(x => x.IsEmpty) .Returns(() => { if (++hitCount == 2) { cancellationSource.Cancel(); } return hitCount >= 5; }); // Act var actual = target.Fire(5, cancellationSource.Token); // Assert Assert.Equal(2, actual); _actionExecutor.Verify(ae => ae.Execute(It.IsAny<IExecutionContext>(), It.Is<IActionContext>(ac => ac.CancellationToken == cancellationSource.Token))); } } [Fact] public void Fire_PassesCancellationTokenToActionContext() { using (var cancellationSource = new CancellationTokenSource()) { // Arrange var target = CreateTarget(); _agenda.Setup(x => x.Pop()).Returns(StubActivation()); _agenda.SetupSequence(x => x.IsEmpty) .Returns(false).Returns(true); // Act var actual = target.Fire(cancellationSource.Token); // Assert Assert.Equal(1, actual); _actionExecutor.Verify(ae => ae.Execute(It.IsAny<IExecutionContext>(), It.Is<IActionContext>(ac => ac.CancellationToken == cancellationSource.Token))); } } [Fact] public void Fire_PassesCancellationTokenToActionContext_WithMaxRules() { using (var cancellationSource = new CancellationTokenSource()) { // Arrange var target = CreateTarget(); _agenda.Setup(x => x.Pop()).Returns(StubActivation()); _agenda.SetupSequence(x => x.IsEmpty) .Returns(false).Returns(true); // Act var actual = target.Fire(2, cancellationSource.Token); // Assert Assert.Equal(1, actual); _actionExecutor.Verify(ae => ae.Execute(It.IsAny<IExecutionContext>(), It.Is<IActionContext>(ac => ac.CancellationToken == cancellationSource.Token))); } } private Session CreateTarget() { var session = new Session(_network.Object, _agenda.Object, _workingMemory.Object, _eventAggregator.Object, _metricsAggregator.Object, _actionExecutor.Object, _idGenerator.Object, _dependencyResolver.Object, _actionInterceptor.Object); return session; } private static Activation StubActivation() { var rule = new Mock<ICompiledRule>(); rule.Setup(x => x.Actions).Returns(new IRuleAction[0]); var activation = new Activation(rule.Object, null); return activation; } } }
/* * @author Valentin Simonov / http://va.lent.in/ */ using System; using TouchScript.Hit; using UnityEngine; using System.Collections.Generic; using TouchScript.Layers.UI; using TouchScript.Pointers; using UnityEngine.EventSystems; using UnityEngine.UI; using System.Collections; using TouchScript.Utils.Attributes; namespace TouchScript.Layers { /// <summary> /// A layer which combines all types of hit recognition into one: UI (Screen Space and World), 3D and 2D. /// </summary> /// <seealso cref="TouchScript.Layers.TouchLayer" /> [AddComponentMenu("TouchScript/Layers/Standard Layer")] [HelpURL("http://touchscript.github.io/docs/html/T_TouchScript_Layers_StandardLayer.htm")] public class StandardLayer : TouchLayer { #region Public properties /// <summary> /// Indicates that the layer should look for 3D objects in the scene. Set this to <c>false</c> to optimize hit processing. /// </summary> public bool Hit3DObjects { get { return hit3DObjects; } set { hit3DObjects = value; updateVariants(); } } /// <summary> /// Indicates that the layer should look for 2D objects in the scene. Set this to <c>false</c> to optimize hit processing. /// </summary> public bool Hit2DObjects { get { return hit2DObjects; } set { hit2DObjects = value; updateVariants(); } } /// <summary> /// Indicates that the layer should look for World UI objects in the scene. Set this to <c>false</c> to optimize hit processing. /// </summary> public bool HitWorldSpaceUI { get { return hitWorldSpaceUI; } set { hitWorldSpaceUI = value; setupInputModule(); updateVariants(); } } /// <summary> /// Indicates that the layer should look for Screen Space UI objects in the scene. Set this to <c>false</c> to optimize hit processing. /// </summary> public bool HitScreenSpaceUI { get { return hitScreenSpaceUI; } set { hitScreenSpaceUI = value; setupInputModule(); } } /// <summary> /// Indicates that the layer should query for <see cref="HitTest"/> components on target objects. Set this to <c>false</c> to optimize hit processing. /// </summary> public bool UseHitFilters { get { return useHitFilters; } set { useHitFilters = value; } } /// <summary> /// Gets or sets the layer mask which is used to select layers which should be touchable from this layer. /// </summary> /// <value>A mask to exclude objects from possibly touchable list.</value> public LayerMask LayerMask { get { return layerMask; } set { layerMask = value; } } /// <inheritdoc /> public override Vector3 WorldProjectionNormal { get { if (_camera == null) return Vector3.forward; return _camera.transform.forward; } } #endregion #region Private variables private static Comparison<RaycastHitUI> _raycastHitUIComparerFunc = raycastHitUIComparerFunc; private static Comparison<RaycastHit> _raycastHitComparerFunc = raycastHitComparerFunc; private static Comparison<HitData> _hitDataComparerFunc = hitDataComparerFunc; private static Dictionary<int, ProjectionParams> projectionParamsCache = new Dictionary<int, ProjectionParams>(); private static List<BaseRaycaster> raycasters; private static List<RaycastHitUI> raycastHitUIList = new List<RaycastHitUI>(20); private static List<RaycastHit> raycastHitList = new List<RaycastHit>(20); private static List<HitData> hitList = new List<HitData>(20); #if UNITY_5_3_OR_NEWER private static RaycastHit[] raycastHits = new RaycastHit[20]; #endif private static RaycastHit2D[] raycastHits2D = new RaycastHit2D[20]; #pragma warning disable CS0414 [SerializeField] [HideInInspector] private bool basicEditor = true; [SerializeField] [HideInInspector] private bool advancedProps; // is used to save if advanced properties are opened or closed #pragma warning restore CS0414 [SerializeField] [HideInInspector] private bool hitProps; [SerializeField] [ToggleLeft] private bool hit3DObjects = true; [SerializeField] [ToggleLeft] private bool hit2DObjects = true; [SerializeField] [ToggleLeft] private bool hitWorldSpaceUI = true; [SerializeField] [ToggleLeft] private bool hitScreenSpaceUI = true; [SerializeField] private LayerMask layerMask = -1; [SerializeField] [ToggleLeft] private bool useHitFilters = false; private bool lookForCameraObjects = false; private TouchScriptInputModule inputModule; /// <summary> /// Camera. /// </summary> protected Camera _camera; #endregion #region Public methods /// <inheritdoc /> public override HitResult Hit(IPointer pointer, out HitData hit) { if (base.Hit(pointer, out hit) != HitResult.Hit) return HitResult.Miss; var result = HitResult.Miss; if (hitScreenSpaceUI) { result = performSSUISearch(pointer, out hit); switch (result) { case HitResult.Hit: return result; case HitResult.Discard: hit = default(HitData); return result; } } if (lookForCameraObjects) { result = performWorldSearch(pointer, out hit); switch (result) { case HitResult.Hit: return result; case HitResult.Discard: hit = default(HitData); return result; } } return HitResult.Miss; } /// <inheritdoc /> public override ProjectionParams GetProjectionParams(Pointer pointer) { var press = pointer.GetPressData(); if ((press.Type == HitData.HitType.World2D) || (press.Type == HitData.HitType.World3D)) return layerProjectionParams; var graphic = press.RaycastHitUI.Graphic; if (graphic == null) return layerProjectionParams; var canvas = graphic.canvas; if (canvas == null) return layerProjectionParams; ProjectionParams pp; if (!projectionParamsCache.TryGetValue(canvas.GetInstanceID(), out pp)) { // TODO: memory leak pp = new WorldSpaceCanvasProjectionParams(canvas); projectionParamsCache.Add(canvas.GetInstanceID(), pp); } return pp; } #endregion #region Unity methods /// <inheritdoc /> protected override void Awake() { updateCamera(); updateVariants(); base.Awake(); } private void OnEnable() { if (!Application.isPlaying) return; TouchManager.Instance.FrameStarted += frameStartedHandler; StartCoroutine(lateEnable()); } private IEnumerator lateEnable() { // Need to wait while EventSystem initializes yield return new WaitForEndOfFrame(); setupInputModule(); } private void OnDisable() { if (!Application.isPlaying) return; if (inputModule != null) inputModule.INTERNAL_Release(); if (TouchManager.Instance != null) TouchManager.Instance.FrameStarted -= frameStartedHandler; } [ContextMenu("Basic Editor")] private void switchToBasicEditor() { basicEditor = true; } #endregion #region Protected functions /// <summary> /// Finds a camera. /// </summary> protected virtual void updateCamera() { _camera = GetComponent<Camera>(); } /// <inheritdoc /> protected override ProjectionParams createProjectionParams() { return new CameraProjectionParams(_camera); } /// <inheritdoc /> protected override void setName() { if (string.IsNullOrEmpty(Name)) if (_camera != null) Name = _camera.name; else Name = "Layer"; } #endregion #region Private functions private void setupInputModule() { if (inputModule == null) { if (!hitWorldSpaceUI && !hitScreenSpaceUI) return; inputModule = TouchScriptInputModule.Instance; if (inputModule != null) TouchScriptInputModule.Instance.INTERNAL_Retain(); } else { if (hitWorldSpaceUI || hitScreenSpaceUI) return; inputModule.INTERNAL_Release(); inputModule = null; } } private HitResult performWorldSearch(IPointer pointer, out HitData hit) { hit = default(HitData); if (_camera == null) return HitResult.Miss; if ((_camera.enabled == false) || (_camera.gameObject.activeInHierarchy == false)) return HitResult.Miss; var position = pointer.Position; if (!_camera.pixelRect.Contains(position)) return HitResult.Miss; hitList.Clear(); var ray = _camera.ScreenPointToRay(position); int count; bool exclusiveSet = manager.HasExclusive; if (hit3DObjects) { #if UNITY_5_3_OR_NEWER count = Physics.RaycastNonAlloc(ray, raycastHits, float.PositiveInfinity, layerMask); #else var raycastHits = Physics.RaycastAll(ray, float.PositiveInfinity, layerMask); var count = raycastHits.Length; #endif // Try to do some optimizations if 2D and WS UI are not required if (!hit2DObjects && !hitWorldSpaceUI) { RaycastHit raycast; if (count == 0) return HitResult.Miss; if (count > 1) { raycastHitList.Clear(); for (var i = 0; i < count; i++) { raycast = raycastHits[i]; if (exclusiveSet && !manager.IsExclusive(raycast.transform)) continue; raycastHitList.Add(raycast); } if (raycastHitList.Count == 0) return HitResult.Miss; raycastHitList.Sort(_raycastHitComparerFunc); if (useHitFilters) { for (var i = 0; i < count; i++) { var result = doHit(pointer, raycastHitList[i], out hit); if (result != HitResult.Miss) return result; } return HitResult.Miss; } hit = new HitData(raycastHitList[0], this); return HitResult.Hit; } raycast = raycastHits[0]; if (exclusiveSet && !manager.IsExclusive(raycast.transform)) return HitResult.Miss; if (useHitFilters) return doHit(pointer, raycast, out hit); hit = new HitData(raycast, this); return HitResult.Hit; } for (var i = 0; i < count; i++) { var raycast = raycastHits[i]; if (exclusiveSet && !manager.IsExclusive(raycast.transform)) continue; hitList.Add(new HitData(raycastHits[i], this)); } } if (hit2DObjects) { count = Physics2D.GetRayIntersectionNonAlloc(ray, raycastHits2D, float.MaxValue, layerMask); for (var i = 0; i < count; i++) { var raycast = raycastHits2D[i]; if (exclusiveSet && !manager.IsExclusive(raycast.transform)) continue; hitList.Add(new HitData(raycast, this)); } } if (hitWorldSpaceUI) { raycastHitUIList.Clear(); if (raycasters == null) raycasters = TouchScriptInputModule.Instance.GetRaycasters(); count = raycasters.Count; for (var i = 0; i < count; i++) { var raycaster = raycasters[i] as GraphicRaycaster; if (raycaster == null) continue; var canvas = TouchScriptInputModule.Instance.GetCanvasForRaycaster(raycaster); if ((canvas == null) || (canvas.renderMode == RenderMode.ScreenSpaceOverlay) || (canvas.worldCamera != _camera)) continue; performUISearchForCanvas(pointer, canvas, raycaster, _camera, float.MaxValue, ray); } count = raycastHitUIList.Count; for (var i = 0; i < count; i++) hitList.Add(new HitData(raycastHitUIList[i], this)); } count = hitList.Count; if (hitList.Count == 0) return HitResult.Miss; if (count > 1) { hitList.Sort(_hitDataComparerFunc); if (useHitFilters) { for (var i = 0; i < count; ++i) { hit = hitList[i]; var result = checkHitFilters(pointer, hit); if (result != HitResult.Miss) return result; } return HitResult.Miss; } else { hit = hitList[0]; return HitResult.Hit; } } hit = hitList[0]; if (useHitFilters) return checkHitFilters(pointer, hit); return HitResult.Hit; } private HitResult performSSUISearch(IPointer pointer, out HitData hit) { hit = default(HitData); raycastHitUIList.Clear(); if (raycasters == null) raycasters = TouchScriptInputModule.Instance.GetRaycasters(); var count = raycasters.Count; for (var i = 0; i < count; i++) { var raycaster = raycasters[i] as GraphicRaycaster; if (raycaster == null) continue; var canvas = TouchScriptInputModule.Instance.GetCanvasForRaycaster(raycaster); if ((canvas == null) || (canvas.renderMode != RenderMode.ScreenSpaceOverlay)) continue; performUISearchForCanvas(pointer, canvas, raycaster); } count = raycastHitUIList.Count; if (count == 0) return HitResult.Miss; if (count > 1) { raycastHitUIList.Sort(_raycastHitUIComparerFunc); if (useHitFilters) { for (var i = 0; i < count; ++i) { var result = doHit(pointer, raycastHitUIList[i], out hit); if (result != HitResult.Miss) return result; } return HitResult.Miss; } hit = new HitData(raycastHitUIList[0], this, true); return HitResult.Hit; } if (useHitFilters) return doHit(pointer, raycastHitUIList[0], out hit); hit = new HitData(raycastHitUIList[0], this, true); return HitResult.Hit; } private void performUISearchForCanvas(IPointer pointer, Canvas canvas, GraphicRaycaster raycaster, Camera eventCamera = null, float maxDistance = float.MaxValue, Ray ray = default(Ray)) { var position = pointer.Position; var foundGraphics = GraphicRegistry.GetGraphicsForCanvas(canvas); var count = foundGraphics.Count; var exclusiveSet = manager.HasExclusive; for (var i = 0; i < count; i++) { var graphic = foundGraphics[i]; var t = graphic.transform; if (exclusiveSet && !manager.IsExclusive(t)) continue; if ((layerMask.value != -1) && ((layerMask.value & (1 << graphic.gameObject.layer)) == 0)) continue; // -1 means it hasn't been processed by the canvas, which means it isn't actually drawn if ((graphic.depth == -1) || !graphic.raycastTarget) continue; if (!RectTransformUtility.RectangleContainsScreenPoint(graphic.rectTransform, position, eventCamera)) continue; if (graphic.Raycast(position, eventCamera)) { if (raycaster.ignoreReversedGraphics) if (eventCamera == null) { // If we dont have a camera we know that we should always be facing forward var dir = t.rotation * Vector3.forward; if (Vector3.Dot(Vector3.forward, dir) <= 0) continue; } else { // If we have a camera compare the direction against the cameras forward. var cameraFoward = eventCamera.transform.rotation * Vector3.forward; var dir = t.rotation * Vector3.forward; if (Vector3.Dot(cameraFoward, dir) <= 0) continue; } float distance = 0; if ((eventCamera == null) || (canvas.renderMode == RenderMode.ScreenSpaceOverlay)) {} else { var transForward = t.forward; // http://geomalgorithms.com/a06-_intersect-2.html distance = Vector3.Dot(transForward, t.position - ray.origin) / Vector3.Dot(transForward, ray.direction); // Check to see if the go is behind the camera. if (distance < 0) continue; if (distance >= maxDistance) continue; } raycastHitUIList.Add( new RaycastHitUI() { Target = graphic.transform, Raycaster = raycaster, Graphic = graphic, GraphicIndex = raycastHitUIList.Count, Depth = graphic.depth, SortingLayer = canvas.sortingLayerID, SortingOrder = canvas.sortingOrder, Distance = distance }); } } } private HitResult doHit(IPointer pointer, RaycastHitUI raycastHit, out HitData hit) { hit = new HitData(raycastHit, this, true); return checkHitFilters(pointer, hit); } private HitResult doHit(IPointer pointer, RaycastHit raycastHit, out HitData hit) { hit = new HitData(raycastHit, this); return checkHitFilters(pointer, hit); } private void updateVariants() { lookForCameraObjects = _camera != null && (hit3DObjects || hit2DObjects || hitWorldSpaceUI); } #endregion #region Compare functions private static int raycastHitUIComparerFunc(RaycastHitUI lhs, RaycastHitUI rhs) { if (lhs.SortingLayer != rhs.SortingLayer) { // Uses the layer value to properly compare the relative order of the layers. var rid = SortingLayer.GetLayerValueFromID(rhs.SortingLayer); var lid = SortingLayer.GetLayerValueFromID(lhs.SortingLayer); return rid.CompareTo(lid); } if (lhs.SortingOrder != rhs.SortingOrder) return rhs.SortingOrder.CompareTo(lhs.SortingOrder); if (lhs.Depth != rhs.Depth) return rhs.Depth.CompareTo(lhs.Depth); if (!Mathf.Approximately(lhs.Distance, rhs.Distance)) return lhs.Distance.CompareTo(rhs.Distance); return lhs.GraphicIndex.CompareTo(rhs.GraphicIndex); } private static int raycastHitComparerFunc(RaycastHit lhs, RaycastHit rhs) { return lhs.distance < rhs.distance ? -1 : 1; } private static int hitDataComparerFunc(HitData lhs, HitData rhs) { if (lhs.SortingLayer != rhs.SortingLayer) { // Uses the layer value to properly compare the relative order of the layers. var rid = SortingLayer.GetLayerValueFromID(rhs.SortingLayer); var lid = SortingLayer.GetLayerValueFromID(lhs.SortingLayer); return rid.CompareTo(lid); } if (lhs.SortingOrder != rhs.SortingOrder) return rhs.SortingOrder.CompareTo(lhs.SortingOrder); if ((lhs.Type == HitData.HitType.UI) && (rhs.Type == HitData.HitType.UI)) { if (lhs.RaycastHitUI.Depth != rhs.RaycastHitUI.Depth) return rhs.RaycastHitUI.Depth.CompareTo(lhs.RaycastHitUI.Depth); if (!Mathf.Approximately(lhs.Distance, rhs.Distance)) return lhs.Distance.CompareTo(rhs.Distance); if (lhs.RaycastHitUI.GraphicIndex != rhs.RaycastHitUI.GraphicIndex) return rhs.RaycastHitUI.GraphicIndex.CompareTo(lhs.RaycastHitUI.GraphicIndex); } return lhs.Distance < rhs.Distance ? -1 : 1; } #endregion #region Event handlers private void frameStartedHandler(object sender, EventArgs eventArgs) { raycasters = null; } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsLro { using Azure; using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; /// <summary> /// Long-running Operation for AutoRest /// </summary> public partial class AutoRestLongRunningOperationTestServiceClient : ServiceClient<AutoRestLongRunningOperationTestServiceClient>, IAutoRestLongRunningOperationTestServiceClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the ILROsOperations. /// </summary> public virtual ILROsOperations LROs { get; private set; } /// <summary> /// Gets the ILRORetrysOperations. /// </summary> public virtual ILRORetrysOperations LRORetrys { get; private set; } /// <summary> /// Gets the ILROSADsOperations. /// </summary> public virtual ILROSADsOperations LROSADs { get; private set; } /// <summary> /// Gets the ILROsCustomHeaderOperations. /// </summary> public virtual ILROsCustomHeaderOperations LROsCustomHeader { get; private set; } /// <summary> /// Initializes a new instance of the AutoRestLongRunningOperationTestServiceClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestLongRunningOperationTestServiceClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestLongRunningOperationTestServiceClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected AutoRestLongRunningOperationTestServiceClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestLongRunningOperationTestServiceClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestLongRunningOperationTestServiceClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestLongRunningOperationTestServiceClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected AutoRestLongRunningOperationTestServiceClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestLongRunningOperationTestServiceClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestLongRunningOperationTestServiceClient(ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestLongRunningOperationTestServiceClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestLongRunningOperationTestServiceClient(ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestLongRunningOperationTestServiceClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestLongRunningOperationTestServiceClient(System.Uri baseUri, ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the AutoRestLongRunningOperationTestServiceClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestLongRunningOperationTestServiceClient(System.Uri baseUri, ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } BaseUri = baseUri; Credentials = credentials; if (Credentials != null) { Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { LROs = new LROsOperations(this); LRORetrys = new LRORetrysOperations(this); LROSADs = new LROSADsOperations(this); LROsCustomHeader = new LROsCustomHeaderOperations(this); BaseUri = new System.Uri("http://localhost"); AcceptLanguage = "en-US"; LongRunningOperationRetryTimeout = 30; GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
/* * 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 lambda-2015-03-31.normal.json service model. */ using System; using System.IO; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using Amazon.Lambda; using Amazon.Lambda.Model; using Amazon.Lambda.Model.Internal.MarshallTransformations; using Amazon.Runtime.Internal.Transform; using Amazon.Util; using ServiceClientGenerator; using AWSSDK_DotNet35.UnitTests.TestTools; namespace AWSSDK_DotNet35.UnitTests.Marshalling { [TestClass] public partial class LambdaMarshallingTests { static readonly ServiceModel service_model = Utils.LoadServiceModel("lambda-2015-03-31.normal.json", "lambda.customizations.json"); [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("Lambda")] public void AddPermissionMarshallTest() { var operation = service_model.FindOperation("AddPermission"); var request = InstantiateClassGenerator.Execute<AddPermissionRequest>(); var marshaller = new AddPermissionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("AddPermission", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = AddPermissionResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as AddPermissionResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("Lambda")] public void CreateEventSourceMappingMarshallTest() { var operation = service_model.FindOperation("CreateEventSourceMapping"); var request = InstantiateClassGenerator.Execute<CreateEventSourceMappingRequest>(); var marshaller = new CreateEventSourceMappingRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("CreateEventSourceMapping", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = CreateEventSourceMappingResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as CreateEventSourceMappingResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("Lambda")] public void CreateFunctionMarshallTest() { var operation = service_model.FindOperation("CreateFunction"); var request = InstantiateClassGenerator.Execute<CreateFunctionRequest>(); var marshaller = new CreateFunctionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("CreateFunction", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = CreateFunctionResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as CreateFunctionResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("Lambda")] public void DeleteEventSourceMappingMarshallTest() { var operation = service_model.FindOperation("DeleteEventSourceMapping"); var request = InstantiateClassGenerator.Execute<DeleteEventSourceMappingRequest>(); var marshaller = new DeleteEventSourceMappingRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("DeleteEventSourceMapping", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = DeleteEventSourceMappingResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as DeleteEventSourceMappingResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("Lambda")] public void DeleteFunctionMarshallTest() { var operation = service_model.FindOperation("DeleteFunction"); var request = InstantiateClassGenerator.Execute<DeleteFunctionRequest>(); var marshaller = new DeleteFunctionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("DeleteFunction", request, internalRequest, service_model); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("Lambda")] public void GetEventSourceMappingMarshallTest() { var operation = service_model.FindOperation("GetEventSourceMapping"); var request = InstantiateClassGenerator.Execute<GetEventSourceMappingRequest>(); var marshaller = new GetEventSourceMappingRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetEventSourceMapping", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetEventSourceMappingResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetEventSourceMappingResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("Lambda")] public void GetFunctionMarshallTest() { var operation = service_model.FindOperation("GetFunction"); var request = InstantiateClassGenerator.Execute<GetFunctionRequest>(); var marshaller = new GetFunctionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetFunction", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetFunctionResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetFunctionResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("Lambda")] public void GetFunctionConfigurationMarshallTest() { var operation = service_model.FindOperation("GetFunctionConfiguration"); var request = InstantiateClassGenerator.Execute<GetFunctionConfigurationRequest>(); var marshaller = new GetFunctionConfigurationRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetFunctionConfiguration", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetFunctionConfigurationResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetFunctionConfigurationResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("Lambda")] public void GetPolicyMarshallTest() { var operation = service_model.FindOperation("GetPolicy"); var request = InstantiateClassGenerator.Execute<GetPolicyRequest>(); var marshaller = new GetPolicyRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("GetPolicy", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = GetPolicyResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as GetPolicyResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("Lambda")] public void InvokeMarshallTest() { var operation = service_model.FindOperation("Invoke"); var request = InstantiateClassGenerator.Execute<InvokeRequest>(); var marshaller = new InvokeRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("Invoke", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"X-Amz-Function-Error","X-Amz-Function-Error_Value"}, {"X-Amz-Log-Result","X-Amz-Log-Result_Value"}, {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = InvokeResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as InvokeResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("Lambda")] public void InvokeAsyncMarshallTest() { var operation = service_model.FindOperation("InvokeAsync"); var request = InstantiateClassGenerator.Execute<InvokeAsyncRequest>(); var marshaller = new InvokeAsyncRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("InvokeAsync", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = InvokeAsyncResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as InvokeAsyncResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("Lambda")] public void ListEventSourceMappingsMarshallTest() { var operation = service_model.FindOperation("ListEventSourceMappings"); var request = InstantiateClassGenerator.Execute<ListEventSourceMappingsRequest>(); var marshaller = new ListEventSourceMappingsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("ListEventSourceMappings", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = ListEventSourceMappingsResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as ListEventSourceMappingsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("Lambda")] public void ListFunctionsMarshallTest() { var operation = service_model.FindOperation("ListFunctions"); var request = InstantiateClassGenerator.Execute<ListFunctionsRequest>(); var marshaller = new ListFunctionsRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("ListFunctions", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = ListFunctionsResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as ListFunctionsResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("Lambda")] public void RemovePermissionMarshallTest() { var operation = service_model.FindOperation("RemovePermission"); var request = InstantiateClassGenerator.Execute<RemovePermissionRequest>(); var marshaller = new RemovePermissionRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("RemovePermission", request, internalRequest, service_model); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("Lambda")] public void UpdateEventSourceMappingMarshallTest() { var operation = service_model.FindOperation("UpdateEventSourceMapping"); var request = InstantiateClassGenerator.Execute<UpdateEventSourceMappingRequest>(); var marshaller = new UpdateEventSourceMappingRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("UpdateEventSourceMapping", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = UpdateEventSourceMappingResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as UpdateEventSourceMappingResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("Lambda")] public void UpdateFunctionCodeMarshallTest() { var operation = service_model.FindOperation("UpdateFunctionCode"); var request = InstantiateClassGenerator.Execute<UpdateFunctionCodeRequest>(); var marshaller = new UpdateFunctionCodeRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("UpdateFunctionCode", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = UpdateFunctionCodeResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as UpdateFunctionCodeResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } [TestMethod] [TestCategory("UnitTest")] [TestCategory("Rest_Json")] [TestCategory("Lambda")] public void UpdateFunctionConfigurationMarshallTest() { var operation = service_model.FindOperation("UpdateFunctionConfiguration"); var request = InstantiateClassGenerator.Execute<UpdateFunctionConfigurationRequest>(); var marshaller = new UpdateFunctionConfigurationRequestMarshaller(); var internalRequest = marshaller.Marshall(request); RequestValidator.Validate("UpdateFunctionConfiguration", request, internalRequest, service_model); var webResponse = new WebResponseData { Headers = { {"x-amzn-RequestId", Guid.NewGuid().ToString()}, {"x-amz-crc32","0"} } }; var payloadResponse = new JsonSampleGenerator(service_model, operation.ResponseStructure).Execute(); webResponse.Headers.Add("Content-Length", UTF8Encoding.UTF8.GetBytes(payloadResponse).Length.ToString()); var context = new JsonUnmarshallerContext(Utils.CreateStreamFromString(payloadResponse), false, webResponse); ResponseUnmarshaller unmarshaller = UpdateFunctionConfigurationResponseUnmarshaller.Instance; var response = unmarshaller.Unmarshall(context) as UpdateFunctionConfigurationResponse; InstantiateClassGenerator.ValidateObjectFullyInstantiated(response); } } }
namespace android.database { [global::MonoJavaBridge.JavaClass()] public partial class CursorWindow : android.database.sqlite.SQLiteClosable, android.os.Parcelable { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static CursorWindow() { InitJNI(); } protected CursorWindow(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _finalize2611; protected override void finalize() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.CursorWindow._finalize2611); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._finalize2611); } internal static global::MonoJavaBridge.MethodId _getShort2612; public virtual short getShort(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallShortMethod(this.JvmHandle, global::android.database.CursorWindow._getShort2612, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualShortMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._getShort2612, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _getInt2613; public virtual int getInt(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.database.CursorWindow._getInt2613, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._getInt2613, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _getLong2614; public virtual long getLong(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallLongMethod(this.JvmHandle, global::android.database.CursorWindow._getLong2614, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualLongMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._getLong2614, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _putLong2615; public virtual bool putLong(long arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.CursorWindow._putLong2615, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._putLong2615, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _getFloat2616; public virtual float getFloat(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallFloatMethod(this.JvmHandle, global::android.database.CursorWindow._getFloat2616, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._getFloat2616, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _getDouble2617; public virtual double getDouble(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallDoubleMethod(this.JvmHandle, global::android.database.CursorWindow._getDouble2617, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualDoubleMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._getDouble2617, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _putDouble2618; public virtual bool putDouble(double arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.CursorWindow._putDouble2618, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._putDouble2618, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _clear2619; public virtual void clear() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.CursorWindow._clear2619); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._clear2619); } internal static global::MonoJavaBridge.MethodId _close2620; public virtual void close() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.CursorWindow._close2620); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._close2620); } internal static global::MonoJavaBridge.MethodId _getString2621; public virtual global::java.lang.String getString(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.database.CursorWindow._getString2621, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String; else return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._getString2621, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as java.lang.String; } internal static global::MonoJavaBridge.MethodId _putNull2622; public virtual bool putNull(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.CursorWindow._putNull2622, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._putNull2622, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _writeToParcel2623; public virtual void writeToParcel(android.os.Parcel arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.CursorWindow._writeToParcel2623, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._writeToParcel2623, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _describeContents2624; public virtual int describeContents() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.database.CursorWindow._describeContents2624); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._describeContents2624); } internal static global::MonoJavaBridge.MethodId _onAllReferencesReleased2625; protected override void onAllReferencesReleased() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.CursorWindow._onAllReferencesReleased2625); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._onAllReferencesReleased2625); } internal static global::MonoJavaBridge.MethodId _putString2626; public virtual bool putString(java.lang.String arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.CursorWindow._putString2626, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._putString2626, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _getBlob2627; public virtual byte[] getBlob(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallObjectMethod(this.JvmHandle, global::android.database.CursorWindow._getBlob2627, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as byte[]; else return global::MonoJavaBridge.JavaBridge.WrapJavaArrayObject<byte>(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._getBlob2627, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as byte[]; } internal static global::MonoJavaBridge.MethodId _copyStringToBuffer2628; public virtual void copyStringToBuffer(int arg0, int arg1, android.database.CharArrayBuffer arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.CursorWindow._copyStringToBuffer2628, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._copyStringToBuffer2628, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _isNull2629; public virtual bool isNull(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.CursorWindow._isNull2629, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._isNull2629, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _getStartPosition2630; public virtual int getStartPosition() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.database.CursorWindow._getStartPosition2630); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._getStartPosition2630); } internal static global::MonoJavaBridge.MethodId _setStartPosition2631; public virtual void setStartPosition(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.CursorWindow._setStartPosition2631, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._setStartPosition2631, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getNumRows2632; public virtual int getNumRows() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.database.CursorWindow._getNumRows2632); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._getNumRows2632); } internal static global::MonoJavaBridge.MethodId _setNumColumns2633; public virtual bool setNumColumns(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.CursorWindow._setNumColumns2633, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._setNumColumns2633, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _allocRow2634; public virtual bool allocRow() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.CursorWindow._allocRow2634); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._allocRow2634); } internal static global::MonoJavaBridge.MethodId _freeLastRow2635; public virtual void freeLastRow() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.database.CursorWindow._freeLastRow2635); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._freeLastRow2635); } internal static global::MonoJavaBridge.MethodId _putBlob2636; public virtual bool putBlob(byte[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.CursorWindow._putBlob2636, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._putBlob2636, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } internal static global::MonoJavaBridge.MethodId _isBlob2637; public virtual bool isBlob(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.CursorWindow._isBlob2637, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._isBlob2637, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _isLong2638; public virtual bool isLong(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.CursorWindow._isLong2638, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._isLong2638, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _isFloat2639; public virtual bool isFloat(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.CursorWindow._isFloat2639, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._isFloat2639, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _isString2640; public virtual bool isString(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.database.CursorWindow._isString2640, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.database.CursorWindow.staticClass, global::android.database.CursorWindow._isString2640, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _newFromParcel2641; public static global::android.database.CursorWindow newFromParcel(android.os.Parcel arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallStaticObjectMethod(android.database.CursorWindow.staticClass, global::android.database.CursorWindow._newFromParcel2641, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0))) as android.database.CursorWindow; } internal static global::MonoJavaBridge.MethodId _CursorWindow2642; public CursorWindow(bool arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.database.CursorWindow.staticClass, global::android.database.CursorWindow._CursorWindow2642, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } internal static global::MonoJavaBridge.FieldId _CREATOR2643; public static global::android.os.Parcelable_Creator CREATOR { get { return default(global::android.os.Parcelable_Creator); } } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.database.CursorWindow.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/database/CursorWindow")); global::android.database.CursorWindow._finalize2611 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "finalize", "()V"); global::android.database.CursorWindow._getShort2612 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "getShort", "(II)S"); global::android.database.CursorWindow._getInt2613 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "getInt", "(II)I"); global::android.database.CursorWindow._getLong2614 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "getLong", "(II)J"); global::android.database.CursorWindow._putLong2615 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "putLong", "(JII)Z"); global::android.database.CursorWindow._getFloat2616 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "getFloat", "(II)F"); global::android.database.CursorWindow._getDouble2617 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "getDouble", "(II)D"); global::android.database.CursorWindow._putDouble2618 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "putDouble", "(DII)Z"); global::android.database.CursorWindow._clear2619 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "clear", "()V"); global::android.database.CursorWindow._close2620 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "close", "()V"); global::android.database.CursorWindow._getString2621 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "getString", "(II)Ljava/lang/String;"); global::android.database.CursorWindow._putNull2622 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "putNull", "(II)Z"); global::android.database.CursorWindow._writeToParcel2623 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V"); global::android.database.CursorWindow._describeContents2624 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "describeContents", "()I"); global::android.database.CursorWindow._onAllReferencesReleased2625 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "onAllReferencesReleased", "()V"); global::android.database.CursorWindow._putString2626 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "putString", "(Ljava/lang/String;II)Z"); global::android.database.CursorWindow._getBlob2627 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "getBlob", "(II)[B"); global::android.database.CursorWindow._copyStringToBuffer2628 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "copyStringToBuffer", "(IILandroid/database/CharArrayBuffer;)V"); global::android.database.CursorWindow._isNull2629 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "isNull", "(II)Z"); global::android.database.CursorWindow._getStartPosition2630 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "getStartPosition", "()I"); global::android.database.CursorWindow._setStartPosition2631 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "setStartPosition", "(I)V"); global::android.database.CursorWindow._getNumRows2632 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "getNumRows", "()I"); global::android.database.CursorWindow._setNumColumns2633 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "setNumColumns", "(I)Z"); global::android.database.CursorWindow._allocRow2634 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "allocRow", "()Z"); global::android.database.CursorWindow._freeLastRow2635 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "freeLastRow", "()V"); global::android.database.CursorWindow._putBlob2636 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "putBlob", "([BII)Z"); global::android.database.CursorWindow._isBlob2637 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "isBlob", "(II)Z"); global::android.database.CursorWindow._isLong2638 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "isLong", "(II)Z"); global::android.database.CursorWindow._isFloat2639 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "isFloat", "(II)Z"); global::android.database.CursorWindow._isString2640 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "isString", "(II)Z"); global::android.database.CursorWindow._newFromParcel2641 = @__env.GetStaticMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "newFromParcel", "(Landroid/os/Parcel;)Landroid/database/CursorWindow;"); global::android.database.CursorWindow._CursorWindow2642 = @__env.GetMethodIDNoThrow(global::android.database.CursorWindow.staticClass, "<init>", "(Z)V"); } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Numerics; using System.Xml; using System.Xml.XPath; using System.Text; using System.Diagnostics.Contracts; using Microsoft.Win32.SafeHandles; namespace System.Security.Cryptography { /// <summary> /// Utility class to convert NCrypt keys into XML and back using a format similar to the one described /// in RFC 4050 (http://www.ietf.org/rfc/rfc4050.txt). /// /// #RFC4050ECKeyFormat /// /// The format looks similar to the following: /// /// <ECDSAKeyValue xmlns="http://www.w3.org/2001/04/xmldsig-more#"> /// <DomainParameters> /// <NamedCurve URN="urn:oid:1.3.132.0.35" /> /// </DomainParameters> /// <PublicKey> /// <X Value="0123456789..." xsi:type="PrimeFieldElemType" /> /// <Y Value="0123456789..." xsi:type="PrimeFieldElemType" /> /// </PublicKey> /// </ECDSAKeyValue> /// </summary> internal static class Rfc4050KeyFormatter { private const string DomainParametersRoot = "DomainParameters"; private const string ECDHRoot = "ECDHKeyValue"; private const string ECDsaRoot = "ECDSAKeyValue"; private const string NamedCurveElement = "NamedCurve"; private const string Namespace = "http://www.w3.org/2001/04/xmldsig-more#"; private const string PublicKeyRoot = "PublicKey"; private const string UrnAttribute = "URN"; private const string ValueAttribute = "Value"; private const string XElement = "X"; private const string YElement = "Y"; private const string XsiTypeAttribute = "type"; private const string XsiTypeAttributeValue = "PrimeFieldElemType"; private const string XsiNamespace = "http://www.w3.org/2001/XMLSchema-instance"; private const string XsiNamespacePrefix = "xsi"; private const string Prime256CurveUrn = "urn:oid:1.2.840.10045.3.1.7"; private const string Prime384CurveUrn = "urn:oid:1.3.132.0.34"; private const string Prime521CurveUrn = "urn:oid:1.3.132.0.35"; /// <summary> /// Restore a key from XML /// </summary> internal static CngKey FromXml(string xml) { Contract.Requires(xml != null); Contract.Ensures(Contract.Result<CngKey>() != null); // Load the XML into an XPathNavigator to access sub elements using (TextReader textReader = new StringReader(xml)) using (XmlTextReader xmlReader = new XmlTextReader(textReader)) { XPathDocument document = new XPathDocument(xmlReader); XPathNavigator navigator = document.CreateNavigator(); // Move into the root element - we don't do a specific namespace check here for compatibility // with XML that Windows generates. if (!navigator.MoveToFirstChild()) { throw new ArgumentException(SR.GetString(SR.Cryptography_MissingDomainParameters)); } // First figure out which algorithm this key belongs to CngAlgorithm algorithm = ReadAlgorithm(navigator); // Then read out the public key value if (!navigator.MoveToNext(XPathNodeType.Element)) { throw new ArgumentException(SR.GetString(SR.Cryptography_MissingPublicKey)); } BigInteger x; BigInteger y; ReadPublicKey(navigator, out x, out y); // Finally, convert them into a key blob to import into a CngKey byte[] keyBlob = NCryptNative.BuildEccPublicBlob(algorithm.Algorithm, x, y); return CngKey.Import(keyBlob, CngKeyBlobFormat.EccPublicBlob); } } /// <summary> /// Map a curve URN to the size of the key associated with the curve /// </summary> [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Justification = "The parameters to the exception are in the correct order")] private static int GetKeySize(string urn) { Contract.Requires(!String.IsNullOrEmpty(urn)); Contract.Ensures(Contract.Result<int>() > 0); switch (urn) { case Prime256CurveUrn: return 256; case Prime384CurveUrn: return 384; case Prime521CurveUrn: return 521; default: throw new ArgumentException(SR.GetString(SR.Cryptography_UnknownEllipticCurve), "algorithm"); } } /// <summary> /// Get the OID which represents an elliptic curve /// </summary> private static string GetCurveUrn(CngAlgorithm algorithm) { Contract.Requires(algorithm != null); if (algorithm == CngAlgorithm.ECDsaP256 || algorithm == CngAlgorithm.ECDiffieHellmanP256) { return Prime256CurveUrn; } else if (algorithm == CngAlgorithm.ECDsaP384 || algorithm == CngAlgorithm.ECDiffieHellmanP384) { return Prime384CurveUrn; } else if (algorithm == CngAlgorithm.ECDsaP521 || algorithm == CngAlgorithm.ECDiffieHellmanP521) { return Prime521CurveUrn; } else { throw new ArgumentException(SR.GetString(SR.Cryptography_UnknownEllipticCurve), "algorithm"); } } /// <summary> /// Determine which ECC algorithm the key refers to /// </summary> private static CngAlgorithm ReadAlgorithm(XPathNavigator navigator) { Contract.Requires(navigator != null); Contract.Ensures(Contract.Result<CngAlgorithm>() != null); if (navigator.NamespaceURI != Namespace) { throw new ArgumentException(SR.GetString(SR.Cryptography_UnexpectedXmlNamespace, navigator.NamespaceURI, Namespace)); } // // The name of the root element determines which algorithm to use, while the DomainParameters // element specifies which curve we should be using. // bool isDHKey = navigator.Name == ECDHRoot; bool isDsaKey = navigator.Name == ECDsaRoot; if (!isDHKey && !isDsaKey) { throw new ArgumentException(SR.GetString(SR.Cryptography_UnknownEllipticCurveAlgorithm)); } // Move into the DomainParameters element if (!navigator.MoveToFirstChild() || navigator.Name != DomainParametersRoot) { throw new ArgumentException(SR.GetString(SR.Cryptography_MissingDomainParameters)); } // Now move into the NamedCurve element if (!navigator.MoveToFirstChild() || navigator.Name != NamedCurveElement) { throw new ArgumentException(SR.GetString(SR.Cryptography_MissingDomainParameters)); } // And read its URN value if (!navigator.MoveToFirstAttribute() || navigator.Name != UrnAttribute || String.IsNullOrEmpty(navigator.Value)) { throw new ArgumentException(SR.GetString(SR.Cryptography_MissingDomainParameters)); } int keySize = GetKeySize(navigator.Value); // position the navigator at the end of the domain parameters navigator.MoveToParent(); // NamedCurve navigator.MoveToParent(); // DomainParameters // // Given the algorithm type and key size, we can now map back to a CNG algorithm ID // if (isDHKey) { if (keySize == 256) { return CngAlgorithm.ECDiffieHellmanP256; } else if (keySize == 384) { return CngAlgorithm.ECDiffieHellmanP384; } else { Debug.Assert(keySize == 521, "keySize == 521"); return CngAlgorithm.ECDiffieHellmanP521; } } else { Debug.Assert(isDsaKey, "isDsaKey"); if (keySize == 256) { return CngAlgorithm.ECDsaP256; } else if (keySize == 384) { return CngAlgorithm.ECDsaP384; } else { Debug.Assert(keySize == 521, "keySize == 521"); return CngAlgorithm.ECDsaP521; } } } /// <summary> /// Read the x and y components of the public key /// </summary> private static void ReadPublicKey(XPathNavigator navigator, out BigInteger x, out BigInteger y) { Contract.Requires(navigator != null); if (navigator.NamespaceURI != Namespace) { throw new ArgumentException(SR.GetString(SR.Cryptography_UnexpectedXmlNamespace, navigator.NamespaceURI, Namespace)); } if (navigator.Name != PublicKeyRoot) { throw new ArgumentException(SR.GetString(SR.Cryptography_MissingPublicKey)); } // First get the x parameter if (!navigator.MoveToFirstChild() || navigator.Name != XElement) { throw new ArgumentException(SR.GetString(SR.Cryptography_MissingPublicKey)); } if (!navigator.MoveToFirstAttribute() || navigator.Name != ValueAttribute || String.IsNullOrEmpty(navigator.Value)) { throw new ArgumentException(SR.GetString(SR.Cryptography_MissingPublicKey)); } x = BigInteger.Parse(navigator.Value, CultureInfo.InvariantCulture); navigator.MoveToParent(); // Then the y parameter if (!navigator.MoveToNext(XPathNodeType.Element) || navigator.Name != YElement) { throw new ArgumentException(SR.GetString(SR.Cryptography_MissingPublicKey)); } if (!navigator.MoveToFirstAttribute() || navigator.Name != ValueAttribute || String.IsNullOrEmpty(navigator.Value)) { throw new ArgumentException(SR.GetString(SR.Cryptography_MissingPublicKey)); } y = BigInteger.Parse(navigator.Value, CultureInfo.InvariantCulture); } /// <summary> /// Serialize out information about the elliptic curve /// </summary> private static void WriteDomainParameters(XmlWriter writer, CngKey key) { Contract.Requires(writer != null); Contract.Requires(key != null && (key.AlgorithmGroup == CngAlgorithmGroup.ECDsa || key.AlgorithmGroup == CngAlgorithmGroup.ECDiffieHellman)); writer.WriteStartElement(DomainParametersRoot); // We always use OIDs for the named prime curves writer.WriteStartElement(NamedCurveElement); writer.WriteAttributeString(UrnAttribute, GetCurveUrn(key.Algorithm)); writer.WriteEndElement(); // </NamedCurve> writer.WriteEndElement(); // </DomainParameters> } private static void WritePublicKeyValue(XmlWriter writer, CngKey key) { Contract.Requires(writer != null); Contract.Requires(key != null && (key.AlgorithmGroup == CngAlgorithmGroup.ECDsa || key.AlgorithmGroup == CngAlgorithmGroup.ECDiffieHellman)); writer.WriteStartElement(PublicKeyRoot); byte[] exportedKey = key.Export(CngKeyBlobFormat.EccPublicBlob); BigInteger x; BigInteger y; NCryptNative.UnpackEccPublicBlob(exportedKey, out x, out y); writer.WriteStartElement(XElement); writer.WriteAttributeString(ValueAttribute, x.ToString("R", CultureInfo.InvariantCulture)); writer.WriteAttributeString(XsiNamespacePrefix, XsiTypeAttribute, XsiNamespace, XsiTypeAttributeValue); writer.WriteEndElement(); // </X> writer.WriteStartElement(YElement); writer.WriteAttributeString(ValueAttribute, y.ToString("R", CultureInfo.InvariantCulture)); writer.WriteAttributeString(XsiNamespacePrefix, XsiTypeAttribute, XsiNamespace, XsiTypeAttributeValue); writer.WriteEndElement(); // </Y> writer.WriteEndElement(); // </PublicKey> } /// <summary> /// Convert a key to XML /// </summary> internal static string ToXml(CngKey key) { Contract.Requires(key != null && (key.AlgorithmGroup == CngAlgorithmGroup.ECDsa || key.AlgorithmGroup == CngAlgorithmGroup.ECDiffieHellman)); Contract.Ensures(Contract.Result<String>() != null); StringBuilder keyXml = new StringBuilder(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = " "; settings.OmitXmlDeclaration = true; using (XmlWriter writer = XmlWriter.Create(keyXml, settings)) { // The root element depends upon the type of key string rootElement = key.AlgorithmGroup == CngAlgorithmGroup.ECDsa ? ECDsaRoot : ECDHRoot; writer.WriteStartElement(rootElement, Namespace); WriteDomainParameters(writer, key); WritePublicKeyValue(writer, key); writer.WriteEndElement(); // root element } return keyXml.ToString(); } } }
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using Google.Api.Gax; using Google.Api.Gax.Grpc; using Google.Protobuf.WellKnownTypes; using Grpc.Core; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Threading; using System.Threading.Tasks; namespace Google.Cloud.ErrorReporting.V1Beta1 { /// <summary> /// Settings for a <see cref="ReportErrorsServiceClient"/>. /// </summary> public sealed partial class ReportErrorsServiceSettings : ServiceSettingsBase { /// <summary> /// Get a new instance of the default <see cref="ReportErrorsServiceSettings"/>. /// </summary> /// <returns> /// A new instance of the default <see cref="ReportErrorsServiceSettings"/>. /// </returns> public static ReportErrorsServiceSettings GetDefault() => new ReportErrorsServiceSettings(); /// <summary> /// Constructs a new <see cref="ReportErrorsServiceSettings"/> object with default settings. /// </summary> public ReportErrorsServiceSettings() { } private ReportErrorsServiceSettings(ReportErrorsServiceSettings existing) : base(existing) { GaxPreconditions.CheckNotNull(existing, nameof(existing)); ReportErrorEventSettings = existing.ReportErrorEventSettings; OnCopy(existing); } partial void OnCopy(ReportErrorsServiceSettings existing); /// <summary> /// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry /// for "Idempotent" <see cref="ReportErrorsServiceClient"/> RPC methods. /// </summary> /// <remarks> /// The eligible RPC <see cref="StatusCode"/>s for retry for "Idempotent" RPC methods are: /// <list type="bullet"> /// <item><description><see cref="StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="StatusCode.Unavailable"/></description></item> /// </list> /// </remarks> public static Predicate<RpcException> IdempotentRetryFilter { get; } = RetrySettings.FilterForStatusCodes(StatusCode.DeadlineExceeded, StatusCode.Unavailable); /// <summary> /// The filter specifying which RPC <see cref="StatusCode"/>s are eligible for retry /// for "NonIdempotent" <see cref="ReportErrorsServiceClient"/> RPC methods. /// </summary> /// <remarks> /// There are no RPC <see cref="StatusCode"/>s eligible for retry for "NonIdempotent" RPC methods. /// </remarks> public static Predicate<RpcException> NonIdempotentRetryFilter { get; } = RetrySettings.FilterForStatusCodes(); /// <summary> /// "Default" retry backoff for <see cref="ReportErrorsServiceClient"/> RPC methods. /// </summary> /// <returns> /// The "Default" retry backoff for <see cref="ReportErrorsServiceClient"/> RPC methods. /// </returns> /// <remarks> /// The "Default" retry backoff for <see cref="ReportErrorsServiceClient"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial delay: 100 milliseconds</description></item> /// <item><description>Maximum delay: 60000 milliseconds</description></item> /// <item><description>Delay multiplier: 1.3</description></item> /// </list> /// </remarks> public static BackoffSettings GetDefaultRetryBackoff() => new BackoffSettings( delay: TimeSpan.FromMilliseconds(100), maxDelay: TimeSpan.FromMilliseconds(60000), delayMultiplier: 1.3 ); /// <summary> /// "Default" timeout backoff for <see cref="ReportErrorsServiceClient"/> RPC methods. /// </summary> /// <returns> /// The "Default" timeout backoff for <see cref="ReportErrorsServiceClient"/> RPC methods. /// </returns> /// <remarks> /// The "Default" timeout backoff for <see cref="ReportErrorsServiceClient"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Maximum timeout: 20000 milliseconds</description></item> /// </list> /// </remarks> public static BackoffSettings GetDefaultTimeoutBackoff() => new BackoffSettings( delay: TimeSpan.FromMilliseconds(20000), maxDelay: TimeSpan.FromMilliseconds(20000), delayMultiplier: 1.0 ); /// <summary> /// <see cref="CallSettings"/> for synchronous and asynchronous calls to /// <c>ReportErrorsServiceClient.ReportErrorEvent</c> and <c>ReportErrorsServiceClient.ReportErrorEventAsync</c>. /// </summary> /// <remarks> /// The default <c>ReportErrorsServiceClient.ReportErrorEvent</c> and /// <c>ReportErrorsServiceClient.ReportErrorEventAsync</c> <see cref="RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 20000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 20000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description>No status codes</description></item> /// </list> /// Default RPC expiration is 600000 milliseconds. /// </remarks> public CallSettings ReportErrorEventSettings { get; set; } = CallSettings.FromCallTiming( CallTiming.FromRetry(new RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: Expiration.FromTimeout(TimeSpan.FromMilliseconds(600000)), retryFilter: NonIdempotentRetryFilter ))); /// <summary> /// Creates a deep clone of this object, with all the same property values. /// </summary> /// <returns>A deep clone of this <see cref="ReportErrorsServiceSettings"/> object.</returns> public ReportErrorsServiceSettings Clone() => new ReportErrorsServiceSettings(this); } /// <summary> /// ReportErrorsService client wrapper, for convenient use. /// </summary> public abstract partial class ReportErrorsServiceClient { /// <summary> /// The default endpoint for the ReportErrorsService service, which is a host of "clouderrorreporting.googleapis.com" and a port of 443. /// </summary> public static ServiceEndpoint DefaultEndpoint { get; } = new ServiceEndpoint("clouderrorreporting.googleapis.com", 443); /// <summary> /// The default ReportErrorsService scopes. /// </summary> /// <remarks> /// The default ReportErrorsService scopes are: /// <list type="bullet"> /// <item><description>"https://www.googleapis.com/auth/cloud-platform"</description></item> /// </list> /// </remarks> public static IReadOnlyList<string> DefaultScopes { get; } = new ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", }); private static readonly ChannelPool s_channelPool = new ChannelPool(DefaultScopes); // Note: we could have parameterless overloads of Create and CreateAsync, // documented to just use the default endpoint, settings and credentials. // Pros: // - Might be more reassuring on first use // - Allows method group conversions // Con: overloads! /// <summary> /// Asynchronously creates a <see cref="ReportErrorsServiceClient"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. /// </summary> /// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="ReportErrorsServiceSettings"/>.</param> /// <returns>The task representing the created <see cref="ReportErrorsServiceClient"/>.</returns> public static async Task<ReportErrorsServiceClient> CreateAsync(ServiceEndpoint endpoint = null, ReportErrorsServiceSettings settings = null) { Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false); return Create(channel, settings); } /// <summary> /// Synchronously creates a <see cref="ReportErrorsServiceClient"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. /// </summary> /// <param name="endpoint">Optional <see cref="ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="ReportErrorsServiceSettings"/>.</param> /// <returns>The created <see cref="ReportErrorsServiceClient"/>.</returns> public static ReportErrorsServiceClient Create(ServiceEndpoint endpoint = null, ReportErrorsServiceSettings settings = null) { Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint); return Create(channel, settings); } /// <summary> /// Creates a <see cref="ReportErrorsServiceClient"/> which uses the specified channel for remote operations. /// </summary> /// <param name="channel">The <see cref="Channel"/> for remote operations. Must not be null.</param> /// <param name="settings">Optional <see cref="ReportErrorsServiceSettings"/>.</param> /// <returns>The created <see cref="ReportErrorsServiceClient"/>.</returns> public static ReportErrorsServiceClient Create(Channel channel, ReportErrorsServiceSettings settings = null) { GaxPreconditions.CheckNotNull(channel, nameof(channel)); ReportErrorsService.ReportErrorsServiceClient grpcClient = new ReportErrorsService.ReportErrorsServiceClient(channel); return new ReportErrorsServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create(ServiceEndpoint, ReportErrorsServiceSettings)"/> /// and <see cref="CreateAsync(ServiceEndpoint, ReportErrorsServiceSettings)"/>. Channels which weren't automatically /// created are not affected. /// </summary> /// <remarks>After calling this method, further calls to <see cref="Create(ServiceEndpoint, ReportErrorsServiceSettings)"/> /// and <see cref="CreateAsync(ServiceEndpoint, ReportErrorsServiceSettings)"/> will create new channels, which could /// in turn be shut down by another call to this method.</remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync(); /// <summary> /// The underlying gRPC ReportErrorsService client. /// </summary> public virtual ReportErrorsService.ReportErrorsServiceClient GrpcClient { get { throw new NotImplementedException(); } } /// <summary> /// Report an individual error event. /// /// This endpoint accepts &lt;strong&gt;either&lt;/strong&gt; an OAuth token, /// &lt;strong&gt;or&lt;/strong&gt; an /// &lt;a href="https://support.google.com/cloud/answer/6158862"&gt;API key&lt;/a&gt; /// for authentication. To use an API key, append it to the URL as the value of /// a `key` parameter. For example: /// &lt;pre&gt;POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456&lt;/pre&gt; /// </summary> /// <param name="projectName"> /// [Required] The resource name of the Google Cloud Platform project. Written /// as `projects/` plus the /// [Google Cloud Platform project ID](https://support.google.com/cloud/answer/6158840). /// Example: `projects/my-project-123`. /// </param> /// <param name="event"> /// [Required] The error event to be reported. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<ReportErrorEventResponse> ReportErrorEventAsync( ProjectName projectName, ReportedErrorEvent @event, CallSettings callSettings = null) => ReportErrorEventAsync( new ReportErrorEventRequest { ProjectNameAsProjectName = GaxPreconditions.CheckNotNull(projectName, nameof(projectName)), Event = GaxPreconditions.CheckNotNull(@event, nameof(@event)), }, callSettings); /// <summary> /// Report an individual error event. /// /// This endpoint accepts &lt;strong&gt;either&lt;/strong&gt; an OAuth token, /// &lt;strong&gt;or&lt;/strong&gt; an /// &lt;a href="https://support.google.com/cloud/answer/6158862"&gt;API key&lt;/a&gt; /// for authentication. To use an API key, append it to the URL as the value of /// a `key` parameter. For example: /// &lt;pre&gt;POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456&lt;/pre&gt; /// </summary> /// <param name="projectName"> /// [Required] The resource name of the Google Cloud Platform project. Written /// as `projects/` plus the /// [Google Cloud Platform project ID](https://support.google.com/cloud/answer/6158840). /// Example: `projects/my-project-123`. /// </param> /// <param name="event"> /// [Required] The error event to be reported. /// </param> /// <param name="cancellationToken"> /// A <see cref="CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<ReportErrorEventResponse> ReportErrorEventAsync( ProjectName projectName, ReportedErrorEvent @event, CancellationToken cancellationToken) => ReportErrorEventAsync( projectName, @event, CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Report an individual error event. /// /// This endpoint accepts &lt;strong&gt;either&lt;/strong&gt; an OAuth token, /// &lt;strong&gt;or&lt;/strong&gt; an /// &lt;a href="https://support.google.com/cloud/answer/6158862"&gt;API key&lt;/a&gt; /// for authentication. To use an API key, append it to the URL as the value of /// a `key` parameter. For example: /// &lt;pre&gt;POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456&lt;/pre&gt; /// </summary> /// <param name="projectName"> /// [Required] The resource name of the Google Cloud Platform project. Written /// as `projects/` plus the /// [Google Cloud Platform project ID](https://support.google.com/cloud/answer/6158840). /// Example: `projects/my-project-123`. /// </param> /// <param name="event"> /// [Required] The error event to be reported. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual ReportErrorEventResponse ReportErrorEvent( ProjectName projectName, ReportedErrorEvent @event, CallSettings callSettings = null) => ReportErrorEvent( new ReportErrorEventRequest { ProjectNameAsProjectName = GaxPreconditions.CheckNotNull(projectName, nameof(projectName)), Event = GaxPreconditions.CheckNotNull(@event, nameof(@event)), }, callSettings); /// <summary> /// Report an individual error event. /// /// This endpoint accepts &lt;strong&gt;either&lt;/strong&gt; an OAuth token, /// &lt;strong&gt;or&lt;/strong&gt; an /// &lt;a href="https://support.google.com/cloud/answer/6158862"&gt;API key&lt;/a&gt; /// for authentication. To use an API key, append it to the URL as the value of /// a `key` parameter. For example: /// &lt;pre&gt;POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456&lt;/pre&gt; /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual Task<ReportErrorEventResponse> ReportErrorEventAsync( ReportErrorEventRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } /// <summary> /// Report an individual error event. /// /// This endpoint accepts &lt;strong&gt;either&lt;/strong&gt; an OAuth token, /// &lt;strong&gt;or&lt;/strong&gt; an /// &lt;a href="https://support.google.com/cloud/answer/6158862"&gt;API key&lt;/a&gt; /// for authentication. To use an API key, append it to the URL as the value of /// a `key` parameter. For example: /// &lt;pre&gt;POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456&lt;/pre&gt; /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual ReportErrorEventResponse ReportErrorEvent( ReportErrorEventRequest request, CallSettings callSettings = null) { throw new NotImplementedException(); } } /// <summary> /// ReportErrorsService client wrapper implementation, for convenient use. /// </summary> public sealed partial class ReportErrorsServiceClientImpl : ReportErrorsServiceClient { private readonly ApiCall<ReportErrorEventRequest, ReportErrorEventResponse> _callReportErrorEvent; /// <summary> /// Constructs a client wrapper for the ReportErrorsService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="ReportErrorsServiceSettings"/> used within this client </param> public ReportErrorsServiceClientImpl(ReportErrorsService.ReportErrorsServiceClient grpcClient, ReportErrorsServiceSettings settings) { GrpcClient = grpcClient; ReportErrorsServiceSettings effectiveSettings = settings ?? ReportErrorsServiceSettings.GetDefault(); ClientHelper clientHelper = new ClientHelper(effectiveSettings); _callReportErrorEvent = clientHelper.BuildApiCall<ReportErrorEventRequest, ReportErrorEventResponse>( GrpcClient.ReportErrorEventAsync, GrpcClient.ReportErrorEvent, effectiveSettings.ReportErrorEventSettings); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void OnConstruction(ReportErrorsService.ReportErrorsServiceClient grpcClient, ReportErrorsServiceSettings effectiveSettings, ClientHelper clientHelper); /// <summary> /// The underlying gRPC ReportErrorsService client. /// </summary> public override ReportErrorsService.ReportErrorsServiceClient GrpcClient { get; } // Partial modifier methods contain '_' to ensure no name conflicts with RPC methods. partial void Modify_ReportErrorEventRequest(ref ReportErrorEventRequest request, ref CallSettings settings); /// <summary> /// Report an individual error event. /// /// This endpoint accepts &lt;strong&gt;either&lt;/strong&gt; an OAuth token, /// &lt;strong&gt;or&lt;/strong&gt; an /// &lt;a href="https://support.google.com/cloud/answer/6158862"&gt;API key&lt;/a&gt; /// for authentication. To use an API key, append it to the URL as the value of /// a `key` parameter. For example: /// &lt;pre&gt;POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456&lt;/pre&gt; /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override Task<ReportErrorEventResponse> ReportErrorEventAsync( ReportErrorEventRequest request, CallSettings callSettings = null) { Modify_ReportErrorEventRequest(ref request, ref callSettings); return _callReportErrorEvent.Async(request, callSettings); } /// <summary> /// Report an individual error event. /// /// This endpoint accepts &lt;strong&gt;either&lt;/strong&gt; an OAuth token, /// &lt;strong&gt;or&lt;/strong&gt; an /// &lt;a href="https://support.google.com/cloud/answer/6158862"&gt;API key&lt;/a&gt; /// for authentication. To use an API key, append it to the URL as the value of /// a `key` parameter. For example: /// &lt;pre&gt;POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456&lt;/pre&gt; /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override ReportErrorEventResponse ReportErrorEvent( ReportErrorEventRequest request, CallSettings callSettings = null) { Modify_ReportErrorEventRequest(ref request, ref callSettings); return _callReportErrorEvent.Sync(request, callSettings); } } // Partial classes to enable page-streaming }
using UnityEditor; using UnityEngine; using System.Collections.Generic; namespace Rx { [CustomEditor( typeof( DebugShape2 ), true )] public class DebugShape2Editor : Editor { public void OnSceneGUI() { DebugShape2 targetShape = (DebugShape2)target; UpdateSelection( targetShape ); // Get the mouse position. Ray ray = HandleUtility.GUIPointToWorldRay( Event.current.mousePosition ); Vector3 mousePosition = ray.GetPoint( ( targetShape.transform.position - Camera.current.transform.position ).magnitude ); switch ( Event.current.type ) { case EventType.mouseDrag: { targetShape.OnMouseDrag( mousePosition ); EditorUtility.SetDirty( targetShape ); } break; case EventType.mouseMove: { targetShape.OnMouseMove( mousePosition ); EditorUtility.SetDirty( targetShape ); } break; case EventType.mouseDown: { targetShape.OnMouseDown( mousePosition ); EditorUtility.SetDirty( targetShape ); } break; case EventType.keyDown: { targetShape.OnKeyDown( Event.current.keyCode, mousePosition ); EditorUtility.SetDirty( targetShape ); } break; case EventType.layout: { // This blocks mouse clicks from deselecting the nav mesh while in edit mode. int controlID = GUIUtility.GetControlID( FocusType.Passive ); HandleUtility.AddDefaultControl( controlID ); } break; } } protected void UpdateSelection( DebugShape2 selectedShape ) { DebugShape2[] debugShapes = FindObjectsOfType( typeof( DebugShape2 ) ) as DebugShape2[]; foreach ( DebugShape2 debugShape in debugShapes ) { debugShape.IsSelected = false; } selectedShape.IsSelected = true; } public override void OnInspectorGUI() { base.OnInspectorGUI(); ClearHighlighting(); DebugShape2 selectedShape = (DebugShape2)target; if ( selectedShape is DebugPoint2 ) { OnDebugPointInspectorGUI( selectedShape as DebugPoint2 ); } else if ( selectedShape is DebugLine2 ) { OnDebugLineInspectorGUI( selectedShape as DebugLine2 ); } else if ( selectedShape is DebugRay2 ) { OnDebugRayInspectorGUI( selectedShape as DebugRay2 ); } else if ( selectedShape is DebugTriangle2 ) { OnDebugTriangleInspectorGUI( selectedShape as DebugTriangle2 ); } else if ( selectedShape is DebugPolygon2 ) { OnDebugPolygonInspectorGUI( selectedShape as DebugPolygon2 ); } EditorUtility.SetDirty( selectedShape ); } protected void ClearHighlighting() { DebugShape2[] debugShapes = FindObjectsOfType( typeof( DebugShape2 ) ) as DebugShape2[]; foreach ( DebugShape2 debugShape in debugShapes ) { debugShape.IsHighlighted = false; debugShape.PointsOfIntersection = new List<Vector2>(); } } protected void OnDebugPointInspectorGUI( DebugPoint2 selectedDebugPoint ) { GUILayout.BeginVertical(); selectedDebugPoint.CheckContainingPolygons = GUILayout.Toggle( selectedDebugPoint.CheckContainingPolygons, "Containment (Polygons)" ); GUILayout.EndVertical(); if ( selectedDebugPoint.CheckContainingPolygons ) { DebugPolygon2[] debugPolygons = FindObjectsOfType( typeof( DebugPolygon2 ) ) as DebugPolygon2[]; Vector2 worldPoint = selectedDebugPoint.GetWorldVertices()[0]; foreach ( DebugPolygon2 debugPolygon in debugPolygons ) { List<Vector2> worldPolygon = debugPolygon.GetWorldVertices(); if ( Geometry2.PolygonIsConvex( worldPolygon ) ) { if ( Geometry2.ConvexPolygonContainsPoint( worldPolygon, worldPoint ) ) { debugPolygon.IsHighlighted = true; EditorUtility.SetDirty( debugPolygon ); } } else { if ( Geometry2.PolygonContainsPoint( worldPolygon, worldPoint ) ) { debugPolygon.IsHighlighted = true; EditorUtility.SetDirty( debugPolygon ); } } } } } protected void OnDebugLineInspectorGUI( DebugLine2 selectedDebugLine ) { GUILayout.BeginVertical(); selectedDebugLine.CheckIntersectingSegments = GUILayout.Toggle( selectedDebugLine.CheckIntersectingSegments, "Intersection (Segments)" ); selectedDebugLine.ShowPointsOfIntersectionWithSegments = GUILayout.Toggle( selectedDebugLine.ShowPointsOfIntersectionWithSegments, "Points of Intersection (Segment)" ); selectedDebugLine.CheckIntersectingPolygons = GUILayout.Toggle( selectedDebugLine.CheckIntersectingPolygons, "Intersection (Polygons)" ); bool centerGizmo = GUILayout.Button( "Center Gizmo" ); GUILayout.EndVertical(); if ( selectedDebugLine.CheckIntersectingSegments || selectedDebugLine.ShowPointsOfIntersectionWithSegments ) { DebugLine2[] debugLines = FindObjectsOfType( typeof( DebugLine2 ) ) as DebugLine2[]; List<Vector2> selectedDebugLineVertices = selectedDebugLine.GetWorldVertices(); List<Vector2> pointsOfIntersection = new List<Vector2>(); foreach ( DebugLine2 debugLine in debugLines ) { if ( debugLine != selectedDebugLine ) { List<Vector2> debugLineVertices = debugLine.GetWorldVertices(); if ( selectedDebugLine.ShowPointsOfIntersectionWithSegments ) { Vector2 pointOfIntersection; if ( Geometry2.SegmentAgainstSegment( debugLineVertices[0], debugLineVertices[1], selectedDebugLineVertices[0], selectedDebugLineVertices[1], out pointOfIntersection ) ) { pointsOfIntersection.Add( pointOfIntersection ); if ( selectedDebugLine.CheckIntersectingSegments ) { debugLine.IsHighlighted = true; EditorUtility.SetDirty( debugLine ); } } } else { if ( Geometry2.SegmentsIntersect( debugLineVertices[0], debugLineVertices[1], selectedDebugLineVertices[0], selectedDebugLineVertices[1] ) ) { debugLine.IsHighlighted = true; EditorUtility.SetDirty( debugLine ); } } } } selectedDebugLine.PointsOfIntersection.AddRange( pointsOfIntersection ); EditorUtility.SetDirty( selectedDebugLine ); } if ( selectedDebugLine.CheckIntersectingPolygons ) { DebugPolygon2[] debugPolygons = FindObjectsOfType( typeof( DebugPolygon2 ) ) as DebugPolygon2[]; List<Vector2> selectedDebugLineVertices = selectedDebugLine.GetWorldVertices(); foreach ( DebugPolygon2 debugPolygon in debugPolygons ) { List<Vector2> pointsOfIntersection = Geometry2.SegmentAgainstPolygon( selectedDebugLineVertices[0], selectedDebugLineVertices[1], debugPolygon.GetWorldVertices() ); if ( pointsOfIntersection.Count > 0 ) { debugPolygon.IsHighlighted = true; EditorUtility.SetDirty( debugPolygon ); selectedDebugLine.PointsOfIntersection.AddRange( pointsOfIntersection ); EditorUtility.SetDirty( selectedDebugLine ); } } } if ( centerGizmo ) { selectedDebugLine.CenterGizmo(); } } protected void OnDebugRayInspectorGUI( DebugRay2 selectedDebugRay ) { GUILayout.BeginVertical(); selectedDebugRay.CheckIntersectingSegments = GUILayout.Toggle( selectedDebugRay.CheckIntersectingSegments, "Intersection (Segments)" ); selectedDebugRay.ShowPointsOfIntersectionWithSegments = GUILayout.Toggle( selectedDebugRay.ShowPointsOfIntersectionWithSegments, "Points of Intersection (Segment)" ); selectedDebugRay.CheckIntersectingPolygons = GUILayout.Toggle( selectedDebugRay.CheckIntersectingPolygons, "Intersection (Polygons)" ); bool centerGizmo = GUILayout.Button( "Center Gizmo" ); GUILayout.EndVertical(); List<Vector2> selectedDebugRayVertices = selectedDebugRay.GetWorldVertices(); Vector2 selectedDebugRayStart = selectedDebugRayVertices[0]; Vector2 selectedDebugRayDir = selectedDebugRayVertices[1] - selectedDebugRayVertices[0]; if ( selectedDebugRay.CheckIntersectingSegments || selectedDebugRay.ShowPointsOfIntersectionWithSegments ) { DebugLine2[] debugLines = FindObjectsOfType( typeof( DebugLine2 ) ) as DebugLine2[]; List<Vector2> pointsOfIntersection = new List<Vector2>(); foreach ( DebugLine2 debugLine in debugLines ) { List<Vector2> debugLineVertices = debugLine.GetWorldVertices(); if ( selectedDebugRay.ShowPointsOfIntersectionWithSegments ) { Vector2 pointOfIntersection; if ( Geometry2.RayAgainstSegment( selectedDebugRayStart, selectedDebugRayDir, debugLineVertices[0], debugLineVertices[1], out pointOfIntersection ) ) { pointsOfIntersection.Add( pointOfIntersection ); if ( selectedDebugRay.CheckIntersectingSegments ) { debugLine.IsHighlighted = true; EditorUtility.SetDirty( debugLine ); } } } else { if ( Geometry2.RayIntersectsSegment( selectedDebugRayStart, selectedDebugRayDir, debugLineVertices[0], debugLineVertices[1] ) ) { debugLine.IsHighlighted = true; EditorUtility.SetDirty( debugLine ); } } } selectedDebugRay.PointsOfIntersection.AddRange( pointsOfIntersection ); EditorUtility.SetDirty( selectedDebugRay ); } if ( selectedDebugRay.CheckIntersectingPolygons ) { DebugPolygon2[] debugPolygons = FindObjectsOfType( typeof( DebugPolygon2 ) ) as DebugPolygon2[]; foreach ( DebugPolygon2 debugPolygon in debugPolygons ) { List<Vector2> pointsOfIntersection = Geometry2.RayAgainstPolygon( selectedDebugRayStart, selectedDebugRayDir, debugPolygon.GetWorldVertices() ); if ( pointsOfIntersection.Count > 0 ) { debugPolygon.IsHighlighted = true; EditorUtility.SetDirty( debugPolygon ); selectedDebugRay.PointsOfIntersection.AddRange( pointsOfIntersection ); EditorUtility.SetDirty( selectedDebugRay ); } } } if ( centerGizmo ) { selectedDebugRay.CenterGizmo(); } } protected void OnDebugTriangleInspectorGUI( DebugTriangle2 selectedDebugTriangle ) { List<Vector2> debugTriangleVertices = selectedDebugTriangle.GetWorldVertices(); string windingLabelText = "Winding: "; float area = Geometry2.SignedTriangleArea( debugTriangleVertices[0], debugTriangleVertices[1], debugTriangleVertices[2] ); if ( area > 0 ) { windingLabelText += "CCW"; } else if ( area < 0 ) { windingLabelText += "CW"; } else { windingLabelText += "DEGENERATE"; } GUILayout.BeginVertical(); GUILayout.Label( windingLabelText ); selectedDebugTriangle.CheckPointsInside = GUILayout.Toggle( selectedDebugTriangle.CheckPointsInside, "Containing (Points)" ); bool centerGizmo = GUILayout.Button( "Center Gizmo" ); GUILayout.EndVertical(); if ( selectedDebugTriangle.CheckPointsInside ) { DebugPoint2[] debugPoints = FindObjectsOfType( typeof( DebugPoint2 ) ) as DebugPoint2[]; foreach ( DebugPoint2 debugPoint in debugPoints ) { if ( Geometry2.TriangleContainsPoint( debugTriangleVertices[0], debugTriangleVertices[1], debugTriangleVertices[2], debugPoint.GetWorldVertices()[0] ) ) { debugPoint.IsHighlighted = true; EditorUtility.SetDirty( debugPoint ); } } } if ( centerGizmo ) { selectedDebugTriangle.CenterGizmo(); } } protected void OnDebugPolygonInspectorGUI( DebugPolygon2 selectedDebugPolygon ) { DebugShape2.hackHide = false; List<Vector2> selectedDebugPolygonVertices = selectedDebugPolygon.GetWorldVertices(); bool debugPolygonIsConvex = Geometry2.PolygonIsConvex( selectedDebugPolygonVertices ); string convexityLabelText = "Convexity: "; if ( debugPolygonIsConvex ) { convexityLabelText += "Convex"; } else { convexityLabelText += "Concave"; } string windingLabelText = "Winding: "; if ( Geometry2.PolygonIsCCW( selectedDebugPolygonVertices ) ) { windingLabelText += "CCW"; } else { windingLabelText += "CW"; } GUILayout.BeginVertical(); selectedDebugPolygon.CheckPointsInside = GUILayout.Toggle( selectedDebugPolygon.CheckPointsInside, "Containing (Points)" ); selectedDebugPolygon.CheckIntersectingSegments = GUILayout.Toggle( selectedDebugPolygon.CheckIntersectingSegments, "Intersecting (Segments)" ); selectedDebugPolygon.CheckIntersectingPolygons = GUILayout.Toggle( selectedDebugPolygon.CheckIntersectingPolygons, "Intersecting (Polygons)" ); selectedDebugPolygon.CheckPolygonsInside = GUILayout.Toggle( selectedDebugPolygon.CheckPolygonsInside, "Containing (Polygons)" ); GUILayout.Label( convexityLabelText ); GUILayout.Label( windingLabelText ); bool fuseWithOverlappingPolygons = GUILayout.Button( "Fuse" ); bool reverseWinding = GUILayout.Button( "Reverse Winding" ); bool shiftUp = GUILayout.Button( "Shift Up" ); bool checkForErrors = GUILayout.Button( "Check for Errors" ); bool centerGizmo = GUILayout.Button( "Center Gizmo" ); GUILayout.EndVertical(); if ( reverseWinding ) { selectedDebugPolygon.ReverseVertices(); } if ( shiftUp ) { selectedDebugPolygon.ShiftUpVertices(); } if ( selectedDebugPolygon.CheckPointsInside ) { DebugPoint2[] debugPoints = FindObjectsOfType( typeof( DebugPoint2 ) ) as DebugPoint2[]; if ( Geometry2.PolygonIsConvex( selectedDebugPolygonVertices ) ) { foreach ( DebugPoint2 debugPoint in debugPoints ) { if ( Geometry2.ConvexPolygonContainsPoint( selectedDebugPolygonVertices, debugPoint.GetWorldVertices()[0] ) ) { debugPoint.IsHighlighted = true; EditorUtility.SetDirty( debugPoint ); } } } else { foreach ( DebugPoint2 debugPoint in debugPoints ) { if ( Geometry2.PolygonContainsPoint( selectedDebugPolygonVertices, debugPoint.GetWorldVertices()[0] ) ) { debugPoint.IsHighlighted = true; EditorUtility.SetDirty( debugPoint ); } } } } if ( selectedDebugPolygon.CheckIntersectingSegments ) { DebugLine2[] debugLines = FindObjectsOfType( typeof( DebugLine2 ) ) as DebugLine2[]; List<Vector2> pointsOfIntersection = new List<Vector2>(); foreach ( DebugLine2 debugLine in debugLines ) { List<Vector2> debugLineVertices = debugLine.GetWorldVertices(); List<Vector2> result = Geometry2.SegmentAgainstPolygon( debugLineVertices[0], debugLineVertices[1], selectedDebugPolygonVertices ); if ( result.Count > 0 ) { debugLine.IsHighlighted = true; EditorUtility.SetDirty( debugLine ); pointsOfIntersection.AddRange( result ); } } selectedDebugPolygon.PointsOfIntersection.AddRange( pointsOfIntersection ); EditorUtility.SetDirty( selectedDebugPolygon ); } if ( selectedDebugPolygon.CheckIntersectingPolygons ) { DebugPolygon2[] debugPolygons = FindObjectsOfType( typeof( DebugPolygon2 ) ) as DebugPolygon2[]; List<Vector2> pointsOfIntersection = new List<Vector2>(); foreach ( DebugPolygon2 debugPolygon in debugPolygons ) { if ( selectedDebugPolygon != debugPolygon ) { List<Vector2> debugPolygonVertices = debugPolygon.GetWorldVertices(); List<Vector2> result = Geometry2.PolygonAgainstPolygon( selectedDebugPolygonVertices, debugPolygonVertices ); if ( result.Count > 0 ) { debugPolygon.IsHighlighted = true; EditorUtility.SetDirty( debugPolygon ); pointsOfIntersection.AddRange( result ); } } } selectedDebugPolygon.PointsOfIntersection.AddRange( pointsOfIntersection ); EditorUtility.SetDirty( selectedDebugPolygon ); } if ( selectedDebugPolygon.CheckPolygonsInside ) { DebugPolygon2[] debugPolygons = FindObjectsOfType( typeof( DebugPolygon2 ) ) as DebugPolygon2[]; foreach ( DebugPolygon2 debugPolygon in debugPolygons ) { if ( selectedDebugPolygon != debugPolygon ) { List<Vector2> debugPolygonVertices = debugPolygon.GetWorldVertices(); if ( Geometry2.PolygonContainsPolygon( selectedDebugPolygonVertices, debugPolygonVertices ) ) { debugPolygon.IsHighlighted = true; EditorUtility.SetDirty( debugPolygon ); } } } } if ( fuseWithOverlappingPolygons ) { DebugPolygon2[] debugPolygons = FindObjectsOfType( typeof( DebugPolygon2 ) ) as DebugPolygon2[]; List< List<Vector2> > polygons = new List< List<Vector2> >( debugPolygons.Length ); foreach ( DebugPolygon2 debugPolygon in debugPolygons ) { polygons.Add( debugPolygon.GetWorldVertices() ); } Polygon2Clipper clipper = new Polygon2Clipper(); List< List<Vector2> > result = new List<List<Vector2>>(); if ( polygons.Count == 2 ) { // TODO: clip against all intersecting polygons clipper.Reset(); clipper.AddAdditivePolygon( polygons[0] ); clipper.AddAdditivePolygon( polygons[1] ); result = clipper.FusePolygons(); } GameObject parentObject = new GameObject( "FuseResult" ); foreach ( List<Vector2> polygon in result ) { GameObject newObject = new GameObject( "Polygon" ); newObject.AddComponent( "DebugPolygon2" ); DebugPolygon2 newDebugPolygon = newObject.GetComponent<DebugPolygon2>(); newDebugPolygon.vertices = polygon; newObject.transform.parent = parentObject.transform; } /*DebugPolygon2[] debugPolygons = FindObjectsOfType( typeof( DebugPolygon2 ) ) as DebugPolygon2[]; List<int> visitedPolygons = new List<int>(); List<Vector2> result = selectedDebugPolygonVertices; for ( int i = 0; i < debugPolygons.Length; ) { if ( !visitedPolygons.Contains( i ) && ( selectedDebugPolygon != debugPolygons[i] ) ) { List<Vector2> debugPolygonVertices = debugPolygons[i].GetWorldVertices(); if ( Geometry2.PolygonsIntersect( result, debugPolygonVertices ) ) { result = Geometry2.FusePolygons( result, debugPolygonVertices ); visitedPolygons.Add( i ); i = 0; } else { ++i; } } else { ++i; } } GameObject newObject = new GameObject( "FuseResult" ); newObject.AddComponent( "DebugPolygon2" ); DebugPolygon2 newDebugPolygon = newObject.GetComponent<DebugPolygon2>(); newDebugPolygon.vertices = result;*/ } if ( checkForErrors ) { CheckPolygonForErrors( selectedDebugPolygon ); } if ( centerGizmo ) { selectedDebugPolygon.CenterGizmo(); } } protected void CheckPolygonForErrors( DebugPolygon2 debugPolygon ) { bool allClear = true; List<Vector2> vertices = debugPolygon.vertices; List<Vector2> worldVertices = debugPolygon.GetWorldVertices(); // Polygons must have at least three points. if ( vertices.Count < 3 ) { Debug.LogWarning( "Polygon [" + debugPolygon + "] doesn't have enough vertices." ); } // Check for duplicate vertices. for ( int i = 0; i < vertices.Count; ++i ) { for ( int j = i + 1; j < vertices.Count; ++j ) { if ( vertices[i] == vertices[j] ) { Debug.LogWarning( "Polygon [" + debugPolygon + "] has duplicate vertices at" + worldVertices[i] ); allClear = false; } } } // Check for self intersection. if ( Geometry2.PolygonsIntersect( worldVertices, worldVertices ) ) { Debug.LogWarning( "Polygon [" + debugPolygon + "] intersects with itself." ); allClear = false; } if ( allClear ) { Debug.Log( "No problems found for polygon [" + debugPolygon + "]." ); } } } }
//--------------------------------------------------------------------------- // // <copyright file="RadialGradientBrush.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.KnownBoxes; using MS.Internal.Collections; using MS.Internal.PresentationCore; using MS.Utility; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.ComponentModel.Design.Serialization; using System.Text; using System.Windows; using System.Windows.Media; using System.Windows.Media.Effects; using System.Windows.Media.Media3D; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using System.Windows.Media.Imaging; using System.Windows.Markup; using System.Windows.Media.Converters; using System.Security; using System.Security.Permissions; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; // These types are aliased to match the unamanaged names used in interop using BOOL = System.UInt32; using WORD = System.UInt16; using Float = System.Single; namespace System.Windows.Media { sealed partial class RadialGradientBrush : GradientBrush { //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Shadows inherited Clone() with a strongly typed /// version for convenience. /// </summary> public new RadialGradientBrush Clone() { return (RadialGradientBrush)base.Clone(); } /// <summary> /// Shadows inherited CloneCurrentValue() with a strongly typed /// version for convenience. /// </summary> public new RadialGradientBrush CloneCurrentValue() { return (RadialGradientBrush)base.CloneCurrentValue(); } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ private static void CenterPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { RadialGradientBrush target = ((RadialGradientBrush) d); target.PropertyChanged(CenterProperty); } private static void RadiusXPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { RadialGradientBrush target = ((RadialGradientBrush) d); target.PropertyChanged(RadiusXProperty); } private static void RadiusYPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { RadialGradientBrush target = ((RadialGradientBrush) d); target.PropertyChanged(RadiusYProperty); } private static void GradientOriginPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { RadialGradientBrush target = ((RadialGradientBrush) d); target.PropertyChanged(GradientOriginProperty); } #region Public Properties /// <summary> /// Center - Point. Default value is new Point(0.5,0.5). /// </summary> public Point Center { get { return (Point) GetValue(CenterProperty); } set { SetValueInternal(CenterProperty, value); } } /// <summary> /// RadiusX - double. Default value is 0.5. /// </summary> public double RadiusX { get { return (double) GetValue(RadiusXProperty); } set { SetValueInternal(RadiusXProperty, value); } } /// <summary> /// RadiusY - double. Default value is 0.5. /// </summary> public double RadiusY { get { return (double) GetValue(RadiusYProperty); } set { SetValueInternal(RadiusYProperty, value); } } /// <summary> /// GradientOrigin - Point. Default value is new Point(0.5,0.5). /// </summary> public Point GradientOrigin { get { return (Point) GetValue(GradientOriginProperty); } set { SetValueInternal(GradientOriginProperty, value); } } #endregion Public Properties //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new RadialGradientBrush(); } #endregion ProtectedMethods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods /// <SecurityNote> /// Critical: This code calls into an unsafe code block /// TreatAsSafe: This code does not return any critical data.It is ok to expose /// Channels are safe to call into and do not go cross domain and cross process /// </SecurityNote> [SecurityCritical,SecurityTreatAsSafe] internal override void UpdateResource(DUCE.Channel channel, bool skipOnChannelCheck) { ManualUpdateResource(channel, skipOnChannelCheck); base.UpdateResource(channel, skipOnChannelCheck); } internal override DUCE.ResourceHandle AddRefOnChannelCore(DUCE.Channel channel) { if (_duceResource.CreateOrAddRefOnChannel(this, channel, System.Windows.Media.Composition.DUCE.ResourceType.TYPE_RADIALGRADIENTBRUSH)) { Transform vTransform = Transform; if (vTransform != null) ((DUCE.IResource)vTransform).AddRefOnChannel(channel); Transform vRelativeTransform = RelativeTransform; if (vRelativeTransform != null) ((DUCE.IResource)vRelativeTransform).AddRefOnChannel(channel); AddRefOnChannelAnimations(channel); UpdateResource(channel, true /* skip "on channel" check - we already know that we're on channel */ ); } return _duceResource.GetHandle(channel); } internal override void ReleaseOnChannelCore(DUCE.Channel channel) { Debug.Assert(_duceResource.IsOnChannel(channel)); if (_duceResource.ReleaseOnChannel(channel)) { Transform vTransform = Transform; if (vTransform != null) ((DUCE.IResource)vTransform).ReleaseOnChannel(channel); Transform vRelativeTransform = RelativeTransform; if (vRelativeTransform != null) ((DUCE.IResource)vRelativeTransform).ReleaseOnChannel(channel); ReleaseOnChannelAnimations(channel); } } internal override DUCE.ResourceHandle GetHandleCore(DUCE.Channel channel) { // Note that we are in a lock here already. return _duceResource.GetHandle(channel); } internal override int GetChannelCountCore() { // must already be in composition lock here return _duceResource.GetChannelCount(); } internal override DUCE.Channel GetChannelCore(int index) { // Note that we are in a lock here already. return _duceResource.GetChannel(index); } #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties // // This property finds the correct initial size for the _effectiveValues store on the // current DependencyObject as a performance optimization // // This includes: // GradientStops // internal override int EffectiveValuesInitialSize { get { return 1; } } #endregion Internal Properties //------------------------------------------------------ // // Dependency Properties // //------------------------------------------------------ #region Dependency Properties /// <summary> /// The DependencyProperty for the RadialGradientBrush.Center property. /// </summary> public static readonly DependencyProperty CenterProperty; /// <summary> /// The DependencyProperty for the RadialGradientBrush.RadiusX property. /// </summary> public static readonly DependencyProperty RadiusXProperty; /// <summary> /// The DependencyProperty for the RadialGradientBrush.RadiusY property. /// </summary> public static readonly DependencyProperty RadiusYProperty; /// <summary> /// The DependencyProperty for the RadialGradientBrush.GradientOrigin property. /// </summary> public static readonly DependencyProperty GradientOriginProperty; #endregion Dependency Properties //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ #region Internal Fields internal System.Windows.Media.Composition.DUCE.MultiChannelResource _duceResource = new System.Windows.Media.Composition.DUCE.MultiChannelResource(); internal static Point s_Center = new Point(0.5,0.5); internal const double c_RadiusX = 0.5; internal const double c_RadiusY = 0.5; internal static Point s_GradientOrigin = new Point(0.5,0.5); #endregion Internal Fields #region Constructors //------------------------------------------------------ // // Constructors // //------------------------------------------------------ static RadialGradientBrush() { // We check our static default fields which are of type Freezable // to make sure that they are not mutable, otherwise we will throw // if these get touched by more than one thread in the lifetime // of your app. (Windows OS Bug #947272) // // Initializations Type typeofThis = typeof(RadialGradientBrush); CenterProperty = RegisterProperty("Center", typeof(Point), typeofThis, new Point(0.5,0.5), new PropertyChangedCallback(CenterPropertyChanged), null, /* isIndependentlyAnimated = */ true, /* coerceValueCallback */ null); RadiusXProperty = RegisterProperty("RadiusX", typeof(double), typeofThis, 0.5, new PropertyChangedCallback(RadiusXPropertyChanged), null, /* isIndependentlyAnimated = */ true, /* coerceValueCallback */ null); RadiusYProperty = RegisterProperty("RadiusY", typeof(double), typeofThis, 0.5, new PropertyChangedCallback(RadiusYPropertyChanged), null, /* isIndependentlyAnimated = */ true, /* coerceValueCallback */ null); GradientOriginProperty = RegisterProperty("GradientOrigin", typeof(Point), typeofThis, new Point(0.5,0.5), new PropertyChangedCallback(GradientOriginPropertyChanged), null, /* isIndependentlyAnimated = */ true, /* coerceValueCallback */ null); } #endregion Constructors } }
using System; using Fonet.DataTypes; namespace Fonet.Fo.Properties { internal class GenericSpace : SpaceProperty.Maker { internal class Enums { internal class Precedence { public const int FORCE = Constants.FORCE; } internal class Conditionality { public const int DISCARD = Constants.DISCARD; public const int RETAIN = Constants.RETAIN; } } private static readonly PropertyMaker s_MinimumMaker = new LengthProperty.Maker("generic-space.minimum"); private static readonly PropertyMaker s_OptimumMaker = new LengthProperty.Maker("generic-space.optimum"); private static readonly PropertyMaker s_MaximumMaker = new LengthProperty.Maker("generic-space.maximum"); private class SP_PrecedenceMaker : NumberProperty.Maker { protected internal SP_PrecedenceMaker(string sPropName) : base(sPropName) { } protected internal static readonly EnumProperty s_propFORCE = new EnumProperty(Enums.Precedence.FORCE); public override Property CheckEnumValues(string value) { if (value.Equals("force")) { return s_propFORCE; } return base.CheckEnumValues(value); } } private static readonly PropertyMaker s_PrecedenceMaker = new SP_PrecedenceMaker("generic-space.precedence"); private class SP_ConditionalityMaker : EnumProperty.Maker { protected internal SP_ConditionalityMaker(string sPropName) : base(sPropName) { } protected internal static readonly EnumProperty s_propDISCARD = new EnumProperty(Enums.Conditionality.DISCARD); protected internal static readonly EnumProperty s_propRETAIN = new EnumProperty(Enums.Conditionality.RETAIN); public override Property CheckEnumValues(string value) { if (value.Equals("discard")) { return s_propDISCARD; } if (value.Equals("retain")) { return s_propRETAIN; } return base.CheckEnumValues(value); } } private static readonly PropertyMaker s_ConditionalityMaker = new SP_ConditionalityMaker("generic-space.conditionality"); new public static PropertyMaker Maker(string propName) { return new GenericSpace(propName); } protected GenericSpace(string name) : base(name) { m_shorthandMaker = GetSubpropMaker("minimum"); } private PropertyMaker m_shorthandMaker; public override Property CheckEnumValues(string value) { return m_shorthandMaker.CheckEnumValues(value); } protected override bool IsCompoundMaker() { return true; } protected override PropertyMaker GetSubpropMaker(string subprop) { if (subprop.Equals("minimum")) { return s_MinimumMaker; } if (subprop.Equals("optimum")) { return s_OptimumMaker; } if (subprop.Equals("maximum")) { return s_MaximumMaker; } if (subprop.Equals("precedence")) { return s_PrecedenceMaker; } if (subprop.Equals("conditionality")) { return s_ConditionalityMaker; } return base.GetSubpropMaker(subprop); } protected override Property SetSubprop(Property baseProp, string subpropName, Property subProp) { Space val = baseProp.GetSpace(); val.SetComponent(subpropName, subProp, false); return baseProp; } public override Property GetSubpropValue(Property baseProp, string subpropName) { Space val = baseProp.GetSpace(); return val.GetComponent(subpropName); } private Property m_defaultProp = null; public override Property Make(PropertyList propertyList) { if (m_defaultProp == null) { m_defaultProp = MakeCompound(propertyList, propertyList.getParentFObj()); } return m_defaultProp; } protected override Property MakeCompound(PropertyList pList, FObj fo) { Space p = new Space(); Property subProp; subProp = GetSubpropMaker("minimum").Make(pList, GetDefaultForMinimum(), fo); p.SetComponent("minimum", subProp, true); subProp = GetSubpropMaker("optimum").Make(pList, GetDefaultForOptimum(), fo); p.SetComponent("optimum", subProp, true); subProp = GetSubpropMaker("maximum").Make(pList, GetDefaultForMaximum(), fo); p.SetComponent("maximum", subProp, true); subProp = GetSubpropMaker("precedence").Make(pList, getDefaultForPrecedence(), fo); p.SetComponent("precedence", subProp, true); subProp = GetSubpropMaker("conditionality").Make(pList, getDefaultForConditionality(), fo); p.SetComponent("conditionality", subProp, true); return new SpaceProperty(p); } protected virtual String GetDefaultForMinimum() { return "0pt"; } protected virtual String GetDefaultForOptimum() { return "0pt"; } protected virtual String GetDefaultForMaximum() { return "0pt"; } protected virtual String getDefaultForPrecedence() { return "0"; } protected virtual String getDefaultForConditionality() { return "discard"; } public override Property ConvertProperty(Property p, PropertyList pList, FObj fo) { if (p is SpaceProperty) { return p; } if (!(p is EnumProperty)) { p = m_shorthandMaker.ConvertProperty(p, pList, fo); } if (p != null) { Property prop = MakeCompound(pList, fo); Space pval = prop.GetSpace(); pval.SetComponent("minimum", p, false); pval.SetComponent("optimum", p, false); pval.SetComponent("maximum", p, false); return prop; } else { return null; } } public override bool IsInherited() { return false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ConvertToVector128Int64Byte() { var test = new SimpleUnaryOpTest__ConvertToVector128Int64Byte(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates basic functionality works, using the pointer overload test.RunBasicScenario_Ptr(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates calling via reflection works, using the pointer overload test.RunReflectionScenario_Ptr(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ConvertToVector128Int64Byte { private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int64>>() / sizeof(Int64); private static Byte[] _data = new Byte[Op1ElementCount]; private static Vector128<Byte> _clsVar; private Vector128<Byte> _fld; private SimpleUnaryOpTest__DataTable<Int64, Byte> _dataTable; static SimpleUnaryOpTest__ConvertToVector128Int64Byte() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar), ref Unsafe.As<Byte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public SimpleUnaryOpTest__ConvertToVector128Int64Byte() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (byte)(random.Next(0, byte.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld), ref Unsafe.As<Byte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (byte)(random.Next(0, byte.MaxValue)); } _dataTable = new SimpleUnaryOpTest__DataTable<Int64, Byte>(_data, new Int64[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse41.ConvertToVector128Int64( Unsafe.Read<Vector128<Byte>>(_dataTable.inArrayPtr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Ptr() { var result = Sse41.ConvertToVector128Int64( (Byte*)(_dataTable.inArrayPtr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse41.ConvertToVector128Int64( Sse2.LoadVector128((Byte*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse41.ConvertToVector128Int64( Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse41).GetMethod(nameof(Sse41.ConvertToVector128Int64), new Type[] { typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArrayPtr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Ptr() { var result = typeof(Sse41).GetMethod(nameof(Sse41.ConvertToVector128Int64), new Type[] { typeof(Byte*) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArrayPtr, typeof(Byte*)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse41).GetMethod(nameof(Sse41.ConvertToVector128Int64), new Type[] { typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Byte*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse41).GetMethod(nameof(Sse41.ConvertToVector128Int64), new Type[] { typeof(Vector128<Byte>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse41.ConvertToVector128Int64( _clsVar ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector128<Byte>>(_dataTable.inArrayPtr); var result = Sse41.ConvertToVector128Int64(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Sse2.LoadVector128((Byte*)(_dataTable.inArrayPtr)); var result = Sse41.ConvertToVector128Int64(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArrayPtr)); var result = Sse41.ConvertToVector128Int64(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__ConvertToVector128Int64Byte(); var result = Sse41.ConvertToVector128Int64(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse41.ConvertToVector128Int64(_fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Byte> firstOp, void* result, [CallerMemberName] string method = "") { Byte[] inArray = new Byte[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Byte[] inArray = new Byte[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Byte[] firstOp, Int64[] result, [CallerMemberName] string method = "") { if (result[0] != firstOp[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != firstOp[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.ConvertToVector128Int64)}<Int64>(Vector128<Byte>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
//----------------------------------------------------------------------- // <copyright file="BasicServer.cs" company="AllSeen Alliance."> // Copyright (c) 2012, AllSeen Alliance. All rights reserved. // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // </copyright> //----------------------------------------------------------------------- using System; using AllJoynUnity; namespace basic_clientserver { class BasicServer { private const string INTERFACE_NAME = "org.alljoyn.Bus.sample"; private const string SERVICE_NAME = "org.alljoyn.Bus.sample"; private const string SERVICE_PATH = "/sample"; private const ushort SERVICE_PORT = 25; private static readonly string[] connectArgs = {"null:"}; private AllJoyn.BusAttachment msgBus; private MyBusListener busListener; private MySessionPortListener sessionPortListener; private TestBusObject testObj; private AllJoyn.InterfaceDescription testIntf; class TestBusObject : AllJoyn.BusObject { public TestBusObject(AllJoyn.BusAttachment bus, string path) : base(path, false) { AllJoyn.InterfaceDescription exampleIntf = bus.GetInterface(INTERFACE_NAME); AllJoyn.QStatus status = AddInterface(exampleIntf); if(!status) { Console.WriteLine("Server Failed to add interface {0}", status); } AllJoyn.InterfaceDescription.Member catMember = exampleIntf.GetMember("cat"); status = AddMethodHandler(catMember, this.Cat); if(!status) { Console.WriteLine("Server Failed to add method handler {0}", status); } } protected override void OnObjectRegistered() { Console.WriteLine("Server ObjectRegistered has been called"); } protected void Cat(AllJoyn.InterfaceDescription.Member member, AllJoyn.Message message) { string outStr = (string)message[0] + (string)message[1]; AllJoyn.MsgArg outArgs = new AllJoyn.MsgArg(); outArgs = outStr; AllJoyn.QStatus status = MethodReply(message, outArgs); if(!status) { Console.WriteLine("Server Ping: Error sending reply"); } } } class MyBusListener : AllJoyn.BusListener { protected override void NameOwnerChanged(string busName, string previousOwner, string newOwner) { //if(string.Compare(SERVICE_NAME, busName) == 0) { Console.WriteLine("Server NameOwnerChanged: name=" + busName + ", oldOwner=" + previousOwner + ", newOwner=" + newOwner); } } } class MySessionPortListener : AllJoyn.SessionPortListener { protected override bool AcceptSessionJoiner(ushort sessionPort, string joiner, AllJoyn.SessionOpts opts) { if (sessionPort != SERVICE_PORT) { Console.WriteLine("Server Rejecting join attempt on unexpected session port {0}", sessionPort); return false; } Console.WriteLine("Server Accepting join session request from {0} (opts.proximity={1}, opts.traffic={2}, opts.transports={3})", joiner, opts.Proximity, opts.Traffic, opts.Transports); return true; } } public BasicServer() { // Create message bus msgBus = new AllJoyn.BusAttachment("myApp", true); // Add org.alljoyn.Bus.method_sample interface AllJoyn.QStatus status = msgBus.CreateInterface(INTERFACE_NAME, out testIntf); if(status) { Console.WriteLine("Server Interface Created."); testIntf.AddMember(AllJoyn.Message.Type.MethodCall, "cat", "ss", "s", "inStr1,inStr2,outStr"); testIntf.Activate(); } else { Console.WriteLine("Failed to create interface 'org.alljoyn.Bus.method_sample'"); } // Create a bus listener busListener = new MyBusListener(); if(status) { msgBus.RegisterBusListener(busListener); Console.WriteLine("Server BusListener Registered."); } // Set up bus object testObj = new TestBusObject(msgBus, SERVICE_PATH); // Start the msg bus if(status) { status = msgBus.Start(); if(status) { Console.WriteLine("Server BusAttachment started."); msgBus.RegisterBusObject(testObj); for (int i = 0; i < connectArgs.Length; ++i) { status = msgBus.Connect(connectArgs[i]); if (status) { Console.WriteLine("BusAttchement.Connect(" + connectArgs[i] + ") SUCCEDED."); break; } else { Console.WriteLine("BusAttachment.Connect(" + connectArgs[i] + ") failed."); } } if (!status) { Console.WriteLine("BusAttachment.Connect failed."); } } else { Console.WriteLine("Server BusAttachment.Start failed."); } } // Request name if(status) { status = msgBus.RequestName(SERVICE_NAME, AllJoyn.DBus.NameFlags.ReplaceExisting | AllJoyn.DBus.NameFlags.DoNotQueue); if(!status) { Console.WriteLine("Server RequestName({0}) failed (status={1})", SERVICE_NAME, status); } } // Create session AllJoyn.SessionOpts opts = new AllJoyn.SessionOpts(AllJoyn.SessionOpts.TrafficType.Messages, false, AllJoyn.SessionOpts.ProximityType.Any, AllJoyn.TransportMask.Any); if(status) { ushort sessionPort = SERVICE_PORT; sessionPortListener = new MySessionPortListener(); status = msgBus.BindSessionPort(ref sessionPort, opts, sessionPortListener); if(!status || sessionPort != SERVICE_PORT) { Console.WriteLine("Server BindSessionPort failed ({0})", status); } } // Advertise name if(status) { status = msgBus.AdvertiseName(SERVICE_NAME, opts.Transports); if(!status) { Console.WriteLine("Server Failed to advertise name {0} ({1})", SERVICE_NAME, status); } } Console.WriteLine("Should have setup server"); } public bool KeepRunning { get { return true; } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using System.Collections.Generic; namespace OpenSim.Region.Physics.Manager { public delegate void AssetReceivedDelegate(AssetBase asset); public delegate void JointDeactivated(PhysicsJoint joint); public delegate void JointErrorMessage(PhysicsJoint joint, string message); public delegate void JointMoved(PhysicsJoint joint); public delegate void physicsCrash(); public delegate void RayCallback(List<ContactResult> list); public delegate void RaycastCallback(bool hitYN, Vector3 collisionPoint, uint localid, float distance, Vector3 normal); // this refers to an "error message due to a problem", not "amount of joint constraint violation" public delegate void RequestAssetDelegate(UUID assetID, AssetReceivedDelegate callback); public enum RayFilterFlags : ushort { // the flags water = 0x01, land = 0x02, agent = 0x04, nonphysical = 0x08, physical = 0x10, phantom = 0x20, volumedtc = 0x40, // ray cast colision control (may only work for meshs) ContactsUnImportant = 0x2000, BackFaceCull = 0x4000, ClosestHit = 0x8000, // some combinations LSLPhantom = phantom | volumedtc, PrimsNonPhantom = nonphysical | physical, PrimsNonPhantomAgents = nonphysical | physical | agent, AllPrims = nonphysical | phantom | volumedtc | physical, AllButLand = agent | nonphysical | physical | phantom | volumedtc, ClosestAndBackCull = ClosestHit | BackFaceCull, All = 0x3f } /// <summary> /// Contact result from a raycast. /// </summary> public struct ContactResult { public uint ConsumerID; public float Depth; public Vector3 Normal; public Vector3 Pos; } public abstract class PhysicsScene { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public event JointDeactivated OnJointDeactivated; public event JointErrorMessage OnJointErrorMessage; public event JointMoved OnJointMoved; // The only thing that should register for this event is the SceneGraph // Anything else could cause problems. public event physicsCrash OnPhysicsCrash; public static PhysicsScene Null { get { return new NullPhysicsScene(); } } /// <summary> /// A string identifying the family of this physics engine. Most common values returned /// are "OpenDynamicsEngine" and "BulletSim" but others are possible. /// </summary> public string EngineType { get; protected set; } public abstract bool IsThreaded { get; } /// <summary> /// A unique identifying string for this instance of the physics engine. /// Useful in debug messages to distinguish one OdeScene instance from another. /// Usually set to include the region name that the physics engine is acting for. /// </summary> public string Name { get; protected set; } public RequestAssetDelegate RequestAssetMethod { get; set; } public virtual bool SupportsNINJAJoints { get { return false; } } public virtual float TimeDilation { get { return 1.0f; } } /// <summary> /// Add an avatar /// </summary> /// <param name="avName"></param> /// <param name="position"></param> /// <param name="size"></param> /// <param name="isFlying"></param> /// <returns></returns> public abstract PhysicsActor AddAvatar(string avName, Vector3 position, Vector3 size, bool isFlying); /// <summary> /// Add an avatar /// </summary> /// <param name="localID"></param> /// <param name="avName"></param> /// <param name="position"></param> /// <param name="size"></param> /// <param name="isFlying"></param> /// <returns></returns> public virtual PhysicsActor AddAvatar(uint localID, string avName, Vector3 position, Vector3 size, bool isFlying) { PhysicsActor ret = AddAvatar(avName, position, size, isFlying); if (ret != null) ret.LocalID = localID; return ret; } public abstract void AddPhysicsActorTaint(PhysicsActor prim); public abstract PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position, Vector3 size, Quaternion rotation, bool isPhysical, uint localid); public virtual PhysicsActor AddPrimShape(string primName, PrimitiveBaseShape pbs, Vector3 position, Vector3 size, Quaternion rotation, bool isPhysical, bool isPhantom, byte shapetype, uint localid) { return AddPrimShape(primName, pbs, position, size, rotation, isPhysical, localid); } public virtual void Combine(PhysicsScene pScene, Vector3 offset, Vector3 extents) { } public abstract void DeleteTerrain(); public abstract void Dispose(); public virtual void DumpJointInfo() { return; } // Extendable interface for new, physics engine specific operations public virtual object Extension(string pFunct, params object[] pParams) { // A NOP if the extension thing is not implemented by the physics engine return null; } public virtual Vector3 GetJointAnchor(PhysicsJoint joint) { return Vector3.Zero; } public virtual Vector3 GetJointAxis(PhysicsJoint joint) { return Vector3.Zero; } public abstract void GetResults(); /// <summary> /// Get statistics about this scene. /// </summary> /// <remarks>This facility is currently experimental and subject to change.</remarks> /// <returns> /// A dictionary where the key is the statistic name. If no statistics are supplied then returns null. /// </returns> public virtual Dictionary<string, float> GetStats() { return null; } public abstract Dictionary<uint, float> GetTopColliders(); // Deprecated. Do not use this for new physics engines. public abstract void Initialise(IMesher meshmerizer, IConfigSource config); // For older physics engines that do not implement non-legacy region sizes. // If the physics engine handles the region extent feature, it overrides this function. public virtual void Initialise(IMesher meshmerizer, IConfigSource config, Vector3 regionExtent) { // If not overridden, call the old initialization entry. Initialise(meshmerizer, config); } /// <summary> /// Queue a raycast against the physics scene. /// The provided callback method will be called when the raycast is complete /// /// Many physics engines don't support collision testing at the same time as /// manipulating the physics scene, so we queue the request up and callback /// a custom method when the raycast is complete. /// This allows physics engines that give an immediate result to callback immediately /// and ones that don't, to callback when it gets a result back. /// /// ODE for example will not allow you to change the scene while collision testing or /// it asserts, 'opteration not valid for locked space'. This includes adding a ray to the scene. /// /// This is named RayCastWorld to not conflict with modrex's Raycast method. /// </summary> /// <param name="position">Origin of the ray</param> /// <param name="direction">Direction of the ray</param> /// <param name="length">Length of ray in meters</param> /// <param name="retMethod">Method to call when the raycast is complete</param> public virtual void RaycastWorld(Vector3 position, Vector3 direction, float length, RaycastCallback retMethod) { if (retMethod != null) retMethod(false, Vector3.Zero, 0, 999999999999f, Vector3.Zero); } public virtual void RaycastWorld(Vector3 position, Vector3 direction, float length, int Count, RayCallback retMethod) { if (retMethod != null) retMethod(new List<ContactResult>()); } public virtual List<ContactResult> RaycastWorld(Vector3 position, Vector3 direction, float length, int Count) { return new List<ContactResult>(); } public virtual object RaycastWorld(Vector3 position, Vector3 direction, float length, int Count, RayFilterFlags filter) { return null; } public virtual void RemoveAllJointsConnectedToActorThreadLocked(PhysicsActor actor) { return; } /// <summary> /// Remove an avatar. /// </summary> /// <param name="actor"></param> public abstract void RemoveAvatar(PhysicsActor actor); /// <summary> /// Remove a prim. /// </summary> /// <param name="prim"></param> public abstract void RemovePrim(PhysicsActor prim); public virtual PhysicsJoint RequestJointCreation(string objectNameInScene, PhysicsJointType jointType, Vector3 position, Quaternion rotation, string parms, List<string> bodyNames, string trackedBodyName, Quaternion localRotation) { return null; } public virtual void RequestJointDeletion(string objectNameInScene) { return; } public abstract void SetTerrain(float[] heightMap); public abstract void SetWaterLevel(float baseheight); /// <summary> /// Perform a simulation of the current physics scene over the given timestep. /// </summary> /// <param name="timeStep"></param> /// <returns>The number of frames simulated over that period.</returns> public abstract float Simulate(float timeStep); public virtual bool SupportsCombining() { return false; } /// <summary> /// True if the physics plugin supports raycasting against the physics scene /// </summary> public virtual bool SupportsRayCast() { return false; } public virtual bool SupportsRaycastWorldFiltered() { return false; } public virtual void TriggerPhysicsBasedRestart() { physicsCrash handler = OnPhysicsCrash; if (handler != null) { OnPhysicsCrash(); } } public virtual void UnCombine(PhysicsScene pScene) { } protected virtual void DoJointDeactivated(PhysicsJoint joint) { // We need this to allow subclasses (but not other classes) to invoke the event; C# does // not allow subclasses to invoke the parent class event. if (OnJointDeactivated != null) { OnJointDeactivated(joint); } } protected virtual void DoJointErrorMessage(PhysicsJoint joint, string message) { // We need this to allow subclasses (but not other classes) to invoke the event; C# does // not allow subclasses to invoke the parent class event. if (OnJointErrorMessage != null) { OnJointErrorMessage(joint, message); } } protected virtual void DoJointMoved(PhysicsJoint joint) { // We need this to allow subclasses (but not other classes) to invoke the event; C# does // not allow subclasses to invoke the parent class event. if (OnJointMoved != null) { OnJointMoved(joint); } } } }
//----------------------------------------------------------------------- // <copyright file="Stash.cs" company="None"> // Copyright (c) Brandon Wallace and Jesse Calhoun. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace TQVaultAE.Data { using System; using System.Globalization; using System.IO; using TQVaultAE.Entities; using TQVaultAE.Logs; /// <summary> /// Class for handling the stash file /// </summary> public static class StashProvider { private static readonly log4net.ILog Log = Logger.Get(typeof(StashProvider)); /// <summary> /// Defines the raw data buffer size /// </summary> private const int BUFFERSIZE = 1024; /// <summary> /// CRC32 hash table. Used for calculating the file CRC /// </summary> private static uint[] crc32Table = { 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d, }; /// <summary> /// Saves the stash file /// </summary> /// <param name="fileName">file name of this stash file</param> public static void Save(Stash sta, string fileName) { byte[] data = Encode(sta); data = CalculateCRC(data); using (FileStream outStream = new FileStream(fileName, FileMode.Create, FileAccess.Write)) { outStream.Write(data, 0, data.Length); } // Save the corresponding dxg file data = EncodeBackupFile(data); // Now calculate the CRC for the dxg file data = CalculateCRC(data); string dxgFilename = Path.ChangeExtension(fileName, ".dxg"); using (FileStream dxgOutStream = new FileStream(dxgFilename, FileMode.Create, FileAccess.Write)) { dxgOutStream.Write(data, 0, data.Length); } } /// <summary> /// Converts the live data back into the raw binary data format /// </summary> /// <returns>byte array holding the raw data</returns> public static byte[] Encode(Stash sta) { // We need to encode the item data to a memory stream return EncodeItemData(sta); } /// <summary> /// Loads a stash file /// </summary> /// <returns>false if the file does not exist otherwise true.</returns> public static bool LoadFile(Stash sta) { if (!File.Exists(sta.StashFile)) { return false; } using (FileStream file = new FileStream(sta.StashFile, FileMode.Open, FileAccess.Read)) { using (BinaryReader reader = new BinaryReader(file)) { // Just suck the entire file into memory sta.rawData = reader.ReadBytes((int)file.Length); } } try { // Now Parse the file ParseRawData(sta); } catch (ArgumentException ex) { Log.Error("ParseRawData fail !", ex); throw; } return true; } /// <summary> /// Changes the file name extension in the raw file data to .dxg /// </summary> /// <param name="data">the raw file data</param> /// <returns>raw file data with the updated file name extension</returns> private static byte[] EncodeBackupFile(byte[] data) { // Find the length of the filename string. // It's an Int32 starting at offset 52 in the file. int offset = data[52] + (256 * data[53]) + (65536 * data[54]) + (16777216 * data[55]); // Adjust for the location of the filename string - 1 // which is at offset 56. Subtract 1 to get the last letter of the filename. offset += 55; // look for the 'b' in .dxb if (data[offset] == 98 || data[offset] == 66) { // and change it to 'g' data[offset] = Convert.ToByte(103, CultureInfo.InvariantCulture); } // zero out the checksum for (int i = 0; i < 4; i++) { data[i] = Convert.ToByte(0, CultureInfo.InvariantCulture); } return data; } /// <summary> /// Calculates the CRC32 of the raw data /// </summary> /// <param name="data">raw file data we are calculating</param> /// <returns>raw file data with the crc calculated and inserted into the proper field</returns> private static byte[] CalculateCRC(byte[] data) { using (BinaryReader reader = new BinaryReader(new MemoryStream(data, false))) { uint crc32Result = 0; byte[] buffer = new byte[BUFFERSIZE]; int readSize = BUFFERSIZE; int count = reader.Read(buffer, 0, readSize); while (count > 0) { for (int i = 0; i < count; i++) { crc32Result = (crc32Result >> 8) ^ crc32Table[buffer[i] ^ (crc32Result & 0x000000FF)]; } count = reader.Read(buffer, 0, readSize); } // Put the data into the stream data[3] = Convert.ToByte((crc32Result & 0xFF000000) >> 24, CultureInfo.InvariantCulture); data[2] = Convert.ToByte((crc32Result & 0x00FF0000) >> 16, CultureInfo.InvariantCulture); data[1] = Convert.ToByte((crc32Result & 0x0000FF00) >> 8, CultureInfo.InvariantCulture); data[0] = Convert.ToByte(crc32Result & 0x000000FF, CultureInfo.InvariantCulture); } return data; } /// <summary> /// Parses the raw data and converts to internal data. /// </summary> private static void ParseRawData(Stash sta) { // First create a memory stream so we can decode the binary data as needed. using (BinaryReader reader = new BinaryReader(new MemoryStream(sta.rawData, false))) { int offset = 0; try { ParseItemBlock(sta, offset, reader); } catch (ArgumentException) { throw; } try { string outfile = string.Concat(Path.Combine(TQData.TQVaultSaveFolder, sta.PlayerName), " Export.txt"); using (StreamWriter outStream = new StreamWriter(outfile, false)) { outStream.WriteLine("Number of Sacks = {0}", sta.numberOfSacks); if (!sta.sack.IsEmpty) { outStream.WriteLine(); outStream.WriteLine("SACK 0"); int itemNumber = 0; foreach (Item item in sta.sack) { object[] params1 = new object[20]; params1[0] = itemNumber; params1[1] = ItemProvider.ToFriendlyName(item); params1[2] = item.PositionX; params1[3] = item.PositionY; params1[4] = item.Seed; outStream.WriteLine(" {0,5:n0} {1}", params1); itemNumber++; } } } } catch (IOException exception) { Log.ErrorFormat(exception, "Error Exporting - '{0} Export.txt'", Path.Combine(TQData.TQVaultSaveFolder, sta.PlayerName)); } } } /// <summary> /// Encodes the internal item data back into raw data /// </summary> /// <returns>raw data for the item data</returns> private static byte[] EncodeItemData(Stash sta) { int dataLength; byte[] data; // Encode the item data into a memory stream using (MemoryStream writeStream = new MemoryStream(2048)) { using (BinaryWriter writer = new BinaryWriter(writeStream)) { // Write zero into the checksum value writer.Write(Convert.ToInt32(0, CultureInfo.InvariantCulture)); TQData.WriteCString(writer, "begin_block"); writer.Write(sta.beginBlockCrap); TQData.WriteCString(writer, "stashVersion"); writer.Write(sta.stashVersion); TQData.WriteCString(writer, "fName"); // Changed to raw data to support extended characters writer.Write(sta.name.Length); writer.Write(sta.name); TQData.WriteCString(writer, "sackWidth"); writer.Write(sta.Width); TQData.WriteCString(writer, "sackHeight"); writer.Write(sta.Height); // SackType should already be set at sta point SackCollectionProvider.Encode(sta.sack, writer); dataLength = (int)writeStream.Length; } // now just return the buffer we wrote to. data = writeStream.GetBuffer(); } // The problem is that data[] may be bigger than the amount of data in it. // We need to resize the array if (dataLength == data.Length) { return data; } byte[] realData = new byte[dataLength]; Array.Copy(data, realData, dataLength); return realData; } /// <summary> /// Parses an item block within the file and coverts raw item data into internal item data /// </summary> /// <param name="fileOffset">Offset into the file</param> /// <param name="reader">BinaryReader instance</param> private static void ParseItemBlock(Stash sta, int fileOffset, BinaryReader reader) { try { reader.BaseStream.Seek(fileOffset, SeekOrigin.Begin); reader.ReadInt32(); TQData.ValidateNextString("begin_block", reader); sta.beginBlockCrap = reader.ReadInt32(); TQData.ValidateNextString("stashVersion", reader); sta.stashVersion = reader.ReadInt32(); TQData.ValidateNextString("fName", reader); // Changed to raw data to support extended characters int stringLength = reader.ReadInt32(); sta.name = reader.ReadBytes(stringLength); TQData.ValidateNextString("sackWidth", reader); sta.Width = reader.ReadInt32(); TQData.ValidateNextString("sackHeight", reader); sta.Height = reader.ReadInt32(); sta.numberOfSacks = 1; sta.sack = new SackCollection(); sta.sack.SackType = SackType.Stash; sta.sack.IsImmortalThrone = true; SackCollectionProvider.Parse(sta.sack, reader); } catch (ArgumentException) { // The ValidateNextString Method can throw an ArgumentException. // We just pass it along at sta point. throw; } } } }
using System; using Org.BouncyCastle.Crypto.Parameters; namespace Org.BouncyCastle.Crypto.Engines { /** * Implementation of Bob Jenkin's ISAAC (Indirection Shift Accumulate Add and Count). * see: http://www.burtleburtle.net/bob/rand/isaacafa.html */ public class IsaacEngine : IStreamCipher { // Constants private static readonly int sizeL = 8, stateArraySize = sizeL<<5; // 256 // Cipher's internal state private uint[] engineState = null, // mm results = null; // randrsl private uint a = 0, b = 0, c = 0; // Engine state private int index = 0; private byte[] keyStream = new byte[stateArraySize<<2], // results expanded into bytes workingKey = null; private bool initialised = false; /** * initialise an ISAAC cipher. * * @param forEncryption whether or not we are for encryption. * @param params the parameters required to set up the cipher. * @exception ArgumentException if the params argument is * inappropriate. */ public void Init( bool forEncryption, ICipherParameters parameters) { if (!(parameters is KeyParameter)) throw new ArgumentException( "invalid parameter passed to ISAAC Init - " + parameters.GetType().Name, "parameters"); /* * ISAAC encryption and decryption is completely * symmetrical, so the 'forEncryption' is * irrelevant. */ KeyParameter p = (KeyParameter) parameters; setKey(p.GetKey()); } public byte ReturnByte( byte input) { if (index == 0) { isaac(); keyStream = intToByteLittle(results); } byte output = (byte)(keyStream[index]^input); index = (index + 1) & 1023; return output; } public void ProcessBytes( byte[] input, int inOff, int len, byte[] output, int outOff) { if (!initialised) throw new InvalidOperationException(AlgorithmName + " not initialised"); if ((inOff + len) > input.Length) throw new DataLengthException("input buffer too short"); if ((outOff + len) > output.Length) throw new DataLengthException("output buffer too short"); for (int i = 0; i < len; i++) { if (index == 0) { isaac(); keyStream = intToByteLittle(results); } output[i+outOff] = (byte)(keyStream[index]^input[i+inOff]); index = (index + 1) & 1023; } } public string AlgorithmName { get { return "ISAAC"; } } public void Reset() { setKey(workingKey); } // Private implementation private void setKey( byte[] keyBytes) { workingKey = keyBytes; if (engineState == null) { engineState = new uint[stateArraySize]; } if (results == null) { results = new uint[stateArraySize]; } int i, j, k; // Reset state for (i = 0; i < stateArraySize; i++) { engineState[i] = results[i] = 0; } a = b = c = 0; // Reset index counter for output index = 0; // Convert the key bytes to ints and put them into results[] for initialization byte[] t = new byte[keyBytes.Length + (keyBytes.Length & 3)]; Array.Copy(keyBytes, 0, t, 0, keyBytes.Length); for (i = 0; i < t.Length; i+=4) { results[i>>2] = byteToIntLittle(t, i); } // It has begun? uint[] abcdefgh = new uint[sizeL]; for (i = 0; i < sizeL; i++) { abcdefgh[i] = 0x9e3779b9; // Phi (golden ratio) } for (i = 0; i < 4; i++) { mix(abcdefgh); } for (i = 0; i < 2; i++) { for (j = 0; j < stateArraySize; j+=sizeL) { for (k = 0; k < sizeL; k++) { abcdefgh[k] += (i<1) ? results[j+k] : engineState[j+k]; } mix(abcdefgh); for (k = 0; k < sizeL; k++) { engineState[j+k] = abcdefgh[k]; } } } isaac(); initialised = true; } private void isaac() { uint x, y; b += ++c; for (int i = 0; i < stateArraySize; i++) { x = engineState[i]; switch (i & 3) { case 0: a ^= (a << 13); break; case 1: a ^= (a >> 6); break; case 2: a ^= (a << 2); break; case 3: a ^= (a >> 16); break; } a += engineState[(i+128) & 0xFF]; engineState[i] = y = engineState[(int)((uint)x >> 2) & 0xFF] + a + b; results[i] = b = engineState[(int)((uint)y >> 10) & 0xFF] + x; } } private void mix(uint[] x) { // x[0]^=x[1]<< 11; x[3]+=x[0]; x[1]+=x[2]; // x[1]^=x[2]>>> 2; x[4]+=x[1]; x[2]+=x[3]; // x[2]^=x[3]<< 8; x[5]+=x[2]; x[3]+=x[4]; // x[3]^=x[4]>>>16; x[6]+=x[3]; x[4]+=x[5]; // x[4]^=x[5]<< 10; x[7]+=x[4]; x[5]+=x[6]; // x[5]^=x[6]>>> 4; x[0]+=x[5]; x[6]+=x[7]; // x[6]^=x[7]<< 8; x[1]+=x[6]; x[7]+=x[0]; // x[7]^=x[0]>>> 9; x[2]+=x[7]; x[0]+=x[1]; x[0]^=x[1]<< 11; x[3]+=x[0]; x[1]+=x[2]; x[1]^=x[2]>> 2; x[4]+=x[1]; x[2]+=x[3]; x[2]^=x[3]<< 8; x[5]+=x[2]; x[3]+=x[4]; x[3]^=x[4]>> 16; x[6]+=x[3]; x[4]+=x[5]; x[4]^=x[5]<< 10; x[7]+=x[4]; x[5]+=x[6]; x[5]^=x[6]>> 4; x[0]+=x[5]; x[6]+=x[7]; x[6]^=x[7]<< 8; x[1]+=x[6]; x[7]+=x[0]; x[7]^=x[0]>> 9; x[2]+=x[7]; x[0]+=x[1]; } private uint byteToIntLittle( byte[] x, int offset) { uint result = (byte) x[offset + 3]; result = (result << 8) | x[offset + 2]; result = (result << 8) | x[offset + 1]; result = (result << 8) | x[offset + 0]; return result; } private byte[] intToByteLittle( uint x) { byte[] output = new byte[4]; output[3] = (byte)x; output[2] = (byte)(x >> 8); output[1] = (byte)(x >> 16); output[0] = (byte)(x >> 24); return output; } private byte[] intToByteLittle( uint[] x) { byte[] output = new byte[4*x.Length]; for (int i = 0, j = 0; i < x.Length; i++,j+=4) { Array.Copy(intToByteLittle(x[i]), 0, output, j, 4); } return output; } } }
using System; using System.Runtime.InteropServices; using System.Text; namespace NSane.Local { /// <summary> /// This contains the p/invoke signatures for the native method calls /// required to interface with the SANE C API. /// </summary> internal static class NativeMethods { /// <summary> /// Initialize SANE /// </summary> /// <param name="version">The version of sane</param> /// <param name="callback">The authentication callback handle</param> /// <returns></returns> [DllImport("libsane", EntryPoint = "sane_init")] public extern static SaneStatus SaneInitialize(out int version, IntPtr callback); /// <summary> /// Open SANE /// </summary> /// <param name="name"></param> /// <param name="handle"></param> /// <returns></returns> [DllImport("libsane", EntryPoint = "sane_open", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)] public extern static SaneStatus SaneOpen(string name, out IntPtr handle); /// <summary> /// Close SANE /// </summary> /// <param name="handle"></param> [DllImport("libsane", EntryPoint = "sane_close")] public extern static void SaneClose(IntPtr handle); /// <summary> /// Exit SANE /// </summary> [DllImport("libsane", EntryPoint = "sane_exit")] public extern static void SaneExit(); /// <summary> /// Get the status /// </summary> /// <param name="status"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This is here so we have the complete API wrapped")] [DllImport("libsane", EntryPoint = "sane_strstatus")] public extern static IntPtr SaneStatus(SaneStatus status); /// <summary> /// Gets the available devices /// </summary> /// <param name="deviceList"></param> /// <param name="localOnly"></param> /// <returns></returns> [DllImport("libsane", EntryPoint = "sane_get_devices")] public extern static SaneStatus SaneGetDevices(ref IntPtr deviceList, [MarshalAs(UnmanagedType.Bool)] bool localOnly); /// <summary> /// Set a control option /// </summary> /// <param name="handle"></param> /// <param name="n"></param> /// <param name="a"></param> /// <param name="v"></param> /// <param name="i"></param> /// <returns></returns> [DllImport("libsane", EntryPoint = "sane_control_option")] public extern static SaneStatus SaneControlOption(IntPtr handle, int n, SaneOptionAction a, out IntPtr v, ref int i); /// <summary> /// Set a control option /// </summary> /// <param name="handle"></param> /// <param name="n"></param> /// <param name="a"></param> /// <param name="v"></param> /// <param name="i"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This is here so we have the complete API wrapped")] [DllImport("libsane", EntryPoint = "sane_control_option")] public extern static SaneStatus SaneControlOption2(IntPtr handle, int n, SaneOptionAction a, ref IntPtr v, ref int i); /// <summary> /// Set a control option /// </summary> /// <param name="handle"></param> /// <param name="n"></param> /// <param name="a"></param> /// <param name="v"></param> /// <param name="i"></param> /// <returns></returns> [DllImport("libsane", EntryPoint = "sane_control_option")] public extern static SaneStatus SaneControlOptionInteger(IntPtr handle, int n, SaneOptionAction a, ref int v, ref int i); /// <summary> /// Set a control option /// </summary> /// <param name="handle"></param> /// <param name="n"></param> /// <param name="a"></param> /// <param name="v"></param> /// <param name="i"></param> /// <returns></returns> [DllImport("libsane", EntryPoint = "sane_control_option")] public extern static SaneStatus SaneControlOptionString(IntPtr handle, int n, SaneOptionAction a, ref string v, ref int i); /// <summary> /// Set a control option /// </summary> /// <param name="handle"></param> /// <param name="n"></param> /// <param name="a"></param> /// <param name="v"></param> /// <param name="i"></param> /// <returns></returns> [DllImport("libsane", EntryPoint = "sane_control_option", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)] public extern static SaneStatus SaneControlOptionStringBuilder(IntPtr handle, int n, SaneOptionAction a, StringBuilder v, ref int i); /// <summary> /// Set a control option /// </summary> /// <param name="handle"></param> /// <param name="n"></param> /// <param name="a"></param> /// <param name="v"></param> /// <param name="i"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This is here so we have the complete API wrapped")] [DllImport("libsane", EntryPoint = "sane_control_option")] public extern static SaneStatus SaneControlOptionFixed(IntPtr handle, int n, SaneOptionAction a, ref int v, ref int i); /// <summary> /// Set a control option /// </summary> /// <param name="handle"></param> /// <param name="n"></param> /// <param name="a"></param> /// <param name="v"></param> /// <param name="i"></param> /// <returns></returns> [DllImport("libsane", EntryPoint = "sane_control_option")] public extern static SaneStatus SaneControlOptionBoolean(IntPtr handle, int n, SaneOptionAction a, [MarshalAs(UnmanagedType.Bool)] ref bool v, ref int i); /// <summary> /// Set a control option /// </summary> /// <param name="handle"></param> /// <param name="n"></param> /// <param name="a"></param> /// <param name="v"></param> /// <param name="i"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This is here so we have the complete API wrapped")] [DllImport("libsane", EntryPoint = "sane_control_option")] public extern static SaneStatus SaneControlOption(IntPtr handle, int n, SaneOptionAction a, ref IntPtr v, ref IntPtr i); /// <summary> /// Set a control option /// </summary> /// <param name="handle"></param> /// <param name="n"></param> /// <param name="a"></param> /// <param name="v"></param> /// <param name="i"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This is here so we have the complete API wrapped")] [DllImport("libsane", EntryPoint = "sane_control_option")] public extern static SaneStatus SaneControlOption(IntPtr handle, int n, SaneOptionAction a, ref float v, ref int i); /// <summary> /// Set a control option /// </summary> /// <param name="handle"></param> /// <param name="n"></param> /// <param name="a"></param> /// <param name="v"></param> /// <param name="i"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This is here so we have the complete API wrapped")] [DllImport("libsane", EntryPoint = "sane_control_option", CharSet = CharSet.Ansi, BestFitMapping = false, ThrowOnUnmappableChar = true)] public extern static SaneStatus SaneControlOption(IntPtr handle, int n, SaneOptionAction a, StringBuilder v, ref int i); /// <summary> /// Get option descriptor /// </summary> /// <param name="handle"></param> /// <param name="n"></param> /// <returns></returns> [DllImport("libsane", EntryPoint = "sane_get_option_descriptor")] public extern static IntPtr SaneGetOptionDescriptor(IntPtr handle, int n); /// <summary> /// Read /// </summary> /// <param name="handle"></param> /// <param name="buf"></param> /// <param name="maxlen"></param> /// <param name="len"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This is here so we have the complete API wrapped")] [DllImport("libsane", EntryPoint = "sane_read")] public extern static SaneStatus SaneRead(IntPtr handle, out IntPtr buf, int maxlen, ref int len); /// <summary> /// Read /// </summary> /// <param name="handle"></param> /// <param name="buf"></param> /// <param name="maxlen"></param> /// <param name="len"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This is here so we have the complete API wrapped")] [DllImport("libsane", EntryPoint = "sane_read")] public extern static SaneStatus SaneRead(IntPtr handle, [Out, MarshalAs(UnmanagedType.LPArray, SizeConst = 32768)] byte[] buf, int maxlen, ref int len); /// <summary> /// Get parameters /// </summary> /// <param name="handle"></param> /// <param name="p"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This is here so we have the complete API wrapped")] [DllImport("libsane", EntryPoint = "sane_get_parameters")] public extern static SaneStatus SaneGetParameters(IntPtr handle, ref IntPtr p); /// <summary> /// Get parameters /// </summary> /// <param name="handle"></param> /// <param name="p"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This is here so we have the complete API wrapped")] [DllImport("libsane", EntryPoint = "sane_get_parameters")] public extern static SaneStatus SaneGetParameters(IntPtr handle, [In, Out, MarshalAs(UnmanagedType.LPStruct)] SaneParameters p); /// <summary> /// Get parameters /// </summary> /// <param name="handle"></param> /// <param name="p"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This is here so we have the complete API wrapped")] [DllImport("libsane", EntryPoint = "sane_get_parameters")] public extern static SaneStatus SaneGetParameters(IntPtr handle, IntPtr p); /// <summary> /// Start /// </summary> /// <param name="handle"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This is here so we have the complete API wrapped")] [DllImport("libsane", EntryPoint = "sane_start")] public extern static SaneStatus SaneStart(IntPtr handle); /// <summary> /// Cancel /// </summary> /// <param name="handle"></param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This is here so we have the complete API wrapped")] [DllImport("libsane", EntryPoint = "sane_cancel")] public extern static void SaneCancel(IntPtr handle); /// <summary> /// Set I/O mode /// </summary> /// <param name="handle"></param> /// <param name="async"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This is here so we have the complete API wrapped")] [DllImport("libsane", EntryPoint = "sane_set_io_mode")] public extern static SaneStatus SaneSetIoMode(IntPtr handle, [MarshalAs(UnmanagedType.Bool)] bool async); /// <summary> /// Select feature descriptor /// </summary> /// <param name="handle"></param> /// <param name="fd"></param> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "This is here so we have the complete API wrapped")] [DllImport("libsane", EntryPoint = "sane_get_select_fd")] public extern static SaneStatus SaneGetSelectFd(IntPtr handle, out IntPtr fd); } }
namespace iControl { using System.Xml.Serialization; using System.Web.Services; using System.ComponentModel; using System.Web.Services.Protocols; using System; using System.Diagnostics; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Web.Services.WebServiceBindingAttribute(Name="PEM.ServiceChainEndpointBinding", Namespace="urn:iControl")] public partial class PEMServiceChainEndpoint : iControlInterface { public PEMServiceChainEndpoint() { this.Url = "https://url_to_service"; } //======================================================================= // Operations //======================================================================= //----------------------------------------------------------------------- // add_service_endpoint //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:PEM/ServiceChainEndpoint", RequestNamespace="urn:iControl:PEM/ServiceChainEndpoint", ResponseNamespace="urn:iControl:PEM/ServiceChainEndpoint")] public void add_service_endpoint( string [] endpoints, string [] [] service_endpoints, string [] [] vlans, string [] [] to_endpoints, long [] [] orders ) { this.Invoke("add_service_endpoint", new object [] { endpoints, service_endpoints, vlans, to_endpoints, orders}); } public System.IAsyncResult Beginadd_service_endpoint(string [] endpoints,string [] [] service_endpoints,string [] [] vlans,string [] [] to_endpoints,long [] [] orders, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("add_service_endpoint", new object[] { endpoints, service_endpoints, vlans, to_endpoints, orders}, callback, asyncState); } public void Endadd_service_endpoint(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // create //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:PEM/ServiceChainEndpoint", RequestNamespace="urn:iControl:PEM/ServiceChainEndpoint", ResponseNamespace="urn:iControl:PEM/ServiceChainEndpoint")] public void create( string [] endpoints ) { this.Invoke("create", new object [] { endpoints}); } public System.IAsyncResult Begincreate(string [] endpoints, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("create", new object[] { endpoints}, callback, asyncState); } public void Endcreate(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_all_service_chain_endpoints //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:PEM/ServiceChainEndpoint", RequestNamespace="urn:iControl:PEM/ServiceChainEndpoint", ResponseNamespace="urn:iControl:PEM/ServiceChainEndpoint")] public void delete_all_service_chain_endpoints( ) { this.Invoke("delete_all_service_chain_endpoints", new object [0]); } public System.IAsyncResult Begindelete_all_service_chain_endpoints(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_all_service_chain_endpoints", new object[0], callback, asyncState); } public void Enddelete_all_service_chain_endpoints(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // delete_service_chain_endpoint //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:PEM/ServiceChainEndpoint", RequestNamespace="urn:iControl:PEM/ServiceChainEndpoint", ResponseNamespace="urn:iControl:PEM/ServiceChainEndpoint")] public void delete_service_chain_endpoint( string [] endpoints ) { this.Invoke("delete_service_chain_endpoint", new object [] { endpoints}); } public System.IAsyncResult Begindelete_service_chain_endpoint(string [] endpoints, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("delete_service_chain_endpoint", new object[] { endpoints}, callback, asyncState); } public void Enddelete_service_chain_endpoint(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // get_list //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:PEM/ServiceChainEndpoint", RequestNamespace="urn:iControl:PEM/ServiceChainEndpoint", ResponseNamespace="urn:iControl:PEM/ServiceChainEndpoint")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] get_list( ) { object [] results = this.Invoke("get_list", new object [0]); return ((string [])(results[0])); } public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_list", new object[0], callback, asyncState); } public string [] Endget_list(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [])(results[0])); } //----------------------------------------------------------------------- // get_service_endpoint //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:PEM/ServiceChainEndpoint", RequestNamespace="urn:iControl:PEM/ServiceChainEndpoint", ResponseNamespace="urn:iControl:PEM/ServiceChainEndpoint")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] [] get_service_endpoint( string [] endpoints ) { object [] results = this.Invoke("get_service_endpoint", new object [] { endpoints}); return ((string [] [])(results[0])); } public System.IAsyncResult Beginget_service_endpoint(string [] endpoints, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_service_endpoint", new object[] { endpoints}, callback, asyncState); } public string [] [] Endget_service_endpoint(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [] [])(results[0])); } //----------------------------------------------------------------------- // get_service_endpoint_from_vlan //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:PEM/ServiceChainEndpoint", RequestNamespace="urn:iControl:PEM/ServiceChainEndpoint", ResponseNamespace="urn:iControl:PEM/ServiceChainEndpoint")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] [] get_service_endpoint_from_vlan( string [] endpoints, string [] [] service_endpoints ) { object [] results = this.Invoke("get_service_endpoint_from_vlan", new object [] { endpoints, service_endpoints}); return ((string [] [])(results[0])); } public System.IAsyncResult Beginget_service_endpoint_from_vlan(string [] endpoints,string [] [] service_endpoints, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_service_endpoint_from_vlan", new object[] { endpoints, service_endpoints}, callback, asyncState); } public string [] [] Endget_service_endpoint_from_vlan(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [] [])(results[0])); } //----------------------------------------------------------------------- // get_service_endpoint_internal_virtual_server //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:PEM/ServiceChainEndpoint", RequestNamespace="urn:iControl:PEM/ServiceChainEndpoint", ResponseNamespace="urn:iControl:PEM/ServiceChainEndpoint")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] [] get_service_endpoint_internal_virtual_server( string [] chains, string [] [] endpoints ) { object [] results = this.Invoke("get_service_endpoint_internal_virtual_server", new object [] { chains, endpoints}); return ((string [] [])(results[0])); } public System.IAsyncResult Beginget_service_endpoint_internal_virtual_server(string [] chains,string [] [] endpoints, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_service_endpoint_internal_virtual_server", new object[] { chains, endpoints}, callback, asyncState); } public string [] [] Endget_service_endpoint_internal_virtual_server(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [] [])(results[0])); } //----------------------------------------------------------------------- // get_service_endpoint_option_type //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:PEM/ServiceChainEndpoint", RequestNamespace="urn:iControl:PEM/ServiceChainEndpoint", ResponseNamespace="urn:iControl:PEM/ServiceChainEndpoint")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public PEMServiceChainEndpointServiceOptionType [] [] get_service_endpoint_option_type( string [] endpoints, string [] [] service_endpoints ) { object [] results = this.Invoke("get_service_endpoint_option_type", new object [] { endpoints, service_endpoints}); return ((PEMServiceChainEndpointServiceOptionType [] [])(results[0])); } public System.IAsyncResult Beginget_service_endpoint_option_type(string [] endpoints,string [] [] service_endpoints, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_service_endpoint_option_type", new object[] { endpoints, service_endpoints}, callback, asyncState); } public PEMServiceChainEndpointServiceOptionType [] [] Endget_service_endpoint_option_type(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((PEMServiceChainEndpointServiceOptionType [] [])(results[0])); } //----------------------------------------------------------------------- // get_service_endpoint_order //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:PEM/ServiceChainEndpoint", RequestNamespace="urn:iControl:PEM/ServiceChainEndpoint", ResponseNamespace="urn:iControl:PEM/ServiceChainEndpoint")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public long [] [] get_service_endpoint_order( string [] endpoints, string [] [] service_endpoints ) { object [] results = this.Invoke("get_service_endpoint_order", new object [] { endpoints, service_endpoints}); return ((long [] [])(results[0])); } public System.IAsyncResult Beginget_service_endpoint_order(string [] endpoints,string [] [] service_endpoints, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_service_endpoint_order", new object[] { endpoints, service_endpoints}, callback, asyncState); } public long [] [] Endget_service_endpoint_order(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((long [] [])(results[0])); } //----------------------------------------------------------------------- // get_service_endpoint_steering_policy //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:PEM/ServiceChainEndpoint", RequestNamespace="urn:iControl:PEM/ServiceChainEndpoint", ResponseNamespace="urn:iControl:PEM/ServiceChainEndpoint")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] [] get_service_endpoint_steering_policy( string [] chains, string [] [] endpoints ) { object [] results = this.Invoke("get_service_endpoint_steering_policy", new object [] { chains, endpoints}); return ((string [] [])(results[0])); } public System.IAsyncResult Beginget_service_endpoint_steering_policy(string [] chains,string [] [] endpoints, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_service_endpoint_steering_policy", new object[] { chains, endpoints}, callback, asyncState); } public string [] [] Endget_service_endpoint_steering_policy(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [] [])(results[0])); } //----------------------------------------------------------------------- // get_service_endpoint_to_endpoint //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:PEM/ServiceChainEndpoint", RequestNamespace="urn:iControl:PEM/ServiceChainEndpoint", ResponseNamespace="urn:iControl:PEM/ServiceChainEndpoint")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string [] [] get_service_endpoint_to_endpoint( string [] endpoints, string [] [] service_endpoints ) { object [] results = this.Invoke("get_service_endpoint_to_endpoint", new object [] { endpoints, service_endpoints}); return ((string [] [])(results[0])); } public System.IAsyncResult Beginget_service_endpoint_to_endpoint(string [] endpoints,string [] [] service_endpoints, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_service_endpoint_to_endpoint", new object[] { endpoints, service_endpoints}, callback, asyncState); } public string [] [] Endget_service_endpoint_to_endpoint(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string [] [])(results[0])); } //----------------------------------------------------------------------- // get_version //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:PEM/ServiceChainEndpoint", RequestNamespace="urn:iControl:PEM/ServiceChainEndpoint", ResponseNamespace="urn:iControl:PEM/ServiceChainEndpoint")] [return: System.Xml.Serialization.SoapElementAttribute("return")] public string get_version( ) { object [] results = this.Invoke("get_version", new object [] { }); return ((string)(results[0])); } public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("get_version", new object[] { }, callback, asyncState); } public string Endget_version(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); return ((string)(results[0])); } //----------------------------------------------------------------------- // remove_all_service_endpoints //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:PEM/ServiceChainEndpoint", RequestNamespace="urn:iControl:PEM/ServiceChainEndpoint", ResponseNamespace="urn:iControl:PEM/ServiceChainEndpoint")] public void remove_all_service_endpoints( string [] endpoints ) { this.Invoke("remove_all_service_endpoints", new object [] { endpoints}); } public System.IAsyncResult Beginremove_all_service_endpoints(string [] endpoints, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_all_service_endpoints", new object[] { endpoints}, callback, asyncState); } public void Endremove_all_service_endpoints(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // remove_service_endpoint //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:PEM/ServiceChainEndpoint", RequestNamespace="urn:iControl:PEM/ServiceChainEndpoint", ResponseNamespace="urn:iControl:PEM/ServiceChainEndpoint")] public void remove_service_endpoint( string [] endpoints, string [] [] service_endpoints ) { this.Invoke("remove_service_endpoint", new object [] { endpoints, service_endpoints}); } public System.IAsyncResult Beginremove_service_endpoint(string [] endpoints,string [] [] service_endpoints, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("remove_service_endpoint", new object[] { endpoints, service_endpoints}, callback, asyncState); } public void Endremove_service_endpoint(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_service_endpoint_from_vlan //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:PEM/ServiceChainEndpoint", RequestNamespace="urn:iControl:PEM/ServiceChainEndpoint", ResponseNamespace="urn:iControl:PEM/ServiceChainEndpoint")] public void set_service_endpoint_from_vlan( string [] endpoints, string [] [] service_endpoints, string [] [] vlans ) { this.Invoke("set_service_endpoint_from_vlan", new object [] { endpoints, service_endpoints, vlans}); } public System.IAsyncResult Beginset_service_endpoint_from_vlan(string [] endpoints,string [] [] service_endpoints,string [] [] vlans, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_service_endpoint_from_vlan", new object[] { endpoints, service_endpoints, vlans}, callback, asyncState); } public void Endset_service_endpoint_from_vlan(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_service_endpoint_internal_virtual_server //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:PEM/ServiceChainEndpoint", RequestNamespace="urn:iControl:PEM/ServiceChainEndpoint", ResponseNamespace="urn:iControl:PEM/ServiceChainEndpoint")] public void set_service_endpoint_internal_virtual_server( string [] chains, string [] [] endpoints, string [] [] virtual_servers ) { this.Invoke("set_service_endpoint_internal_virtual_server", new object [] { chains, endpoints, virtual_servers}); } public System.IAsyncResult Beginset_service_endpoint_internal_virtual_server(string [] chains,string [] [] endpoints,string [] [] virtual_servers, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_service_endpoint_internal_virtual_server", new object[] { chains, endpoints, virtual_servers}, callback, asyncState); } public void Endset_service_endpoint_internal_virtual_server(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_service_endpoint_option_type //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:PEM/ServiceChainEndpoint", RequestNamespace="urn:iControl:PEM/ServiceChainEndpoint", ResponseNamespace="urn:iControl:PEM/ServiceChainEndpoint")] public void set_service_endpoint_option_type( string [] endpoints, string [] [] service_endpoints, PEMServiceChainEndpointServiceOptionType [] [] types ) { this.Invoke("set_service_endpoint_option_type", new object [] { endpoints, service_endpoints, types}); } public System.IAsyncResult Beginset_service_endpoint_option_type(string [] endpoints,string [] [] service_endpoints,PEMServiceChainEndpointServiceOptionType [] [] types, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_service_endpoint_option_type", new object[] { endpoints, service_endpoints, types}, callback, asyncState); } public void Endset_service_endpoint_option_type(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_service_endpoint_order //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:PEM/ServiceChainEndpoint", RequestNamespace="urn:iControl:PEM/ServiceChainEndpoint", ResponseNamespace="urn:iControl:PEM/ServiceChainEndpoint")] public void set_service_endpoint_order( string [] endpoints, string [] [] service_endpoints, long [] [] orders ) { this.Invoke("set_service_endpoint_order", new object [] { endpoints, service_endpoints, orders}); } public System.IAsyncResult Beginset_service_endpoint_order(string [] endpoints,string [] [] service_endpoints,long [] [] orders, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_service_endpoint_order", new object[] { endpoints, service_endpoints, orders}, callback, asyncState); } public void Endset_service_endpoint_order(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_service_endpoint_steering_policy //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:PEM/ServiceChainEndpoint", RequestNamespace="urn:iControl:PEM/ServiceChainEndpoint", ResponseNamespace="urn:iControl:PEM/ServiceChainEndpoint")] public void set_service_endpoint_steering_policy( string [] chains, string [] [] endpoints, string [] [] values ) { this.Invoke("set_service_endpoint_steering_policy", new object [] { chains, endpoints, values}); } public System.IAsyncResult Beginset_service_endpoint_steering_policy(string [] chains,string [] [] endpoints,string [] [] values, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_service_endpoint_steering_policy", new object[] { chains, endpoints, values}, callback, asyncState); } public void Endset_service_endpoint_steering_policy(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } //----------------------------------------------------------------------- // set_service_endpoint_to_endpoint //----------------------------------------------------------------------- [System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:PEM/ServiceChainEndpoint", RequestNamespace="urn:iControl:PEM/ServiceChainEndpoint", ResponseNamespace="urn:iControl:PEM/ServiceChainEndpoint")] public void set_service_endpoint_to_endpoint( string [] endpoints, string [] [] service_endpoints, string [] [] to_endpoints ) { this.Invoke("set_service_endpoint_to_endpoint", new object [] { endpoints, service_endpoints, to_endpoints}); } public System.IAsyncResult Beginset_service_endpoint_to_endpoint(string [] endpoints,string [] [] service_endpoints,string [] [] to_endpoints, System.AsyncCallback callback, object asyncState) { return this.BeginInvoke("set_service_endpoint_to_endpoint", new object[] { endpoints, service_endpoints, to_endpoints}, callback, asyncState); } public void Endset_service_endpoint_to_endpoint(System.IAsyncResult asyncResult) { object [] results = this.EndInvoke(asyncResult); } } //======================================================================= // Enums //======================================================================= /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")] [System.SerializableAttribute()] [System.Xml.Serialization.SoapTypeAttribute(TypeName = "PEM.ServiceChainEndpoint.ServiceOptionType", Namespace = "urn:iControl")] public enum PEMServiceChainEndpointServiceOptionType { SERVICE_OPTION_TYPE_UNKNOWN, SERVICE_OPTION_TYPE_OPTIONAL, SERVICE_OPTION_TYPE_MANDATORY, } //======================================================================= // Structs //======================================================================= }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ExtractInt321() { var test = new SimpleUnaryOpTest__ExtractInt321(); try { if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } } catch (PlatformNotSupportedException) { test.Succeeded = true; } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ExtractInt321 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Int32); private const int RetElementCount = VectorSize / sizeof(Int32); private static Int32[] _data = new Int32[Op1ElementCount]; private static Vector128<Int32> _clsVar; private Vector128<Int32> _fld; private SimpleUnaryOpTest__DataTable<Int32, Int32> _dataTable; static SimpleUnaryOpTest__ExtractInt321() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__ExtractInt321() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)(random.Next(0, int.MaxValue)); } _dataTable = new SimpleUnaryOpTest__DataTable<Int32, Int32>(_data, new Int32[RetElementCount], VectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse41.Extract( Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse41.Extract( Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse41.Extract( Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Int32)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Int32)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse41).GetMethod(nameof(Sse41.Extract), new Type[] { typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Int32)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse41.Extract( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr); var result = Sse41.Extract(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)); var result = Sse41.Extract(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)); var result = Sse41.Extract(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__ExtractInt321(); var result = Sse41.Extract(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse41.Extract(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Int32> firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "") { if ((result[0] != firstOp[1])) { Succeeded = false; } if (!Succeeded) { Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.Extract)}<Int32>(Vector128<Int32><9>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using System.Xml.XPath; namespace System.Xml { internal class XmlAsyncCheckWriter : XmlWriter { private readonly XmlWriter _coreWriter = null; private Task _lastTask = Task.CompletedTask; internal XmlWriter CoreWriter { get { return _coreWriter; } } public XmlAsyncCheckWriter(XmlWriter writer) { _coreWriter = writer; } private void CheckAsync() { if (!_lastTask.IsCompleted) { throw new InvalidOperationException(SR.Xml_AsyncIsRunningException); } } #region Sync Methods, Properties Check public override XmlWriterSettings Settings { get { XmlWriterSettings settings = _coreWriter.Settings; if (null != settings) { settings = settings.Clone(); } else { settings = new XmlWriterSettings(); } settings.Async = true; settings.ReadOnly = true; return settings; } } public override void WriteStartDocument() { CheckAsync(); _coreWriter.WriteStartDocument(); } public override void WriteStartDocument(bool standalone) { CheckAsync(); _coreWriter.WriteStartDocument(standalone); } public override void WriteEndDocument() { CheckAsync(); _coreWriter.WriteEndDocument(); } public override void WriteDocType(string name, string pubid, string sysid, string subset) { CheckAsync(); _coreWriter.WriteDocType(name, pubid, sysid, subset); } public override void WriteStartElement(string prefix, string localName, string ns) { CheckAsync(); _coreWriter.WriteStartElement(prefix, localName, ns); } public override void WriteEndElement() { CheckAsync(); _coreWriter.WriteEndElement(); } public override void WriteFullEndElement() { CheckAsync(); _coreWriter.WriteFullEndElement(); } public override void WriteStartAttribute(string prefix, string localName, string ns) { CheckAsync(); _coreWriter.WriteStartAttribute(prefix, localName, ns); } public override void WriteEndAttribute() { CheckAsync(); _coreWriter.WriteEndAttribute(); } public override void WriteCData(string text) { CheckAsync(); _coreWriter.WriteCData(text); } public override void WriteComment(string text) { CheckAsync(); _coreWriter.WriteComment(text); } public override void WriteProcessingInstruction(string name, string text) { CheckAsync(); _coreWriter.WriteProcessingInstruction(name, text); } public override void WriteEntityRef(string name) { CheckAsync(); _coreWriter.WriteEntityRef(name); } public override void WriteCharEntity(char ch) { CheckAsync(); _coreWriter.WriteCharEntity(ch); } public override void WriteWhitespace(string ws) { CheckAsync(); _coreWriter.WriteWhitespace(ws); } public override void WriteString(string text) { CheckAsync(); _coreWriter.WriteString(text); } public override void WriteSurrogateCharEntity(char lowChar, char highChar) { CheckAsync(); _coreWriter.WriteSurrogateCharEntity(lowChar, highChar); } public override void WriteChars(char[] buffer, int index, int count) { CheckAsync(); _coreWriter.WriteChars(buffer, index, count); } public override void WriteRaw(char[] buffer, int index, int count) { CheckAsync(); _coreWriter.WriteRaw(buffer, index, count); } public override void WriteRaw(string data) { CheckAsync(); _coreWriter.WriteRaw(data); } public override void WriteBase64(byte[] buffer, int index, int count) { CheckAsync(); _coreWriter.WriteBase64(buffer, index, count); } public override void WriteBinHex(byte[] buffer, int index, int count) { CheckAsync(); _coreWriter.WriteBinHex(buffer, index, count); } public override WriteState WriteState { get { CheckAsync(); return _coreWriter.WriteState; } } public override void Close() { CheckAsync(); _coreWriter.Close(); } public override void Flush() { CheckAsync(); _coreWriter.Flush(); } public override string LookupPrefix(string ns) { CheckAsync(); return _coreWriter.LookupPrefix(ns); } public override XmlSpace XmlSpace { get { CheckAsync(); return _coreWriter.XmlSpace; } } public override string XmlLang { get { CheckAsync(); return _coreWriter.XmlLang; } } public override void WriteNmToken(string name) { CheckAsync(); _coreWriter.WriteNmToken(name); } public override void WriteName(string name) { CheckAsync(); _coreWriter.WriteName(name); } public override void WriteQualifiedName(string localName, string ns) { CheckAsync(); _coreWriter.WriteQualifiedName(localName, ns); } public override void WriteValue(object value) { CheckAsync(); _coreWriter.WriteValue(value); } public override void WriteValue(string value) { CheckAsync(); _coreWriter.WriteValue(value); } public override void WriteValue(bool value) { CheckAsync(); _coreWriter.WriteValue(value); } public override void WriteValue(DateTime value) { CheckAsync(); _coreWriter.WriteValue(value); } public override void WriteValue(DateTimeOffset value) { CheckAsync(); _coreWriter.WriteValue(value); } public override void WriteValue(double value) { CheckAsync(); _coreWriter.WriteValue(value); } public override void WriteValue(float value) { CheckAsync(); _coreWriter.WriteValue(value); } public override void WriteValue(decimal value) { CheckAsync(); _coreWriter.WriteValue(value); } public override void WriteValue(int value) { CheckAsync(); _coreWriter.WriteValue(value); } public override void WriteValue(long value) { CheckAsync(); _coreWriter.WriteValue(value); } public override void WriteAttributes(XmlReader reader, bool defattr) { CheckAsync(); _coreWriter.WriteAttributes(reader, defattr); } public override void WriteNode(XmlReader reader, bool defattr) { CheckAsync(); _coreWriter.WriteNode(reader, defattr); } public override void WriteNode(XPathNavigator navigator, bool defattr) { CheckAsync(); _coreWriter.WriteNode(navigator, defattr); } protected override void Dispose(bool disposing) { if (disposing) { CheckAsync(); //since it is protected method, we can't call coreWriter.Dispose(disposing). //Internal, it is always called to Dispose(true). So call coreWriter.Dispose() is OK. _coreWriter.Dispose(); } } #endregion #region Async Methods public override Task WriteStartDocumentAsync() { CheckAsync(); var task = _coreWriter.WriteStartDocumentAsync(); _lastTask = task; return task; } public override Task WriteStartDocumentAsync(bool standalone) { CheckAsync(); var task = _coreWriter.WriteStartDocumentAsync(standalone); _lastTask = task; return task; } public override Task WriteEndDocumentAsync() { CheckAsync(); var task = _coreWriter.WriteEndDocumentAsync(); _lastTask = task; return task; } public override Task WriteDocTypeAsync(string name, string pubid, string sysid, string subset) { CheckAsync(); var task = _coreWriter.WriteDocTypeAsync(name, pubid, sysid, subset); _lastTask = task; return task; } public override Task WriteStartElementAsync(string prefix, string localName, string ns) { CheckAsync(); var task = _coreWriter.WriteStartElementAsync(prefix, localName, ns); _lastTask = task; return task; } public override Task WriteEndElementAsync() { CheckAsync(); var task = _coreWriter.WriteEndElementAsync(); _lastTask = task; return task; } public override Task WriteFullEndElementAsync() { CheckAsync(); var task = _coreWriter.WriteFullEndElementAsync(); _lastTask = task; return task; } protected internal override Task WriteStartAttributeAsync(string prefix, string localName, string ns) { CheckAsync(); var task = _coreWriter.WriteStartAttributeAsync(prefix, localName, ns); _lastTask = task; return task; } protected internal override Task WriteEndAttributeAsync() { CheckAsync(); var task = _coreWriter.WriteEndAttributeAsync(); _lastTask = task; return task; } public override Task WriteCDataAsync(string text) { CheckAsync(); var task = _coreWriter.WriteCDataAsync(text); _lastTask = task; return task; } public override Task WriteCommentAsync(string text) { CheckAsync(); var task = _coreWriter.WriteCommentAsync(text); _lastTask = task; return task; } public override Task WriteProcessingInstructionAsync(string name, string text) { CheckAsync(); var task = _coreWriter.WriteProcessingInstructionAsync(name, text); _lastTask = task; return task; } public override Task WriteEntityRefAsync(string name) { CheckAsync(); var task = _coreWriter.WriteEntityRefAsync(name); _lastTask = task; return task; } public override Task WriteCharEntityAsync(char ch) { CheckAsync(); var task = _coreWriter.WriteCharEntityAsync(ch); _lastTask = task; return task; } public override Task WriteWhitespaceAsync(string ws) { CheckAsync(); var task = _coreWriter.WriteWhitespaceAsync(ws); _lastTask = task; return task; } public override Task WriteStringAsync(string text) { CheckAsync(); var task = _coreWriter.WriteStringAsync(text); _lastTask = task; return task; } public override Task WriteSurrogateCharEntityAsync(char lowChar, char highChar) { CheckAsync(); var task = _coreWriter.WriteSurrogateCharEntityAsync(lowChar, highChar); _lastTask = task; return task; } public override Task WriteCharsAsync(char[] buffer, int index, int count) { CheckAsync(); var task = _coreWriter.WriteCharsAsync(buffer, index, count); _lastTask = task; return task; } public override Task WriteRawAsync(char[] buffer, int index, int count) { CheckAsync(); var task = _coreWriter.WriteRawAsync(buffer, index, count); _lastTask = task; return task; } public override Task WriteRawAsync(string data) { CheckAsync(); var task = _coreWriter.WriteRawAsync(data); _lastTask = task; return task; } public override Task WriteBase64Async(byte[] buffer, int index, int count) { CheckAsync(); var task = _coreWriter.WriteBase64Async(buffer, index, count); _lastTask = task; return task; } public override Task WriteBinHexAsync(byte[] buffer, int index, int count) { CheckAsync(); var task = _coreWriter.WriteBinHexAsync(buffer, index, count); _lastTask = task; return task; } public override Task FlushAsync() { CheckAsync(); var task = _coreWriter.FlushAsync(); _lastTask = task; return task; } public override Task WriteNmTokenAsync(string name) { CheckAsync(); var task = _coreWriter.WriteNmTokenAsync(name); _lastTask = task; return task; } public override Task WriteNameAsync(string name) { CheckAsync(); var task = _coreWriter.WriteNameAsync(name); _lastTask = task; return task; } public override Task WriteQualifiedNameAsync(string localName, string ns) { CheckAsync(); var task = _coreWriter.WriteQualifiedNameAsync(localName, ns); _lastTask = task; return task; } public override Task WriteAttributesAsync(XmlReader reader, bool defattr) { CheckAsync(); var task = _coreWriter.WriteAttributesAsync(reader, defattr); _lastTask = task; return task; } public override Task WriteNodeAsync(XmlReader reader, bool defattr) { CheckAsync(); var task = _coreWriter.WriteNodeAsync(reader, defattr); _lastTask = task; return task; } public override Task WriteNodeAsync(XPathNavigator navigator, bool defattr) { CheckAsync(); var task = _coreWriter.WriteNodeAsync(navigator, defattr); _lastTask = task; return task; } #endregion } }
using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Drawing; using System.Drawing.Imaging; namespace Libraries.Imaging { public struct Pixel1 { public byte Intensity { get; set; } public Pixel1(byte intensity) : this() { Intensity = intensity; } public static explicit operator Pixel3(Pixel1 pix) { return new Pixel3(pix.Intensity, pix.Intensity, pix.Intensity); } public static explicit operator Pixel4(Pixel1 pix) { return new Pixel4(pix.Intensity, pix.Intensity, pix.Intensity, (byte)255); } } public unsafe struct Pixel4 { public byte Red { get; set; } public byte Green { get; set; } public byte Blue { get; set; } public byte Alpha { get; set; } public Pixel4(byte* b) : this(b[0], b[1], b[2],b[3]) { } public Pixel4(byte red, byte green, byte blue, byte alpha) : this() { Red = red; Green = green; Blue = blue; Alpha = alpha; } public static explicit operator Pixel1(Pixel4 pix) { float f0 = 0.3f * (float)pix.Red; float f1 = 0.59f * (float)pix.Green; float f2 = 0.11f * (float)pix.Blue; return new Pixel1((byte)(f0 + f1 + f2)); //how do I select the b } public static explicit operator Pixel3(Pixel4 pix) { return new Pixel3(pix.Red, pix.Green, pix.Blue); } } public unsafe struct Pixel3 { public byte Red { get; set; } public byte Green { get; set; } public byte Blue { get; set; } public Pixel3(byte* input) : this(input[0], input[1], input[2]) { } public Pixel3(byte red, byte green, byte blue) : this() { Red = red; Green = green; Blue = blue; } public static explicit operator Pixel1(Pixel3 pix) { float f0 = 0.3f * (float)pix.Red; float f1 = 0.59f * (float)pix.Green; float f2 = 0.11f * (float)pix.Blue; return new Pixel1((byte)(f0 + f1 + f2)); //how do I select the b } public static explicit operator Pixel4(Pixel3 pix) { return new Pixel4(pix.Red, pix.Green, pix.Blue, (byte)255); } } public unsafe delegate void UnsafeImageTransformation(BitmapData data, byte* b); public static partial class ImageExtensions { public unsafe static void ApplyTranslationTableToBitmap(this Bitmap image, byte[] translationTable) { image.UnsafeTransformation((data, pointer) => ApplyTranslationTable(data, pointer, translationTable)); } public unsafe static void ApplyTranslationTable(BitmapData data, byte* pointer, byte[] translationTable) { for(int i = 0; i < data.Width; i++) { for(int j = 0; j < data.Height; j++) { byte tmp; if(TryGetGrayScaleValue(pointer, out tmp)) SetGrayScaleValue(pointer, translationTable[tmp]); else { //color } pointer += 4; } } } public static IEnumerable<T> GrabNeighborhood<T>(this T[][] image, int centerX, int centerY, int width, int height, int squareSize) { //generate a starting location that would define this properly //since we know centerX and centerY //compute startPoint, the factor that determines how to grab values from //this neighborhood int startPoint = (squareSize - 1) / 2; //this is the factor int endPoint = startPoint + 1; //this is the end condition for(int x = centerX - startPoint; x < centerX + endPoint; x++) { if(x >= 0 && x < width) { for(int y = centerY - startPoint; y < centerY + endPoint; y++) { if(y >= 0 && y < height) yield return image[x][y]; } } } } public static IEnumerable<byte> GrabNeighborhood(this byte[][] image, int centerX, int centerY, int width, int height, int squareSize) { return GrabNeighborhood<byte>(image, centerX, centerY, width, height, squareSize); } public static IEnumerable<int> GrabNeighborhood(this int[][] image, int centerX, int centerY, int width, int height, int squareSize) { return GrabNeighborhood<int>(image, centerX, centerY, width, height, squareSize); } public static unsafe byte[,] ToGreyScaleImage(byte* input, int width, int height) { byte[,] elements = new byte[width, height]; for(int i = 0; i < width; i++) { for(int j = 0; j < height; j++) { elements[i, j] = input[0]; input += 4; } } return elements; //assume 32bit rgb } public static unsafe byte[,] ToGreyScaleImage(byte* input, BitmapData data) { return ToGreyScaleImage(input, data.Width, data.Height); } public static unsafe byte[,] ToGreyScaleImage(this Bitmap b) { byte[,] result = null; b.UnsafeTransformation((x,y) => result = ToGreyScaleImage(y, x)); return result; } private static void Empty(int input) { } public static unsafe void ApplyByteArrayToImage(this byte[,] b, int width, int height, byte* data) { TraverseAcrossImage(width, height, (x, y) => { unsafe{ SetGrayScaleValue(data, b[x,y]); data += 4; }}); } public static void TraverseAcrossImage(this BitmapData data, Action<int, int> inner) { TraverseAcrossImage(data, inner, Empty); } public static void TraverseAcrossImage(this BitmapData data, Action<int, int> inner, Action<int> outer) { TraverseAcrossImage(data.Width, data.Height, inner, outer); } public static void TraverseAcrossImage(int width, int height, Action<int, int> inner) { TraverseAcrossImage(width, height, inner, Empty); } public static void TraverseAcrossImage(int width, int height, Action<int,int> inner, Action<int> outer) { for(int i = 0; i < width; i++) { outer(i); for(int j = 0; j < height; j++) inner(i,j); } } public static unsafe void UnsafeTransformation(this Bitmap b, UnsafeImageTransformation transformer, PixelFormat format, ImageLockMode m) { BitmapData bits = b.LockBits(b.GetImageSizeRectangle(), m, format); unsafe { byte* input = (byte*)bits.Scan0; transformer(bits, input); } b.UnlockBits(bits); } public static unsafe void UnsafeTransformation(this Bitmap b, UnsafeImageTransformation transformer, PixelFormat format) { UnsafeTransformation(b, transformer, format, ImageLockMode.ReadWrite); } public static unsafe void UnsafeTransformation(this Bitmap b, UnsafeImageTransformation transformer) { UnsafeTransformation(b, transformer, b.PixelFormat); } public static Rectangle GetImageSizeRectangle(this Bitmap b) { return new Rectangle(0, 0, b.Width, b.Height); } public static unsafe void SetColorValue(byte* data, byte r, byte g, byte b) { data[0] = r; data[1] = g; data[2] = b; } public static unsafe bool TryGetGrayScaleValue(byte* data, out byte value) { byte r = data[0]; byte g = data[1]; byte b = data[2]; bool gotValue = r == g && g == b; if(gotValue) value = r; else value = (byte)0; return gotValue; } public static unsafe void SetGrayScaleValue(byte* data, byte value) { data[0] = value; data[1] = value; data[2] = value; data[3] = (byte)255; } } }
// // NOT FOR USE IN PRODUCTION // // THIS IS SAMPLE CODE, IT WILL HELP YOU GET STARTED, BUT NOT MUCH MORE THAN THAT // // using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; class SourceStream : Stream { Stream source; public SourceStream (Stream source) { this.source = source; } public override bool CanRead { get {return true; } } public override bool CanWrite { get { return false; } } public override bool CanSeek { get { return false; } } public override long Length { get { return source.Length; }} public override long Position { get { throw new Exception (); } set { throw new Exception (); }} public override void Flush () { throw new Exception (); } public override int Read (byte [] buf, int offset, int count) { int n = 0; for (int i = 0; i < count; i++){ int c = ReadByte (); if (c == -1) return n; buf [offset + n] = (byte) c; n++; } return n; } public override long Seek (long p, SeekOrigin o) { throw new Exception (); } public override void SetLength (long l) { throw new Exception (); } public override void Write (byte [] b, int a, int c) { throw new Exception (); } public override int ReadByte () { restart: int n = source.ReadByte (); if (n == -1) return -1; if (n == '/'){ int p = source.ReadByte (); if (p == '/'){ while (true) { n = source.ReadByte (); if (n == -1) return -1; if (n == '\n') return n; } } else if (p == '*'){ while (true){ n = source.ReadByte (); if (n == -1) return -1; while (n == '*'){ n = source.ReadByte (); if (n == -1) return -1; if (n == '/') goto restart; } } } source.Position = source.Position - 1; return '/'; } return n; } } class Declaration { public string selector, retval, parameters; public bool is_abstract, is_static; public Declaration (string selector, string retval, string parameters, bool is_abstract, bool is_static) { this.selector = selector; this.retval = retval; this.parameters = parameters; this.is_abstract = is_abstract; this.is_static = is_static; } } class Declarations { List<Declaration> decls = new List<Declaration> (); StreamWriter gencs; public Declarations (StreamWriter gencs) { this.gencs = gencs; } public void Add (Declaration d) { if (d == null) return; decls.Add (d); } int Count (string s, char k) { int count = 0; foreach (char c in s) if (c == k) count++; return count; } string HasGetter (string getter1, string getter2) { if (HasGetter (getter1)) return getter1; if (HasGetter (getter2)) return getter2; return null; } bool HasGetter (string getter) { var found = (from d in decls let sel = d.selector where Count (sel, ':') == 0 && sel == getter select d).FirstOrDefault (); return found != null; } bool Remove (string sel) { ignore.Add (sel); return true; } List<string> ignore = new List<string> (); public void Generate () { var copy = decls; var properties = (from d in copy let sel = d.selector where sel.StartsWith ("set") && sel.EndsWith (":") && Count (sel, ':') == 1 let getter1 = Char.ToLower (sel [3]) + sel.Substring (4).Trim (':') let getter2 = "is" + sel.Substring (3).Trim (':') let getter = HasGetter (getter1, getter2) where getter != null let r = Remove (sel) select getter).ToList (); foreach (var d in decls){ if (ignore.Contains (d.selector) || properties.Contains (d.selector)) continue; if (d.is_abstract) gencs.WriteLine ("\t\t[Abstract]"); if (d.is_static) gencs.WriteLine ("\t\t[Static]"); gencs.WriteLine ("\t\t[Export (\"{0}\")]", d.selector); gencs.WriteLine ("\t\t{0} {1} ({2});", d.retval, TrivialParser.AsMethod (TrivialParser.CleanSelector (d.selector)), d.parameters); gencs.WriteLine (); } if (properties.Count > 0) gencs.WriteLine ("\t\t//Detected properties"); foreach (var d in properties){ var decl = (from x in decls where x.selector == d select x).FirstOrDefault (); var sel = decl.selector; if (sel.StartsWith ("is")) sel = Char.ToLower (sel [2]) + sel.Substring (3); if (decl.is_abstract) gencs.WriteLine ("\t\t[Abstract]"); if (decl.is_static) gencs.WriteLine ("\t\t[Static]"); gencs.WriteLine ("\t\t[Export (\"{0}\")]", sel); gencs.WriteLine ("\t\t{0} {1} {{ {2}get; set; }}", decl.retval, TrivialParser.AsMethod (sel), d.StartsWith ("is") ? "[Bind (\"" + d + "\")]" : ""); gencs.WriteLine (); } } } class TrivialParser { StreamWriter gencs = File.CreateText ("gen.cs"); StreamWriter other = File.CreateText ("other.c"); StreamReader r; ArrayList types = new ArrayList (); void ProcessProperty (string line) { bool ro = false; string getter = null; line = CleanDeclaration (line); if (line.Length == 0) return; int p = line.IndexOf (')'); var sub = line.Substring (0, p+1); if (sub.IndexOf ("readonly") != -1){ ro = true; } int j = sub.IndexOf ("getter="); if (j != -1){ int k = sub.IndexOfAny (new char [] { ',', ')'}, j +1); //Console.WriteLine ("j={0} k={1} str={2}", j, k, sub); getter = sub.Substring (j + 7, k-(j+7)); } var type = new StringBuilder (); int i = p+1; for (; i < line.Length; i++){ char c = line [i]; if (!Char.IsWhiteSpace (c)) break; } for (; i < line.Length; i++){ char c = line [i]; if (Char.IsWhiteSpace (c)) break; type.Append (c); } for (; i < line.Length; i++){ char c = line [i]; if (Char.IsWhiteSpace (c) || c == '*') continue; else break; } var selector = new StringBuilder (); for (; i < line.Length; i++){ char c = line [i]; if (Char.IsWhiteSpace (c) || c == ';') break; selector.Append (c); } gencs.WriteLine ("\t\t[Export (\"{0}\")]", selector); gencs.WriteLine ("\t\t{0} {1} {{ {2} {3} }}", RemapType (type.ToString ()), selector, getter != null ? "[Bind (\"" + getter + "\")] get;" : "get;", ro ? "" : "set; "); gencs.WriteLine (); } public static string AsMethod (string msg) { return Char.ToUpper (msg [0]) + msg.Substring (1); } string MakeSelector (string sig) { StringBuilder sb = new StringBuilder (); for (int i = 0; i < sig.Length; i++){ char c = sig [i]; if (c == ' ') continue; if (c == ';') break; else if (c == ':'){ sb.Append (c); i++; for (; i < sig.Length; i++){ c = sig [i]; if (c == ')'){ for (++i; i < sig.Length; i++){ if (!Char.IsLetterOrDigit (sig [i])) break; } break; } } } else sb.Append (c); } return sb.ToString (); } enum State { SkipToType, EndOfType, Parameter, } string MakeParameters (string sig) { //Console.WriteLine ("Making Parameters: [{0}]", sig); int colon = sig.IndexOf (':'); if (colon == -1) return ""; var sb = new StringBuilder (); var tsb = new StringBuilder (); State state = State.SkipToType; for (int i = 0; i < sig.Length; i++){ char c = sig [i]; switch (state){ case State.SkipToType: if (Char.IsWhiteSpace (c)) continue; if (c == '('){ tsb = new StringBuilder (); state = State.EndOfType; } break; case State.EndOfType: if (c == ')'){ state = State.Parameter; sb.Append (RemapType (tsb.ToString ())); sb.Append (' '); } else { if (c != '*') tsb.Append (c); } break; case State.Parameter: if (Char.IsWhiteSpace (c)){ state = State.SkipToType; sb.Append (", "); } else { if (c != ';') sb.Append (c); } break; } } //Console.WriteLine (" -> {0}", sb); return sb.ToString (); } string RemapType (string type) { if (type.EndsWith ("*")) type = type.Substring (0, type.Length-1); type = type.Trim (); switch (type){ case "NSInteger": return "int"; case "CGFloat": return "float"; case "NSTextAlignment": return "uint"; case "NSString": case "NSString *": return "string"; case "NSSize": case "CGSize": return "SizeF"; case "NSRect": case "CGRect": return "RectangleF"; case "NSPoint": case "CGPoint": return "PointF"; case "NSGlyph": return "uint"; case "NSUInteger": return "uint"; case "id": return "NSObject"; case "BOOL": return "bool"; case "SEL": return "Selector"; case "NSURL": return "NSUrl"; case "NSTimeInterval": return "double"; } return type; } Regex rx = new Regex ("__OSX_AVAILABLE_STARTING\\(.*\\)"); Regex rx2 = new Regex ("AVAILABLE_MAC_OS_X_VERSION[_A-Z0-9]*"); string CleanDeclaration (string line) { return rx2.Replace (rx.Replace (line, ""), ""); } public static string CleanSelector (string selector) { return selector.Replace (":", ""); } Declaration ProcessDeclaration (bool isProtocol, string line, bool is_optional) { line = CleanDeclaration (line); if (line.Length == 0) return null; bool is_abstract = isProtocol && !is_optional; if (line.StartsWith ("@property")){ if (is_abstract) gencs.WriteLine ("\t\t[Abstract]"); ProcessProperty (line); return null; } //Console.WriteLine ("PROCESSING: {0}", line); bool is_static = line.StartsWith ("+"); int p, q; p = line.IndexOf ('('); if (p == -1) return null; q = line.IndexOf (')'); //Console.WriteLine ("->{0}\np={1} q-p={2}", line, p, q-p); string retval = RemapType (line.Substring (p+1, q-p-1)); p = line.IndexOf (';'); string signature = line.Substring (q+1, p-q); string selector = MakeSelector (signature); string parameters = MakeParameters (signature); //Console.WriteLine ("signature: {0}", signature); //Console.WriteLine ("selector: {0}", selector); return new Declaration (selector, retval, parameters, is_abstract, is_static); } void ProcessInterface (string iface) { bool need_close = iface.IndexOf ("{") != -1; var cols = iface.Split (); string line; //Console.WriteLine ("**** {0} ", iface); types.Add (cols [1]); if (cols.Length >= 4) gencs.WriteLine ("\n\t[BaseType (typeof ({0}))]", cols [3]); gencs.WriteLine ("\tinterface {0} {{", cols [1]); while ((line = r.ReadLine ()) != null && (need_close && !line.StartsWith ("}"))){ if (line == "{") need_close = true; } var decl = new Declarations (gencs); while ((line = r.ReadLine ()) != null && !line.StartsWith ("@end")){ string full = ""; while ((line = r.ReadLine ()) != null && !line.StartsWith ("@end")){ full += line; if (full.IndexOf (';') != -1){ full = full.Replace ('\n', ' '); decl.Add (ProcessDeclaration (false, full, false)); full = ""; } } break; } decl.Generate (); gencs.WriteLine ("\t}"); } void ProcessProtocol (string proto) { string [] d = proto.Split (new char [] { ' ', '<', '>'}); string line; types.Add (d [1]); gencs.WriteLine ("\n\t[BaseType (typeof ({0}))]", d.Length > 2 ? d [2] : "NSObject"); gencs.WriteLine ("\t[Model]"); gencs.WriteLine ("\tinterface {0} {{", d [1]); bool optional = false; var decl = new Declarations (gencs); while ((line = r.ReadLine ()) != null && !line.StartsWith ("@end")){ if (line.StartsWith ("@optional")) optional = true; string full = ""; while ((line = r.ReadLine ()) != null && !line.StartsWith ("@end")){ full += line; if (full.IndexOf (';') != -1){ full = full.Replace ('\n', ' '); decl.Add (ProcessDeclaration (true, full, optional)); full = ""; } } if (line.StartsWith ("@end")) break; } decl.Generate (); gencs.WriteLine ("\t}"); } TrivialParser () {} void Run (string [] args) { foreach (string f in args){ using (var fs = File.OpenRead (f)){ r = new StreamReader (new SourceStream (fs)); string line; while ((line = r.ReadLine ()) != null){ line = line.Replace ("UIKIT_EXTERN_CLASS ",""); if (line.StartsWith ("#")) continue; if (line.Length == 0) continue; if (line.StartsWith ("@class")) continue; if (line.StartsWith ("@interface")) ProcessInterface (line); if (line.StartsWith ("@protocol") && !line.EndsWith (";")) // && line.IndexOf ("<") != -1) ProcessProtocol (line); other.WriteLine (line); } } } foreach (string s in types){ Console.WriteLine ("\t\ttypeof ({0}),", s); } gencs.Close (); other.Close (); } public static void Main (string [] args) { var tp = new TrivialParser (); tp.Run (args); } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ResourceManager { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; /// <summary> /// PolicyDefinitionsOperations operations. /// </summary> internal partial class PolicyDefinitionsOperations : IServiceOperations<PolicyClient>, IPolicyDefinitionsOperations { /// <summary> /// Initializes a new instance of the PolicyDefinitionsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal PolicyDefinitionsOperations(PolicyClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the PolicyClient /// </summary> public PolicyClient Client { get; private set; } /// <summary> /// Create or update a policy definition. /// </summary> /// <param name='policyDefinitionName'> /// The policy definition name. /// </param> /// <param name='parameters'> /// The policy definition properties. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<PolicyDefinition>> CreateOrUpdateWithHttpMessagesAsync(string policyDefinitionName, PolicyDefinition parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (policyDefinitionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "policyDefinitionName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("policyDefinitionName", policyDefinitionName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}").ToString(); _url = _url.Replace("{policyDefinitionName}", Uri.EscapeDataString(policyDefinitionName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<PolicyDefinition>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<PolicyDefinition>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes the policy definition. /// </summary> /// <param name='policyDefinitionName'> /// The policy definition name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string policyDefinitionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (policyDefinitionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "policyDefinitionName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("policyDefinitionName", policyDefinitionName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}").ToString(); _url = _url.Replace("{policyDefinitionName}", Uri.EscapeDataString(policyDefinitionName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets the policy definition. /// </summary> /// <param name='policyDefinitionName'> /// The policy definition name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<PolicyDefinition>> GetWithHttpMessagesAsync(string policyDefinitionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (policyDefinitionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "policyDefinitionName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("policyDefinitionName", policyDefinitionName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions/{policyDefinitionName}").ToString(); _url = _url.Replace("{policyDefinitionName}", Uri.EscapeDataString(policyDefinitionName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<PolicyDefinition>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<PolicyDefinition>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the policy definitions of a subscription. /// </summary> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IPage<PolicyDefinition>>> ListWithHttpMessagesAsync(ODataQuery<PolicyDefinition> odataQuery = default(ODataQuery<PolicyDefinition>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policydefinitions").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<PolicyDefinition>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<PolicyDefinition>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets all the policy definitions of a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<IPage<PolicyDefinition>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<PolicyDefinition>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<PolicyDefinition>>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Logic { using Azure; using Management; using Rest; using Rest.Azure; using Rest.Azure.OData; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// WorkflowRunActionsOperations operations. /// </summary> internal partial class WorkflowRunActionsOperations : IServiceOperations<LogicManagementClient>, IWorkflowRunActionsOperations { /// <summary> /// Initializes a new instance of the WorkflowRunActionsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal WorkflowRunActionsOperations(LogicManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the LogicManagementClient /// </summary> public LogicManagementClient Client { get; private set; } /// <summary> /// Gets a list of workflow run actions. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='runName'> /// The workflow run name. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<WorkflowRunAction>>> ListWithHttpMessagesAsync(string resourceGroupName, string workflowName, string runName, ODataQuery<WorkflowRunActionFilter> odataQuery = default(ODataQuery<WorkflowRunActionFilter>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (workflowName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "workflowName"); } if (runName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "runName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("workflowName", workflowName); tracingParameters.Add("runName", runName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/workflows/{workflowName}/runs/{runName}/actions").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{workflowName}", System.Uri.EscapeDataString(workflowName)); _url = _url.Replace("{runName}", System.Uri.EscapeDataString(runName)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<WorkflowRunAction>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<WorkflowRunAction>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets a workflow run action. /// </summary> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='runName'> /// The workflow run name. /// </param> /// <param name='actionName'> /// The workflow action name. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<WorkflowRunAction>> GetWithHttpMessagesAsync(string resourceGroupName, string workflowName, string runName, string actionName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (workflowName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "workflowName"); } if (runName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "runName"); } if (actionName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "actionName"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("workflowName", workflowName); tracingParameters.Add("runName", runName); tracingParameters.Add("actionName", actionName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Logic/workflows/{workflowName}/runs/{runName}/actions/{actionName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{workflowName}", System.Uri.EscapeDataString(workflowName)); _url = _url.Replace("{runName}", System.Uri.EscapeDataString(runName)); _url = _url.Replace("{actionName}", System.Uri.EscapeDataString(actionName)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<WorkflowRunAction>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<WorkflowRunAction>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets a list of workflow run actions. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<WorkflowRunAction>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<WorkflowRunAction>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<WorkflowRunAction>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Soap; using System.IO; using System.Collections; using System.Windows.Forms; using System.Drawing; using System.Text; // For ASCIIEncoding using SpiffLib; using ICSharpCode.SharpZipLib.Zip; using System.Collections.Specialized; using System.Text.RegularExpressions; using System.Diagnostics; namespace SpiffCode { /// <summary> /// Summary description for AnimDoc. /// </summary> [Serializable] public class AnimDoc : ISerializable { // Persistable state private int m_nTileSize; private XBitmapSet m_xbms; private StripSet m_stps; private int m_msFrameRate; // private bool m_fDirty = false; private bool m_fHires = false; private string m_strFileName = "untitled.amx"; private Strip m_stpActive; // Public properties public XBitmapSet XBitmapSet { get { return m_xbms; } } public StripSet StripSet { get { return m_stps; } } public bool Hires { get { return m_fHires; } set { m_fHires = value; } } // Exposed for anyone who wants to keep track of this AnimDoc's ActiveStrip public event EventHandler ActiveStripChanged; public Strip ActiveStrip { get { return m_stpActive; } set { m_stpActive = value; if (ActiveStripChanged != null) ActiveStripChanged(this, EventArgs.Empty); } } public bool Dirty { get { return m_fDirty; } set { m_fDirty = value; } } public string FileName { get { return m_strFileName; } set { m_strFileName = value; Dirty = true; } } public int FrameRate { get { return m_msFrameRate; } set { m_msFrameRate = value; } } public int TileSize { get { return m_nTileSize; } set { m_nTileSize = value; Dirty = true; } } // public AnimDoc(int nTileSize, int cmsFrameRate) { m_nTileSize = nTileSize; m_msFrameRate = cmsFrameRate; m_xbms = new XBitmapSet(); m_stps = new StripSet(); m_fDirty = true; } public static AnimDoc Load(string strFileName) { if (!File.Exists(strFileName)) throw new FileNotFoundException("File Not found", strFileName); return Load(strFileName, null); } public static AnimDoc Load(string strFileName, Stream stmZamx) { string strFileNameOrig = strFileName; string strExt = Path.GetExtension(strFileName).ToLower(); bool fZip = strExt == ".zip" || strExt == ".zamx"; string strCurrentDirSav = null; string strTempDir = null; // Remember current dir strCurrentDirSav = Directory.GetCurrentDirectory(); if (fZip) { // Change current dir to temp dir strTempDir = Path.Combine(Path.GetTempPath(), "AniMax_temp_extract_dir"); Directory.CreateDirectory(strTempDir); Directory.SetCurrentDirectory(strTempDir); // Extract the .zip to the temp dir ZipInputStream zipi = new ZipInputStream(stmZamx != null ? stmZamx : File.OpenRead(strFileName)); ZipEntry zipe; while ((zipe = zipi.GetNextEntry()) != null) { string strDir = Path.GetDirectoryName(zipe.Name); if (Path.GetExtension(zipe.Name).ToLower() == ".amx") strFileName = zipe.Name; if (strDir != null && strDir != "") { if (!Directory.Exists(strDir)) Directory.CreateDirectory(strDir); } FileStream stm = File.Create(zipe.Name); byte[] abT = new byte[zipe.Size]; // For some reason due to its implementation, ZipInputStream.Read can return // fewer than the requested number of bytes. Loop until we have them all. while (true) { int cbRead = zipi.Read(abT, 0, abT.Length); if (cbRead <= 0) break; stm.Write(abT, 0, cbRead); } stm.Close(); } zipi.Close(); // Convert filename from, say, c:\ht\data\foo.zip or foo.zamx to foo.amx strFileName = Path.GetFileNameWithoutExtension(strFileName) + ".amx"; } FileStream stmAmx = File.Open(strFileName, FileMode.Open, FileAccess.Read); SoapFormatter spfmt = new SoapFormatter(); spfmt.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple; spfmt.Binder = new RelaxedSerializationBinder(); if (!fZip) { // If .amx being loaded is in a directory other than the current one, // change to it so deserialization will find the contained bitmaps in // their proper place. string strPath = Path.GetDirectoryName(strFileName); if (strPath != null && strPath != "") Directory.SetCurrentDirectory(strPath); } AnimDoc doc = null; try { doc = (AnimDoc)spfmt.Deserialize(stmAmx); } catch (Exception ex) { MessageBox.Show(ex.ToString()); Console.WriteLine(ex); } stmAmx.Close(); // Restore current dir (NOTE: can't delete temp dir until it isn't current) Directory.SetCurrentDirectory(strCurrentDirSav); if (fZip) { // Delete temp extraction dir and its contents Directory.Delete(strTempDir, true); } if (doc == null) return null; doc.m_strFileName = strFileNameOrig; return doc; } public void Save(string strFileName) { string strExt = Path.GetExtension(strFileName).ToLower(); bool fZip = strExt == ".zip" || strExt == ".zamx"; // Update the XBitmaps to have paths relative to the specified file // in a subdirectory named after the file. m_strFileName = strFileName; // Create a sub-directory for all the Bitmaps // UNDONE: clean it out? string strName = Path.GetFileNameWithoutExtension(strFileName); string strBitmapDir = Path.Combine(Path.GetDirectoryName(strFileName), strName); foreach (XBitmap xbm in XBitmapSet) xbm.FileName = Path.Combine(strName, Path.GetFileName(xbm.FileName)); string strAmxFileName = fZip ? strFileName + ".temporary_file" : strFileName; FileStream stm = File.Open(strAmxFileName, FileMode.Create, FileAccess.Write); SoapFormatter spfmt = new SoapFormatter(); // This cuts down on the verbosity of the generated XML file spfmt.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple; spfmt.Serialize(stm, this); stm.Close(); if (fZip) { ZipOutputStream zipo = null; zipo = new ZipOutputStream(File.Create(strFileName)); zipo.SetLevel(9); // maximum compression // Read temporary .amx file stm = File.OpenRead(strAmxFileName); byte[] abT = new byte[stm.Length]; stm.Read(abT, 0, abT.Length); stm.Close(); // Delete temporary .amx file File.Delete(strAmxFileName); // Write .amx file to .zip ZipEntry zipe = new ZipEntry(strName + ".amx"); zipo.PutNextEntry(zipe); zipo.Write(abT, 0, abT.Length); // Write the bitmaps too foreach (XBitmap xbm in m_xbms) { // Write temporary bitmap file xbm.Save(strAmxFileName); // Read temporary bitmap file stm = File.OpenRead(strAmxFileName); abT = new byte[stm.Length]; stm.Read(abT, 0, abT.Length); stm.Close(); // Delete the temporary bitmap file File.Delete(strAmxFileName); // Write bitmap to .zip zipe = new ZipEntry(Path.Combine(strName, Path.GetFileName(xbm.FileName))); zipo.PutNextEntry(zipe); zipo.Write(abT, 0, abT.Length); } zipo.Finish(); zipo.Close(); } else { // Save the Bitmaps too Directory.CreateDirectory(strBitmapDir); foreach (XBitmap xbm in m_xbms) xbm.Save(Path.Combine(strBitmapDir, Path.GetFileName(xbm.FileName))); } m_fDirty = false; } public static bool ParseNameValueString(string str, out string strName, out string strValue) { int ichEquals = str.IndexOf('='); if (ichEquals == -1) { strName = null; strValue = null; return false; } strName = str.Substring(0, ichEquals).Trim(); strValue = str.Substring(ichEquals + 1); return true; } public bool Import(string[] astrFileNames) { // Is this a SideWinder framedata.txt file? if (astrFileNames.Length == 1 && Path.GetFileName(astrFileNames[0]).ToLower() == "framedata.txt") { // Yep, open it up and parse it StreamReader stmr = new StreamReader(astrFileNames[0]); int iLine = 0; string str; do { iLine++; str = stmr.ReadLine(); } while (str == ""); // skip blank lines if (str == null) { MessageBox.Show(null, "Reached the end of the file before it was expected", "Error"); return false; } string strName, strValue; if (!ParseNameValueString(str, out strName, out strValue)) { MessageBox.Show(null, String.Format("Syntax error on line %d: %s", iLine, str), "Error"); return false; } if (strName != "cfrm") { MessageBox.Show(null, "Expected a 'cfrm =' statement but didn't find it", "Error"); return false; } // Find a unique name for this strip int iStrip = 0; while (StripSet["strip" + iStrip] != null) iStrip++; Strip stp = new Strip("strip" + iStrip); StripSet.Add(stp); int cfr = int.Parse(strValue); for (int ifr = 0; ifr < cfr; ifr++) { // 1. Read the bitmap from it and add it to the Document's XBitmapSet XBitmap xbm; string strBitmap = "frame" + ifr + ".bmp"; try { xbm = new XBitmap(strBitmap, true); } catch { MessageBox.Show(null, String.Format("Can't load \"{0}\"", strBitmap), "Error"); return false; } XBitmapSet.Add(xbm); // 2. Create a Frame to go with the Bitmap and add it to the appropriate // Strip. If no strip exists, create one. Frame fr = new Frame(); fr.BitmapPlacers.Add(new BitmapPlacer()); fr.BitmapPlacers[0].XBitmap = xbm; stp[ifr] = fr; bool fDone = false; while (!fDone) { do { iLine++; str = stmr.ReadLine(); } while (str == ""); // skip blank lines if (!ParseNameValueString(str, out strName, out strValue)) { MessageBox.Show(null, String.Format("Syntax error on line %d: %s", iLine, str), "Error"); return false; } switch (strName) { case "flags": Debug.Assert(strValue.Trim() == "0"); break; case "xCenter": fr.BitmapPlacers[0].X = int.Parse(strValue); break; case "yCenter": fr.BitmapPlacers[0].Y = int.Parse(strValue); break; case "xGrab": fr.SpecialPoint = new Point(int.Parse(strValue) - fr.BitmapPlacers[0].X, fr.SpecialPoint.Y); break; case "yGrab": fr.SpecialPoint = new Point(fr.SpecialPoint.X, int.Parse(strValue) - fr.BitmapPlacers[0].Y); break; case "xWidth": Debug.Assert(int.Parse(strValue.Trim()) == xbm.Width); break; case "yHeight": Debug.Assert(int.Parse(strValue.Trim()) == xbm.Height); fDone = true; break; } } } } else { // XBitmap encapsulates special filename rules astrFileNames = XBitmap.FilterFileNames(astrFileNames); // By sorting the filenames we introduce a useful bit of // determinism. Array.Sort(astrFileNames); // Enumerate all the filenames and for each one: foreach (string strFile in astrFileNames) { // 0. Verify the filename fits the pattern we're expecting string[] astr = strFile.Substring(strFile.LastIndexOf('\\') + 1).Split('_', '.'); if (astr.Length != 5) { MessageBox.Show(null, String.Format("File {0} does not match the requisite naming pattern. Skipping and continuing.", strFile), "Error"); continue; } string strAnimDoc = astr[0]; string strStripA = astr[1]; string strStripB = astr[2]; int ifr = Convert.ToInt32(astr[3]); // 1. Read the bitmap from it and add it to the Document's XBitmapSet XBitmap xbm; try { xbm = new XBitmap(strFile); } catch { MessageBox.Show(null, String.Format("Can't load \"{0}\"", strFile), "Error"); return false; } XBitmapSet.Add(xbm); // 2. Create a Frame to go with the Bitmap and add it to the appropriate // Strip. If no strip exists, create one. Frame fr = new Frame(); fr.BitmapPlacers.Add(new BitmapPlacer()); fr.BitmapPlacers[0].XBitmap = xbm; fr.BitmapPlacers[0].X = xbm.Width / 2; fr.BitmapPlacers[0].Y = xbm.Height / 2; string strStripName = strStripA + " " + strStripB; Strip stp = StripSet[strStripName]; if (stp == null) { stp = new Strip(strStripName); StripSet.Add(stp); } stp[ifr] = fr; } } Dirty = true; return true; } public bool WriteAnir(Palette pal, string strExportPath, string strAnimName) { Color clrTransparent = Color.FromArgb(0xff, 0, 0xff); SolidBrush brTransparent = new SolidBrush(clrTransparent); ASCIIEncoding enc = new ASCIIEncoding(); FileStream stm = new FileStream(strExportPath + Path.DirectorySeparatorChar + strAnimName + ".anir", FileMode.Create, FileAccess.Write); BinaryWriter stmw = new BinaryWriter(stm); // Count the number of Strips ushort cstpd = (ushort)StripSet.Count; // Write AnimationFileHeader.cstpd stmw.Write(Misc.SwapUShort(cstpd)); // Write array of offsets to StripDatas (AnimationFileHeader.aoffStpd) ushort offStpd = (ushort)(2 + (2 * cstpd)); ArrayList albm = new ArrayList(); foreach (Strip stp in StripSet) { stmw.Write(Misc.SwapUShort(offStpd)); // Advance offset to where the next StripData will be offStpd += (ushort)((26+1+1+2) /* sizeof(StripData) - sizeof(FrameData) */ + ((1+1+1+1+1+1+1+1+1) /* sizeof(FrameData) */ * stp.Count)); // Force word alignment of StripDatas if ((offStpd & 1) == 1) offStpd++; } // Write array of StripDatas foreach (Strip stp in StripSet) { // Write StripData.Name byte[] abT = new byte[26]; enc.GetBytes(stp.Name, 0, Math.Min(stp.Name.Length, 25), abT, 0); abT[25] = 0; stmw.Write(abT); // Write StripData.cHold stmw.Write((byte)stp.DefHoldCount); // Write StripData.bfFlags stmw.Write((byte)0); // Write StripData.cfrmd ushort cfrmd = (ushort)stp.Count; stmw.Write(Misc.SwapUShort(cfrmd)); // Write array of FrameDatas foreach (Frame fr in stp) { // Add the Frame's Bitmap for output int ibm = -1; Bitmap bm; if (fr.BitmapPlacers.Count > 0) { bm = fr.BitmapPlacers[0].XBitmap.Bitmap; ibm = albm.IndexOf(bm); if (ibm == -1) ibm = albm.Add(bm); } // Write FrameData.ibm (the index of the Bitmap as it will be in the Bitmap array) stmw.Write((byte)ibm); ibm = -1; if (fr.BitmapPlacers.Count > 1) { // Add the Frame's Bitmap for output bm = fr.BitmapPlacers[1].XBitmap.Bitmap; ibm = albm.IndexOf(bm); if (ibm == -1) ibm = albm.Add(bm); } // Write FrameData.ibm2 (the index of the Bitmap as it will be in the Bitmap array) stmw.Write((byte)ibm); // Write FrameData.cHold stmw.Write((byte)fr.HoldCount); // Write FrameData.xOrigin, FrameData.yOrigin if (fr.BitmapPlacers.Count > 0) { stmw.Write((byte)fr.BitmapPlacers[0].X); stmw.Write((byte)fr.BitmapPlacers[0].Y); } else { stmw.Write((byte)0); stmw.Write((byte)0); } if (fr.BitmapPlacers.Count > 1) { stmw.Write((byte)fr.BitmapPlacers[1].X); stmw.Write((byte)fr.BitmapPlacers[1].Y); } else { stmw.Write((byte)0); stmw.Write((byte)0); } // Write FrameData.bCustomData1, FrameData.bCustomData2 stmw.Write((byte)fr.SpecialPoint.X); stmw.Write((byte)fr.SpecialPoint.Y); #if false // Write FrameData.bCustomData3 stmw.Write((byte)0); #endif } // Force word alignment of StripDatas given that FrameDatas are an odd // number of bytes long and there may be an odd number of frames. if ((cfrmd & 1) == 1) stmw.Write((byte)0); } stmw.Close(); // Write out .tbm if (albm.Count != 0) { string strFileName = strExportPath + Path.DirectorySeparatorChar + strAnimName + ".tbm"; // if (gfSuperVerbose) // Console.WriteLine("Crunching and writing " + strFileName); TBitmap.Save((Bitmap[])albm.ToArray(typeof(Bitmap)), pal, strFileName); } return true; } // ISerializable interface implementation private AnimDoc(SerializationInfo seri, StreamingContext stmc) { m_xbms = (XBitmapSet)seri.GetValue("Bitmaps", typeof(XBitmapSet)); m_stps = (StripSet)seri.GetValue("Strips", typeof(StripSet)); m_msFrameRate = seri.GetInt32("FrameRate"); try { bool fHires = seri.GetBoolean("Hires"); if (fHires) { m_nTileSize = 24; } else { m_nTileSize = 16; } } catch { m_nTileSize = -1; } if (m_nTileSize == -1) { m_nTileSize = seri.GetInt32("TileSize"); } } void ISerializable.GetObjectData(SerializationInfo seri, StreamingContext stmc) { seri.AddValue("Bitmaps", m_xbms); seri.AddValue("Strips", m_stps); seri.AddValue("FrameRate", m_msFrameRate); seri.AddValue("TileSize", m_nTileSize); } } // This class is implemented to allow one Assembly read a .amx file written by a // different Assembly -- what a concept! public class RelaxedSerializationBinder : SerializationBinder { public override Type BindToType(string strAssemblyName, string strTypeName) { return Type.GetType(strTypeName); } } }
// Copyright (c) 2015 hugula // direct https://github.com/tenvick/hugula // using UnityEngine; using System.Collections.Generic; using System.IO; [SLua.CustomLuaClass] public class CUtils { /// <summary> /// Gets the Suffix of the URL file. /// </summary> /// <returns> /// The URL file type. /// </returns> /// <param name='url'> /// url. /// </param> public static string GetURLFileSuffix(string url) { if (string.IsNullOrEmpty (url)) return string.Empty; int last=url.LastIndexOf("."); int end=url.IndexOf("?"); if(end==-1) end=url.Length; else { last=url.IndexOf(".",0,end); } // Debug.Log(string.Format("last={0},end={1}",last,end)); string cut=url.Substring(last,end-last).Replace(".",""); return cut; } /// <summary> /// Gets the name of the URL file. /// </summary> /// <returns> /// The URL file name. /// </returns> /// <param name='url'> /// URL. /// </param> public static string GetURLFileName(string url) { if (string.IsNullOrEmpty (url)) return string.Empty; string re = ""; int len = url.Length - 1; char[] arr=url.ToCharArray(); while (len >= 0 && arr[len] != '/' && arr[len] != '\\') len = len - 1; //int sub = (url.Length - 1) - len; //int end=url.Length-sub; re = url.Substring(len+1); int last=re.LastIndexOf("."); if (last == -1) last = re.Length; string cut=re.Substring(0,last); return cut; } /// <summary> /// /// </summary> /// <param name="url"></param> /// <returns></returns> public static string GetKeyURLFileName(string url) { //Debug.Log(url); if (string.IsNullOrEmpty (url)) return string.Empty; string re = ""; int len = url.Length - 1; char[] arr = url.ToCharArray(); while (len >= 0 && arr[len] != '/' && arr[len] != '\\') len = len - 1; //int sub = (url.Length - 1) - len; //int end=url.Length-sub; re = url.Substring(len + 1); int last = re.LastIndexOf("."); if (last == -1) last = re.Length; string cut = re.Substring(0, last); cut = cut.Replace('.', '_'); return cut; } public static string GetURLFullFileName(string url) { if (string.IsNullOrEmpty (url)) return string.Empty; string re = ""; int len = url.Length - 1; char[] arr=url.ToCharArray(); while (len >= 0 && arr[len] != '/' && arr[len] != '\\') len = len - 1; re = url.Substring(len+1); return re; } /// <summary> /// Gets the file full path for www /// form Application.dataPath /// </summary> /// <returns> /// The file full path. /// </returns> /// <param name='absolutePath'> /// Absolute path. /// </param> public static string GetFileFullPath(string absolutePath) { string path=""; path=Application.persistentDataPath+"/"+absolutePath; currPersistentExist=File.Exists(path); if(!currPersistentExist) path=Application.streamingAssetsPath+"/"+absolutePath; if (path.IndexOf("://")==-1) { path="file://"+path; } return path; } /// <summary> /// get assetBunld full path /// </summary> /// <param name="assetPath"></param> /// <returns></returns> public static string GetAssetFullPath(string assetPath) { string path = GetFileFullPath(GetAssetPath(assetPath)); return path; } /// <summary> /// Gets the file full path. /// </summary> /// <returns> /// The file full path. /// </returns> /// <param name='absolutePath'> /// Absolute path. /// </param> public static string GetFileFullPathNoProtocol(string absolutePath) { string path=Application.persistentDataPath+"/"+absolutePath; currPersistentExist=File.Exists(path); if(!currPersistentExist) path=Application.streamingAssetsPath+"/"+absolutePath; return path; } public static string GetDirectoryFullPathNoProtocol(string absolutePath) { string path=Application.persistentDataPath+"/"+absolutePath; currPersistentExist=Directory.Exists(path); if(!currPersistentExist) path=Application.streamingAssetsPath+"/"+absolutePath; return path; } public static string dataPath { get{ #if UNITY_EDITOR return Application.streamingAssetsPath; #else return Application.persistentDataPath; #endif } } public static string GetAssetPath(string name) { string Platform=""; #if UNITY_IOS Platform="iOS"; #elif UNITY_ANDROID Platform ="Android"; #elif UNITY_WEBPLAYER Platform ="WebPlayer"; #elif UNITY_WP8 Platform="WP8Player"; #elif UNITY_METRO Platform = "MetroPlayer"; #elif UNITY_OSX || UNITY_STANDALONE_OSX Platform = "StandaloneOSXIntel"; #else Platform = "StandaloneWindows"; #endif string path = Path.Combine(Platform, name); //System.String.Format("{0}/{1}", Platform, name); return path; } public static string GetPlatformFolderForAssetBundles() { #if UNITY_IOS return "iOS"; #elif UNITY_ANDROID return "Android"; #elif UNITY_WEBPLAYER return "WebPlayer"; #elif UNITY_WP8 return "WP8Player"; #elif UNITY_METRO return "MetroPlayer"; #elif UNITY_OSX return "OSX"; #elif UNITY_STANDALONE_OSX return "StandaloneOSXIntel"; #else return "Windows"; #endif } public static bool currPersistentExist=false; public static void Collect() { System.GC.Collect(); } /// <summary> /// /// </summary> /// <param name="list"></param> static public void Execute(IList<System.Action> list) { if (list != null) { for (int i = 0; i < list.Count; ) { System.Action del = list[i]; if (del != null) { del(); if (i >= list.Count) break; if (list[i] != del) continue; } ++i; } } } /// <summary> /// /// </summary> /// <param name="list"></param> static public void Execute(BetterList<System.Action> list) { if (list != null) { for (int i = 0; i < list.size; ) { System.Action del = list[i]; if (del != null) { del(); if (i >= list.size) break; if (list[i] != del) continue; } ++i; } } } }
using System; using System.Linq; using Signum.Utilities; using Signum.Entities.UserAssets; using Signum.Entities.Chart; using System.Reflection; using System.Xml.Linq; using Signum.Utilities.DataStructures; using Signum.Entities.UserQueries; using Signum.Entities; using System.Linq.Expressions; namespace Signum.Entities.Dashboard { [Serializable] public class PanelPartEmbedded : EmbeddedEntity, IGridEntity { [StringLengthValidator(Min = 3, Max = 100)] public string? Title { get; set; } [StringLengthValidator(Min = 3, Max = 100)] public string? IconName { get; set; } [StringLengthValidator(Min = 3, Max = 100)] public string? IconColor { get; set; } [NumberIsValidator(ComparisonType.GreaterThanOrEqualTo, 0)] public int Row { get; set; } [NumberBetweenValidator(0, 11)] public int StartColumn { get; set; } [NumberBetweenValidator(1, 12)] public int Columns { get; set; } public PanelStyle Style { get; set; } [ImplementedBy( typeof(UserChartPartEntity), typeof(UserQueryPartEntity), typeof(ValueUserQueryListPartEntity), typeof(LinkListPartEntity))] public IPartEntity Content { get; set; } public override string ToString() { return Title.HasText() ? Title : Content==null?"": Content.ToString()!; } protected override string? PropertyValidation(PropertyInfo pi) { if (pi.Name == nameof(Title) && string.IsNullOrEmpty(Title)) { if (Content != null && Content.RequiresTitle) return DashboardMessage.DashboardDN_TitleMustBeSpecifiedFor0.NiceToString().FormatWith(Content.GetType().NicePluralName()); } return base.PropertyValidation(pi); } public PanelPartEmbedded Clone() { return new PanelPartEmbedded { Columns = Columns, StartColumn = StartColumn, Content = Content.Clone(), Title = Title, Row = Row, Style = Style, }; } internal void NotifyRowColumn() { Notify(() => StartColumn); Notify(() => Columns); } internal XElement ToXml(IToXmlContext ctx) { return new XElement("Part", new XAttribute("Row", Row), new XAttribute("StartColumn", StartColumn), new XAttribute("Columns", Columns), Title == null ? null : new XAttribute("Title", Title), IconName == null ? null : new XAttribute("IconName", IconName), IconColor == null ? null : new XAttribute("IconColor", IconColor), new XAttribute("Style", Style), Content.ToXml(ctx)); } internal void FromXml(XElement x, IFromXmlContext ctx) { Row = int.Parse(x.Attribute("Row").Value); StartColumn = int.Parse(x.Attribute("StartColumn").Value); Columns = int.Parse(x.Attribute("Columns").Value); Title = x.Attribute("Title")?.Value; IconName = x.Attribute("IconName")?.Value; IconColor = x.Attribute("IconColor")?.Value; Style = (PanelStyle)(x.Attribute("Style")?.Let(a => Enum.Parse(typeof(PanelStyle), a.Value)) ?? PanelStyle.Light); Content = ctx.GetPart(Content, x.Elements().Single()); } internal Interval<int> ColumnInterval() { return new Interval<int>(this.StartColumn, this.StartColumn + this.Columns); } } public enum PanelStyle { Light, Dark, Primary, Secondary, Success, Info, Warning, Danger, } public interface IGridEntity { int Row { get; set; } int StartColumn { get; set; } int Columns { get; set; } } public interface IPartEntity : IEntity { bool RequiresTitle { get; } IPartEntity Clone(); XElement ToXml(IToXmlContext ctx); void FromXml(XElement element, IFromXmlContext ctx); } [Serializable, EntityKind(EntityKind.Part, EntityData.Master)] public class UserQueryPartEntity : Entity, IPartEntity { public UserQueryEntity UserQuery { get; set; } public UserQueryPartRenderMode RenderMode { get; set; } public bool AllowSelection { get; set; } public bool ShowFooter { get; set; } public bool CreateNew { get; set; } = false; [AutoExpressionField] public override string ToString() => As.Expression(() => UserQuery + ""); public bool RequiresTitle { get { return false; } } public IPartEntity Clone() { return new UserQueryPartEntity { UserQuery = this.UserQuery, RenderMode = this.RenderMode, AllowSelection = this.AllowSelection, ShowFooter = this.ShowFooter, CreateNew = this.CreateNew, }; } public XElement ToXml(IToXmlContext ctx) { return new XElement("UserQueryPart", new XAttribute("UserQuery", ctx.Include(UserQuery)), new XAttribute("RenderMode", RenderMode.ToString()), new XAttribute("AllowSelection", AllowSelection.ToString()), new XAttribute("ShowFooter", ShowFooter.ToString()), new XAttribute("CreateNew", CreateNew.ToString()) ); } public void FromXml(XElement element, IFromXmlContext ctx) { UserQuery = (UserQueryEntity)ctx.GetEntity(Guid.Parse(element.Attribute("UserQuery").Value)); RenderMode = element.Attribute("RenderMode")?.Value.ToEnum<UserQueryPartRenderMode>() ?? UserQueryPartRenderMode.SearchControl; AllowSelection = element.Attribute("AllowSelection")?.Value.ToBool() ?? true; ShowFooter = element.Attribute("ShowFooter")?.Value.ToBool() ?? false; CreateNew = element.Attribute("CreateNew")?.Value.ToBool() ?? false; } } public enum UserQueryPartRenderMode { SearchControl, BigValue, } [Serializable, EntityKind(EntityKind.Part, EntityData.Master)] public class UserTreePartEntity : Entity, IPartEntity { public UserQueryEntity UserQuery { get; set; } [AutoExpressionField] public override string ToString() => As.Expression(() => UserQuery + ""); public bool RequiresTitle { get { return false; } } public IPartEntity Clone() { return new UserTreePartEntity { UserQuery = this.UserQuery, }; } public XElement ToXml(IToXmlContext ctx) { return new XElement("UserTreePart", new XAttribute("UserQuery", ctx.Include(UserQuery)) ); } public void FromXml(XElement element, IFromXmlContext ctx) { UserQuery = (UserQueryEntity)ctx.GetEntity(Guid.Parse(element.Attribute("UserQuery").Value)); } } [Serializable, EntityKind(EntityKind.Part, EntityData.Master)] public class UserChartPartEntity : Entity, IPartEntity { public UserChartEntity UserChart { get; set; } public bool ShowData { get; set; } = false; public bool AllowChangeShowData { get; set; } = false; public bool CreateNew { get; set; } = false; [AutoExpressionField] public override string ToString() => As.Expression(() => UserChart + ""); public bool RequiresTitle { get { return false; } } public IPartEntity Clone() { return new UserChartPartEntity { UserChart = this.UserChart, ShowData = this.ShowData, AllowChangeShowData = this.AllowChangeShowData, }; } public XElement ToXml(IToXmlContext ctx) { return new XElement("UserChartPart", new XAttribute("ShowData", ShowData), new XAttribute("AllowChangeShowData", AllowChangeShowData), CreateNew ? new XAttribute("CreateNew", CreateNew) : null, new XAttribute("UserChart", ctx.Include(UserChart))); } public void FromXml(XElement element, IFromXmlContext ctx) { ShowData = element.Attribute("ShowData")?.Value.ToBool() ?? false; AllowChangeShowData = element.Attribute("AllowChangeShowData")?.Value.ToBool() ?? false; CreateNew = element.Attribute("CreateNew")?.Value.ToBool() ?? false; UserChart = (UserChartEntity)ctx.GetEntity(Guid.Parse(element.Attribute("UserChart").Value)); } } [Serializable, EntityKind(EntityKind.Part, EntityData.Master)] public class ValueUserQueryListPartEntity : Entity, IPartEntity { public MList<ValueUserQueryElementEmbedded> UserQueries { get; set; } = new MList<ValueUserQueryElementEmbedded>(); public override string ToString() { return "{0} {1}".FormatWith(UserQueries.Count, typeof(UserQueryEntity).NicePluralName()); } public bool RequiresTitle { get { return true; } } public IPartEntity Clone() { return new ValueUserQueryListPartEntity { UserQueries = this.UserQueries.Select(e => e.Clone()).ToMList(), }; } public XElement ToXml(IToXmlContext ctx) { return new XElement("ValueUserQueryListPart", UserQueries.Select(cuqe => cuqe.ToXml(ctx))); } public void FromXml(XElement element, IFromXmlContext ctx) { UserQueries.Synchronize(element.Elements().ToList(), (cuqe, x) => cuqe.FromXml(x, ctx)); } } [Serializable] public class ValueUserQueryElementEmbedded : EmbeddedEntity { [StringLengthValidator(Max = 200)] public string? Label { get; set; } public UserQueryEntity UserQuery { get; set; } [StringLengthValidator(Max = 200)] public string? Href { get; set; } public ValueUserQueryElementEmbedded Clone() { return new ValueUserQueryElementEmbedded { Href = this.Href, Label = this.Label, UserQuery = UserQuery, }; } internal XElement ToXml(IToXmlContext ctx) { return new XElement("ValueUserQueryElement", Label == null ? null : new XAttribute("Label", Label), Href == null ? null : new XAttribute("Href", Href), new XAttribute("UserQuery", ctx.Include(UserQuery))); } internal void FromXml(XElement element, IFromXmlContext ctx) { Label = element.Attribute("Label")?.Value; Href = element.Attribute("Href")?.Value; UserQuery = (UserQueryEntity)ctx.GetEntity(Guid.Parse(element.Attribute("UserQuery").Value)); } } [Serializable, EntityKind(EntityKind.Part, EntityData.Master)] public class LinkListPartEntity : Entity, IPartEntity { public MList<LinkElementEmbedded> Links { get; set; } = new MList<LinkElementEmbedded>(); public override string ToString() { return "{0} {1}".FormatWith(Links.Count, typeof(LinkElementEmbedded).NicePluralName()); } public bool RequiresTitle { get { return true; } } public IPartEntity Clone() { return new LinkListPartEntity { Links = this.Links.Select(e => e.Clone()).ToMList(), }; } public XElement ToXml(IToXmlContext ctx) { return new XElement("LinkListPart", Links.Select(lin => lin.ToXml(ctx))); } public void FromXml(XElement element, IFromXmlContext ctx) { Links.Synchronize(element.Elements().ToList(), (le, x) => le.FromXml(x)); } } [Serializable] public class LinkElementEmbedded : EmbeddedEntity { [StringLengthValidator(Max = 200)] public string Label { get; set; } [URLValidator(absolute: true, aspNetSiteRelative: true), StringLengthValidator(Max = int.MaxValue)] public string Link { get; set; } public LinkElementEmbedded Clone() { return new LinkElementEmbedded { Label = this.Label, Link = this.Link }; } internal XElement ToXml(IToXmlContext ctx) { return new XElement("LinkElement", new XAttribute("Label", Label), new XAttribute("Link", Link)); } internal void FromXml(XElement element) { Label = element.Attribute("Label").Value; Link = element.Attribute("Link").Value; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using System; class r4NaNmul { //user-defined class that overloads operator * public class numHolder { float f_num; public numHolder(float f_num) { this.f_num = Convert.ToSingle(f_num); } public static float operator *(numHolder a, float b) { return a.f_num * b; } public static float operator *(numHolder a, numHolder b) { return a.f_num * b.f_num; } } static float f_s_test1_op1 = Single.PositiveInfinity; static float f_s_test1_op2 = 0; static float f_s_test2_op1 = Single.NegativeInfinity; static float f_s_test2_op2 = 0; static float f_s_test3_op1 = 3; static float f_s_test3_op2 = Single.NaN; public static float f_test1_f(String s) { if (s == "test1_op1") return Single.PositiveInfinity; else return 0; } public static float f_test2_f(String s) { if (s == "test2_op1") return Single.NegativeInfinity; else return 0; } public static float f_test3_f(String s) { if (s == "test3_op1") return 3; else return Single.NaN; } class CL { public float f_cl_test1_op1 = Single.PositiveInfinity; public float f_cl_test1_op2 = 0; public float f_cl_test2_op1 = Single.NegativeInfinity; public float f_cl_test2_op2 = 0; public float f_cl_test3_op1 = 3; public float f_cl_test3_op2 = Single.NaN; } struct VT { public float f_vt_test1_op1; public float f_vt_test1_op2; public float f_vt_test2_op1; public float f_vt_test2_op2; public float f_vt_test3_op1; public float f_vt_test3_op2; } public static int Main() { bool passed = true; //initialize class CL cl1 = new CL(); //initialize struct VT vt1; vt1.f_vt_test1_op1 = Single.PositiveInfinity; vt1.f_vt_test1_op2 = 0; vt1.f_vt_test2_op1 = Single.NegativeInfinity; vt1.f_vt_test2_op2 = 0; vt1.f_vt_test3_op1 = 3; vt1.f_vt_test3_op2 = Single.NaN; float[] f_arr1d_test1_op1 = { 0, Single.PositiveInfinity }; float[,] f_arr2d_test1_op1 = { { 0, Single.PositiveInfinity }, { 1, 1 } }; float[, ,] f_arr3d_test1_op1 = { { { 0, Single.PositiveInfinity }, { 1, 1 } } }; float[] f_arr1d_test1_op2 = { 0, 0, 1 }; float[,] f_arr2d_test1_op2 = { { 0, 0 }, { 1, 1 } }; float[, ,] f_arr3d_test1_op2 = { { { 0, 0 }, { 1, 1 } } }; float[] f_arr1d_test2_op1 = { 0, Single.NegativeInfinity }; float[,] f_arr2d_test2_op1 = { { 0, Single.NegativeInfinity }, { 1, 1 } }; float[, ,] f_arr3d_test2_op1 = { { { 0, Single.NegativeInfinity }, { 1, 1 } } }; float[] f_arr1d_test2_op2 = { 0, 0, 1 }; float[,] f_arr2d_test2_op2 = { { 0, 0 }, { 1, 1 } }; float[, ,] f_arr3d_test2_op2 = { { { 0, 0 }, { 1, 1 } } }; float[] f_arr1d_test3_op1 = { 0, 3 }; float[,] f_arr2d_test3_op1 = { { 0, 3 }, { 1, 1 } }; float[, ,] f_arr3d_test3_op1 = { { { 0, 3 }, { 1, 1 } } }; float[] f_arr1d_test3_op2 = { Single.NaN, 0, 1 }; float[,] f_arr2d_test3_op2 = { { 0, Single.NaN }, { 1, 1 } }; float[, ,] f_arr3d_test3_op2 = { { { 0, Single.NaN }, { 1, 1 } } }; int[,] index = { { 0, 0 }, { 1, 1 } }; { float f_l_test1_op1 = Single.PositiveInfinity; float f_l_test1_op2 = 0; if (!Single.IsNaN(f_l_test1_op1 * f_l_test1_op2)) { Console.WriteLine("Test1_testcase 1 failed"); passed = false; } if (!Single.IsNaN(f_l_test1_op1 * f_s_test1_op2)) { Console.WriteLine("Test1_testcase 2 failed"); passed = false; } if (!Single.IsNaN(f_l_test1_op1 * f_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 3 failed"); passed = false; } if (!Single.IsNaN(f_l_test1_op1 * cl1.f_cl_test1_op2)) { Console.WriteLine("Test1_testcase 4 failed"); passed = false; } if (!Single.IsNaN(f_l_test1_op1 * vt1.f_vt_test1_op2)) { Console.WriteLine("Test1_testcase 5 failed"); passed = false; } if (!Single.IsNaN(f_l_test1_op1 * f_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 6 failed"); passed = false; } if (!Single.IsNaN(f_l_test1_op1 * f_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 7 failed"); passed = false; } if (!Single.IsNaN(f_l_test1_op1 * f_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 8 failed"); passed = false; } if (!Single.IsNaN(f_s_test1_op1 * f_l_test1_op2)) { Console.WriteLine("Test1_testcase 9 failed"); passed = false; } if (!Single.IsNaN(f_s_test1_op1 * f_s_test1_op2)) { Console.WriteLine("Test1_testcase 10 failed"); passed = false; } if (!Single.IsNaN(f_s_test1_op1 * f_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 11 failed"); passed = false; } if (!Single.IsNaN(f_s_test1_op1 * cl1.f_cl_test1_op2)) { Console.WriteLine("Test1_testcase 12 failed"); passed = false; } if (!Single.IsNaN(f_s_test1_op1 * vt1.f_vt_test1_op2)) { Console.WriteLine("Test1_testcase 13 failed"); passed = false; } if (!Single.IsNaN(f_s_test1_op1 * f_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 14 failed"); passed = false; } if (!Single.IsNaN(f_s_test1_op1 * f_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 15 failed"); passed = false; } if (!Single.IsNaN(f_s_test1_op1 * f_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 16 failed"); passed = false; } if (!Single.IsNaN(f_test1_f("test1_op1") * f_l_test1_op2)) { Console.WriteLine("Test1_testcase 17 failed"); passed = false; } if (!Single.IsNaN(f_test1_f("test1_op1") * f_s_test1_op2)) { Console.WriteLine("Test1_testcase 18 failed"); passed = false; } if (!Single.IsNaN(f_test1_f("test1_op1") * f_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 19 failed"); passed = false; } if (!Single.IsNaN(f_test1_f("test1_op1") * cl1.f_cl_test1_op2)) { Console.WriteLine("Test1_testcase 20 failed"); passed = false; } if (!Single.IsNaN(f_test1_f("test1_op1") * vt1.f_vt_test1_op2)) { Console.WriteLine("Test1_testcase 21 failed"); passed = false; } if (!Single.IsNaN(f_test1_f("test1_op1") * f_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 22 failed"); passed = false; } if (!Single.IsNaN(f_test1_f("test1_op1") * f_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 23 failed"); passed = false; } if (!Single.IsNaN(f_test1_f("test1_op1") * f_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 24 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test1_op1 * f_l_test1_op2)) { Console.WriteLine("Test1_testcase 25 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test1_op1 * f_s_test1_op2)) { Console.WriteLine("Test1_testcase 26 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test1_op1 * f_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 27 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test1_op1 * cl1.f_cl_test1_op2)) { Console.WriteLine("Test1_testcase 28 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test1_op1 * vt1.f_vt_test1_op2)) { Console.WriteLine("Test1_testcase 29 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test1_op1 * f_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 30 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test1_op1 * f_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 31 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test1_op1 * f_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 32 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test1_op1 * f_l_test1_op2)) { Console.WriteLine("Test1_testcase 33 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test1_op1 * f_s_test1_op2)) { Console.WriteLine("Test1_testcase 34 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test1_op1 * f_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 35 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test1_op1 * cl1.f_cl_test1_op2)) { Console.WriteLine("Test1_testcase 36 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test1_op1 * vt1.f_vt_test1_op2)) { Console.WriteLine("Test1_testcase 37 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test1_op1 * f_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 38 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test1_op1 * f_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 39 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test1_op1 * f_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 40 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test1_op1[1] * f_l_test1_op2)) { Console.WriteLine("Test1_testcase 41 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test1_op1[1] * f_s_test1_op2)) { Console.WriteLine("Test1_testcase 42 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test1_op1[1] * f_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 43 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test1_op1[1] * cl1.f_cl_test1_op2)) { Console.WriteLine("Test1_testcase 44 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test1_op1[1] * vt1.f_vt_test1_op2)) { Console.WriteLine("Test1_testcase 45 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test1_op1[1] * f_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 46 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test1_op1[1] * f_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 47 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test1_op1[1] * f_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 48 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test1_op1[index[0, 1], index[1, 0]] * f_l_test1_op2)) { Console.WriteLine("Test1_testcase 49 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test1_op1[index[0, 1], index[1, 0]] * f_s_test1_op2)) { Console.WriteLine("Test1_testcase 50 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test1_op1[index[0, 1], index[1, 0]] * f_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 51 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test1_op1[index[0, 1], index[1, 0]] * cl1.f_cl_test1_op2)) { Console.WriteLine("Test1_testcase 52 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test1_op1[index[0, 1], index[1, 0]] * vt1.f_vt_test1_op2)) { Console.WriteLine("Test1_testcase 53 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test1_op1[index[0, 1], index[1, 0]] * f_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 54 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test1_op1[index[0, 1], index[1, 0]] * f_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 55 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test1_op1[index[0, 1], index[1, 0]] * f_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 56 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] * f_l_test1_op2)) { Console.WriteLine("Test1_testcase 57 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] * f_s_test1_op2)) { Console.WriteLine("Test1_testcase 58 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] * f_test1_f("test1_op2"))) { Console.WriteLine("Test1_testcase 59 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] * cl1.f_cl_test1_op2)) { Console.WriteLine("Test1_testcase 60 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] * vt1.f_vt_test1_op2)) { Console.WriteLine("Test1_testcase 61 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] * f_arr1d_test1_op2[0])) { Console.WriteLine("Test1_testcase 62 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] * f_arr2d_test1_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test1_testcase 63 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test1_op1[index[0, 0], 0, index[1, 1]] * f_arr3d_test1_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test1_testcase 64 failed"); passed = false; } } { float f_l_test2_op1 = Single.NegativeInfinity; float f_l_test2_op2 = 0; if (!Single.IsNaN(f_l_test2_op1 * f_l_test2_op2)) { Console.WriteLine("Test2_testcase 1 failed"); passed = false; } if (!Single.IsNaN(f_l_test2_op1 * f_s_test2_op2)) { Console.WriteLine("Test2_testcase 2 failed"); passed = false; } if (!Single.IsNaN(f_l_test2_op1 * f_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 3 failed"); passed = false; } if (!Single.IsNaN(f_l_test2_op1 * cl1.f_cl_test2_op2)) { Console.WriteLine("Test2_testcase 4 failed"); passed = false; } if (!Single.IsNaN(f_l_test2_op1 * vt1.f_vt_test2_op2)) { Console.WriteLine("Test2_testcase 5 failed"); passed = false; } if (!Single.IsNaN(f_l_test2_op1 * f_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 6 failed"); passed = false; } if (!Single.IsNaN(f_l_test2_op1 * f_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 7 failed"); passed = false; } if (!Single.IsNaN(f_l_test2_op1 * f_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 8 failed"); passed = false; } if (!Single.IsNaN(f_s_test2_op1 * f_l_test2_op2)) { Console.WriteLine("Test2_testcase 9 failed"); passed = false; } if (!Single.IsNaN(f_s_test2_op1 * f_s_test2_op2)) { Console.WriteLine("Test2_testcase 10 failed"); passed = false; } if (!Single.IsNaN(f_s_test2_op1 * f_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 11 failed"); passed = false; } if (!Single.IsNaN(f_s_test2_op1 * cl1.f_cl_test2_op2)) { Console.WriteLine("Test2_testcase 12 failed"); passed = false; } if (!Single.IsNaN(f_s_test2_op1 * vt1.f_vt_test2_op2)) { Console.WriteLine("Test2_testcase 13 failed"); passed = false; } if (!Single.IsNaN(f_s_test2_op1 * f_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 14 failed"); passed = false; } if (!Single.IsNaN(f_s_test2_op1 * f_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 15 failed"); passed = false; } if (!Single.IsNaN(f_s_test2_op1 * f_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 16 failed"); passed = false; } if (!Single.IsNaN(f_test2_f("test2_op1") * f_l_test2_op2)) { Console.WriteLine("Test2_testcase 17 failed"); passed = false; } if (!Single.IsNaN(f_test2_f("test2_op1") * f_s_test2_op2)) { Console.WriteLine("Test2_testcase 18 failed"); passed = false; } if (!Single.IsNaN(f_test2_f("test2_op1") * f_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 19 failed"); passed = false; } if (!Single.IsNaN(f_test2_f("test2_op1") * cl1.f_cl_test2_op2)) { Console.WriteLine("Test2_testcase 20 failed"); passed = false; } if (!Single.IsNaN(f_test2_f("test2_op1") * vt1.f_vt_test2_op2)) { Console.WriteLine("Test2_testcase 21 failed"); passed = false; } if (!Single.IsNaN(f_test2_f("test2_op1") * f_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 22 failed"); passed = false; } if (!Single.IsNaN(f_test2_f("test2_op1") * f_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 23 failed"); passed = false; } if (!Single.IsNaN(f_test2_f("test2_op1") * f_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 24 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test2_op1 * f_l_test2_op2)) { Console.WriteLine("Test2_testcase 25 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test2_op1 * f_s_test2_op2)) { Console.WriteLine("Test2_testcase 26 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test2_op1 * f_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 27 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test2_op1 * cl1.f_cl_test2_op2)) { Console.WriteLine("Test2_testcase 28 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test2_op1 * vt1.f_vt_test2_op2)) { Console.WriteLine("Test2_testcase 29 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test2_op1 * f_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 30 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test2_op1 * f_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 31 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test2_op1 * f_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 32 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test2_op1 * f_l_test2_op2)) { Console.WriteLine("Test2_testcase 33 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test2_op1 * f_s_test2_op2)) { Console.WriteLine("Test2_testcase 34 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test2_op1 * f_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 35 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test2_op1 * cl1.f_cl_test2_op2)) { Console.WriteLine("Test2_testcase 36 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test2_op1 * vt1.f_vt_test2_op2)) { Console.WriteLine("Test2_testcase 37 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test2_op1 * f_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 38 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test2_op1 * f_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 39 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test2_op1 * f_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 40 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test2_op1[1] * f_l_test2_op2)) { Console.WriteLine("Test2_testcase 41 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test2_op1[1] * f_s_test2_op2)) { Console.WriteLine("Test2_testcase 42 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test2_op1[1] * f_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 43 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test2_op1[1] * cl1.f_cl_test2_op2)) { Console.WriteLine("Test2_testcase 44 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test2_op1[1] * vt1.f_vt_test2_op2)) { Console.WriteLine("Test2_testcase 45 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test2_op1[1] * f_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 46 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test2_op1[1] * f_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 47 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test2_op1[1] * f_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 48 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test2_op1[index[0, 1], index[1, 0]] * f_l_test2_op2)) { Console.WriteLine("Test2_testcase 49 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test2_op1[index[0, 1], index[1, 0]] * f_s_test2_op2)) { Console.WriteLine("Test2_testcase 50 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test2_op1[index[0, 1], index[1, 0]] * f_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 51 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test2_op1[index[0, 1], index[1, 0]] * cl1.f_cl_test2_op2)) { Console.WriteLine("Test2_testcase 52 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test2_op1[index[0, 1], index[1, 0]] * vt1.f_vt_test2_op2)) { Console.WriteLine("Test2_testcase 53 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test2_op1[index[0, 1], index[1, 0]] * f_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 54 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test2_op1[index[0, 1], index[1, 0]] * f_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 55 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test2_op1[index[0, 1], index[1, 0]] * f_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 56 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] * f_l_test2_op2)) { Console.WriteLine("Test2_testcase 57 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] * f_s_test2_op2)) { Console.WriteLine("Test2_testcase 58 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] * f_test2_f("test2_op2"))) { Console.WriteLine("Test2_testcase 59 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] * cl1.f_cl_test2_op2)) { Console.WriteLine("Test2_testcase 60 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] * vt1.f_vt_test2_op2)) { Console.WriteLine("Test2_testcase 61 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] * f_arr1d_test2_op2[0])) { Console.WriteLine("Test2_testcase 62 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] * f_arr2d_test2_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test2_testcase 63 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test2_op1[index[0, 0], 0, index[1, 1]] * f_arr3d_test2_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test2_testcase 64 failed"); passed = false; } } { float f_l_test3_op1 = 3; float f_l_test3_op2 = Single.NaN; if (!Single.IsNaN(f_l_test3_op1 * f_l_test3_op2)) { Console.WriteLine("Test3_testcase 1 failed"); passed = false; } if (!Single.IsNaN(f_l_test3_op1 * f_s_test3_op2)) { Console.WriteLine("Test3_testcase 2 failed"); passed = false; } if (!Single.IsNaN(f_l_test3_op1 * f_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 3 failed"); passed = false; } if (!Single.IsNaN(f_l_test3_op1 * cl1.f_cl_test3_op2)) { Console.WriteLine("Test3_testcase 4 failed"); passed = false; } if (!Single.IsNaN(f_l_test3_op1 * vt1.f_vt_test3_op2)) { Console.WriteLine("Test3_testcase 5 failed"); passed = false; } if (!Single.IsNaN(f_l_test3_op1 * f_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 6 failed"); passed = false; } if (!Single.IsNaN(f_l_test3_op1 * f_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 7 failed"); passed = false; } if (!Single.IsNaN(f_l_test3_op1 * f_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 8 failed"); passed = false; } if (!Single.IsNaN(f_s_test3_op1 * f_l_test3_op2)) { Console.WriteLine("Test3_testcase 9 failed"); passed = false; } if (!Single.IsNaN(f_s_test3_op1 * f_s_test3_op2)) { Console.WriteLine("Test3_testcase 10 failed"); passed = false; } if (!Single.IsNaN(f_s_test3_op1 * f_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 11 failed"); passed = false; } if (!Single.IsNaN(f_s_test3_op1 * cl1.f_cl_test3_op2)) { Console.WriteLine("Test3_testcase 12 failed"); passed = false; } if (!Single.IsNaN(f_s_test3_op1 * vt1.f_vt_test3_op2)) { Console.WriteLine("Test3_testcase 13 failed"); passed = false; } if (!Single.IsNaN(f_s_test3_op1 * f_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 14 failed"); passed = false; } if (!Single.IsNaN(f_s_test3_op1 * f_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 15 failed"); passed = false; } if (!Single.IsNaN(f_s_test3_op1 * f_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 16 failed"); passed = false; } if (!Single.IsNaN(f_test3_f("test3_op1") * f_l_test3_op2)) { Console.WriteLine("Test3_testcase 17 failed"); passed = false; } if (!Single.IsNaN(f_test3_f("test3_op1") * f_s_test3_op2)) { Console.WriteLine("Test3_testcase 18 failed"); passed = false; } if (!Single.IsNaN(f_test3_f("test3_op1") * f_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 19 failed"); passed = false; } if (!Single.IsNaN(f_test3_f("test3_op1") * cl1.f_cl_test3_op2)) { Console.WriteLine("Test3_testcase 20 failed"); passed = false; } if (!Single.IsNaN(f_test3_f("test3_op1") * vt1.f_vt_test3_op2)) { Console.WriteLine("Test3_testcase 21 failed"); passed = false; } if (!Single.IsNaN(f_test3_f("test3_op1") * f_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 22 failed"); passed = false; } if (!Single.IsNaN(f_test3_f("test3_op1") * f_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 23 failed"); passed = false; } if (!Single.IsNaN(f_test3_f("test3_op1") * f_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 24 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test3_op1 * f_l_test3_op2)) { Console.WriteLine("Test3_testcase 25 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test3_op1 * f_s_test3_op2)) { Console.WriteLine("Test3_testcase 26 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test3_op1 * f_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 27 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test3_op1 * cl1.f_cl_test3_op2)) { Console.WriteLine("Test3_testcase 28 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test3_op1 * vt1.f_vt_test3_op2)) { Console.WriteLine("Test3_testcase 29 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test3_op1 * f_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 30 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test3_op1 * f_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 31 failed"); passed = false; } if (!Single.IsNaN(cl1.f_cl_test3_op1 * f_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 32 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test3_op1 * f_l_test3_op2)) { Console.WriteLine("Test3_testcase 33 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test3_op1 * f_s_test3_op2)) { Console.WriteLine("Test3_testcase 34 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test3_op1 * f_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 35 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test3_op1 * cl1.f_cl_test3_op2)) { Console.WriteLine("Test3_testcase 36 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test3_op1 * vt1.f_vt_test3_op2)) { Console.WriteLine("Test3_testcase 37 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test3_op1 * f_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 38 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test3_op1 * f_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 39 failed"); passed = false; } if (!Single.IsNaN(vt1.f_vt_test3_op1 * f_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 40 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test3_op1[1] * f_l_test3_op2)) { Console.WriteLine("Test3_testcase 41 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test3_op1[1] * f_s_test3_op2)) { Console.WriteLine("Test3_testcase 42 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test3_op1[1] * f_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 43 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test3_op1[1] * cl1.f_cl_test3_op2)) { Console.WriteLine("Test3_testcase 44 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test3_op1[1] * vt1.f_vt_test3_op2)) { Console.WriteLine("Test3_testcase 45 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test3_op1[1] * f_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 46 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test3_op1[1] * f_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 47 failed"); passed = false; } if (!Single.IsNaN(f_arr1d_test3_op1[1] * f_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 48 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test3_op1[index[0, 1], index[1, 0]] * f_l_test3_op2)) { Console.WriteLine("Test3_testcase 49 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test3_op1[index[0, 1], index[1, 0]] * f_s_test3_op2)) { Console.WriteLine("Test3_testcase 50 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test3_op1[index[0, 1], index[1, 0]] * f_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 51 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test3_op1[index[0, 1], index[1, 0]] * cl1.f_cl_test3_op2)) { Console.WriteLine("Test3_testcase 52 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test3_op1[index[0, 1], index[1, 0]] * vt1.f_vt_test3_op2)) { Console.WriteLine("Test3_testcase 53 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test3_op1[index[0, 1], index[1, 0]] * f_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 54 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test3_op1[index[0, 1], index[1, 0]] * f_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 55 failed"); passed = false; } if (!Single.IsNaN(f_arr2d_test3_op1[index[0, 1], index[1, 0]] * f_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 56 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] * f_l_test3_op2)) { Console.WriteLine("Test3_testcase 57 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] * f_s_test3_op2)) { Console.WriteLine("Test3_testcase 58 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] * f_test3_f("test3_op2"))) { Console.WriteLine("Test3_testcase 59 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] * cl1.f_cl_test3_op2)) { Console.WriteLine("Test3_testcase 60 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] * vt1.f_vt_test3_op2)) { Console.WriteLine("Test3_testcase 61 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] * f_arr1d_test3_op2[0])) { Console.WriteLine("Test3_testcase 62 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] * f_arr2d_test3_op2[index[0, 1], index[1, 0]])) { Console.WriteLine("Test3_testcase 63 failed"); passed = false; } if (!Single.IsNaN(f_arr3d_test3_op1[index[0, 0], 0, index[1, 1]] * f_arr3d_test3_op2[index[0, 0], 0, index[1, 1]])) { Console.WriteLine("Test3_testcase 64 failed"); passed = false; } } if (!passed) { Console.WriteLine("FAILED"); return 1; } else { Console.WriteLine("PASSED"); 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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void TestZInt16() { var test = new BooleanBinaryOpTest__TestZInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class BooleanBinaryOpTest__TestZInt16 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Int16); private const int Op2ElementCount = VectorSize / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector128<Int16> _clsVar1; private static Vector128<Int16> _clsVar2; private Vector128<Int16> _fld1; private Vector128<Int16> _fld2; private BooleanBinaryOpTest__DataTable<Int16, Int16> _dataTable; static BooleanBinaryOpTest__TestZInt16() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize); } public BooleanBinaryOpTest__TestZInt16() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); } _dataTable = new BooleanBinaryOpTest__DataTable<Int16, Int16>(_data1, _data2, VectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse41.TestZ( Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_Load() { var result = Sse41.TestZ( Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunBasicScenario_LoadAligned() { var result = Sse41.TestZ( Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { var method = typeof(Sse41).GetMethod(nameof(Sse41.TestZ), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }); if (method != null) { var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunReflectionScenario_Load() { var method = typeof(Sse41).GetMethod(nameof(Sse41.TestZ), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }); if (method != null) { var result = method.Invoke(null, new object[] { Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunReflectionScenario_LoadAligned() { var method = typeof(Sse41).GetMethod(nameof(Sse41.TestZ), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }); if (method != null) { var result = method.Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } } public void RunClsVarScenario() { var result = Sse41.TestZ( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr); var result = Sse41.TestZ(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr)); var result = Sse41.TestZ(left, right); ValidateResult(left, right, result); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr)); var result = Sse41.TestZ(left, right); ValidateResult(left, right, result); } public void RunLclFldScenario() { var test = new BooleanBinaryOpTest__TestZInt16(); var result = Sse41.TestZ(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunFldScenario() { var result = Sse41.TestZ(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Int16> left, Vector128<Int16> right, bool result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* left, void* right, bool result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Int16[] left, Int16[] right, bool result, [CallerMemberName] string method = "") { var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= ((left[i] & right[i]) == 0); } if (expectedResult != result) { Succeeded = false; Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.TestZ)}<Int16>(Vector128<Int16>, Vector128<Int16>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Tracing; using System.Linq; using System.Net.Http.Headers; using System.Net.Test.Common; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Microsoft.DotNet.RemoteExecutor; using Xunit; using Xunit.Abstractions; namespace System.Net.Http.Functional.Tests { using Configuration = System.Net.Test.Common.Configuration; public abstract class DiagnosticsTest : HttpClientHandlerTestBase { private const string EnableActivityPropagationEnvironmentVariableSettingName = "DOTNET_SYSTEM_NET_HTTP_ENABLEACTIVITYPROPAGATION"; private const string EnableActivityPropagationAppCtxSettingName = "System.Net.Http.EnableActivityPropagation"; private static bool EnableActivityPropagationEnvironmentVariableIsNotSet => string.IsNullOrEmpty(Environment.GetEnvironmentVariable(EnableActivityPropagationEnvironmentVariableSettingName)); public DiagnosticsTest(ITestOutputHelper output) : base(output) { } [Fact] public static void EventSource_ExistsWithCorrectId() { Type esType = typeof(HttpClient).GetTypeInfo().Assembly .GetType("System.Net.NetEventSource", throwOnError: true, ignoreCase: false); Assert.NotNull(esType); Assert.Equal("Microsoft-System-Net-Http", EventSource.GetName(esType)); Assert.Equal(Guid.Parse("bdd9a83e-1929-5482-0d73-2fe5e1c0e16d"), EventSource.GetGuid(esType)); Assert.NotEmpty(EventSource.GenerateManifest(esType, "assemblyPathToIncludeInManifest")); } // Diagnostic tests are each invoked in their own process as they enable/disable // process-wide EventSource-based tracing, and other tests in the same process // could interfere with the tests, as well as the enabling of tracing interfering // with those tests. /// <remarks> /// This test must be in the same test collection as any others testing HttpClient/WinHttpHandler /// DiagnosticSources, since the global logging mechanism makes them conflict inherently. /// </remarks> [OuterLoop("Uses external server")] [Fact] public void SendAsync_ExpectedDiagnosticSourceLogging() { RemoteExecutor.Invoke((useSocketsHttpHandlerString, useHttp2String) => { bool requestLogged = false; Guid requestGuid = Guid.Empty; bool responseLogged = false; Guid responseGuid = Guid.Empty; bool exceptionLogged = false; bool activityLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.Request")) { Assert.NotNull(kvp.Value); GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request"); requestGuid = GetPropertyValueFromAnonymousTypeInstance<Guid>(kvp.Value, "LoggingRequestId"); requestLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Response")) { Assert.NotNull(kvp.Value); GetPropertyValueFromAnonymousTypeInstance<HttpResponseMessage>(kvp.Value, "Response"); responseGuid = GetPropertyValueFromAnonymousTypeInstance<Guid>(kvp.Value, "LoggingRequestId"); var requestStatus = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus"); Assert.Equal(TaskStatus.RanToCompletion, requestStatus); responseLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Exception")) { exceptionLogged = true; } else if (kvp.Key.StartsWith("System.Net.Http.HttpRequestOut")) { activityLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(s => !s.Contains("HttpRequestOut")); using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString, useHttp2String)) { client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose(); } Assert.True(requestLogged, "Request was not logged."); // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => responseLogged, TimeSpan.FromSeconds(1), "Response was not logged within 1 second timeout."); Assert.Equal(requestGuid, responseGuid); Assert.False(exceptionLogged, "Exception was logged for successful request"); Assert.False(activityLogged, "HttpOutReq was logged while HttpOutReq logging was disabled"); diagnosticListenerObserver.Disable(); } }, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose(); } /// <remarks> /// This test must be in the same test collection as any others testing HttpClient/WinHttpHandler /// DiagnosticSources, since the global logging mechanism makes them conflict inherently. /// </remarks> [OuterLoop("Uses external server")] [Fact] public void SendAsync_ExpectedDiagnosticSourceNoLogging() { RemoteExecutor.Invoke((useSocketsHttpHandlerString, useHttp2String) => { bool requestLogged = false; bool responseLogged = false; bool activityStartLogged = false; bool activityStopLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.Request")) { requestLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Response")) { responseLogged = true; } else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start")) { activityStartLogged = true; } else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { activityStopLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString, useHttp2String)) { LoopbackServer.CreateServerAsync(async (server, url) => { Task<List<string>> requestLines = server.AcceptConnectionSendResponseAndCloseAsync(); Task<HttpResponseMessage> response = client.GetAsync(url); await new Task[] { response, requestLines }.WhenAllOrAnyFailed(); AssertNoHeadersAreInjected(requestLines.Result); response.Result.Dispose(); }).GetAwaiter().GetResult(); } Assert.False(requestLogged, "Request was logged while logging disabled."); Assert.False(activityStartLogged, "HttpRequestOut.Start was logged while logging disabled."); WaitForFalse(() => responseLogged, TimeSpan.FromSeconds(1), "Response was logged while logging disabled."); Assert.False(activityStopLogged, "HttpRequestOut.Stop was logged while logging disabled."); } }, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose(); } [ActiveIssue(23771, TestPlatforms.AnyUnix)] [OuterLoop("Uses external server")] [Theory] [InlineData(false)] [InlineData(true)] public void SendAsync_HttpTracingEnabled_Succeeds(bool useSsl) { RemoteExecutor.Invoke(async (useSocketsHttpHandlerString, useHttp2String, useSslString) => { using (var listener = new TestEventListener("Microsoft-System-Net-Http", EventLevel.Verbose)) { var events = new ConcurrentQueue<EventWrittenEventArgs>(); await listener.RunWithCallbackAsync(events.Enqueue, async () => { // Exercise various code paths to get coverage of tracing using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString, useHttp2String)) { // Do a get to a loopback server await LoopbackServer.CreateServerAsync(async (server, url) => { await TestHelper.WhenAllCompletedOrAnyFailed( server.AcceptConnectionSendResponseAndCloseAsync(), client.GetAsync(url)); }); // Do a post to a remote server byte[] expectedData = Enumerable.Range(0, 20000).Select(i => unchecked((byte)i)).ToArray(); Uri remoteServer = bool.Parse(useSslString) ? Configuration.Http.SecureRemoteEchoServer : Configuration.Http.RemoteEchoServer; var content = new ByteArrayContent(expectedData); content.Headers.ContentMD5 = TestHelper.ComputeMD5Hash(expectedData); using (HttpResponseMessage response = await client.PostAsync(remoteServer, content)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } }); // We don't validate receiving specific events, but rather that we do at least // receive some events, and that enabling tracing doesn't cause other failures // in processing. Assert.DoesNotContain(events, ev => ev.EventId == 0); // make sure there are no event source error messages Assert.InRange(events.Count, 1, int.MaxValue); } }, UseSocketsHttpHandler.ToString(), UseHttp2.ToString(), useSsl.ToString()).Dispose(); } [OuterLoop("Uses external server")] [Fact] public void SendAsync_ExpectedDiagnosticExceptionLogging() { RemoteExecutor.Invoke((useSocketsHttpHandlerString, useHttp2String) => { bool exceptionLogged = false; bool responseLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.Response")) { Assert.NotNull(kvp.Value); var requestStatus = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus"); Assert.Equal(TaskStatus.Faulted, requestStatus); responseLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Exception")) { Assert.NotNull(kvp.Value); GetPropertyValueFromAnonymousTypeInstance<Exception>(kvp.Value, "Exception"); exceptionLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(s => !s.Contains("HttpRequestOut")); using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString, useHttp2String)) { Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync($"http://_{Guid.NewGuid().ToString("N")}.com")) .GetAwaiter().GetResult(); } // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => responseLogged, TimeSpan.FromSeconds(1), "Response with exception was not logged within 1 second timeout."); Assert.True(exceptionLogged, "Exception was not logged"); diagnosticListenerObserver.Disable(); } }, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose(); } [ActiveIssue(23209)] [OuterLoop("Uses external server")] [Fact] public void SendAsync_ExpectedDiagnosticCancelledLogging() { RemoteExecutor.Invoke((useSocketsHttpHandlerString, useHttp2String) => { bool cancelLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.Response")) { Assert.NotNull(kvp.Value); var status = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus"); Assert.Equal(TaskStatus.Canceled, status); Volatile.Write(ref cancelLogged, true); } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(s => !s.Contains("HttpRequestOut")); using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString, useHttp2String)) { LoopbackServer.CreateServerAsync(async (server, url) => { CancellationTokenSource tcs = new CancellationTokenSource(); Task request = server.AcceptConnectionAsync(connection => { tcs.Cancel(); return connection.ReadRequestHeaderAndSendResponseAsync(); }); Task response = client.GetAsync(url, tcs.Token); await Assert.ThrowsAnyAsync<Exception>(() => TestHelper.WhenAllCompletedOrAnyFailed(response, request)); }).GetAwaiter().GetResult(); } } // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => Volatile.Read(ref cancelLogged), TimeSpan.FromSeconds(1), "Cancellation was not logged within 1 second timeout."); diagnosticListenerObserver.Disable(); }, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose(); } [Fact] public void SendAsync_ExpectedDiagnosticSourceActivityLoggingRequestId() { RemoteExecutor.Invoke((useSocketsHttpHandlerString, useHttp2String) => { bool requestLogged = false; bool responseLogged = false; bool activityStartLogged = false; bool activityStopLogged = false; bool exceptionLogged = false; Activity parentActivity = new Activity("parent"); parentActivity.AddBaggage("correlationId", Guid.NewGuid().ToString("N").ToString()); parentActivity.AddBaggage("moreBaggage", Guid.NewGuid().ToString("N").ToString()); parentActivity.AddTag("tag", "tag"); //add tag to ensure it is not injected into request parentActivity.Start(); var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.Request")) { requestLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Response")) { responseLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Exception")) { exceptionLogged = true; } else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start")) { Assert.NotNull(kvp.Value); Assert.NotNull(Activity.Current); Assert.Equal(parentActivity, Activity.Current.Parent); GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request"); activityStartLogged = true; } else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { Assert.NotNull(kvp.Value); Assert.NotNull(Activity.Current); Assert.Equal(parentActivity, Activity.Current.Parent); Assert.True(Activity.Current.Duration != TimeSpan.Zero); GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request"); GetPropertyValueFromAnonymousTypeInstance<HttpResponseMessage>(kvp.Value, "Response"); var requestStatus = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus"); Assert.Equal(TaskStatus.RanToCompletion, requestStatus); activityStopLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(s => s.Contains("HttpRequestOut")); using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString, useHttp2String)) { LoopbackServer.CreateServerAsync(async (server, url) => { Task<List<string>> requestLines = server.AcceptConnectionSendResponseAndCloseAsync(); Task<HttpResponseMessage> response = client.GetAsync(url); await new Task[] { response, requestLines }.WhenAllOrAnyFailed(); AssertHeadersAreInjected(requestLines.Result, parentActivity); response.Result.Dispose(); }).GetAwaiter().GetResult(); } Assert.True(activityStartLogged, "HttpRequestOut.Start was not logged."); Assert.False(requestLogged, "Request was logged when Activity logging was enabled."); // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1), "HttpRequestOut.Stop was not logged within 1 second timeout."); Assert.False(exceptionLogged, "Exception was logged for successful request"); Assert.False(responseLogged, "Response was logged when Activity logging was enabled."); diagnosticListenerObserver.Disable(); } }, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose(); } [Fact] public void SendAsync_ExpectedDiagnosticSourceActivityLoggingW3C() { RemoteExecutor.Invoke((useSocketsHttpHandlerString, useHttp2String) => { bool requestLogged = false; bool responseLogged = false; bool activityStartLogged = false; bool activityStopLogged = false; bool exceptionLogged = false; Activity parentActivity = new Activity("parent"); parentActivity.SetParentId(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom()); parentActivity.AddBaggage("moreBaggage", Guid.NewGuid().ToString("N").ToString()); parentActivity.Start(); var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.Request")) { requestLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Response")) { responseLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Exception")) { exceptionLogged = true; } else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start")) { Assert.NotNull(kvp.Value); Assert.NotNull(Activity.Current); Assert.Equal(parentActivity, Activity.Current.Parent); GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request"); activityStartLogged = true; } else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { Assert.NotNull(kvp.Value); Assert.NotNull(Activity.Current); Assert.Equal(parentActivity, Activity.Current.Parent); Assert.True(Activity.Current.Duration != TimeSpan.Zero); GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request"); GetPropertyValueFromAnonymousTypeInstance<HttpResponseMessage>(kvp.Value, "Response"); var requestStatus = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus"); Assert.Equal(TaskStatus.RanToCompletion, requestStatus); activityStopLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(s => s.Contains("HttpRequestOut")); using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString, useHttp2String)) { LoopbackServer.CreateServerAsync(async (server, url) => { Task<List<string>> requestLines = server.AcceptConnectionSendResponseAndCloseAsync(); Task<HttpResponseMessage> response = client.GetAsync(url); await new Task[] { response, requestLines }.WhenAllOrAnyFailed(); AssertHeadersAreInjected(requestLines.Result, parentActivity); response.Result.Dispose(); }).GetAwaiter().GetResult(); } Assert.True(activityStartLogged, "HttpRequestOut.Start was not logged."); Assert.False(requestLogged, "Request was logged when Activity logging was enabled."); // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1), "HttpRequestOut.Stop was not logged within 1 second timeout."); Assert.False(exceptionLogged, "Exception was logged for successful request"); Assert.False(responseLogged, "Response was logged when Activity logging was enabled."); diagnosticListenerObserver.Disable(); } }, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose(); } [OuterLoop("Uses external server")] [Fact] public void SendAsync_ExpectedDiagnosticSourceActivityLogging_InvalidBaggage() { RemoteExecutor.Invoke((useSocketsHttpHandlerString, useHttp2String) => { bool activityStopLogged = false; bool exceptionLogged = false; Activity parentActivity = new Activity("parent"); parentActivity.AddBaggage("bad/key", "value"); parentActivity.AddBaggage("goodkey", "bad/value"); parentActivity.AddBaggage("key", "value"); parentActivity.Start(); var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { Assert.NotNull(kvp.Value); Assert.NotNull(Activity.Current); Assert.Equal(parentActivity, Activity.Current.Parent); Assert.True(Activity.Current.Duration != TimeSpan.Zero); var request = GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request"); Assert.True(request.Headers.TryGetValues("Request-Id", out var requestId)); Assert.True(request.Headers.TryGetValues("Correlation-Context", out var correlationContext)); Assert.Equal(3, correlationContext.Count()); Assert.Contains("key=value", correlationContext); Assert.Contains("bad%2Fkey=value", correlationContext); Assert.Contains("goodkey=bad%2Fvalue", correlationContext); var requestStatus = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus"); Assert.Equal(TaskStatus.RanToCompletion, requestStatus); activityStopLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Exception")) { exceptionLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(s => s.Contains("HttpRequestOut")); using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString, useHttp2String)) { client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose(); } // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1), "Response was not logged within 1 second timeout."); Assert.False(exceptionLogged, "Exception was logged for successful request"); diagnosticListenerObserver.Disable(); } }, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose(); } [OuterLoop("Uses external server")] [Fact] public void SendAsync_ExpectedDiagnosticSourceActivityLoggingDoesNotOverwriteHeader() { RemoteExecutor.Invoke((useSocketsHttpHandlerString, useHttp2String) => { bool activityStartLogged = false; bool activityStopLogged = false; Activity parentActivity = new Activity("parent"); parentActivity.AddBaggage("correlationId", Guid.NewGuid().ToString("N").ToString()); parentActivity.Start(); string customRequestIdHeader = "|foo.bar."; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start")) { var request = GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request"); request.Headers.Add("Request-Id", customRequestIdHeader); activityStartLogged = true; } else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { var request = GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request"); Assert.Single(request.Headers.GetValues("Request-Id")); Assert.Equal(customRequestIdHeader, request.Headers.GetValues("Request-Id").Single()); Assert.False(request.Headers.TryGetValues("traceparent", out var _)); Assert.False(request.Headers.TryGetValues("tracestate", out var _)); activityStopLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(); using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString, useHttp2String)) { client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose(); } Assert.True(activityStartLogged, "HttpRequestOut.Start was not logged."); // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1), "HttpRequestOut.Stop was not logged within 1 second timeout."); diagnosticListenerObserver.Disable(); } }, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose(); } [OuterLoop("Uses external server")] [Fact] public void SendAsync_ExpectedDiagnosticSourceActivityLoggingDoesNotOverwriteW3CTraceParentHeader() { Assert.False(UseHttp2, "The test currently ignores UseHttp2."); RemoteExecutor.Invoke((useSocketsHttpHandlerString, useHttp2String) => { bool activityStartLogged = false; bool activityStopLogged = false; Activity parentActivity = new Activity("parent"); parentActivity.SetParentId(ActivityTraceId.CreateRandom(), ActivitySpanId.CreateRandom()); parentActivity.TraceStateString = "some=state"; parentActivity.Start(); string customTraceParentHeader = "00-abcdef0123456789abcdef0123456789-abcdef0123456789-01"; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start")) { var request = GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request"); Assert.Single(request.Headers.GetValues("traceparent")); Assert.False(request.Headers.TryGetValues("tracestate", out var _)); Assert.Equal(customTraceParentHeader, request.Headers.GetValues("traceparent").Single()); Assert.False(request.Headers.TryGetValues("Request-Id", out var _)); activityStartLogged = true; } else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { activityStopLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(); using (var request = new HttpRequestMessage(HttpMethod.Get, Configuration.Http.RemoteEchoServer)) using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString, useHttp2String)) { request.Headers.Add("traceparent", customTraceParentHeader); client.SendAsync(request).Result.Dispose(); } Assert.True(activityStartLogged, "HttpRequestOut.Start was not logged."); // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1), "HttpRequestOut.Stop was not logged within 1 second timeout."); diagnosticListenerObserver.Disable(); } }, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose(); } [OuterLoop("Uses external server")] [Fact] public void SendAsync_ExpectedDiagnosticSourceUrlFilteredActivityLogging() { RemoteExecutor.Invoke((useSocketsHttpHandlerString, useHttp2String) => { bool activityStartLogged = false; bool activityStopLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start")) { activityStartLogged = true; } else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { activityStopLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable((s, r, _) => { if (s.StartsWith("System.Net.Http.HttpRequestOut")) { var request = r as HttpRequestMessage; if (request != null) return !request.RequestUri.Equals(Configuration.Http.RemoteEchoServer); } return true; }); using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString, useHttp2String)) { client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose(); } Assert.False(activityStartLogged, "HttpRequestOut.Start was logged while URL disabled."); // Poll with a timeout since logging response is not synchronized with returning a response. Assert.False(activityStopLogged, "HttpRequestOut.Stop was logged while URL disabled."); diagnosticListenerObserver.Disable(); } }, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose(); } [OuterLoop("Uses external server")] [Fact] public void SendAsync_ExpectedDiagnosticExceptionActivityLogging() { RemoteExecutor.Invoke((useSocketsHttpHandlerString, useHttp2String) => { bool exceptionLogged = false; bool activityStopLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { Assert.NotNull(kvp.Value); GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request"); var requestStatus = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus"); Assert.Equal(TaskStatus.Faulted, requestStatus); activityStopLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Exception")) { Assert.NotNull(kvp.Value); GetPropertyValueFromAnonymousTypeInstance<Exception>(kvp.Value, "Exception"); exceptionLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(); using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString, useHttp2String)) { Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync($"http://_{Guid.NewGuid().ToString("N")}.com")) .GetAwaiter().GetResult(); } // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1), "Response with exception was not logged within 1 second timeout."); Assert.True(exceptionLogged, "Exception was not logged"); diagnosticListenerObserver.Disable(); } }, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose(); } [OuterLoop("Uses external server")] [Fact] public void SendAsync_ExpectedDiagnosticSynchronousExceptionActivityLogging() { if (IsCurlHandler) { // The only way to throw a synchronous exception for CurlHandler through // DiagnosticHandler is when the Request uri scheme is Https, and the // backend doesn't support SSL. return; } RemoteExecutor.Invoke((useSocketsHttpHandlerString, useHttp2String) => { bool exceptionLogged = false; bool activityStopLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { Assert.NotNull(kvp.Value); GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request"); var requestStatus = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus"); Assert.Equal(TaskStatus.Faulted, requestStatus); activityStopLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Exception")) { Assert.NotNull(kvp.Value); GetPropertyValueFromAnonymousTypeInstance<Exception>(kvp.Value, "Exception"); exceptionLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(); using (HttpClientHandler handler = CreateHttpClientHandler(useSocketsHttpHandlerString, useHttp2String)) using (HttpClient client = CreateHttpClient(handler, useHttp2String)) { // Set a https proxy. handler.Proxy = new WebProxy($"https://_{Guid.NewGuid().ToString("N")}.com", false); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, $"http://_{Guid.NewGuid().ToString("N")}.com"); if (bool.Parse(useSocketsHttpHandlerString)) { // Forces a synchronous exception for SocketsHttpHandler. // SocketsHttpHandler only allow http scheme for proxies. // We cannot use Assert.Throws<Exception>(() => { SendAsync(...); }) to verify the // synchronous exception here, because DiagnosticsHandler SendAsync() method has async // modifier, and returns Task. If the call is not awaited, the current test method will continue // run before the call is completed, thus Assert.Throws() will not capture the exception. // We need to wait for the Task to complete synchronously, to validate the exception. Task sendTask = client.SendAsync(request); Assert.True(sendTask.IsFaulted); Assert.IsType<NotSupportedException>(sendTask.Exception.InnerException); } else { // Forces a synchronous exception for WinHttpHandler. // WinHttpHandler will not allow (proxy != null && !UseCustomProxy). handler.UseProxy = false; // We cannot use Assert.Throws<Exception>(() => { SendAsync(...); }) to verify the // synchronous exception here, because DiagnosticsHandler SendAsync() method has async // modifier, and returns Task. If the call is not awaited, the current test method will continue // run before the call is completed, thus Assert.Throws() will not capture the exception. // We need to wait for the Task to complete synchronously, to validate the exception. Task sendTask = client.SendAsync(request); Assert.True(sendTask.IsFaulted); Assert.IsType<InvalidOperationException>(sendTask.Exception.InnerException); } } // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1), "Response with exception was not logged within 1 second timeout."); Assert.True(exceptionLogged, "Exception was not logged"); diagnosticListenerObserver.Disable(); } }, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose(); } [OuterLoop("Uses external server")] [Fact] public void SendAsync_ExpectedDiagnosticSourceNewAndDeprecatedEventsLogging() { RemoteExecutor.Invoke((useSocketsHttpHandlerString, useHttp2String) => { bool requestLogged = false; bool responseLogged = false; bool activityStartLogged = false; bool activityStopLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.Request")) { requestLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Response")) { responseLogged = true; } else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start")) { activityStartLogged = true; } else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { activityStopLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(); using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString, useHttp2String)) { client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose(); } Assert.True(activityStartLogged, "HttpRequestOut.Start was not logged."); Assert.True(requestLogged, "Request was not logged."); // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1), "HttpRequestOut.Stop was not logged within 1 second timeout."); Assert.True(responseLogged, "Response was not logged."); diagnosticListenerObserver.Disable(); } }, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose(); } [OuterLoop("Uses external server")] [Fact] public void SendAsync_ExpectedDiagnosticExceptionOnlyActivityLogging() { RemoteExecutor.Invoke((useSocketsHttpHandlerString, useHttp2String) => { bool exceptionLogged = false; bool activityLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { activityLogged = true; } else if (kvp.Key.Equals("System.Net.Http.Exception")) { Assert.NotNull(kvp.Value); GetPropertyValueFromAnonymousTypeInstance<Exception>(kvp.Value, "Exception"); exceptionLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(s => s.Equals("System.Net.Http.Exception")); using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString, useHttp2String)) { Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync($"http://_{Guid.NewGuid().ToString("N")}.com")) .GetAwaiter().GetResult(); } // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => exceptionLogged, TimeSpan.FromSeconds(1), "Exception was not logged within 1 second timeout."); Assert.False(activityLogged, "HttpOutReq was logged when logging was disabled"); diagnosticListenerObserver.Disable(); } }, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose(); } [OuterLoop("Uses external server")] [Fact] public void SendAsync_ExpectedDiagnosticStopOnlyActivityLogging() { RemoteExecutor.Invoke((useSocketsHttpHandlerString, useHttp2String) => { bool activityStartLogged = false; bool activityStopLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Start")) { activityStartLogged = true; } else if (kvp.Key.Equals("System.Net.Http.HttpRequestOut.Stop")) { Assert.NotNull(Activity.Current); activityStopLogged = true; } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(s => s.Equals("System.Net.Http.HttpRequestOut")); using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString, useHttp2String)) { client.GetAsync(Configuration.Http.RemoteEchoServer).Result.Dispose(); } // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => activityStopLogged, TimeSpan.FromSeconds(1), "HttpRequestOut.Stop was not logged within 1 second timeout."); Assert.False(activityStartLogged, "HttpRequestOut.Start was logged when start logging was disabled"); diagnosticListenerObserver.Disable(); } }, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose(); } [OuterLoop("Uses external server")] [Fact] public void SendAsync_ExpectedActivityPropagationWithoutListener() { RemoteExecutor.Invoke((useSocketsHttpHandlerString, useHttp2String) => { using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString, useHttp2String)) { Activity parent = new Activity("parent").Start(); using HttpResponseMessage response = client.GetAsync(Configuration.Http.RemoteEchoServer).Result; Assert.True(response.RequestMessage.Headers.Contains(parent.IdFormat == ActivityIdFormat.Hierarchical ? "Request-Id" : "traceparent")); parent.Stop(); } }, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose(); } [OuterLoop("Uses external server")] [Fact] public void SendAsync_ExpectedActivityPropagationWithoutListenerOrParentActivity() { RemoteExecutor.Invoke((useSocketsHttpHandlerString, useHttp2String) => { using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString, useHttp2String)) { using HttpResponseMessage response = client.GetAsync(Configuration.Http.RemoteEchoServer).Result; Assert.False(response.RequestMessage.Headers.Contains("Request-Id")); Assert.False(response.RequestMessage.Headers.Contains("traceparent")); Assert.False(response.RequestMessage.Headers.Contains("tracestate")); Assert.False(response.RequestMessage.Headers.Contains("Correlation-Context")); } }, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose(); } [OuterLoop("Uses external server")] [ConditionalTheory(nameof(EnableActivityPropagationEnvironmentVariableIsNotSet))] [InlineData("true", true)] [InlineData("1", true)] [InlineData("0", false)] [InlineData("false", false)] [InlineData("FALSE", false)] [InlineData("fAlSe", false)] [InlineData("helloworld", true)] [InlineData("", true)] public void SendAsync_SuppressedGlobalStaticPropagationEnvVar(string envVarValue, bool isInstrumentationEnabled) { RemoteExecutor.Invoke((innerEnvVarValue, innerIsInstrumentationEnabled) => { Environment.SetEnvironmentVariable(EnableActivityPropagationEnvironmentVariableSettingName, innerEnvVarValue); string eventKey = null; bool anyEventLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { anyEventLogged = true; eventKey = kvp.Key; }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(s => s.Equals("System.Net.Http.HttpRequestOut")); using (HttpClient client = new HttpClient()) { Activity parent = new Activity("parent").Start(); using HttpResponseMessage response = client.GetAsync(Configuration.Http.RemoteEchoServer).Result; parent.Stop(); Assert.Equal(bool.Parse(innerIsInstrumentationEnabled), response.RequestMessage.Headers.Contains( parent.IdFormat == ActivityIdFormat.Hierarchical ? "Request-Id" : "traceparent")); } if (!bool.Parse(innerIsInstrumentationEnabled)) { Assert.False(anyEventLogged, $"{eventKey} event logged when Activity is suppressed globally"); } else { Assert.True(anyEventLogged, $"{eventKey} event was not logged logged when Activity is not suppressed"); } diagnosticListenerObserver.Disable(); } }, envVarValue, isInstrumentationEnabled.ToString()).Dispose(); } [OuterLoop("Uses external server")] [Theory] [InlineData(true)] [InlineData(false)] public void SendAsync_SuppressedGlobalStaticPropagationNoListenerAppCtx(bool switchValue) { RemoteExecutor.Invoke(innerSwitchValue => { AppContext.SetSwitch(EnableActivityPropagationAppCtxSettingName, bool.Parse(innerSwitchValue)); using (HttpClient client = new HttpClient()) { Activity parent = new Activity("parent").Start(); using HttpResponseMessage response = client.GetAsync(Configuration.Http.RemoteEchoServer).Result; parent.Stop(); Assert.Equal(bool.Parse(innerSwitchValue), response.RequestMessage.Headers.Contains( parent.IdFormat == ActivityIdFormat.Hierarchical ? "Request-Id" : "traceparent")); } }, switchValue.ToString()).Dispose(); } [ActiveIssue(23209)] [OuterLoop("Uses external server")] [Fact] public void SendAsync_ExpectedDiagnosticCancelledActivityLogging() { RemoteExecutor.Invoke((useSocketsHttpHandlerString, useHttp2String) => { bool cancelLogged = false; var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(kvp => { if (kvp.Key == "System.Net.Http.HttpRequestOut.Stop") { Assert.NotNull(kvp.Value); GetPropertyValueFromAnonymousTypeInstance<HttpRequestMessage>(kvp.Value, "Request"); var status = GetPropertyValueFromAnonymousTypeInstance<TaskStatus>(kvp.Value, "RequestTaskStatus"); Assert.Equal(TaskStatus.Canceled, status); Volatile.Write(ref cancelLogged, true); } }); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(); using (HttpClient client = CreateHttpClient(useSocketsHttpHandlerString, useHttp2String)) { LoopbackServer.CreateServerAsync(async (server, url) => { CancellationTokenSource tcs = new CancellationTokenSource(); Task request = server.AcceptConnectionAsync(connection => { tcs.Cancel(); return connection.ReadRequestHeaderAndSendResponseAsync(); }); Task response = client.GetAsync(url, tcs.Token); await Assert.ThrowsAnyAsync<Exception>(() => TestHelper.WhenAllCompletedOrAnyFailed(response, request)); }).GetAwaiter().GetResult(); } } // Poll with a timeout since logging response is not synchronized with returning a response. WaitForTrue(() => Volatile.Read(ref cancelLogged), TimeSpan.FromSeconds(1), "Cancellation was not logged within 1 second timeout."); diagnosticListenerObserver.Disable(); }, UseSocketsHttpHandler.ToString(), UseHttp2.ToString()).Dispose(); } [Fact] public void SendAsync_NullRequest_ThrowsArgumentNullException() { RemoteExecutor.Invoke(async () => { var diagnosticListenerObserver = new FakeDiagnosticListenerObserver(null); using (DiagnosticListener.AllListeners.Subscribe(diagnosticListenerObserver)) { diagnosticListenerObserver.Enable(); using (MyHandler handler = new MyHandler()) { // Getting the Task first from the .SendAsync() call also tests // that the exception comes from the async Task path. Task t = handler.SendAsync(null); if (PlatformDetection.IsInAppContainer) { await Assert.ThrowsAsync<HttpRequestException>(() => t); } else { await Assert.ThrowsAsync<ArgumentNullException>(() => t); } } } diagnosticListenerObserver.Disable(); }).Dispose(); } private class MyHandler : HttpClientHandler { internal Task<HttpResponseMessage> SendAsync(HttpRequestMessage request) { return SendAsync(request, CancellationToken.None); } } private static T GetPropertyValueFromAnonymousTypeInstance<T>(object obj, string propertyName) { Type t = obj.GetType(); PropertyInfo p = t.GetRuntimeProperty(propertyName); object propertyValue = p.GetValue(obj); Assert.NotNull(propertyValue); Assert.IsAssignableFrom<T>(propertyValue); return (T)propertyValue; } private static void WaitForTrue(Func<bool> p, TimeSpan timeout, string message) { // Assert that spin doesn't time out. Assert.True(SpinWait.SpinUntil(p, timeout), message); } private static void WaitForFalse(Func<bool> p, TimeSpan timeout, string message) { // Assert that spin times out. Assert.False(SpinWait.SpinUntil(p, timeout), message); } private static string GetHeaderValue(string name, List<string> requestLines) { string header = null; foreach (var line in requestLines) { if (line.StartsWith(name)) { header = line.Substring(name.Length).Trim(' ', ':'); } } return header; } private static void AssertHeadersAreInjected(List<string> requestLines, Activity parent) { string requestId = GetHeaderValue("Request-Id", requestLines); string traceparent = GetHeaderValue("traceparent", requestLines); string tracestate = GetHeaderValue("tracestate", requestLines); if (parent.IdFormat == ActivityIdFormat.Hierarchical) { Assert.True(requestId != null, "Request-Id was not injected when instrumentation was enabled"); Assert.StartsWith(parent.Id, requestId); Assert.NotEqual(parent.Id, requestId); Assert.Null(traceparent); Assert.Null(tracestate); } else if (parent.IdFormat == ActivityIdFormat.W3C) { Assert.Null(requestId); Assert.True(traceparent != null, "traceparent was not injected when W3C instrumentation was enabled"); Assert.StartsWith($"00-{parent.TraceId.ToHexString()}-", traceparent); Assert.Equal(parent.TraceStateString, tracestate); } var correlationContext = new List<NameValueHeaderValue>(); foreach (var line in requestLines) { if (line.StartsWith("Correlation-Context")) { var corrCtxString = line.Substring("Correlation-Context".Length).Trim(' ', ':'); foreach (var kvp in corrCtxString.Split(',')) { correlationContext.Add(NameValueHeaderValue.Parse(kvp)); } } } List<KeyValuePair<string, string>> baggage = parent.Baggage.ToList(); Assert.Equal(baggage.Count, correlationContext.Count); foreach (var kvp in baggage) { Assert.Contains(new NameValueHeaderValue(kvp.Key, kvp.Value), correlationContext); } } private static void AssertNoHeadersAreInjected(List<string> requestLines) { foreach (var line in requestLines) { Assert.False(line.StartsWith("Request-Id"), "Request-Id header was injected when instrumentation was disabled"); Assert.False(line.StartsWith("traceparent"), "traceparent header was injected when instrumentation was disabled"); Assert.False(line.StartsWith("tracestate"), "tracestate header was injected when instrumentation was disabled"); Assert.False(line.StartsWith("Correlation-Context"), "Correlation-Context header was injected when instrumentation was disabled"); } } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.AspNet.Razor.Generator; using Microsoft.AspNet.Razor.Parser; using Microsoft.AspNet.Razor.Parser.SyntaxTree; using Microsoft.AspNet.Razor.Test.Framework; using Microsoft.AspNet.Razor.Text; using Xunit; namespace Microsoft.AspNet.Razor.Test.Parser.Html { public class HtmlDocumentTest : CsHtmlMarkupParserTestBase { // TODO: path won't work. Need "." syntax //private static readonly TestFile Nested1000 = TestFile.Create("TestFiles/nested-1000.html"); private static readonly TestFile Nested1000 = TestFile.Create("Microsoft.AspNet.Razor.Test.TestFiles.nested-1000.html"); [Fact] public void ParseDocumentMethodThrowsArgNullExceptionOnNullContext() { // Arrange HtmlMarkupParser parser = new HtmlMarkupParser(); // Act and Assert var exception = Assert.Throws<InvalidOperationException>(() => parser.ParseDocument()); Assert.Equal(RazorResources.Parser_Context_Not_Set, exception.Message); } [Fact] public void ParseSectionMethodThrowsArgNullExceptionOnNullContext() { // Arrange HtmlMarkupParser parser = new HtmlMarkupParser(); // Act and Assert var exception = Assert.Throws<InvalidOperationException>(() => parser.ParseSection(null, true)); Assert.Equal(RazorResources.Parser_Context_Not_Set, exception.Message); } [Fact] public void ParseDocumentOutputsEmptyBlockWithEmptyMarkupSpanIfContentIsEmptyString() { ParseDocumentTest(String.Empty, new MarkupBlock(Factory.EmptyHtml())); } [Fact] public void ParseDocumentOutputsWhitespaceOnlyContentAsSingleWhitespaceMarkupSpan() { SingleSpanDocumentTest(" ", BlockType.Markup, SpanKind.Markup); } [Fact] public void ParseDocumentAcceptsSwapTokenAtEndOfFileAndOutputsZeroLengthCodeSpan() { ParseDocumentTest("@", new MarkupBlock( Factory.EmptyHtml(), new ExpressionBlock( Factory.CodeTransition(), Factory.EmptyCSharp() .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) .Accepts(AcceptedCharacters.NonWhiteSpace)), Factory.EmptyHtml()), new RazorError(RazorResources.ParseError_Unexpected_EndOfFile_At_Start_Of_CodeBlock, 1, 0, 1)); } [Fact] public void ParseDocumentCorrectlyHandlesSingleLineOfMarkupWithEmbeddedStatement() { ParseDocumentTest("<div>Foo @if(true) {} Bar</div>", new MarkupBlock( Factory.Markup("<div>Foo "), new StatementBlock( Factory.CodeTransition(), Factory.Code("if(true) {}").AsStatement()), Factory.Markup(" Bar</div>"))); } [Fact] public void ParseDocumentWithinSectionDoesNotCreateDocumentLevelSpan() { ParseDocumentTest("@section Foo {" + Environment.NewLine + " <html></html>" + Environment.NewLine + "}", new MarkupBlock( Factory.EmptyHtml(), new SectionBlock(new SectionCodeGenerator("Foo"), Factory.CodeTransition(), Factory.MetaCode("section Foo {") .AutoCompleteWith(null, atEndOfSpan: true), new MarkupBlock( Factory.Markup("\r\n <html></html>\r\n")), Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), Factory.EmptyHtml())); } [Fact] public void ParseDocumentParsesWholeContentAsOneSpanIfNoSwapCharacterEncountered() { SingleSpanDocumentTest("foo <bar>baz</bar>", BlockType.Markup, SpanKind.Markup); } [Fact] public void ParseDocumentHandsParsingOverToCodeParserWhenAtSignEncounteredAndEmitsOutput() { ParseDocumentTest("foo @bar baz", new MarkupBlock( Factory.Markup("foo "), new ExpressionBlock( Factory.CodeTransition(), Factory.Code("bar") .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) .Accepts(AcceptedCharacters.NonWhiteSpace)), Factory.Markup(" baz"))); } [Fact] public void ParseDocumentEmitsAtSignAsMarkupIfAtEndOfFile() { ParseDocumentTest("foo @", new MarkupBlock( Factory.Markup("foo "), new ExpressionBlock( Factory.CodeTransition(), Factory.EmptyCSharp() .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) .Accepts(AcceptedCharacters.NonWhiteSpace)), Factory.EmptyHtml()), new RazorError(RazorResources.ParseError_Unexpected_EndOfFile_At_Start_Of_CodeBlock, 5, 0, 5)); } [Fact] public void ParseDocumentEmitsCodeBlockIfFirstCharacterIsSwapCharacter() { ParseDocumentTest("@bar", new MarkupBlock( Factory.EmptyHtml(), new ExpressionBlock( Factory.CodeTransition(), Factory.Code("bar") .AsImplicitExpression(CSharpCodeParser.DefaultKeywords) .Accepts(AcceptedCharacters.NonWhiteSpace)), Factory.EmptyHtml())); } [Fact] public void ParseDocumentDoesNotSwitchToCodeOnEmailAddressInText() { SingleSpanDocumentTest("<foo>anurse@microsoft.com</foo>", BlockType.Markup, SpanKind.Markup); } [Fact] public void ParseDocumentDoesNotSwitchToCodeOnEmailAddressInAttribute() { ParseDocumentTest("<a href=\"mailto:anurse@microsoft.com\">Email me</a>", new MarkupBlock( Factory.Markup("<a"), new MarkupBlock(new AttributeBlockCodeGenerator("href", new LocationTagged<string>(" href=\"", 2, 0, 2), new LocationTagged<string>("\"", 36, 0, 36)), Factory.Markup(" href=\"").With(SpanCodeGenerator.Null), Factory.Markup("mailto:anurse@microsoft.com") .With(new LiteralAttributeCodeGenerator(new LocationTagged<string>(String.Empty, 9, 0, 9), new LocationTagged<string>("mailto:anurse@microsoft.com", 9, 0, 9))), Factory.Markup("\"").With(SpanCodeGenerator.Null)), Factory.Markup(">Email me</a>"))); } [Fact] public void ParseDocumentDoesNotReturnErrorOnMismatchedTags() { SingleSpanDocumentTest("Foo <div><p></p></p> Baz", BlockType.Markup, SpanKind.Markup); } [Fact] public void ParseDocumentReturnsOneMarkupSegmentIfNoCodeBlocksEncountered() { SingleSpanDocumentTest("Foo <p>Baz<!--Foo-->Bar<!-F> Qux", BlockType.Markup, SpanKind.Markup); } [Fact] public void ParseDocumentRendersTextPseudoTagAsMarkup() { SingleSpanDocumentTest("Foo <text>Foo</text>", BlockType.Markup, SpanKind.Markup); } [Fact] public void ParseDocumentAcceptsEndTagWithNoMatchingStartTag() { SingleSpanDocumentTest("Foo </div> Bar", BlockType.Markup, SpanKind.Markup); } [Fact] public void ParseDocumentNoLongerSupportsDollarOpenBraceCombination() { ParseDocumentTest("<foo>${bar}</foo>", new MarkupBlock( Factory.Markup("<foo>${bar}</foo>"))); } [Fact] public void ParseDocumentIgnoresTagsInContentsOfScriptTag() { ParseDocumentTest(@"<script>foo<bar baz='@boz'></script>", new MarkupBlock( Factory.Markup("<script>foo<bar baz='"), new ExpressionBlock( Factory.CodeTransition(), Factory.Code("boz") .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: false) .Accepts(AcceptedCharacters.NonWhiteSpace)), Factory.Markup("'></script>"))); } [Fact] public void ParseSectionIgnoresTagsInContentsOfScriptTag() { ParseDocumentTest(@"@section Foo { <script>foo<bar baz='@boz'></script> }", new MarkupBlock( Factory.EmptyHtml(), new SectionBlock(new SectionCodeGenerator("Foo"), Factory.CodeTransition(), Factory.MetaCode("section Foo {"), new MarkupBlock( Factory.Markup(" <script>foo<bar baz='"), new ExpressionBlock( Factory.CodeTransition(), Factory.Code("boz") .AsImplicitExpression(CSharpCodeParser.DefaultKeywords, acceptTrailingDot: false) .Accepts(AcceptedCharacters.NonWhiteSpace)), Factory.Markup("'></script> ")), Factory.MetaCode("}").Accepts(AcceptedCharacters.None)), Factory.EmptyHtml())); } [Fact] public void ParseBlockCanParse1000NestedElements() { string content = Nested1000.ReadAllText(); SingleSpanDocumentTest(content, BlockType.Markup, SpanKind.Markup); } } }
using System; using System.Collections; using Foundation.Tasks; using UnityEngine; using UnityEngine.UI; namespace Foundation.Example { /// <summary> /// Example of how to use the UnityTask library /// </summary> [AddComponentMenu("Foundation/Examples/TaskTests")] public class TaskTests : MonoBehaviour { public Text Output; protected int Counter = 0; string log; void Awake() { Application.logMessageReceived += Application_logMessageReceived; } void Assert(Func<bool> compare, string testName) { if (!compare.Invoke()) throw new Exception(string.Format("Test {0} Failed", testName)); Debug.Log("Test " + testName + " Passed"); } void Application_logMessageReceived(string condition, string stackTrace, LogType type) { if (Output) { log += (Environment.NewLine + condition); } } void Update() { Output.text = log; } public IEnumerator Start() { log = string.Empty; Debug.Log("Test Starting"); Counter = 0; yield return new WaitForSeconds(2); // Action Debug.Log("Action..."); var mtask = UnityTask.Run(() => { Counter++; }); yield return mtask; Assert(() => Counter == 1, "Action"); yield return new WaitForSeconds(2); // Action with Debug.Log("Action w/ Continue..."); yield return new WaitForSeconds(1); yield return UnityTask.Run(() => { Counter++; }).ContinueWith(task => { Counter++; }); Assert(() => Counter == 3, "Action w/ Continue"); // Coroutine Debug.Log("Continue..."); yield return new WaitForSeconds(1); yield return UnityTask.RunCoroutine(DemoCoroutine); Assert(() => Counter == 4, "Coroutine"); // Coroutine with Continue Debug.Log("Coroutine w/ Continue..."); yield return new WaitForSeconds(1); yield return UnityTask.RunCoroutine(DemoCoroutine).ContinueWith(task => { Counter++; }); Assert(() => Counter == 6, "Coroutine w/ Continue"); // Coroutine with result Debug.Log("Coroutine w/ result..."); yield return new WaitForSeconds(1); var ctask = UnityTask.RunCoroutine<string>(DemoCoroutineWithResult); yield return ctask; Assert(() => Counter == 7, "Coroutine w/ result (A)"); Assert(() => ctask.Result == "Hello", "Coroutine w/ result (B)"); // Coroutine with result and Continue Debug.Log("CoroutineCoroutine w/ result and continue..."); yield return new WaitForSeconds(1); var ctask2 = UnityTask.RunCoroutine<string>(DemoCoroutineWithResult).ContinueWith(t => { Assert(() => t.Result == "Hello", "Coroutine w/ result and continue (A)"); t.Result = "Goodbye"; Counter++; }); yield return ctask2; Assert(() => Counter == 9, "Coroutine w/ result and continue (B)"); Assert(() => ctask2.Result == "Goodbye", "Coroutine w/ result and continue (C)"); // Function Debug.Log("Function..."); yield return new WaitForSeconds(1); var ftask = UnityTask.Run(() => { Counter++; return "Hello"; }); yield return ftask; Assert(() => Counter == 10, "Function"); Assert(() => ftask.Result == "Hello", "Function"); //Exception Debug.Log("Exception..."); yield return new WaitForSeconds(1); var etask = UnityTask.Run(() => { Counter++; throw new Exception("Hello"); }); yield return etask; Assert(() => Counter == 11, "Exception"); Assert(() => etask.IsFaulted && etask.Exception.Message == "Hello", "Exception"); //Main Thread log = string.Empty; Debug.Log("Basic Tests Passed"); Debug.Log("Threading Tests..."); Debug.Log("Background...."); yield return new WaitForSeconds(1); yield return UnityTask.Run(() => { UnityTask.Delay(50); Debug.Log("Sleeping..."); UnityTask.Delay(2000); Debug.Log("Slept"); }); yield return 1; Debug.Log("BackgroundToMain"); yield return new WaitForSeconds(1); yield return UnityTask.Run(() => { UnityTask.Delay(100); var task = UnityTask.RunOnMain(() => { Debug.Log("Hello From Main"); }); while (task.IsRunning) { log += "."; UnityTask.Delay(100); } }); yield return 1; Debug.Log("BackgroundToRotine"); yield return new WaitForSeconds(1); yield return UnityTask.Run(() => { var task = UnityTask.RunCoroutine(LongCoroutine()); while (task.IsRunning) { log += "."; UnityTask.Delay(500); } }); yield return 1; Debug.Log("BackgroundToBackground"); yield return new WaitForSeconds(1); yield return UnityTask.Run(() => { Debug.Log("1 Sleeping..."); UnityTask.Run(() => { Debug.Log("2 Sleeping..."); UnityTask.Delay(2000); Debug.Log("2 Slept"); }); UnityTask.Delay(2000); Debug.Log("1 Slept"); }); yield return 1; Debug.Log("Success All"); } IEnumerator DemoCoroutine() { yield return 1; Counter++; } IEnumerator DemoCoroutineWithResult(UnityTask<string> task) { yield return 1; Counter++; task.Result = "Hello"; } public IEnumerator LongCoroutine() { Debug.Log("LongCoroutine"); yield return new WaitForSeconds(5); Debug.Log("/LongCoroutine"); } } }
// <copyright file="PlayGamesPlatform.cs" company="Google Inc."> // Copyright (C) 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> #if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS)) namespace GooglePlayGames { using GooglePlayGames.BasicApi; using GooglePlayGames.BasicApi.Events; using GooglePlayGames.BasicApi.Multiplayer; using GooglePlayGames.BasicApi.Nearby; using GooglePlayGames.BasicApi.Quests; using GooglePlayGames.BasicApi.SavedGame; using GooglePlayGames.OurUtils; using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.SocialPlatforms; /// <summary> /// Provides access to the Google Play Games platform. This is an implementation of /// UnityEngine.SocialPlatforms.ISocialPlatform. Activate this platform by calling /// the <see cref="Activate" /> method, then authenticate by calling /// the <see cref="Authenticate" /> method. After authentication /// completes, you may call the other methods of this class. This is not a complete /// implementation of the ISocialPlatform interface. Methods lacking an implementation /// or whose behavior is at variance with the standard are noted as such. /// </summary> public class PlayGamesPlatform : ISocialPlatform { /// <summary>Singleton instance</summary> private static volatile PlayGamesPlatform sInstance = null; /// <summary>status of nearby connection initialization.</summary> private static volatile bool sNearbyInitializePending; /// <summary>Reference to the nearby client.</summary> /// <remarks>This is static since it can be used without using play game services.</remarks> private static volatile INearbyConnectionClient sNearbyConnectionClient; /// <summary>Configuration used to create this instance.</summary> private readonly PlayGamesClientConfiguration mConfiguration; /// <summary>The local user.</summary> private PlayGamesLocalUser mLocalUser = null; /// <summary>Reference to the platform specific implementation.</summary> private IPlayGamesClient mClient = null; /// <summary>the default leaderboard we show on ShowLeaderboardUI</summary> private string mDefaultLbUi = null; /// <summary>the mapping table from alias to leaderboard/achievement id.</summary> private Dictionary<string, string> mIdMap = new Dictionary<string, string>(); /// <summary> /// Initializes a new instance of the <see cref="GooglePlayGames.PlayGamesPlatform"/> class. /// </summary> /// <param name="client">Implementation client to use for this instance.</param> internal PlayGamesPlatform(IPlayGamesClient client) { this.mClient = Misc.CheckNotNull(client); this.mLocalUser = new PlayGamesLocalUser(this); this.mConfiguration = PlayGamesClientConfiguration.DefaultConfiguration; } /// <summary> /// Initializes a new instance of the <see cref="GooglePlayGames.PlayGamesPlatform"/> class. /// </summary> /// <param name="configuration">Configuration object to use.</param> private PlayGamesPlatform(PlayGamesClientConfiguration configuration) { this.mLocalUser = new PlayGamesLocalUser(this); this.mConfiguration = configuration; } /// <summary> /// Gets or sets a value indicating whether debug logs are enabled. This property /// may be set before calling <see cref="Activate" /> method. /// </summary> /// <returns> /// <c>true</c> if debug log enabled; otherwise, <c>false</c>. /// </returns> public static bool DebugLogEnabled { get { return GooglePlayGames.OurUtils.Logger.DebugLogEnabled; } set { GooglePlayGames.OurUtils.Logger.DebugLogEnabled = value; } } /// <summary> /// Gets the singleton instance of the Play Games platform. /// </summary> /// <returns> /// The instance. /// </returns> public static PlayGamesPlatform Instance { get { if (sInstance == null) { GooglePlayGames.OurUtils.Logger.d( "Instance was not initialized, using default configuration."); InitializeInstance(PlayGamesClientConfiguration.DefaultConfiguration); } return sInstance; } } /// <summary> /// Gets the nearby connection client. NOTE: Can be null until the nearby client /// is initialized. Call InitializeNearby to use callback to be notified when initialization /// is complete. /// </summary> /// <value>The nearby.</value> public static INearbyConnectionClient Nearby { get { if (sNearbyConnectionClient == null && !sNearbyInitializePending) { sNearbyInitializePending = true; InitializeNearby(null); } return sNearbyConnectionClient; } } /// <summary> Gets the real time multiplayer API object</summary> public IRealTimeMultiplayerClient RealTime { get { return mClient.GetRtmpClient(); } } /// <summary> Gets the turn based multiplayer API object</summary> public ITurnBasedMultiplayerClient TurnBased { get { return mClient.GetTbmpClient(); } } /// <summary>Gets the saved game client object.</summary> /// <value>The saved game client.</value> public ISavedGameClient SavedGame { get { return mClient.GetSavedGameClient(); } } /// <summary>Gets the events client object.</summary> /// <value>The events client.</value> public IEventsClient Events { get { return mClient.GetEventsClient(); } } /// <summary>Gets the quests client object.</summary> /// <value>The quests client.</value> public IQuestsClient Quests { get { return mClient.GetQuestsClient(); } } /// <summary> /// Gets the local user. /// </summary> /// <returns> /// The local user. /// </returns> public ILocalUser localUser { get { return mLocalUser; } } /// <summary> /// Initializes the instance of Play Game Services platform. /// </summary> /// <remarks>This creates the singleton instance of the platform. /// Multiple calls to this method are ignored. /// </remarks> /// <param name="configuration">Configuration to use when initializing.</param> public static void InitializeInstance(PlayGamesClientConfiguration configuration) { if (sInstance != null) { GooglePlayGames.OurUtils.Logger.w( "PlayGamesPlatform already initialized. Ignoring this call."); return; } sInstance = new PlayGamesPlatform(configuration); } /// <summary> /// Initializes the nearby connection platform. /// </summary> /// <remarks>This call initializes the nearby connection platform. This /// is independent of the Play Game Services initialization. Multiple /// calls to this method are ignored. /// </remarks> /// <param name="callback">Callback invoked when complete.</param> public static void InitializeNearby(Action<INearbyConnectionClient> callback) { Debug.Log("Calling InitializeNearby!"); if (sNearbyConnectionClient == null) { #if UNITY_ANDROID && !UNITY_EDITOR NearbyConnectionClientFactory.Create(client => { Debug.Log("Nearby Client Created!!"); sNearbyConnectionClient = client; if (callback != null) { callback.Invoke(client); } else { Debug.Log("Initialize Nearby callback is null"); } }); #else sNearbyConnectionClient = new DummyNearbyConnectionClient(); if (callback != null) { callback.Invoke(sNearbyConnectionClient); } #endif } else if (callback != null) { Debug.Log("Nearby Already initialized: calling callback directly"); callback.Invoke(sNearbyConnectionClient); } else { Debug.Log("Nearby Already initialized"); } } /// <summary> /// Activates the Play Games platform as the implementation of Social.Active. /// After calling this method, you can call methods on Social.Active. For /// example, <c>Social.Active.Authenticate()</c>. /// </summary> /// <returns>The singleton <see cref="PlayGamesPlatform" /> instance.</returns> public static PlayGamesPlatform Activate() { GooglePlayGames.OurUtils.Logger.d("Activating PlayGamesPlatform."); Social.Active = PlayGamesPlatform.Instance; GooglePlayGames.OurUtils.Logger.d( "PlayGamesPlatform activated: " + Social.Active); return PlayGamesPlatform.Instance; } /// <summary>Gets pointer to the Google API client.</summary> /// <remarks>This is provided as a helper to making additional JNI calls. /// This connection is initialized and controlled by the underlying SDK. /// </remarks> /// <returns>The pointer of the client. Zero on non-android platforms.</returns> public IntPtr GetApiClient() { return mClient.GetApiClient(); } /// <summary> /// Specifies that the ID <c>fromId</c> should be implicitly replaced by <c>toId</c> /// on any calls that take a leaderboard or achievement ID. /// </summary> /// <remarks> After a mapping is /// registered, you can use <c>fromId</c> instead of <c>toId</c> when making a call. /// For example, the following two snippets are equivalent: /// <code> /// ReportProgress("Cfiwjew894_AQ", 100.0, callback); /// </code> /// ...is equivalent to: /// <code> /// AddIdMapping("super-combo", "Cfiwjew894_AQ"); /// ReportProgress("super-combo", 100.0, callback); /// </code> /// </remarks> /// <param name='fromId'> /// The identifier to map. /// </param> /// <param name='toId'> /// The identifier that <c>fromId</c> will be mapped to. /// </param> public void AddIdMapping(string fromId, string toId) { mIdMap[fromId] = toId; } /// <summary> /// Authenticate the local user with the Google Play Games service. /// </summary> /// <param name='callback'> /// The callback to call when authentication finishes. It will be called /// with <c>true</c> if authentication was successful, <c>false</c> /// otherwise. /// </param> public void Authenticate(Action<bool> callback) { Authenticate(callback, false); } public void Authenticate(Action<bool, string> callback) { Authenticate(callback, false, "auth error"); } public void Authenticate(Action<bool, string> callback, bool silent, string message) { // make a platform-specific Play Games client if (mClient == null) { GooglePlayGames.OurUtils.Logger.d( "Creating platform-specific Play Games client."); mClient = PlayGamesClientFactory.GetPlatformPlayGamesClient(mConfiguration); } // authenticate! Action<bool> c = (bool a) => callback(a, message); mClient.Authenticate(c, silent); } public void Authenticate(ILocalUser unused, Action<bool, string> callback) { Authenticate(callback, false, "auth error"); } /// <summary> /// Authenticate the local user with the Google Play Games service. /// </summary> /// <param name='callback'> /// The callback to call when authentication finishes. It will be called /// with <c>true</c> if authentication was successful, <c>false</c> /// otherwise. /// </param> /// <param name='silent'> /// Indicates whether authentication should be silent. If <c>false</c>, /// authentication may show popups and interact with the user to obtain /// authorization. If <c>true</c>, there will be no popups or interaction with /// the user, and the authentication will fail instead if such interaction /// is required. A typical pattern is to try silent authentication on startup /// and, if that fails, present the user with a "Sign in" button that then /// triggers normal (not silent) authentication. /// </param> public void Authenticate(Action<bool> callback, bool silent) { // make a platform-specific Play Games client if (mClient == null) { GooglePlayGames.OurUtils.Logger.d( "Creating platform-specific Play Games client."); mClient = PlayGamesClientFactory.GetPlatformPlayGamesClient(mConfiguration); } // authenticate! mClient.Authenticate(callback, silent); } /// <summary> /// Provided for compatibility with ISocialPlatform. /// </summary> /// <seealso cref="Authenticate(Action&lt;bool&gt;,bool)"/> /// <param name="unused">Unused parameter for this implementation.</param> /// <param name="callback">Callback invoked when complete.</param> public void Authenticate(ILocalUser unused, Action<bool> callback) { Authenticate(callback, false); } /// <summary> /// Determines whether the user is authenticated. /// </summary> /// <returns> /// <c>true</c> if the user is authenticated; otherwise, <c>false</c>. /// </returns> public bool IsAuthenticated() { return mClient != null && mClient.IsAuthenticated(); } /// <summary>Sign out. After signing out, /// Authenticate must be called again to sign back in. /// </summary> public void SignOut() { if (mClient != null) { mClient.SignOut(); } mLocalUser = new PlayGamesLocalUser(this); } /// <summary> /// Loads the users. /// </summary> /// <param name="userIds">User identifiers.</param> /// <param name="callback">Callback invoked when complete.</param> public void LoadUsers(string[] userIds, Action<IUserProfile[]> callback) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e( "GetUserId() can only be called after authentication."); callback(new IUserProfile[0]); return; } mClient.LoadUsers(userIds, callback); } /// <summary> /// Returns the user's Google ID. /// </summary> /// <returns> /// The user's Google ID. No guarantees are made as to the meaning or format of /// this identifier except that it is unique to the user who is signed in. /// </returns> public string GetUserId() { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e( "GetUserId() can only be called after authentication."); return "0"; } return mClient.GetUserId(); } /// <summary> /// Get an id token for the user. /// </summary> /// <param name="idTokenCallback"> A callback to be invoked after token is retrieved. Will be passed null value /// on failure. </param> public void GetIdToken(Action<string> idTokenCallback) { if (mClient != null) { mClient.GetIdToken(idTokenCallback); } else { GooglePlayGames.OurUtils.Logger.e( "No client available, calling back with null."); idTokenCallback(null); } } /// <summary> /// Returns an id token for the user. /// </summary> /// <returns> /// An id token for the user. /// </returns> public string GetAccessToken() { if (mClient != null) { return mClient.GetAccessToken(); } return null; } /// <summary> /// Gets the server auth code. /// </summary> /// <remarks>This code is used by the server application in order to get /// an oauth token. For how to use this acccess token please see: /// https://developers.google.com/drive/v2/web/auth/web-server /// </remarks> /// <param name="callback">Callback.</param> public void GetServerAuthCode(Action<CommonStatusCodes, string> callback) { if (mClient != null && mClient.IsAuthenticated()) { if (GameInfo.WebClientIdInitialized()) { mClient.GetServerAuthCode(GameInfo.WebClientId, callback); } else { GooglePlayGames.OurUtils.Logger.e( "GetServerAuthCode requires a webClientId."); callback(CommonStatusCodes.DeveloperError, ""); } } else { GooglePlayGames.OurUtils.Logger.e( "GetServerAuthCode can only be called after authentication."); callback(CommonStatusCodes.SignInRequired, ""); } } /// <summary> /// Gets the user's email. /// </summary> /// <remarks>The email address returned is selected by the user from the accounts present /// on the device. There is no guarantee this uniquely identifies the player. /// For unique identification use the id property of the local player. /// The user can also choose to not select any email address, meaning it is not /// available.</remarks> /// <returns>The user email or null if not authenticated or the permission is /// not available.</returns> public string GetUserEmail() { if (mClient != null) { return mClient.GetUserEmail(); } return null; } /// <summary> /// Gets the user's email with a callback. /// </summary> /// <remarks>The email address returned is selected by the user from the accounts present /// on the device. There is no guarantee this uniquely identifies the player. /// For unique identification use the id property of the local player. /// The user can also choose to not select any email address, meaning it is not /// available.</remarks> /// <param name="callback">The callback with a status code of the request, /// and string which is the email. It can be null.</param> public void GetUserEmail(Action<CommonStatusCodes, string> callback) { mClient.GetUserEmail(callback); } /// <summary> /// Gets the player stats. /// </summary> /// <param name="callback">Callback invoked when completed.</param> public void GetPlayerStats(Action<CommonStatusCodes, PlayerStats> callback) { if (mClient != null && mClient.IsAuthenticated()) { mClient.GetPlayerStats(callback); } else { GooglePlayGames.OurUtils.Logger.e( "GetPlayerStats can only be called after authentication."); callback(CommonStatusCodes.SignInRequired, new PlayerStats()); } } /// <summary> /// Returns the achievement corresponding to the passed achievement identifier. /// </summary> /// <returns> /// The achievement corresponding to the identifer. <code>null</code> if no such /// achievement is found or if the user is not authenticated. /// </returns> /// <param name="achievementId"> /// The identifier of the achievement. /// </param> public Achievement GetAchievement(string achievementId) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e( "GetAchievement can only be called after authentication."); return null; } return mClient.GetAchievement(achievementId); } /// <summary> /// Returns the user's display name. /// </summary> /// <returns> /// The user display name (e.g. "Bruno Oliveira") /// </returns> public string GetUserDisplayName() { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e( "GetUserDisplayName can only be called after authentication."); return string.Empty; } return mClient.GetUserDisplayName(); } /// <summary> /// Returns the user's avatar URL if they have one. /// </summary> /// <returns> /// The URL, or <code>null</code> if the user is not authenticated or does not have /// an avatar. /// </returns> public string GetUserImageUrl() { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e( "GetUserImageUrl can only be called after authentication."); return null; } return mClient.GetUserImageUrl(); } /// <summary> /// Reports the progress of an achievement (reveal, unlock or increment). This method attempts /// to implement the expected behavior of ISocialPlatform.ReportProgress as closely as possible, /// as described below. Although this method works with incremental achievements for compatibility /// purposes, calling this method for incremental achievements is not recommended, /// since the Play Games API exposes incremental achievements in a very different way /// than the interface presented by ISocialPlatform.ReportProgress. The implementation of this /// method for incremental achievements attempts to produce the correct result, but may be /// imprecise. If possible, call <see cref="IncrementAchievement" /> instead. /// </summary> /// <param name='achievementID'> /// The ID of the achievement to unlock, reveal or increment. This can be a raw Google Play /// Games achievement ID (alphanumeric string), or an alias that was previously configured /// by a call to <see cref="AddIdMapping" />. /// </param> /// <param name='progress'> /// Progress of the achievement. If the achievement is standard (not incremental), then /// a progress of 0.0 will reveal the achievement and 100.0 will unlock it. Behavior of other /// values is undefined. If the achievement is incremental, then this value is interpreted /// as the total percentage of the achievement's progress that the player should have /// as a result of this call (regardless of the progress they had before). So if the /// player's previous progress was 30% and this call specifies 50.0, the new progress will /// be 50% (not 80%). /// </param> /// <param name='callback'> /// Callback that will be called to report the result of the operation: <c>true</c> on /// success, <c>false</c> otherwise. /// </param> public void ReportProgress(string achievementID, double progress, Action<bool> callback) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e( "ReportProgress can only be called after authentication."); if (callback != null) { callback.Invoke(false); } return; } // map ID, if it's in the dictionary GooglePlayGames.OurUtils.Logger.d( "ReportProgress, " + achievementID + ", " + progress); achievementID = MapId(achievementID); // if progress is 0.0, we just want to reveal it if (progress < 0.000001) { GooglePlayGames.OurUtils.Logger.d( "Progress 0.00 interpreted as request to reveal."); mClient.RevealAchievement(achievementID, callback); return; } // figure out if it's a standard or incremental achievement bool isIncremental = false; int curSteps = 0, totalSteps = 0; Achievement ach = mClient.GetAchievement(achievementID); if (ach == null) { GooglePlayGames.OurUtils.Logger.w( "Unable to locate achievement " + achievementID); GooglePlayGames.OurUtils.Logger.w( "As a quick fix, assuming it's standard."); isIncremental = false; } else { isIncremental = ach.IsIncremental; curSteps = ach.CurrentSteps; totalSteps = ach.TotalSteps; GooglePlayGames.OurUtils.Logger.d( "Achievement is " + (isIncremental ? "INCREMENTAL" : "STANDARD")); if (isIncremental) { GooglePlayGames.OurUtils.Logger.d( "Current steps: " + curSteps + "/" + totalSteps); } } // do the right thing depending on the achievement type if (isIncremental) { // increment it to the target percentage (approximate) GooglePlayGames.OurUtils.Logger.d("Progress " + progress + " interpreted as incremental target (approximate)."); if (progress >= 0.0 && progress <= 1.0) { // in a previous version, incremental progress was reported by using the range [0-1] GooglePlayGames.OurUtils.Logger.w( "Progress " + progress + " is less than or equal to 1. You might be trying to use values in the range of [0,1], while values are expected to be within the range [0,100]. If you are using the latter, you can safely ignore this message."); } int targetSteps = (int)Math.Round((progress / 100f) * totalSteps); int numSteps = targetSteps - curSteps; GooglePlayGames.OurUtils.Logger.d("Target steps: " + targetSteps + ", cur steps:" + curSteps); GooglePlayGames.OurUtils.Logger.d("Steps to increment: " + numSteps); // handle incremental achievements with 0 steps if (numSteps >= 0) { mClient.IncrementAchievement(achievementID, numSteps, callback); } } else if (progress >= 100) { // unlock it! GooglePlayGames.OurUtils.Logger.d( "Progress " + progress + " interpreted as UNLOCK."); mClient.UnlockAchievement(achievementID, callback); } else { // not enough to unlock GooglePlayGames.OurUtils.Logger.d("Progress " + progress + " not enough to unlock non-incremental achievement."); } } /// <summary> /// Increments an achievement. This is a Play Games extension of the ISocialPlatform API. /// </summary> /// <param name='achievementID'> /// The ID of the achievement to increment. This can be a raw Google Play /// Games achievement ID (alphanumeric string), or an alias that was previously configured /// by a call to <see cref="AddIdMapping" />. /// </param> /// <param name='steps'> /// The number of steps to increment the achievement by. /// </param> /// <param name='callback'> /// The callback to call to report the success or failure of the operation. The callback /// will be called with <c>true</c> to indicate success or <c>false</c> for failure. /// </param> public void IncrementAchievement(string achievementID, int steps, Action<bool> callback) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e( "IncrementAchievement can only be called after authentication."); if (callback != null) { callback.Invoke(false); } return; } // map ID, if it's in the dictionary GooglePlayGames.OurUtils.Logger.d( "IncrementAchievement: " + achievementID + ", steps " + steps); achievementID = MapId(achievementID); mClient.IncrementAchievement(achievementID, steps, callback); } /// <summary> /// Set an achievement to have at least the given number of steps completed. /// Calling this method while the achievement already has more steps than /// the provided value is a no-op. Once the achievement reaches the /// maximum number of steps, the achievement is automatically unlocked, /// and any further mutation operations are ignored. /// </summary> /// <param name='achievementID'> /// The ID of the achievement to increment. This can be a raw Google Play /// Games achievement ID (alphanumeric string), or an alias that was previously configured /// by a call to <see cref="AddIdMapping" />. /// </param> /// <param name='steps'> /// The number of steps to increment the achievement by. /// </param> /// <param name='callback'> /// The callback to call to report the success or failure of the operation. The callback /// will be called with <c>true</c> to indicate success or <c>false</c> for failure. /// </param> public void SetStepsAtLeast(string achievementID, int steps, Action<bool> callback) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e( "SetStepsAtLeast can only be called after authentication."); if (callback != null) { callback.Invoke(false); } return; } // map ID, if it's in the dictionary GooglePlayGames.OurUtils.Logger.d( "SetStepsAtLeast: " + achievementID + ", steps " + steps); achievementID = MapId(achievementID); mClient.SetStepsAtLeast(achievementID, steps, callback); } /// <summary> /// Loads the Achievement descriptions. /// </summary> /// <param name="callback">The callback to receive the descriptions</param> public void LoadAchievementDescriptions(Action<IAchievementDescription[]> callback) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e( "LoadAchievementDescriptions can only be called after authentication."); if (callback != null) { callback.Invoke(null); } return; } mClient.LoadAchievements(ach => { IAchievementDescription[] data = new IAchievementDescription[ach.Length]; for (int i = 0; i < data.Length; i++) { data[i] = new PlayGamesAchievement(ach[i]); } callback.Invoke(data); }); } /// <summary> /// Loads the achievement state for the current user. /// </summary> /// <param name="callback">The callback to receive the achievements</param> public void LoadAchievements(Action<IAchievement[]> callback) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e("LoadAchievements can only be called after authentication."); callback.Invoke(null); return; } mClient.LoadAchievements(ach => { IAchievement[] data = new IAchievement[ach.Length]; for (int i = 0; i < data.Length; i++) { data[i] = new PlayGamesAchievement(ach[i]); } callback.Invoke(data); }); } /// <summary> /// Creates an achievement object which may be subsequently used to report an /// achievement. /// </summary> /// <returns> /// The achievement object. /// </returns> public IAchievement CreateAchievement() { return new PlayGamesAchievement(); } /// <summary> /// Reports a score to a leaderboard. /// </summary> /// <param name='score'> /// The score to report. /// </param> /// <param name='board'> /// The ID of the leaderboard on which the score is to be posted. This may be a raw /// Google Play Games leaderboard ID or an alias configured through a call to /// <see cref="AddIdMapping" />. /// </param> /// <param name='callback'> /// The callback to call to report the success or failure of the operation. The callback /// will be called with <c>true</c> to indicate success or <c>false</c> for failure. /// </param> public void ReportScore(long score, string board, Action<bool> callback) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e("ReportScore can only be called after authentication."); if (callback != null) { callback.Invoke(false); } return; } GooglePlayGames.OurUtils.Logger.d("ReportScore: score=" + score + ", board=" + board); string leaderboardId = MapId(board); mClient.SubmitScore(leaderboardId, score, callback); } /// <summary> /// Submits the score for the currently signed-in player /// to the leaderboard associated with a specific id /// and metadata (such as something the player did to earn the score). /// </summary> /// <param name="score">Score to report.</param> /// <param name="board">leaderboard id.</param> /// <param name="metadata">metadata about the score.</param> /// <param name="callback">Callback invoked upon completion.</param> public void ReportScore(long score, string board, string metadata, Action<bool> callback) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e("ReportScore can only be called after authentication."); if (callback != null) { callback.Invoke(false); } return; } GooglePlayGames.OurUtils.Logger.d("ReportScore: score=" + score + ", board=" + board + " metadata=" + metadata); string leaderboardId = MapId(board); mClient.SubmitScore(leaderboardId, score, metadata, callback); } /// <summary> /// Loads the scores relative the player. /// </summary> /// <remarks>This returns the 25 /// (which is the max results returned by the SDK per call) scores /// that are around the player's score on the Public, all time leaderboard. /// Use the overloaded methods which are specific to GPGS to modify these /// parameters. /// </remarks> /// <param name="leaderboardId">Leaderboard Id</param> /// <param name="callback">Callback to invoke when completed.</param> public void LoadScores(string leaderboardId, Action<IScore[]> callback) { LoadScores( leaderboardId, LeaderboardStart.PlayerCentered, mClient.LeaderboardMaxResults(), LeaderboardCollection.Public, LeaderboardTimeSpan.AllTime, (scoreData) => callback(scoreData.Scores)); } /// <summary> /// Loads the scores using the provided parameters. /// </summary> /// <param name="leaderboardId">Leaderboard identifier.</param> /// <param name="start">Start either top scores, or player centered.</param> /// <param name="rowCount">Row count. the number of rows to return.</param> /// <param name="collection">Collection. social or public</param> /// <param name="timeSpan">Time span. daily, weekly, all-time</param> /// <param name="callback">Callback to invoke when completed.</param> public void LoadScores( string leaderboardId, LeaderboardStart start, int rowCount, LeaderboardCollection collection, LeaderboardTimeSpan timeSpan, Action<LeaderboardScoreData> callback) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e("LoadScores can only be called after authentication."); callback(new LeaderboardScoreData( leaderboardId, ResponseStatus.NotAuthorized)); return; } mClient.LoadScores( leaderboardId, start, rowCount, collection, timeSpan, callback); } /// <summary> /// Loads more scores. /// </summary> /// <remarks>This is used to load the next "page" of scores. </remarks> /// <param name="token">Token used to recording the loading.</param> /// <param name="rowCount">Row count.</param> /// <param name="callback">Callback invoked when complete.</param> public void LoadMoreScores( ScorePageToken token, int rowCount, Action<LeaderboardScoreData> callback) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e("LoadMoreScores can only be called after authentication."); callback( new LeaderboardScoreData( token.LeaderboardId, ResponseStatus.NotAuthorized)); return; } mClient.LoadMoreScores(token, rowCount, callback); } /// <summary> /// Returns a leaderboard object that can be configured to /// load scores. /// </summary> /// <returns>The leaderboard object.</returns> public ILeaderboard CreateLeaderboard() { return new PlayGamesLeaderboard(mDefaultLbUi); } /// <summary> /// Shows the standard Google Play Games achievements user interface, /// which allows the player to browse their achievements. /// </summary> public void ShowAchievementsUI() { ShowAchievementsUI(null); } /// <summary> /// Shows the standard Google Play Games achievements user interface, /// which allows the player to browse their achievements. /// </summary> /// <param name="callback">If non-null, the callback is invoked when /// the achievement UI is dismissed</param> public void ShowAchievementsUI(Action<UIStatus> callback) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e("ShowAchievementsUI can only be called after authentication."); return; } GooglePlayGames.OurUtils.Logger.d("ShowAchievementsUI callback is " + callback); mClient.ShowAchievementsUI(callback); } /// <summary> /// Shows the standard Google Play Games leaderboards user interface, /// which allows the player to browse their leaderboards. If you have /// configured a specific leaderboard as the default through a call to /// <see cref="SetDefaultLeaderboardForUi" />, the UI will show that /// specific leaderboard only. Otherwise, a list of all the leaderboards /// will be shown. /// </summary> public void ShowLeaderboardUI() { GooglePlayGames.OurUtils.Logger.d("ShowLeaderboardUI with default ID"); ShowLeaderboardUI(MapId(mDefaultLbUi), null); } /// <summary> /// Shows the standard Google Play Games leaderboard UI for the given /// leaderboard. /// </summary> /// <param name='leaderboardId'> /// The ID of the leaderboard to display. This may be a raw /// Google Play Games leaderboard ID or an alias configured through a call to /// <see cref="AddIdMapping" />. /// </param> public void ShowLeaderboardUI(string leaderboardId) { if (leaderboardId != null) { leaderboardId = MapId(leaderboardId); } mClient.ShowLeaderboardUI(leaderboardId, LeaderboardTimeSpan.AllTime, null); } /// <summary> /// Shows the leaderboard UI and calls the specified callback upon /// completion. /// </summary> /// <param name="leaderboardId">leaderboard ID, can be null meaning all leaderboards.</param> /// <param name="callback">Callback to call. If null, nothing is called.</param> public void ShowLeaderboardUI(string leaderboardId, Action<UIStatus> callback) { ShowLeaderboardUI(leaderboardId, LeaderboardTimeSpan.AllTime, callback); } /// <summary> /// Shows the leaderboard UI and calls the specified callback upon /// completion. /// </summary> /// <param name="leaderboardId">leaderboard ID, can be null meaning all leaderboards.</param> /// <param name="span">Timespan to display scores in the leaderboard.</param> /// <param name="callback">Callback to call. If null, nothing is called.</param> public void ShowLeaderboardUI( string leaderboardId, LeaderboardTimeSpan span, Action<UIStatus> callback) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e("ShowLeaderboardUI can only be called after authentication."); if (callback != null) { callback(UIStatus.NotAuthorized); } return; } GooglePlayGames.OurUtils.Logger.d("ShowLeaderboardUI, lbId=" + leaderboardId + " callback is " + callback); mClient.ShowLeaderboardUI(leaderboardId, span, callback); } /// <summary> /// Sets the default leaderboard for the leaderboard UI. After calling this /// method, a call to <see cref="ShowLeaderboardUI" /> will show only the specified /// leaderboard instead of showing the list of all leaderboards. /// </summary> /// <param name='lbid'> /// The ID of the leaderboard to display on the default UI. This may be a raw /// Google Play Games leaderboard ID or an alias configured through a call to /// <see cref="AddIdMapping" />. /// </param> public void SetDefaultLeaderboardForUI(string lbid) { GooglePlayGames.OurUtils.Logger.d("SetDefaultLeaderboardForUI: " + lbid); if (lbid != null) { lbid = MapId(lbid); } mDefaultLbUi = lbid; } /// <summary> /// Loads the friends that also play this game. See loadConnectedPlayers. /// </summary> /// <remarks>This is a callback variant of LoadFriends. When completed, /// the friends list set in the user object, so they can accessed via the /// friends property as needed. /// </remarks> /// <param name="user">The current local user</param> /// <param name="callback">Callback invoked when complete.</param> public void LoadFriends(ILocalUser user, Action<bool> callback) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e( "LoadScores can only be called after authentication."); if (callback != null) { callback(false); } return; } mClient.LoadFriends(callback); } /// <summary> /// Loads the leaderboard based on the constraints in the leaderboard /// object. /// </summary> /// <param name="board">The leaderboard object. This is created by /// calling CreateLeaderboard(), and then initialized appropriately.</param> /// <param name="callback">Callback invoked when complete.</param> public void LoadScores(ILeaderboard board, Action<bool> callback) { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.e("LoadScores can only be called after authentication."); if (callback != null) { callback(false); } return; } LeaderboardTimeSpan timeSpan; switch (board.timeScope) { case TimeScope.AllTime: timeSpan = LeaderboardTimeSpan.AllTime; break; case TimeScope.Week: timeSpan = LeaderboardTimeSpan.Weekly; break; case TimeScope.Today: timeSpan = LeaderboardTimeSpan.Daily; break; default: timeSpan = LeaderboardTimeSpan.AllTime; break; } ((PlayGamesLeaderboard)board).loading = true; GooglePlayGames.OurUtils.Logger.d("LoadScores, board=" + board + " callback is " + callback); mClient.LoadScores( board.id, LeaderboardStart.PlayerCentered, board.range.count > 0 ? board.range.count : mClient.LeaderboardMaxResults(), board.userScope == UserScope.FriendsOnly ? LeaderboardCollection.Social : LeaderboardCollection.Public, timeSpan, (scoreData) => HandleLoadingScores( (PlayGamesLeaderboard)board, scoreData, callback)); } /// <summary> /// Check if the leaderboard is currently loading. /// </summary> /// <returns><c>true</c>, if loading was gotten, <c>false</c> otherwise.</returns> /// <param name="board">The leaderboard to check for loading in progress</param> public bool GetLoading(ILeaderboard board) { return board != null && board.loading; } /// <summary> /// Register an invitation delegate to be /// notified when a multiplayer invitation arrives /// </summary> /// <param name="deleg">The delegate to register</param> public void RegisterInvitationDelegate(InvitationReceivedDelegate deleg) { mClient.RegisterInvitationDelegate(deleg); } /// <summary> /// Retrieves a bearer token associated with the current account. /// </summary> /// <returns>A bearer token for authorized requests.</returns> public string GetToken() { return mClient.GetToken(); } /// <summary> /// Handles the processing of scores during loading. /// </summary> /// <param name="board">leaderboard being loaded</param> /// <param name="scoreData">Score data.</param> /// <param name="callback">Callback invoked when complete.</param> internal void HandleLoadingScores( PlayGamesLeaderboard board, LeaderboardScoreData scoreData, Action<bool> callback) { bool ok = board.SetFromData(scoreData); if (ok && !board.HasAllScores() && scoreData.NextPageToken != null) { int rowCount = board.range.count - board.ScoreCount; // need to load more scores mClient.LoadMoreScores( scoreData.NextPageToken, rowCount, (nextScoreData) => HandleLoadingScores(board, nextScoreData, callback)); } else { callback(ok); } } /// <summary> /// Internal implmentation of getFriends.Gets the friends. /// </summary> /// <returns>The friends.</returns> internal IUserProfile[] GetFriends() { if (!IsAuthenticated()) { GooglePlayGames.OurUtils.Logger.d("Cannot get friends when not authenticated!"); return new IUserProfile[0]; } return mClient.GetFriends(); } /// <summary> /// Maps the alias to the identifier. /// </summary> /// <remarks>This maps an aliased ID to the actual id. The intent of /// this method is to allow easy to read constants to be used instead of /// the generated ids. /// </remarks> /// <returns>The identifier, or null if not found.</returns> /// <param name="id">Alias to map</param> private string MapId(string id) { if (id == null) { return null; } if (mIdMap.ContainsKey(id)) { string result = mIdMap[id]; GooglePlayGames.OurUtils.Logger.d("Mapping alias " + id + " to ID " + result); return result; } return id; } } } #endif
namespace Antlr.Runtime { using ConditionalAttribute = System.Diagnostics.ConditionalAttribute; internal abstract class Lexer : BaseRecognizer, ITokenSource { protected ICharStream input; public Lexer() { } public Lexer( ICharStream input ) { this.input = input; } public Lexer( ICharStream input, RecognizerSharedState state ) : base(state) { this.input = input; } #region Properties public string Text { get { if ( state.text != null ) { return state.text; } return input.Substring( state.tokenStartCharIndex, CharIndex - state.tokenStartCharIndex ); } set { state.text = value; } } public int Line { get { return input.Line; } set { input.Line = value; } } public int CharPositionInLine { get { return input.CharPositionInLine; } set { input.CharPositionInLine = value; } } #endregion public override void Reset() { base.Reset(); // reset all recognizer state variables // wack Lexer state variables if ( input != null ) { input.Seek( 0 ); // rewind the input } if ( state == null ) { return; // no shared state work to do } state.token = null; state.type = TokenTypes.Invalid; state.channel = TokenChannels.Default; state.tokenStartCharIndex = -1; state.tokenStartCharPositionInLine = -1; state.tokenStartLine = -1; state.text = null; } public virtual IToken NextToken() { for ( ; ; ) { state.token = null; state.channel = TokenChannels.Default; state.tokenStartCharIndex = input.Index; state.tokenStartCharPositionInLine = input.CharPositionInLine; state.tokenStartLine = input.Line; state.text = null; if ( input.LA( 1 ) == CharStreamConstants.EndOfFile ) { IToken eof = new CommonToken((ICharStream)input, CharStreamConstants.EndOfFile, TokenChannels.Default, input.Index, input.Index); eof.Line = Line; eof.CharPositionInLine = CharPositionInLine; return eof; } try { ParseNextToken(); if ( state.token == null ) { Emit(); } else if ( state.token == Tokens.Skip ) { continue; } return state.token; } catch (MismatchedRangeException mre) { ReportError(mre); // MatchRange() routine has already called recover() } catch (MismatchedTokenException mte) { ReportError(mte); // Match() routine has already called recover() } catch ( RecognitionException re ) { ReportError( re ); Recover( re ); // throw out current char and try again } } } public virtual void Skip() { state.token = Tokens.Skip; } public abstract void mTokens(); public virtual ICharStream CharStream { get { return input; } set { input = null; Reset(); input = value; } } public override string SourceName { get { return input.SourceName; } } public virtual void Emit( IToken token ) { state.token = token; } public virtual IToken Emit() { IToken t = new CommonToken( input, state.type, state.channel, state.tokenStartCharIndex, CharIndex - 1 ); t.Line = state.tokenStartLine; t.Text = state.text; t.CharPositionInLine = state.tokenStartCharPositionInLine; Emit( t ); return t; } public virtual void Match( string s ) { int i = 0; while ( i < s.Length ) { if ( input.LA( 1 ) != s[i] ) { if ( state.backtracking > 0 ) { state.failed = true; return; } MismatchedTokenException mte = new MismatchedTokenException(s[i], input, TokenNames); Recover( mte ); throw mte; } i++; input.Consume(); state.failed = false; } } public virtual void MatchAny() { input.Consume(); } public virtual void Match( int c ) { if ( input.LA( 1 ) != c ) { if ( state.backtracking > 0 ) { state.failed = true; return; } MismatchedTokenException mte = new MismatchedTokenException(c, input, TokenNames); Recover( mte ); // don't really recover; just consume in lexer throw mte; } input.Consume(); state.failed = false; } public virtual void MatchRange( int a, int b ) { if ( input.LA( 1 ) < a || input.LA( 1 ) > b ) { if ( state.backtracking > 0 ) { state.failed = true; return; } MismatchedRangeException mre = new MismatchedRangeException(a, b, input); Recover( mre ); throw mre; } input.Consume(); state.failed = false; } public virtual int CharIndex { get { return input.Index; } } public override void ReportError( RecognitionException e ) { DisplayRecognitionError( this.TokenNames, e ); } public override string GetErrorMessage( RecognitionException e, string[] tokenNames ) { string msg = null; if ( e is MismatchedTokenException ) { MismatchedTokenException mte = (MismatchedTokenException)e; msg = "mismatched character " + GetCharErrorDisplay( e.Character ) + " expecting " + GetCharErrorDisplay( mte.Expecting ); } else if ( e is NoViableAltException ) { NoViableAltException nvae = (NoViableAltException)e; // for development, can add "decision=<<"+nvae.grammarDecisionDescription+">>" // and "(decision="+nvae.decisionNumber+") and // "state "+nvae.stateNumber msg = "no viable alternative at character " + GetCharErrorDisplay( e.Character ); } else if ( e is EarlyExitException ) { EarlyExitException eee = (EarlyExitException)e; // for development, can add "(decision="+eee.decisionNumber+")" msg = "required (...)+ loop did not match anything at character " + GetCharErrorDisplay( e.Character ); } else if ( e is MismatchedNotSetException ) { MismatchedNotSetException mse = (MismatchedNotSetException)e; msg = "mismatched character " + GetCharErrorDisplay( e.Character ) + " expecting set " + mse.Expecting; } else if ( e is MismatchedSetException ) { MismatchedSetException mse = (MismatchedSetException)e; msg = "mismatched character " + GetCharErrorDisplay( e.Character ) + " expecting set " + mse.Expecting; } else if ( e is MismatchedRangeException ) { MismatchedRangeException mre = (MismatchedRangeException)e; msg = "mismatched character " + GetCharErrorDisplay( e.Character ) + " expecting set " + GetCharErrorDisplay( mre.A ) + ".." + GetCharErrorDisplay( mre.B ); } else { msg = base.GetErrorMessage( e, tokenNames ); } return msg; } public virtual string GetCharErrorDisplay( int c ) { string s = ( (char)c ).ToString(); switch ( c ) { case TokenTypes.EndOfFile: s = "<EOF>"; break; case '\n': s = "\\n"; break; case '\t': s = "\\t"; break; case '\r': s = "\\r"; break; } return "'" + s + "'"; } public virtual void Recover( RecognitionException re ) { //System.out.println("consuming char "+(char)input.LA(1)+" during recovery"); //re.printStackTrace(); input.Consume(); } [Conditional("ANTLR_TRACE")] public virtual void TraceIn( string ruleName, int ruleIndex ) { string inputSymbol = ( (char)input.LT( 1 ) ) + " line=" + Line + ":" + CharPositionInLine; base.TraceIn( ruleName, ruleIndex, inputSymbol ); } [Conditional("ANTLR_TRACE")] public virtual void TraceOut( string ruleName, int ruleIndex ) { string inputSymbol = ( (char)input.LT( 1 ) ) + " line=" + Line + ":" + CharPositionInLine; base.TraceOut( ruleName, ruleIndex, inputSymbol ); } protected virtual void ParseNextToken() { mTokens(); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V10.Resources { /// <summary>Resource name for the <c>AssetFieldTypeView</c> resource.</summary> public sealed partial class AssetFieldTypeViewName : gax::IResourceName, sys::IEquatable<AssetFieldTypeViewName> { /// <summary>The possible contents of <see cref="AssetFieldTypeViewName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/assetFieldTypeViews/{field_type}</c>. /// </summary> CustomerFieldType = 1, } private static gax::PathTemplate s_customerFieldType = new gax::PathTemplate("customers/{customer_id}/assetFieldTypeViews/{field_type}"); /// <summary>Creates a <see cref="AssetFieldTypeViewName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="AssetFieldTypeViewName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static AssetFieldTypeViewName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new AssetFieldTypeViewName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="AssetFieldTypeViewName"/> with the pattern /// <c>customers/{customer_id}/assetFieldTypeViews/{field_type}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fieldTypeId">The <c>FieldType</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="AssetFieldTypeViewName"/> constructed from the provided ids.</returns> public static AssetFieldTypeViewName FromCustomerFieldType(string customerId, string fieldTypeId) => new AssetFieldTypeViewName(ResourceNameType.CustomerFieldType, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), fieldTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(fieldTypeId, nameof(fieldTypeId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="AssetFieldTypeViewName"/> with pattern /// <c>customers/{customer_id}/assetFieldTypeViews/{field_type}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fieldTypeId">The <c>FieldType</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AssetFieldTypeViewName"/> with pattern /// <c>customers/{customer_id}/assetFieldTypeViews/{field_type}</c>. /// </returns> public static string Format(string customerId, string fieldTypeId) => FormatCustomerFieldType(customerId, fieldTypeId); /// <summary> /// Formats the IDs into the string representation of this <see cref="AssetFieldTypeViewName"/> with pattern /// <c>customers/{customer_id}/assetFieldTypeViews/{field_type}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fieldTypeId">The <c>FieldType</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AssetFieldTypeViewName"/> with pattern /// <c>customers/{customer_id}/assetFieldTypeViews/{field_type}</c>. /// </returns> public static string FormatCustomerFieldType(string customerId, string fieldTypeId) => s_customerFieldType.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(fieldTypeId, nameof(fieldTypeId))); /// <summary> /// Parses the given resource name string into a new <see cref="AssetFieldTypeViewName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/assetFieldTypeViews/{field_type}</c></description></item> /// </list> /// </remarks> /// <param name="assetFieldTypeViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="AssetFieldTypeViewName"/> if successful.</returns> public static AssetFieldTypeViewName Parse(string assetFieldTypeViewName) => Parse(assetFieldTypeViewName, false); /// <summary> /// Parses the given resource name string into a new <see cref="AssetFieldTypeViewName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/assetFieldTypeViews/{field_type}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="assetFieldTypeViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="AssetFieldTypeViewName"/> if successful.</returns> public static AssetFieldTypeViewName Parse(string assetFieldTypeViewName, bool allowUnparsed) => TryParse(assetFieldTypeViewName, allowUnparsed, out AssetFieldTypeViewName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AssetFieldTypeViewName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/assetFieldTypeViews/{field_type}</c></description></item> /// </list> /// </remarks> /// <param name="assetFieldTypeViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="AssetFieldTypeViewName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string assetFieldTypeViewName, out AssetFieldTypeViewName result) => TryParse(assetFieldTypeViewName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AssetFieldTypeViewName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/assetFieldTypeViews/{field_type}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="assetFieldTypeViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="AssetFieldTypeViewName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string assetFieldTypeViewName, bool allowUnparsed, out AssetFieldTypeViewName result) { gax::GaxPreconditions.CheckNotNull(assetFieldTypeViewName, nameof(assetFieldTypeViewName)); gax::TemplatedResourceName resourceName; if (s_customerFieldType.TryParseName(assetFieldTypeViewName, out resourceName)) { result = FromCustomerFieldType(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(assetFieldTypeViewName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private AssetFieldTypeViewName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string customerId = null, string fieldTypeId = null) { Type = type; UnparsedResource = unparsedResourceName; CustomerId = customerId; FieldTypeId = fieldTypeId; } /// <summary> /// Constructs a new instance of a <see cref="AssetFieldTypeViewName"/> class from the component parts of /// pattern <c>customers/{customer_id}/assetFieldTypeViews/{field_type}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="fieldTypeId">The <c>FieldType</c> ID. Must not be <c>null</c> or empty.</param> public AssetFieldTypeViewName(string customerId, string fieldTypeId) : this(ResourceNameType.CustomerFieldType, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), fieldTypeId: gax::GaxPreconditions.CheckNotNullOrEmpty(fieldTypeId, nameof(fieldTypeId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>FieldType</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string FieldTypeId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerFieldType: return s_customerFieldType.Expand(CustomerId, FieldTypeId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as AssetFieldTypeViewName); /// <inheritdoc/> public bool Equals(AssetFieldTypeViewName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(AssetFieldTypeViewName a, AssetFieldTypeViewName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(AssetFieldTypeViewName a, AssetFieldTypeViewName b) => !(a == b); } public partial class AssetFieldTypeView { /// <summary> /// <see cref="AssetFieldTypeViewName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal AssetFieldTypeViewName ResourceNameAsAssetFieldTypeViewName { get => string.IsNullOrEmpty(ResourceName) ? null : AssetFieldTypeViewName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.Controls.DatePicker.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows.Controls { public partial class DatePicker : Control { #region Methods and constructors public DatePicker() { Contract.Ensures(this.DisplayDate.Kind == ((System.DateTimeKind)(2))); } public override void OnApplyTemplate() { } protected virtual new void OnCalendarClosed(System.Windows.RoutedEventArgs e) { } protected virtual new void OnCalendarOpened(System.Windows.RoutedEventArgs e) { } protected override System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer() { return default(System.Windows.Automation.Peers.AutomationPeer); } protected virtual new void OnDateValidationError(DatePickerDateValidationErrorEventArgs e) { } protected virtual new void OnSelectedDateChanged(SelectionChangedEventArgs e) { } #endregion #region Properties and indexers public CalendarBlackoutDatesCollection BlackoutDates { get { return default(CalendarBlackoutDatesCollection); } } public System.Windows.Style CalendarStyle { get { return default(System.Windows.Style); } set { } } public DateTime DisplayDate { get { return default(DateTime); } set { } } public Nullable<DateTime> DisplayDateEnd { get { return default(Nullable<DateTime>); } set { } } public Nullable<DateTime> DisplayDateStart { get { return default(Nullable<DateTime>); } set { } } public DayOfWeek FirstDayOfWeek { get { return default(DayOfWeek); } set { } } public bool IsDropDownOpen { get { return default(bool); } set { } } public bool IsTodayHighlighted { get { return default(bool); } set { } } public Nullable<DateTime> SelectedDate { get { return default(Nullable<DateTime>); } set { } } public DatePickerFormat SelectedDateFormat { get { return default(DatePickerFormat); } set { } } public string Text { get { return default(string); } set { } } #endregion #region Events public event System.Windows.RoutedEventHandler CalendarClosed { add { } remove { } } public event System.Windows.RoutedEventHandler CalendarOpened { add { } remove { } } public event EventHandler<DatePickerDateValidationErrorEventArgs> DateValidationError { add { } remove { } } public event EventHandler<SelectionChangedEventArgs> SelectedDateChanged { add { } remove { } } #endregion #region Fields public readonly static System.Windows.DependencyProperty CalendarStyleProperty; public readonly static System.Windows.DependencyProperty DisplayDateEndProperty; public readonly static System.Windows.DependencyProperty DisplayDateProperty; public readonly static System.Windows.DependencyProperty DisplayDateStartProperty; public readonly static System.Windows.DependencyProperty FirstDayOfWeekProperty; public readonly static System.Windows.DependencyProperty IsDropDownOpenProperty; public readonly static System.Windows.DependencyProperty IsTodayHighlightedProperty; public readonly static System.Windows.RoutedEvent SelectedDateChangedEvent; public readonly static System.Windows.DependencyProperty SelectedDateFormatProperty; public readonly static System.Windows.DependencyProperty SelectedDateProperty; public readonly static System.Windows.DependencyProperty TextProperty; #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // namespace System.Collections.ObjectModel { using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; [Serializable] [System.Runtime.InteropServices.ComVisible(false)] [DebuggerTypeProxy(typeof(Mscorlib_KeyedCollectionDebugView<,>))] [DebuggerDisplay("Count = {Count}")] public abstract class KeyedCollection<TKey,TItem>: Collection<TItem> { const int defaultThreshold = 0; IEqualityComparer<TKey> comparer; Dictionary<TKey,TItem> dict; int keyCount; int threshold; protected KeyedCollection(): this(null, defaultThreshold) {} protected KeyedCollection(IEqualityComparer<TKey> comparer): this(comparer, defaultThreshold) {} protected KeyedCollection(IEqualityComparer<TKey> comparer, int dictionaryCreationThreshold) { if (comparer == null) { comparer = EqualityComparer<TKey>.Default; } if (dictionaryCreationThreshold == -1) { dictionaryCreationThreshold = int.MaxValue; } if( dictionaryCreationThreshold < -1) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.dictionaryCreationThreshold, ExceptionResource.ArgumentOutOfRange_InvalidThreshold); } this.comparer = comparer; this.threshold = dictionaryCreationThreshold; } public IEqualityComparer<TKey> Comparer { get { return comparer; } } public TItem this[TKey key] { get { if( key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if (dict != null) { return dict[key]; } foreach (TItem item in Items) { if (comparer.Equals(GetKeyForItem(item), key)) return item; } ThrowHelper.ThrowKeyNotFoundException(); return default(TItem); } } public bool Contains(TKey key) { if( key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if (dict != null) { return dict.ContainsKey(key); } if (key != null) { foreach (TItem item in Items) { if (comparer.Equals(GetKeyForItem(item), key)) return true; } } return false; } private bool ContainsItem(TItem item) { TKey key; if( (dict == null) || ((key = GetKeyForItem(item)) == null)) { return Items.Contains(item); } TItem itemInDict; bool exist = dict.TryGetValue(key, out itemInDict); if( exist) { return EqualityComparer<TItem>.Default.Equals(itemInDict, item); } return false; } public bool Remove(TKey key) { if( key == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key); } if (dict != null) { if (dict.ContainsKey(key)) { return Remove(dict[key]); } return false; } if (key != null) { for (int i = 0; i < Items.Count; i++) { if (comparer.Equals(GetKeyForItem(Items[i]), key)) { RemoveItem(i); return true; } } } return false; } protected IDictionary<TKey,TItem> Dictionary { get { return dict; } } protected void ChangeItemKey(TItem item, TKey newKey) { // check if the item exists in the collection if( !ContainsItem(item)) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_ItemNotExist); } TKey oldKey = GetKeyForItem(item); if (!comparer.Equals(oldKey, newKey)) { if (newKey != null) { AddKey(newKey, item); } if (oldKey != null) { RemoveKey(oldKey); } } } protected override void ClearItems() { base.ClearItems(); if (dict != null) { dict.Clear(); } keyCount = 0; } protected abstract TKey GetKeyForItem(TItem item); protected override void InsertItem(int index, TItem item) { TKey key = GetKeyForItem(item); if (key != null) { AddKey(key, item); } base.InsertItem(index, item); } protected override void RemoveItem(int index) { TKey key = GetKeyForItem(Items[index]); if (key != null) { RemoveKey(key); } base.RemoveItem(index); } protected override void SetItem(int index, TItem item) { TKey newKey = GetKeyForItem(item); TKey oldKey = GetKeyForItem(Items[index]); if (comparer.Equals(oldKey, newKey)) { if (newKey != null && dict != null) { dict[newKey] = item; } } else { if (newKey != null) { AddKey(newKey, item); } if (oldKey != null) { RemoveKey(oldKey); } } base.SetItem(index, item); } private void AddKey(TKey key, TItem item) { if (dict != null) { dict.Add(key, item); } else if (keyCount == threshold) { CreateDictionary(); dict.Add(key, item); } else { if (Contains(key)) { ThrowHelper.ThrowArgumentException(ExceptionResource.Argument_AddingDuplicate); } keyCount++; } } private void CreateDictionary() { dict = new Dictionary<TKey,TItem>(comparer); foreach (TItem item in Items) { TKey key = GetKeyForItem(item); if (key != null) { dict.Add(key, item); } } } private void RemoveKey(TKey key) { Contract.Assert(key != null, "key shouldn't be null!"); if (dict != null) { dict.Remove(key); } else { keyCount--; } } } }
// Copyright 2017 Google Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; using PolyToolkit; using PolyToolkitInternal; using System; using System.Text.RegularExpressions; namespace PolyToolkitEditor { /// <summary> /// Window that allows the user to browse and import Poly models. /// /// Note that EditorWindow objects are created and deleted when the window is opened or closed, so this /// object can't be responsible for any background logic like importing assets, etc. It should only deal /// with UI. For all background logic and and real work, we rely on AssetBrowserManager. /// </summary> public class AssetBrowserWindow : EditorWindow { /// <summary> /// Title of the window (shown in the Unity UI). /// </summary> private const string WINDOW_TITLE = "Poly Toolkit"; /// <summary> /// URL of the user's profile page. /// </summary> private const string USER_PROFILE_URL = "https://poly.google.com/user"; /// <summary> /// Width and height of each asset thumbnail image in the grid. /// </summary> private const int THUMBNAIL_WIDTH = 128; private const int THUMBNAIL_HEIGHT = 96; /// <summary> /// Width of each grid cell in the assets grid. /// </summary> private const int CELL_WIDTH = THUMBNAIL_WIDTH; /// <summary> /// Spacing between grid cells in the assets grid. /// </summary> private const int CELL_SPACING = 5; /// <summary> /// Height of the title bar at the top of the window. /// </summary> private const int TITLE_BAR_HEIGHT = 64; /// <summary> /// Height of the bar that contains the back button. /// </summary> private const int BACK_BUTTON_BAR_HEIGHT = 28; /// <summary> /// Height of the title image. /// </summary> private const int TITLE_IMAGE_HEIGHT = 40; /// <summary> /// Padding around title image. /// </summary> private const int TITLE_IMAGE_PADDING = 12; /// <summary> /// Margin from the top where the UI begins. /// This does not account for the back button bar. /// </summary> private const int TOP_MARGIN_BASE = TITLE_BAR_HEIGHT + 10; /// <summary> /// Padding around the window. /// </summary> private const int PADDING = 5; /// <summary> /// Size of the user's profile picture. /// </summary> private const int PROFILE_PICTURE_SIZE = 40; /// <summary> /// Size of the left column (labels), in pixels. /// </summary> private const int LEFT_COL_WIDTH = 140; /// <summary> /// Height of the "successfully imported" box. /// </summary> private const int IMPORT_SUCCESS_BOX_HEIGHT = 120; /// <summary> /// Texture to use for the title bar. /// </summary> private const string TITLE_TEX = "Assets/PolyToolkit/Editor/Textures/PolyToolkitTitle.png"; /// <summary> /// Texture to use for the back button (back arrow) if the skin is Unity pro. /// </summary> private const string BACK_ARROW_LIGHT_TEX = "Assets/PolyToolkit/Editor/Textures/BackArrow.png"; /// <summary> /// Texture to use for the back button (back arrow) if the skin is Unity personal. /// </summary> private const string BACK_ARROW_DARK_TEX = "Assets/PolyToolkit/Editor/Textures/BackArrowDark.png"; /// <summary> /// Texture to use for the back button bar background if the skin is Unity pro. /// </summary> private const string DARK_GREY_TEX = "Assets/PolyToolkit/Editor/Textures/DarkGrey.png"; /// <summary> /// Texture to use for the back button bar background if the skin is Unity personal. /// </summary> private const string LIGHT_GREY_TEX = "Assets/PolyToolkit/Editor/Textures/LightGrey.png"; /// <summary> /// Category key corresponding to selecting the "FEATURED" section. /// </summary> private const string KEY_FEATURED = "_featured"; /// <summary> /// Category key corresponding to selecting the "Your Uploads" section. /// </summary> private const string KEY_YOUR_UPLOADS = "_your_uploads"; /// <summary> /// Category key corresponding to selecting the "Your Uploads" section. /// </summary> private const string KEY_YOUR_LIKES = "_your_likes"; /// <summary> /// Index of the "FEATURED" category below. /// </summary> private const int CATEGORY_FEATURED = 0; /// <summary> /// Categories that the user can choose to browse. /// </summary> private static readonly CategoryInfo[] CATEGORIES = { new CategoryInfo(KEY_FEATURED, "Featured", PolyCategory.UNSPECIFIED), new CategoryInfo(KEY_YOUR_UPLOADS, "Your Uploads", PolyCategory.UNSPECIFIED), new CategoryInfo(KEY_YOUR_LIKES, "Your Likes", PolyCategory.UNSPECIFIED), new CategoryInfo("animals", "Animals and Creatures", PolyCategory.ANIMALS), new CategoryInfo("architecture", "Architecture", PolyCategory.ARCHITECTURE), new CategoryInfo("art", "Art", PolyCategory.ART), new CategoryInfo("food", "Food and Drink", PolyCategory.FOOD), new CategoryInfo("nature", "Nature", PolyCategory.NATURE), new CategoryInfo("objects", "Objects", PolyCategory.OBJECTS), new CategoryInfo("people", "People and Characters", PolyCategory.PEOPLE), new CategoryInfo("places", "Places and Scenes", PolyCategory.PLACES), new CategoryInfo("tech", "Technology", PolyCategory.TECH), new CategoryInfo("transport", "Transport", PolyCategory.TRANSPORT), }; /// <summary> /// Represent the several modes that the UI can be in. /// </summary> private enum UiMode { // Browsing assets by category/type (default mode). BROWSE, // Searching for assets by keyword (search box open). SEARCH, // Viewing the details of a particular asset. DETAILS, }; /// <summary> /// Current UI mode. /// </summary> private UiMode mode = UiMode.BROWSE; /// <summary> /// The previous UI mode. /// </summary> private UiMode previousMode = UiMode.BROWSE; /// <summary> /// Index of the category that is currently selected (in CATEGORIES[]). /// </summary> private int selectedCategory = 0; /// <summary> /// The search terms the user has typed in the search box. /// </summary> private string searchTerms = ""; /// <summary> /// The texture to use in place of a thumbnail when loading the thumbnail. /// </summary> private Texture2D loadingTex = null; /// <summary> /// The texture to use for the back button (back arrow). /// </summary> private Texture2D backArrowTex = null; /// <summary> /// Texture used for back button bar background. /// </summary> private Texture2D backBarBackgroundTex = null; /// <summary> /// Reference to the AssetBrowserManager. /// </summary> private AssetBrowserManager manager; /// <summary> /// Current scrolling position of the scroll view with the list of assets. /// </summary> private Vector2 assetListScrollPos; /// <summary> /// Current scrolling position of the details window. /// </summary> private Vector2 detailsScrollPos; /// <summary> /// If non-null, we're showing the details page for the given asset. If null, /// we are showing the grid screen that shows all assets. /// </summary> private PolyAsset selectedAsset = null; /// <summary> /// Indicates whether the query we're currently showing requires authentication. /// </summary> private bool queryRequiresAuth = false; /// <summary> /// The selected asset path in the "Import" section of the details page. /// </summary> private string ptAssetLocalPath = ""; /// <summary> /// Current asset type filter (indicates the type of asset that the user wishes to see). /// </summary> private PolyFormatFilter? assetTypeFilter = null; /// <summary> /// Texture for the title bar. /// </summary> private Texture2D titleTex; /// <summary> /// The style we use for the asset title in the details page. /// </summary> private GUIStyle detailsTitleStyle; /// <summary> /// GUI helper that keeps track of our open layouts. /// </summary> private GUIHelper guiHelper = new GUIHelper(); /// <summary> /// Currently selected import options. /// </summary> private EditTimeImportOptions importOptions; /// <summary> /// If true, the currently displayed asset was just imported successfully. /// </summary> private bool justImported; /// <summary> /// Shows the browser window. /// </summary> [MenuItem("Poly/Browse Assets...")] public static void BrowsePolyAssets() { GetWindow<AssetBrowserWindow>(WINDOW_TITLE, /* focus */ true); PtAnalytics.SendEvent(PtAnalytics.Action.MENU_BROWSE_ASSETS); } /// <summary> /// Shows the browser window. /// </summary> [MenuItem("Window/Poly: Browse Assets...")] public static void BrowsePolyAssets2() { BrowsePolyAssets(); } /// <summary> /// Notifies this window that the given asset was just imported successfully /// (so we can show this state in the UI). /// </summary> /// <param name="assetId">The ID of the asset that was just imported.</param> public void HandleAssetImported(string assetId) { if (selectedAsset != null && assetId == selectedAsset.name) { justImported = true; } } /// <summary> /// Performs one-time initialization. /// </summary> private void Initialize() { PtDebug.Log("ABW: initializing."); if (manager == null) { manager = new AssetBrowserManager(); manager.SetRefreshCallback(UpdateUi); } loadingTex = new Texture2D(192, 192); titleTex = AssetDatabase.LoadAssetAtPath<Texture2D>(TITLE_TEX); backArrowTex = AssetDatabase.LoadAssetAtPath<Texture2D>( EditorGUIUtility.isProSkin ? BACK_ARROW_LIGHT_TEX : BACK_ARROW_DARK_TEX); backBarBackgroundTex = AssetDatabase.LoadAssetAtPath<Texture2D>( EditorGUIUtility.isProSkin ? DARK_GREY_TEX : LIGHT_GREY_TEX); detailsTitleStyle = new GUIStyle(EditorStyles.wordWrappedLabel); detailsTitleStyle.fontSize = 15; detailsTitleStyle.fontStyle = FontStyle.Bold; } private void SetUiMode(UiMode newMode) { if (newMode != mode) { previousMode = mode; mode = newMode; } PtDebug.Log("ABW: changed UI mode to " + newMode); } /// <summary> /// Renders the window GUI (invoked by Unity). /// </summary> public void OnGUI() { if (Application.isPlaying) { DrawTitleBar(/* withSignInUi */ false); GUILayout.Space(TOP_MARGIN_BASE); guiHelper.BeginHorizontal(); GUILayout.FlexibleSpace(); GUILayout.Label("(This window doesn't work in Play mode)", EditorStyles.wordWrappedLabel); GUILayout.FlexibleSpace(); guiHelper.EndHorizontal(); return; } if (manager == null) { // Initialize, if we haven't yet. We delay this to OnGUI instead of earlier because we need // the Unity GUI system to be completely initialized (so we can create styles, for instance), which // only happens on OnGUI(). PolyRequest request = BuildRequest(); manager = new AssetBrowserManager(request); manager.SetRefreshCallback(UpdateUi); Initialize(); } // We have to check if Poly is ready every time (it's cheap to check). This is because Poly can be // unloaded and wiped every time we enter or exit play mode. manager.EnsurePolyIsReady(); int topMargin; if (!DrawHeader(out topMargin)) { // Abort rendering because a button was pressed (for example, the back button). return; } guiHelper.BeginArea(new Rect(PADDING, PADDING, position.width - 2 * PADDING, position.height - 2 * PADDING)); GUILayout.Space(topMargin); switch (mode) { case UiMode.BROWSE: DrawBrowseUi(); break; case UiMode.SEARCH: DrawSearchUi(); break; case UiMode.DETAILS: DrawDetailsUi(); break; default: throw new System.Exception("Invalid UI mode: " + mode); } guiHelper.EndArea(); guiHelper.FinishAndCheck(); } /// <summary> /// Draws the header and handles header-related events (like the back button). /// </summary> /// <param name="topMargin">(Out param). The top margin at which the rest of the content /// should be rendered. Only valid if this method returns true.</param> /// <returns>True if the header was successfully drawn and rendering should continue. /// False if it was aborted due to a back button press.</returns> private bool DrawHeader(out int topMargin) { DrawTitleBar(withSignInUi: true); bool hasBackButtonBar = HasBackButtonBar(); topMargin = TOP_MARGIN_BASE; if (hasBackButtonBar) { bool backButtonClicked = DrawBackButtonBar(); if (backButtonClicked) { HandleBackButton(); return false; } // Increase the top margin of the content to account for the back button bar. topMargin += BACK_BUTTON_BAR_HEIGHT; } return true; } /// <summary> /// Draws the title bar at the top of the window. /// The title bar includes the user's profile picture and the Sign In/Out UI. /// <param name="withSignInUi">If true, also include the sign in/sign out UI.</param> /// </summary> private void DrawTitleBar(bool withSignInUi) { GUI.DrawTexture(new Rect(0, 0, position.width, TITLE_BAR_HEIGHT), Texture2D.whiteTexture); GUIStyle titleStyle = new GUIStyle (GUI.skin.label); titleStyle.margin = new RectOffset(TITLE_IMAGE_PADDING, TITLE_IMAGE_PADDING, TITLE_IMAGE_PADDING, TITLE_IMAGE_PADDING); if (GUILayout.Button(titleTex, titleStyle, GUILayout.Width(titleTex.width * TITLE_IMAGE_HEIGHT / titleTex.height), GUILayout.Height(TITLE_IMAGE_HEIGHT))) { // Clicked title image. Return to the featured assets page. SetUiMode(UiMode.BROWSE); selectedCategory = CATEGORY_FEATURED; StartRequest(); } if (!withSignInUi) return; guiHelper.BeginArea(new Rect(TITLE_IMAGE_PADDING, TITLE_IMAGE_PADDING, position.width - 2 * TITLE_IMAGE_PADDING, TITLE_BAR_HEIGHT)); if (PolyApi.IsAuthenticated) { // User is authenticated, so show the profie picture. guiHelper.BeginHorizontal(); GUILayout.FlexibleSpace(); Texture2D userTex = PolyApi.UserIcon != null && PolyApi.UserIcon.texture != null ? PolyApi.UserIcon.texture : loadingTex; if (GUILayout.Button(new GUIContent(userTex, /* tooltip */ PolyApi.UserName), GUIStyle.none, GUILayout.Width(PROFILE_PICTURE_SIZE), GUILayout.Height(PROFILE_PICTURE_SIZE))) { // Clicked profile picture. Show the dropdown menu. ShowProfileDropdownMenu(); } guiHelper.EndHorizontal(); } else if (PolyApi.IsAuthenticating) { guiHelper.BeginHorizontal(); GUILayout.FlexibleSpace(); GUILayout.Label("Signing in... Please wait."); guiHelper.EndHorizontal(); guiHelper.BeginHorizontal(); GUILayout.FlexibleSpace(); bool cancelSignInClicked = GUILayout.Button("Cancel", EditorStyles.miniButton); guiHelper.EndHorizontal(); if (cancelSignInClicked) { PtAnalytics.SendEvent(PtAnalytics.Action.ACCOUNT_SIGN_IN_CANCEL); manager.CancelSignIn(); } } else { // Not signed in. Show "Sign In" button. GUILayout.Space(30); guiHelper.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Sign in")) { PtAnalytics.SendEvent(PtAnalytics.Action.ACCOUNT_SIGN_IN_START); manager.LaunchSignInFlow(); } guiHelper.EndHorizontal(); } guiHelper.EndArea(); } /// <summary> /// Draws the "browse" UI. The main UI allows the user to select a category to browse and set filters, /// and allows them to browse the assets grid. When they click on an asset, they go to the details UI. /// </summary> private void DrawBrowseUi() { guiHelper.BeginHorizontal(); GUILayout.FlexibleSpace(); bool searchClicked = GUILayout.Button("Search..."); guiHelper.EndHorizontal(); if (searchClicked) { SetUiMode(UiMode.SEARCH); PtAnalytics.SendEvent(PtAnalytics.Action.BROWSE_SEARCH_CLICKED); manager.ClearRequest(); return; } guiHelper.BeginHorizontal(); // Draw the category dropdowns. GUILayout.Label("Show:", GUILayout.Width(LEFT_COL_WIDTH)); if (EditorGUILayout.DropdownButton(new GUIContent(CATEGORIES[selectedCategory].title), FocusType.Keyboard)) { GenericMenu menu = new GenericMenu(); for (int i = 0; i < CATEGORIES.Length; i++) { if (i == 3) menu.AddSeparator(""); menu.AddItem(new GUIContent(CATEGORIES[i].title), i == selectedCategory, DropdownMenuCallback, i); } menu.ShowAsContext(); } guiHelper.EndHorizontal(); // Draw the "Asset type" toggles. bool showAssetTypeFilter = (CATEGORIES[selectedCategory].key != KEY_YOUR_LIKES); if (showAssetTypeFilter) { guiHelper.BeginHorizontal(); GUILayout.Label("Asset type:", GUILayout.Width(LEFT_COL_WIDTH)); bool blocksToggle = GUILayout.Toggle(assetTypeFilter == PolyFormatFilter.BLOCKS, "Blocks", "Button"); bool tiltBrushToggle = GUILayout.Toggle(assetTypeFilter == PolyFormatFilter.TILT, "Tilt Brush", "Button"); bool allToggle = GUILayout.Toggle(assetTypeFilter == null, "All", "Button"); guiHelper.EndHorizontal(); GUILayout.Space(10); if (blocksToggle && assetTypeFilter != PolyFormatFilter.BLOCKS) { assetTypeFilter = PolyFormatFilter.BLOCKS; PtAnalytics.SendEvent(PtAnalytics.Action.BROWSE_ASSET_TYPE_SELECTED, assetTypeFilter.ToString()); StartRequest(); return; } else if (tiltBrushToggle && assetTypeFilter != PolyFormatFilter.TILT) { assetTypeFilter = PolyFormatFilter.TILT; PtAnalytics.SendEvent(PtAnalytics.Action.BROWSE_ASSET_TYPE_SELECTED, assetTypeFilter.ToString()); StartRequest(); return; } else if (allToggle && assetTypeFilter != null) { assetTypeFilter = null; PtAnalytics.SendEvent(PtAnalytics.Action.BROWSE_ASSET_TYPE_SELECTED, assetTypeFilter.ToString()); StartRequest(); return; } } DrawResultsGrid(); } private void HandleBackButton() { switch (mode) { case UiMode.SEARCH: SetUiMode(UiMode.BROWSE); StartRequest(); return; case UiMode.DETAILS: selectedAsset = null; justImported = false; manager.ClearCurrentAssetResult(); SetUiMode(previousMode); return; default: throw new Exception("Invalid UI mode for back button: " + mode); } } private void DrawSearchUi() { bool searchClicked = false; // Pressing ENTER in the search terms box is the same as clicking "Search". We have to check // this BEFORE we draw the text field, otherwise it will consume the event and we won't see it. if (Event.current != null && Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Return && GUI.GetNameOfFocusedControl() == "searchTerms") { searchClicked = true; } GUILayout.Space(10); GUILayout.Label("Search", EditorStyles.boldLabel); GUILayout.Label("Enter search terms (or a Poly URL) below:", EditorStyles.wordWrappedLabel); GUI.SetNextControlName("searchTerms"); searchTerms = EditorGUILayout.TextField(searchTerms, EditorStyles.textArea); guiHelper.BeginHorizontal(); GUILayout.FlexibleSpace(); searchClicked = GUILayout.Button("Search") || searchClicked; guiHelper.EndHorizontal(); if (searchClicked && searchTerms.Trim().Length > 0) { // Note: for privacy reasons we don't log the search terms, just the fact that a search was made. PtAnalytics.SendEvent(PtAnalytics.Action.BROWSE_SEARCHED); string assetId; if (SearchTermIsAssetPage(searchTerms, out assetId)) { manager.StartRequestForSpecificAsset(assetId); SetUiMode(UiMode.DETAILS); return; } StartRequest(); } DrawResultsGrid(); } /// <summary> /// Returns true if the url was a valid asset url, false if not. /// </summary> /// <param name="url">The url of the asset to get.</param> /// <param name="assetId">The id of the asset to get from the url, null if the url is invalid.</param> private bool SearchTermIsAssetPage(string url, out string assetId) { Regex regex = new Regex("^(http[s]?:\\/\\/)?.*\\/view\\/([^?]+)"); Match match = regex.Match(url); if (match.Success) { assetId = match.Groups[2].ToString(); assetId = assetId.Trim(); return true; } assetId = null; return false; } /// <summary> /// Draws the query results grid, using the current query results as reported by /// the AssetsBrowserManager. /// </summary> private void DrawResultsGrid() { if (manager.IsQuerying) { GUILayout.Space(30); GUILayout.Label("Fetching assets. Please wait..."); return; } if (manager.CurrentResult == null) { return; } if (manager.CurrentResult != null && !manager.CurrentResult.Status.ok) { GUILayout.Space(30); GUILayout.Label("There was a problem with that request! Please try again later.", EditorStyles.wordWrappedLabel); guiHelper.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Retry")) { // Retry the previous request. manager.ClearCaches(); StartRequest(); } GUILayout.FlexibleSpace(); guiHelper.EndHorizontal(); return; } if (manager.CurrentResult.Value.assets == null || manager.CurrentResult.Value.assets.Count == 0) { GUILayout.Space(30); GUILayout.Label("No results."); return; } PolyListAssetsResult result = manager.CurrentResult.Value; if (!result.status.ok) { GUILayout.Space(30); GUILayout.Label("*** ERROR fetching results. Try again.."); return; } guiHelper.BeginHorizontal(); string resultCountLabel; resultCountLabel = string.Format("{0} assets found.", result.totalSize); if (result.assets.Count < result.totalSize) { resultCountLabel += string.Format(" (showing 1-{0}).", result.assets.Count); } GUILayout.Label(resultCountLabel, EditorStyles.miniLabel); GUILayout.FlexibleSpace(); bool refreshClicked = GUILayout.Button("Refresh"); guiHelper.EndHorizontal(); GUILayout.Space(5); if (refreshClicked) { PtAnalytics.SendEvent(PtAnalytics.Action.BROWSE_REFRESH_CLICKED); manager.ClearCaches(); StartRequest(); return; } // Calculate how many assets we want to show on each row, based on the window width. // This allows the user to dynamically resize the window and have the assets grid // automatically reflow. int assetsPerRow = Mathf.Clamp( Mathf.FloorToInt((position.width - 40) / (CELL_WIDTH + CELL_SPACING)), 1, 8); int assetsThisRow = 0; // The assets grid is in a scroll view. assetListScrollPos = guiHelper.BeginScrollView(assetListScrollPos); GUILayout.Space(5); guiHelper.BeginVertical(); guiHelper.BeginHorizontal(); PolyAsset clickedAsset = null; foreach (PolyAsset asset in result.assets) { if (assetsThisRow >= assetsPerRow) { // Begin new row. guiHelper.EndHorizontal(); GUILayout.Space(20); guiHelper.BeginHorizontal(); assetsThisRow = 0; } if (assetsThisRow > 0) GUILayout.Space(CELL_SPACING); guiHelper.BeginVertical(); if (GUILayout.Button(asset.thumbnailTexture ?? loadingTex, GUILayout.Width(THUMBNAIL_WIDTH), GUILayout.Height(THUMBNAIL_HEIGHT))) { clickedAsset = asset; } GUILayout.Label(asset.displayName, EditorStyles.boldLabel, GUILayout.Width(CELL_WIDTH)); GUILayout.Label(asset.authorName, GUILayout.Width(CELL_WIDTH)); guiHelper.EndVertical(); assetsThisRow++; } // Complete last row with dummy cells. if (assetsThisRow > 0) { while (assetsThisRow < assetsPerRow) { guiHelper.BeginVertical(); GUILayout.Label("", GUILayout.Width(CELL_WIDTH), GUILayout.Height(THUMBNAIL_HEIGHT)); GUILayout.Label("", EditorStyles.boldLabel, GUILayout.Width(CELL_WIDTH)); GUILayout.Label("", GUILayout.Width(CELL_WIDTH)); guiHelper.EndVertical(); assetsThisRow++; } } guiHelper.EndHorizontal(); GUILayout.Space(10); bool loadMoreClicked = false; if (manager.resultHasMorePages) { // If the current response has at least another page of results left, show the load more button. guiHelper.BeginHorizontal(); GUILayout.FlexibleSpace(); loadMoreClicked = GUILayout.Button("Load more"); GUILayout.FlexibleSpace(); guiHelper.EndHorizontal(); } GUILayout.Space(5); guiHelper.EndVertical(); guiHelper.EndScrollView(); if (loadMoreClicked) { manager.GetNextPageRequest(); return; } if (clickedAsset != null) { PrepareDetailsUi(clickedAsset); PtAnalytics.SendEvent(PtAnalytics.Action.BROWSE_ASSET_DETAILS_CLICKED, GetAssetFormatDescription(selectedAsset)); SetUiMode(UiMode.DETAILS); } } /// <summary> /// Called as a callback by AssetBrowserManager whenever something interesting changes which /// requires us to update our UI. /// </summary> private void UpdateUi() { // Tell Unity to repaint this window, which will invoke OnGUI(). Repaint(); } /// <summary> /// Returns whether or not the given category requires authentication. /// </summary> private bool CategoryRequiresAuth(int category) { string key = CATEGORIES[category].key; return (key == KEY_YOUR_UPLOADS || key == KEY_YOUR_LIKES); } /// <summary> /// Shows the profile dropdown menu (the dropdown menu that appears when the user clicks their profile /// picture). /// </summary> private void ShowProfileDropdownMenu() { GenericMenu menu = new GenericMenu(); menu.AddItem(new GUIContent("My Profile (web)"), /* on */ false, () => { PtAnalytics.SendEvent(PtAnalytics.Action.ACCOUNT_VIEW_PROFILE); Application.OpenURL(USER_PROFILE_URL); }); menu.AddSeparator(""); menu.AddItem(new GUIContent("Sign Out"), /* on */ false, () => { PolyApi.SignOut(); PtAnalytics.SendEvent(PtAnalytics.Action.ACCOUNT_SIGN_OUT); // If the user was viewing a category that requires sign in, reset back to the home page. if (queryRequiresAuth) { selectedCategory = CATEGORY_FEATURED; StartRequest(); } }); menu.ShowAsContext(); } /// <summary> /// Callback invoked when the user picks a new category from the category dropdown. /// </summary> /// <param name="userData">The index of the selected category.</param> private void DropdownMenuCallback(object userData) { int selection = (int)userData; if (selection == selectedCategory) return; // If the user picked a category that requires authentication, and they are not authenticated, // tell them why they can't view it. if (CategoryRequiresAuth(selection) && !PolyApi.IsAuthenticated) { PtAnalytics.SendEvent(PtAnalytics.Action.BROWSE_MISSING_AUTH); EditorUtility.DisplayDialog("Sign in required", "To view your uploads or likes, you must sign in first.", "OK"); return; } selectedCategory = (int)userData; PtAnalytics.SendEvent(PtAnalytics.Action.BROWSE_CATEGORY_SELECTED, CATEGORIES[selectedCategory].key); StartRequest(); } /// <summary> /// Builds and returns a PolyRequest from the current state of the AssetBrowswerWindow variables. /// </summary> private PolyRequest BuildRequest() { CategoryInfo info = CATEGORIES[selectedCategory]; if (info.key == KEY_YOUR_UPLOADS) { PolyListUserAssetsRequest listUserAssetsRequest = PolyListUserAssetsRequest.MyNewest(); listUserAssetsRequest.formatFilter = assetTypeFilter; return listUserAssetsRequest; } if (info.key == KEY_YOUR_LIKES) { PolyListLikedAssetsRequest listLikedAssetsRequest = PolyListLikedAssetsRequest.MyLiked(); return listLikedAssetsRequest; } PolyListAssetsRequest listAssetsRequest; if (info.key == KEY_FEATURED) { listAssetsRequest = PolyListAssetsRequest.Featured(); } else { listAssetsRequest = new PolyListAssetsRequest(); listAssetsRequest.category = info.polyCategory; } listAssetsRequest.formatFilter = assetTypeFilter; // Only show curated results. listAssetsRequest.curated = true; return listAssetsRequest; } /// <summary> /// Sends a list assets request to the assets service according to the parameters currently selected in the UI. /// When the request is done, AssetBrowserManager will inform us through the callback. /// </summary> private void StartRequest() { if (mode == UiMode.BROWSE) { PolyRequest request = BuildRequest(); queryRequiresAuth = CategoryRequiresAuth(selectedCategory); if (!queryRequiresAuth || PolyApi.IsAuthenticated) { manager.StartRequest(request); } } else if (mode == UiMode.SEARCH) { PolyListAssetsRequest request = new PolyListAssetsRequest(); request.keywords = searchTerms; manager.StartRequest(request); } else { throw new System.Exception("Unexpected UI mode for StartQuery: " + mode); } // Reset scroll bar position. assetListScrollPos = Vector2.zero; } /// <summary> /// Set the variables of the details ui page for the newly selected asset. /// </summary> private void PrepareDetailsUi(PolyAsset newSelectedAsset) { selectedAsset = newSelectedAsset; ptAssetLocalPath = PtUtils.GetDefaultPtAssetPath(selectedAsset); detailsScrollPos = Vector2.zero; importOptions = PtSettings.Instance.defaultImportOptions; } /// <summary> /// Draws the asset details page. This is the page that shows the details about the selected asset /// and allows the user to click to import it. /// </summary> private void DrawDetailsUi() { if (manager.IsQuerying) { // Check if manager is querying for a specific asset. GUILayout.Space(30); GUILayout.Label("Fetching asset. Please wait..."); selectedAsset = null; return; } // If we just got the specific asset result, set the details ui import options to the relevant // variables at first. if (manager.CurrentAssetResult != null && selectedAsset == null) { PrepareDetailsUi(manager.CurrentAssetResult); } // Check if the user selected something in the PtAsset picker. if (Event.current != null && Event.current.commandName == "ObjectSelectorUpdated") { UnityEngine.Object picked = EditorGUIUtility.GetObjectPickerObject(); ptAssetLocalPath = (picked != null && picked is PtAsset) ? AssetDatabase.GetAssetPath(picked) : PtUtils.GetDefaultPtAssetPath(selectedAsset); PtAnalytics.SendEvent(PtAnalytics.Action.IMPORT_LOCATION_CHANGED); } if (selectedAsset == null) { manager.ClearCurrentAssetResult(); GUILayout.Space(20); GUILayout.Label("Asset not found."); return; } detailsScrollPos = guiHelper.BeginScrollView(detailsScrollPos); const float width = 150; guiHelper.BeginHorizontal(); GUILayout.Label(selectedAsset.displayName, detailsTitleStyle); guiHelper.EndHorizontal(); guiHelper.BeginHorizontal(); GUILayout.Label(selectedAsset.authorName, EditorStyles.wordWrappedLabel); GUILayout.FlexibleSpace(); if (GUILayout.Button("View on Web", GUILayout.MaxWidth(100))) { PtAnalytics.SendEvent(PtAnalytics.Action.BROWSE_VIEW_ON_WEB); Application.OpenURL(selectedAsset.Url); } GUILayout.Space(5); guiHelper.EndHorizontal(); GUILayout.Space(10); Texture2D image = selectedAsset.thumbnailTexture ?? loadingTex; float displayWidth = position.width - 40; float displayHeight = image.height * displayWidth / image.width; displayHeight = Mathf.Min(image.height, displayHeight); displayWidth = Mathf.Min(image.width, displayWidth); GUILayout.Label(image, GUILayout.Width(displayWidth), GUILayout.Height(displayHeight)); if (manager.IsDownloadingAsset(selectedAsset)) { guiHelper.BeginHorizontal(); GUILayout.FlexibleSpace(); GUILayout.Label("Downloading asset. Please wait..."); GUILayout.FlexibleSpace(); guiHelper.EndHorizontal(); guiHelper.EndScrollView(); return; } else if (justImported) { Rect lastRect = GUILayoutUtility.GetLastRect(); Rect boxRect = new Rect(PADDING, lastRect.yMax + PADDING, position.width - 2 * PADDING, IMPORT_SUCCESS_BOX_HEIGHT); GUI.DrawTexture(boxRect, backBarBackgroundTex); GUILayout.Space(20); guiHelper.BeginHorizontal(); GUILayout.FlexibleSpace(); guiHelper.BeginVertical(); GUILayout.Label("Asset successfully imported."); GUILayout.Label("Saved to: " + PtSettings.Instance.assetObjectsPath); GUILayout.Space(10); if (GUILayout.Button("OK")) { // Dismiss. justImported = false; } guiHelper.EndVertical(); GUILayout.FlexibleSpace(); guiHelper.EndHorizontal(); guiHelper.EndScrollView(); return; } GUILayout.Space(5); GUILayout.Label("Import Options", EditorStyles.boldLabel); GUILayout.Space(5); guiHelper.BeginHorizontal(); GUILayout.Space(12); GUILayout.Label("Import Location", GUILayout.Width(width)); GUILayout.FlexibleSpace(); GUILayout.Label(ptAssetLocalPath, EditorStyles.wordWrappedLabel); GUILayout.Space(5); guiHelper.EndHorizontal(); guiHelper.BeginHorizontal(); GUILayout.Space(width - 10); GUILayout.FlexibleSpace(); if (GUILayout.Button("Replace existing...")) { PtAsset current = AssetDatabase.LoadAssetAtPath<PtAsset>(ptAssetLocalPath); EditorGUIUtility.ShowObjectPicker<PtAsset>(current, /* allowSceneObjects */ false, PtAsset.FilterString, 0); } GUILayout.Space(5); guiHelper.EndHorizontal(); EditTimeImportOptions oldOptions = importOptions; importOptions = ImportOptionsGui.ImportOptionsField(importOptions); if (oldOptions.alsoInstantiate != importOptions.alsoInstantiate) { // Persist 'always instantiate' option if it was changed. PtSettings.Instance.defaultImportOptions.alsoInstantiate = importOptions.alsoInstantiate; } SendImportOptionMutationAnalytics(oldOptions, importOptions); GUILayout.Space(10); GUILayout.Box("", GUILayout.ExpandWidth(true), GUILayout.Height(1)); GUILayout.Space(10); guiHelper.BeginHorizontal(); GUIStyle buttonStyle = new GUIStyle(GUI.skin.button); buttonStyle.fontStyle = FontStyle.Bold; buttonStyle.padding = new RectOffset(10, 10, 8, 8); bool importButtonClicked = GUILayout.Button("Import into Project", buttonStyle); GUILayout.FlexibleSpace(); guiHelper.EndHorizontal(); GUILayout.Space(5); if (!File.Exists(PtUtils.ToAbsolutePath(ptAssetLocalPath))) { GUILayout.Label(PolyInternalUtils.ATTRIBUTION_NOTICE, EditorStyles.wordWrappedLabel); } else { GUILayout.Label("WARNING: The indicated asset already exists and will be OVERWRITTEN by " + "the new asset. Existing instances of the old asset will be automatically updated " + "to the new asset.", EditorStyles.wordWrappedLabel); } guiHelper.EndScrollView(); if (importButtonClicked) { if (!ptAssetLocalPath.StartsWith("Assets/") || !ptAssetLocalPath.EndsWith(".asset")) { EditorUtility.DisplayDialog("Invalid import path", "The import path must begin with Assets/ and have the .asset extension.", "OK"); return; } string errorString; if (!ValidateImportOptions(importOptions.baseOptions, out errorString)) { EditorUtility.DisplayDialog("Invalid import options", errorString, "OK"); return; } PtAnalytics.SendEvent(PtAnalytics.Action.IMPORT_STARTED, GetAssetFormatDescription(selectedAsset)); if (previousMode == UiMode.SEARCH) { PtAnalytics.SendEvent(PtAnalytics.Action.IMPORT_STARTED_FROM_SEARCH, GetAssetFormatDescription(selectedAsset)); } manager.StartDownloadAndImport(selectedAsset, ptAssetLocalPath, importOptions); } } /// <summary> /// Returns whether the import options are valid and, if not, a relevant error message to display. /// </summary> private bool ValidateImportOptions(PolyImportOptions options, out string errorString) { switch (options.rescalingMode) { case PolyImportOptions.RescalingMode.CONVERT: if (options.scaleFactor == 0.0f) { errorString = "Scale factor must not be 0."; return false; } break; case PolyImportOptions.RescalingMode.FIT: if (options.desiredSize == 0.0f) { errorString = "Desired size must not be 0."; return false; } break; default: throw new System.Exception("Import options must hvae a valid rescaling mode"); } errorString = null; return true; } /// <summary> /// Returns true if the current UI mode has a back button bar. /// </summary> /// <returns>True if the current UI mode has a back button bar, false otherwise.</returns> private bool HasBackButtonBar() { return mode == UiMode.DETAILS || mode == UiMode.SEARCH; } /// <summary> /// Draws the "Back" button bar. /// </summary> /// <returns>True if the back button was clicked, false otherwise.</returns> private bool DrawBackButtonBar() { guiHelper.BeginArea(new Rect(0, TITLE_BAR_HEIGHT, position.width, BACK_BUTTON_BAR_HEIGHT)); GUI.DrawTexture(new Rect(0, 0, position.width, BACK_BUTTON_BAR_HEIGHT), backBarBackgroundTex); guiHelper.BeginHorizontal(); GUILayout.Space(PADDING); bool backButtonClicked = GUILayout.Button(new GUIContent("Back", backArrowTex), EditorStyles.miniLabel); GUILayout.FlexibleSpace(); guiHelper.EndHorizontal(); guiHelper.EndArea(); return backButtonClicked; } /// <summary> /// Returns a string with all the asset formats of the given asset. /// </summary> /// <param name="asset">The asset.</param> /// <returns>A string with all the comma-separated asset formats of the given asset.</returns> private string GetAssetFormatDescription(PolyAsset asset) { List<string> formatTypes = new List<string>(); if (asset.formats != null) { foreach (PolyFormat format in asset.formats) { formatTypes.Add(format.formatType.ToString()); } } else { // Shouldn't happen [tm]. formatTypes.Add("NULL"); } formatTypes.Sort(); return string.Join(",", formatTypes.ToArray()); } /// <summary> /// Sends Analytics events for mutations in the given import options. /// </summary> /// <param name="before">The options before the mutation.</param> /// <param name="after">The options after the mutation.</param> private void SendImportOptionMutationAnalytics(EditTimeImportOptions before, EditTimeImportOptions after) { if (before.alsoInstantiate != after.alsoInstantiate) { PtAnalytics.SendEvent(PtAnalytics.Action.IMPORT_INSTANTIATE_TOGGLED, after.alsoInstantiate.ToString()); } if (before.baseOptions.desiredSize != after.baseOptions.desiredSize) { PtAnalytics.SendEvent(PtAnalytics.Action.IMPORT_DESIRED_SIZE_SET, after.baseOptions.desiredSize.ToString()); } if (before.baseOptions.recenter != after.baseOptions.recenter) { PtAnalytics.SendEvent(PtAnalytics.Action.IMPORT_RECENTER_TOGGLED, after.baseOptions.recenter.ToString()); } if (before.baseOptions.rescalingMode != after.baseOptions.rescalingMode) { PtAnalytics.SendEvent(PtAnalytics.Action.IMPORT_SCALE_MODE_CHANGED, after.baseOptions.rescalingMode.ToString()); } if (before.baseOptions.scaleFactor != after.baseOptions.scaleFactor) { PtAnalytics.SendEvent(PtAnalytics.Action.IMPORT_SCALE_FACTOR_CHANGED, after.baseOptions.scaleFactor.ToString()); } } private void OnDestroy() { PtDebug.Log("ABW: destroying."); manager.SetRefreshCallback(null); } private struct CategoryInfo { public string key; public string title; public PolyCategory polyCategory; public CategoryInfo(string key, string title, PolyCategory polyCategory = PolyCategory.UNSPECIFIED) { this.key = key; this.title = title; this.polyCategory = polyCategory; } } } }
namespace FakeItEasy.Specs { using System; using FakeItEasy.Configuration; using FakeItEasy.Tests.TestHelpers; using FluentAssertions; using Xbehave; using Xunit; public static class OrderedCallMatchingSpecs { public interface IFoo { void Bar(int baz); } public interface ISomething { void SomethingMethod(); } public interface ISomethingBaz : ISomething { void BazMethod(); } public interface ISomethingQux : ISomething { void QuxMethod(); } [Scenario] public static void OrderedAssertionsInOrder(IFoo fake, Exception exception) { "Given a Fake" .x(() => fake = A.Fake<IFoo>()); "And a call on the Fake, passing argument 1" .x(() => fake.Bar(1)); "And a call on the Fake, passing argument 1" .x(() => fake.Bar(1)); "And a call on the Fake, passing argument 2" .x(() => fake.Bar(2)); "And a call on the Fake, passing argument 3" .x(() => fake.Bar(3)); "When I assert that a call with argument 1 was made twice exactly, then a call with argument 2, and then a call with argument 3" .x(() => exception = Record.Exception(() => A.CallTo(() => fake.Bar(1)).MustHaveHappenedTwiceExactly() .Then(A.CallTo(() => fake.Bar(2)).MustHaveHappened()) .Then(A.CallTo(() => fake.Bar(3)).MustHaveHappened()))); "Then the assertion should pass" .x(() => exception.Should().BeNull()); } [Scenario] public static void OrderedAssertionsOutOfOrder(IFoo fake, Exception exception) { "Given a Fake" .x(() => fake = A.Fake<IFoo>()); "And a call on the Fake, passing argument 3" .x(() => fake.Bar(3)); "And a call on the Fake, passing argument 1" .x(() => fake.Bar(1)); "And a call on the Fake, passing argument 1" .x(() => fake.Bar(1)); "And a call on the Fake, passing argument 2" .x(() => fake.Bar(2)); "When I assert that a call with argument 1 was made twice exactly, then a call with argument 2, and then a call with argument 3" .x(() => exception = Record.Exception(() => A.CallTo(() => fake.Bar(1)).MustHaveHappenedTwiceExactly() .Then(A.CallTo(() => fake.Bar(2)).MustHaveHappened()) .Then(A.CallTo(() => fake.Bar(3)).MustHaveHappened()))); "Then the assertion should fail" .x(() => exception.Should().BeAnExceptionOfType<ExpectationException>().WithMessageModuloLineEndings(@" Assertion failed for the following calls: 'FakeItEasy.Specs.OrderedCallMatchingSpecs+IFoo.Bar(baz: 1)' twice exactly 'FakeItEasy.Specs.OrderedCallMatchingSpecs+IFoo.Bar(baz: 2)' once or more 'FakeItEasy.Specs.OrderedCallMatchingSpecs+IFoo.Bar(baz: 3)' once or more The calls were found but not in the correct order among the calls: 1: FakeItEasy.Specs.OrderedCallMatchingSpecs+IFoo.Bar(baz: 3) 2: FakeItEasy.Specs.OrderedCallMatchingSpecs+IFoo.Bar(baz: 1) 2 times ... 4: FakeItEasy.Specs.OrderedCallMatchingSpecs+IFoo.Bar(baz: 2)")); } [Scenario] public static void OrderedAssertionsOnDifferentObjectsInOrder(IFoo fake1, IFoo fake2, Exception exception) { "Given a Fake" .x(() => fake1 = A.Fake<IFoo>()); "And another Fake of the same type" .x(() => fake2 = A.Fake<IFoo>()); "And a call on the first Fake, passing argument 1" .x(() => fake1.Bar(1)); "And a call on the second Fake, passing argument 1" .x(() => fake2.Bar(1)); "And a call on the first Fake, passing argument 2" .x(() => fake1.Bar(2)); "When I assert that a call with argument 1 was made on the first Fake, then on the second, and then that a call with argument 2 was made on the first Fake" .x(() => exception = Record.Exception(() => A.CallTo(() => fake1.Bar(1)).MustHaveHappened() .Then(A.CallTo(() => fake2.Bar(1)).MustHaveHappened()) .Then(A.CallTo(() => fake1.Bar(2)).MustHaveHappened()))); "Then the assertion should pass" .x(() => exception.Should().BeNull()); } [Scenario] public static void OrderedAssertionsOnDifferentObjectsOutOfOrder(IFoo fake1, IFoo fake2, Exception exception) { "Given a Fake" .x(() => fake1 = A.Fake<IFoo>()); "And another Fake of the same type" .x(() => fake2 = A.Fake<IFoo>()); "And a call on the second Fake, passing argument 1" .x(() => fake2.Bar(1)); "And a call on the first Fake, passing argument 1" .x(() => fake1.Bar(1)); "And a call on the first Fake, passing argument 2" .x(() => fake1.Bar(2)); "When I assert that a call with argument 1 was made on the first Fake, then on the second, and then that a call with argument 2 was made on the first Fake" .x(() => exception = Record.Exception(() => A.CallTo(() => fake1.Bar(1)).MustHaveHappened() .Then(A.CallTo(() => fake2.Bar(1)).MustHaveHappened()) .Then(A.CallTo(() => fake1.Bar(2)).MustHaveHappened()))); "Then the assertion should fail" .x(() => exception.Should().BeAnExceptionOfType<ExpectationException>().WithMessageModuloLineEndings(@" Assertion failed for the following calls: 'FakeItEasy.Specs.OrderedCallMatchingSpecs+IFoo.Bar(baz: 1)' once or more 'FakeItEasy.Specs.OrderedCallMatchingSpecs+IFoo.Bar(baz: 1)' once or more The calls were found but not in the correct order among the calls: 1: FakeItEasy.Specs.OrderedCallMatchingSpecs+IFoo.Bar(baz: 1) 2: FakeItEasy.Specs.OrderedCallMatchingSpecs+IFoo.Bar(baz: 1) 3: FakeItEasy.Specs.OrderedCallMatchingSpecs+IFoo.Bar(baz: 2) ")); } [Scenario] public static void OrderedAssertionsOnDifferentNamedObjectsOutOfOrder(IFoo fake1, IFoo fake2, Exception exception) { "Given a named Fake" .x(() => fake1 = A.Fake<IFoo>(o => o.Named("Foo1"))); "And another named Fake of the same type" .x(() => fake2 = A.Fake<IFoo>(o => o.Named("Foo2"))); "And a call on the second Fake, passing argument 1" .x(() => fake2.Bar(1)); "And a call on the first Fake, passing argument 1" .x(() => fake1.Bar(1)); "And a call on the first Fake, passing argument 2" .x(() => fake1.Bar(2)); "When I assert that a call with argument 1 was made on the first Fake, then on the second, and then that a call with argument 2 was made on the first Fake" .x(() => exception = Record.Exception(() => A.CallTo(() => fake1.Bar(1)).MustHaveHappened() .Then(A.CallTo(() => fake2.Bar(1)).MustHaveHappened()) .Then(A.CallTo(() => fake1.Bar(2)).MustHaveHappened()))); "Then the assertion should fail" .x(() => exception.Should().BeAnExceptionOfType<ExpectationException>().WithMessageModuloLineEndings(@" Assertion failed for the following calls: 'FakeItEasy.Specs.OrderedCallMatchingSpecs+IFoo.Bar(baz: 1) on Foo1' once or more 'FakeItEasy.Specs.OrderedCallMatchingSpecs+IFoo.Bar(baz: 1) on Foo2' once or more The calls were found but not in the correct order among the calls: 1: FakeItEasy.Specs.OrderedCallMatchingSpecs+IFoo.Bar(baz: 1) on Foo2 2: FakeItEasy.Specs.OrderedCallMatchingSpecs+IFoo.Bar(baz: 1) on Foo1 3: FakeItEasy.Specs.OrderedCallMatchingSpecs+IFoo.Bar(baz: 2) on Foo1 ")); } [Scenario] public static void MultistepOrderedAssertionsInOrder( IFoo fake, Exception exception, IOrderableCallAssertion lastAssertion) { "Given a Fake" .x(() => fake = A.Fake<IFoo>()); "And a call on the Fake, passing argument 1" .x(() => fake.Bar(1)); "And a call on the Fake, passing argument 2" .x(() => fake.Bar(2)); "And a call on the Fake, passing argument 2" .x(() => fake.Bar(2)); "And a call on the Fake, passing argument 3" .x(() => fake.Bar(3)); "When I assert that a call with argument 1 was made once exactly" .x(() => lastAssertion = A.CallTo(() => fake.Bar(1)).MustHaveHappenedOnceExactly()); "And then a call with argument 2" .x(() => lastAssertion = lastAssertion.Then(A.CallTo(() => fake.Bar(2)).MustHaveHappened())); "And then a call with argument 3 once exactly" .x(() => exception = Record.Exception(() => lastAssertion.Then(A.CallTo(() => fake.Bar(3)).MustHaveHappenedOnceExactly()))); "Then the assertions should pass" .x(() => exception.Should().BeNull()); } [Scenario] public static void MultistepOrderedAssertionsOutOfOrder( IFoo fake, Exception exception, IOrderableCallAssertion lastAssertion) { "Given a Fake" .x(() => fake = A.Fake<IFoo>()); "And a call on the Fake, passing argument 3" .x(() => fake.Bar(3)); "And a call on the Fake, passing argument 1" .x(() => fake.Bar(1)); "And a call on the Fake, passing argument 1" .x(() => fake.Bar(1)); "And a call on the Fake, passing argument 2" .x(() => fake.Bar(2)); "When I assert that a call with argument 1 was made twice exactly" .x(() => lastAssertion = A.CallTo(() => fake.Bar(1)).MustHaveHappenedTwiceExactly()); "And then a call with argument 2" .x(() => lastAssertion = lastAssertion.Then(A.CallTo(() => fake.Bar(2)).MustHaveHappened())); "And then that a call with argument 3 was made once exactly" .x(() => exception = Record.Exception(() => lastAssertion.Then(A.CallTo(() => fake.Bar(3)).MustHaveHappenedOnceExactly()))); "Then the last assertion should fail" .x(() => exception.Should().BeAnExceptionOfType<ExpectationException>().WithMessageModuloLineEndings(@" Assertion failed for the following calls: 'FakeItEasy.Specs.OrderedCallMatchingSpecs+IFoo.Bar(baz: 1)' twice exactly 'FakeItEasy.Specs.OrderedCallMatchingSpecs+IFoo.Bar(baz: 2)' once or more 'FakeItEasy.Specs.OrderedCallMatchingSpecs+IFoo.Bar(baz: 3)' once exactly The calls were found but not in the correct order among the calls: 1: FakeItEasy.Specs.OrderedCallMatchingSpecs+IFoo.Bar(baz: 3) 2: FakeItEasy.Specs.OrderedCallMatchingSpecs+IFoo.Bar(baz: 1) 2 times ... 4: FakeItEasy.Specs.OrderedCallMatchingSpecs+IFoo.Bar(baz: 2)")); } // This is perhaps not the most intuitive behavior, but has been // in place since ordered assertions were introduced: the // MustHaveHappened is executed first and checks all calls. [Scenario] public static void OrderedAssertionWithCallCountConstraintFailure( IFoo fake, IOrderableCallAssertion lastAssertion, Exception exception) { "Given a Fake" .x(() => fake = A.Fake<IFoo>()); "And a call on the Fake, passing argument 1" .x(() => fake.Bar(1)); "And a call on the Fake, passing argument 2" .x(() => fake.Bar(2)); "And a call on the Fake, passing argument 1" .x(() => fake.Bar(1)); "When I assert that a call with argument 2 was made" .x(() => lastAssertion = A.CallTo(() => fake.Bar(2)).MustHaveHappened()); "And then that a call with argument 1 was made once exactly" .x(() => exception = Record.Exception(() => lastAssertion.Then(A.CallTo(() => fake.Bar(1)).MustHaveHappenedOnceExactly()))); "Then the last assertion should fail" .x(() => exception.Should().BeAnExceptionOfType<ExpectationException>()); "And the message should say that the call to Bar(1) was found too many times" .x(() => exception.Message.Should().BeModuloLineEndings(@" Assertion failed for the following call: FakeItEasy.Specs.OrderedCallMatchingSpecs+IFoo.Bar(baz: 1) Expected to find it once exactly but found it twice among the calls: 1: FakeItEasy.Specs.OrderedCallMatchingSpecs+IFoo.Bar(baz: 1) 2: FakeItEasy.Specs.OrderedCallMatchingSpecs+IFoo.Bar(baz: 2) 3: FakeItEasy.Specs.OrderedCallMatchingSpecs+IFoo.Bar(baz: 1) ")); } // Reported as issue 182 (https://github.com/FakeItEasy/FakeItEasy/issues/182). [Scenario] public static void OrderedAssertionOnInterfacesWithCommonParent(ISomethingBaz baz, ISomethingQux qux, IOrderableCallAssertion lastAssertion, Exception exception) { "Given a Fake baz" .x(() => baz = A.Fake<ISomethingBaz>()); "And a Fake qux implementing an interface in common with baz" .x(() => qux = A.Fake<ISomethingQux>()); "And a call on qux" .x(() => qux.QuxMethod()); "And a call on baz" .x(() => baz.BazMethod()); "When I assert that the qux call was made" .x(() => lastAssertion = A.CallTo(() => qux.QuxMethod()).MustHaveHappened()); "And I make the same assertion again" .x(() => exception = Record.Exception(() => lastAssertion.Then(A.CallTo(() => qux.QuxMethod()).MustHaveHappened()))); "Then the second assertion should fail" .x(() => exception.Should().BeAnExceptionOfType<ExpectationException>()); } // Reported as issue 1583 (https://github.com/FakeItEasy/FakeItEasy/issues/1583). [Scenario] public static void OrderedAssertionOnCallThatCallsAnotherFakedMethod( ClassWithAMethodThatCallsASibling fake, IOrderableCallAssertion lastAssertion, Exception exception) { "Given a class with a method that calls another class method" .See<ClassWithAMethodThatCallsASibling>(); "And a Fake of that type, configured to call base methods" .x(() => fake = A.Fake<ClassWithAMethodThatCallsASibling>(options => options.CallsBaseMethods())); "And I call the outer method" .x(() => fake.OuterMethod()); "When I assert that the outer method was called" .x(() => lastAssertion = A.CallTo(() => fake.OuterMethod()).MustHaveHappened()); "And then I assert that the inner method was called afterward" .x(() => exception = Record.Exception(() => lastAssertion.Then(A.CallTo(() => fake.InnerMethod()).MustHaveHappened()))); "Then the assertions pass" .x(() => exception.Should().BeNull()); } public abstract class ClassWithAMethodThatCallsASibling { public virtual void OuterMethod() => this.InnerMethod(); public abstract void InnerMethod(); } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion [assembly: Elmah.Scc("$Id: Error.cs 923 2011-12-23 22:02:10Z azizatif $")] namespace Elmah { #region Imports using System; using System.Diagnostics; using System.Security; using System.Security.Principal; using System.Web; using System.Xml; using Mannex; using Thread = System.Threading.Thread; using NameValueCollection = System.Collections.Specialized.NameValueCollection; #endregion /// <summary> /// Represents a logical application error (as opposed to the actual /// exception it may be representing). /// </summary> [Serializable] public sealed class Error : ICloneable { private readonly Exception _exception; private string _applicationName; private string _hostName; private string _typeName; private string _source; private string _message; private string _detail; private string _user; private DateTime _time; private int _statusCode; private string _webHostHtmlMessage; private NameValueCollection _additionalData; private NameValueCollection _serverVariables; private NameValueCollection _queryString; private NameValueCollection _form; private NameValueCollection _cookies; /// <summary> /// Initializes a new instance of the <see cref="Error"/> class. /// </summary> public Error() { } /// <summary> /// Initializes a new instance of the <see cref="Error"/> class /// from a given <see cref="Exception"/> instance. /// </summary> public Error(Exception e) : this(e, null) { } /// <summary> /// Initializes a new instance of the <see cref="Error"/> class /// from a given <see cref="Exception"/> instance and /// <see cref="HttpContext"/> instance representing the HTTP /// context during the exception. /// </summary> public Error(Exception e, HttpContextBase context) { if (e == null) throw new ArgumentNullException("e"); _exception = e; Exception baseException = e.GetBaseException(); // // Load the basic information. // _hostName = Environment.TryGetMachineName(context); _typeName = baseException.GetType().FullName; _message = baseException.Message; _source = baseException.Source; _detail = e.ToString(); _user = Thread.CurrentPrincipal.Identity.Name ?? string.Empty; _time = DateTime.Now; // // If this is an HTTP exception, then get the status code // and detailed HTML message provided by the host. // HttpException httpException = e as HttpException; if (httpException != null) { _statusCode = httpException.GetHttpCode(); _webHostHtmlMessage = TryGetHtmlErrorMessage(httpException) ?? string.Empty; } // // If the HTTP context is available, then capture the // collections that represent the state request as well as // the user. // if (context != null) { IPrincipal webUser = context.User; if (webUser != null && (webUser.Identity.Name ?? string.Empty).Length > 0) { _user = webUser.Identity.Name; } var request = context.Request; var qsfc = request.TryGetUnvalidatedCollections((form, qs, cookies) => new { QueryString = qs, Form = form, Cookies = cookies, }); _serverVariables = CopyCollection(request.ServerVariables); _queryString = CopyCollection(qsfc.QueryString); _form = CopyCollection(qsfc.Form); _cookies = CopyCollection(qsfc.Cookies); } var callerInfo = e.TryGetCallerInfo() ?? CallerInfo.Empty; if (!callerInfo.IsEmpty) { _detail = "# caller: " + callerInfo + System.Environment.NewLine + _detail; } } private static string TryGetHtmlErrorMessage(HttpException e) { Debug.Assert(e != null); try { return e.GetHtmlErrorMessage(); } catch (SecurityException se) { // In partial trust environments, HttpException.GetHtmlErrorMessage() // has been known to throw: // System.Security.SecurityException: Request for the // permission of type 'System.Web.AspNetHostingPermission' failed. // // See issue #179 for more background: // http://code.google.com/p/elmah/issues/detail?id=179 Trace.WriteLine(se); return null; } } /// <summary> /// Gets the <see cref="Exception"/> instance used to initialize this /// instance. /// </summary> /// <remarks> /// This is a run-time property only that is not written or read /// during XML serialization via <see cref="ErrorXml.Decode"/> and /// <see cref="ErrorXml.Encode(Error,XmlWriter)"/>. /// </remarks> public Exception Exception { get { return _exception; } } /// <summary> /// Gets or sets the name of application in which this error occurred. /// </summary> public string ApplicationName { get { return _applicationName ?? string.Empty; } set { _applicationName = value; } } /// <summary> /// Gets or sets name of host machine where this error occurred. /// </summary> public string HostName { get { return _hostName ?? string.Empty; } set { _hostName = value; } } /// <summary> /// Gets or sets the type, class or category of the error. /// </summary> public string Type { get { return _typeName ?? string.Empty; } set { _typeName = value; } } /// <summary> /// Gets or sets the source that is the cause of the error. /// </summary> public string Source { get { return _source ?? string.Empty; } set { _source = value; } } /// <summary> /// Gets or sets a brief text describing the error. /// </summary> public string Message { get { return _message ?? string.Empty; } set { _message = value; } } /// <summary> /// Gets or sets a detailed text describing the error, such as a /// stack trace. /// </summary> public string Detail { get { return _detail ?? string.Empty; } set { _detail = value; } } /// <summary> /// Gets or sets the user logged into the application at the time /// of the error. /// </summary> public string User { get { return _user ?? string.Empty; } set { _user = value; } } /// <summary> /// Gets or sets the date and time (in local time) at which the /// error occurred. /// </summary> public DateTime Time { get { return _time; } set { _time = value; } } /// <summary> /// Gets or sets the HTTP status code of the output returned to the /// client for the error. /// </summary> /// <remarks> /// For cases where this value cannot always be reliably determined, /// the value may be reported as zero. /// </remarks> public int StatusCode { get { return _statusCode; } set { _statusCode = value; } } /// <summary> /// Gets or sets the HTML message generated by the web host (ASP.NET) /// for the given error. /// </summary> public string WebHostHtmlMessage { get { return _webHostHtmlMessage ?? string.Empty; } set { _webHostHtmlMessage = value; } } /// <summary> /// Gets a collection representing the Web server variables /// captured as part of diagnostic data for the error. /// </summary> public NameValueCollection ServerVariables { get { return FaultIn(ref _serverVariables); } } /// <summary> /// Gets a collection representing the Web query string variables /// captured as part of diagnostic data for the error. /// </summary> public NameValueCollection QueryString { get { return FaultIn(ref _queryString); } } /// <summary> /// Gets a collection representing the form variables captured as /// part of diagnostic data for the error. /// </summary> public NameValueCollection Form { get { return FaultIn(ref _form); } } /// <summary> /// Gets a collection representing the client cookies /// captured as part of diagnostic data for the error. /// </summary> public NameValueCollection Cookies { get { return FaultIn(ref _cookies); } } /// <summary> /// Gets a collection representing custom storage /// </summary> public NameValueCollection AdditionalData { get { return FaultIn(ref _additionalData); } } /// <summary> /// Returns the value of the <see cref="Message"/> property. /// </summary> public override string ToString() { return this.Message; } /// <summary> /// Creates a new object that is a copy of the current instance. /// </summary> object ICloneable.Clone() { // // Make a base shallow copy of all the members. // Error copy = (Error)MemberwiseClone(); // // Now make a deep copy of items that are mutable. // copy._serverVariables = CopyCollection(_serverVariables); copy._queryString = CopyCollection(_queryString); copy._form = CopyCollection(_form); copy._cookies = CopyCollection(_cookies); copy._additionalData = CopyCollection(_additionalData); return copy; } private static NameValueCollection CopyCollection(NameValueCollection collection) { if (collection == null || collection.Count == 0) return null; return new NameValueCollection(collection); } private static NameValueCollection CopyCollection(HttpCookieCollection cookies) { if (cookies == null || cookies.Count == 0) return null; NameValueCollection copy = new NameValueCollection(cookies.Count); for (int i = 0; i < cookies.Count; i++) { HttpCookie cookie = cookies[i]; // // NOTE: We drop the Path and Domain properties of the // cookie for sake of simplicity. // copy.Add(cookie.Name, cookie.Value); } return copy; } private static NameValueCollection FaultIn(ref NameValueCollection collection) { if (collection == null) collection = new NameValueCollection(); return collection; } } }