context
stringlengths
2.52k
185k
gt
stringclasses
1 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; using System.Collections.Generic; using System.Text; using System.Runtime.ExceptionServices; using Microsoft.VisualStudio.Debugger.Interop; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; using MICore; using System.Globalization; using Microsoft.DebugEngineHost; namespace Microsoft.MIDebugEngine { // AD7Engine is the primary entrypoint object for the sample engine. // // It implements: // // IDebugEngine2: This interface represents a debug engine (DE). It is used to manage various aspects of a debugging session, // from creating breakpoints to setting and clearing exceptions. // // IDebugEngineLaunch2: Used by a debug engine (DE) to launch and terminate programs. // // IDebugProgram3: This interface represents a program that is running in a process. Since this engine only debugs one process at a time and each // process only contains one program, it is implemented on the engine. // // IDebugEngineProgram2: This interface provides simultanious debugging of multiple threads in a debuggee. [System.Runtime.InteropServices.ComVisible(true)] [System.Runtime.InteropServices.Guid("0fc2f352-2fc1-4f80-8736-51cd1ab28f16")] sealed public class AD7Engine : IDebugEngine2, IDebugEngineLaunch2, IDebugProgram3, IDebugEngineProgram2, IDebugMemoryBytes2, IDebugEngine110 { // used to send events to the debugger. Some examples of these events are thread create, exception thrown, module load. private EngineCallback _engineCallback; // The sample debug engine is split into two parts: a managed front-end and a mixed-mode back end. DebuggedProcess is the primary // object in the back-end. AD7Engine holds a reference to it. private DebuggedProcess _debuggedProcess; // This object facilitates calling from this thread into the worker thread of the engine. This is necessary because the Win32 debugging // api requires thread affinity to several operations. private WorkerThread _pollThread; // This object manages breakpoints in the sample engine. private BreakpointManager _breakpointManager; // A unique identifier for the program being debugged. private Guid _ad7ProgramId; private HostConfigurationStore _configStore; private IDebugSettingsCallback110 _settingsCallback; public AD7Engine() { Host.EnsureMainThreadInitialized(); _breakpointManager = new BreakpointManager(this); } ~AD7Engine() { if (_pollThread != null) { _pollThread.Close(); } } internal EngineCallback Callback { get { return _engineCallback; } } internal DebuggedProcess DebuggedProcess { get { return _debuggedProcess; } } internal uint CurrentRadix() { uint radix; if (_settingsCallback != null && _settingsCallback.GetDisplayRadix(out radix) == Constants.S_OK) { if (radix != _debuggedProcess.MICommandFactory.Radix) { _debuggedProcess.WorkerThread.RunOperation(async () => { await _debuggedProcess.MICommandFactory.SetRadix(radix); }); } } return _debuggedProcess.MICommandFactory.Radix; } internal bool ProgramCreateEventSent { get; private set; } public string GetAddressDescription(ulong ip) { return EngineUtils.GetAddressDescription(_debuggedProcess, ip); } public object GetMetric(string metric) { return _configStore.GetEngineMetric(metric); } #region IDebugEngine2 Members // Attach the debug engine to a program. int IDebugEngine2.Attach(IDebugProgram2[] rgpPrograms, IDebugProgramNode2[] rgpProgramNodes, uint celtPrograms, IDebugEventCallback2 ad7Callback, enum_ATTACH_REASON dwReason) { Debug.Assert(_ad7ProgramId == Guid.Empty); if (celtPrograms != 1) { Debug.Fail("SampleEngine only expects to see one program in a process"); throw new ArgumentException(); } try { AD_PROCESS_ID processId = EngineUtils.GetProcessId(rgpPrograms[0]); EngineUtils.RequireOk(rgpPrograms[0].GetProgramId(out _ad7ProgramId)); // Attach can either be called to attach to a new process, or to complete an attach // to a launched process if (_pollThread == null) { // We are being asked to debug a process when we currently aren't debugging anything _pollThread = new WorkerThread(); _engineCallback = new EngineCallback(this, ad7Callback); // Complete the win32 attach on the poll thread _pollThread.RunOperation(new Operation(delegate { throw new NotImplementedException(); })); _pollThread.PostedOperationErrorEvent += _debuggedProcess.OnPostedOperationError; } else { if (!EngineUtils.ProcIdEquals(processId, _debuggedProcess.Id)) { Debug.Fail("Asked to attach to a process while we are debugging"); return Constants.E_FAIL; } } AD7EngineCreateEvent.Send(this); AD7ProgramCreateEvent.Send(this); this.ProgramCreateEventSent = true; return Constants.S_OK; } catch (MIException e) { return e.HResult; } catch (Exception e) { return EngineUtils.UnexpectedException(e); } } // Requests that all programs being debugged by this DE stop execution the next time one of their threads attempts to run. // This is normally called in response to the user clicking on the pause button in the debugger. // When the break is complete, an AsyncBreakComplete event will be sent back to the debugger. int IDebugEngine2.CauseBreak() { return ((IDebugProgram2)this).CauseBreak(); } // Called by the SDM to indicate that a synchronous debug event, previously sent by the DE to the SDM, // was received and processed. The only event the sample engine sends in this fashion is Program Destroy. // It responds to that event by shutting down the engine. int IDebugEngine2.ContinueFromSynchronousEvent(IDebugEvent2 eventObject) { try { if (eventObject is AD7ProgramCreateEvent) { Exception exception = null; try { // At this point breakpoints and exception settings have been sent down, so we can resume the target _pollThread.RunOperation(() => { return _debuggedProcess.ResumeFromLaunch(); }); } catch (Exception e) { exception = e; // Return from the catch block so that we can let the exception unwind - the stack can get kind of big } if (exception != null) { // If something goes wrong, report the error and then stop debugging. The SDM will drop errors // from ContinueFromSynchronousEvent, so we want to deal with them ourself. SendStartDebuggingError(exception); _debuggedProcess.Terminate(); } return Constants.S_OK; } else if (eventObject is AD7ProgramDestroyEvent) { Dispose(); } else { Debug.Fail("Unknown syncronious event"); } } catch (Exception e) { return EngineUtils.UnexpectedException(e); } return Constants.S_OK; } private void Dispose() { WorkerThread pollThread = _pollThread; DebuggedProcess debuggedProcess = _debuggedProcess; _engineCallback = null; _debuggedProcess = null; _pollThread = null; _ad7ProgramId = Guid.Empty; debuggedProcess?.Close(); pollThread?.Close(); } // Creates a pending breakpoint in the engine. A pending breakpoint is contains all the information needed to bind a breakpoint to // a location in the debuggee. int IDebugEngine2.CreatePendingBreakpoint(IDebugBreakpointRequest2 pBPRequest, out IDebugPendingBreakpoint2 ppPendingBP) { Debug.Assert(_breakpointManager != null); ppPendingBP = null; try { _breakpointManager.CreatePendingBreakpoint(pBPRequest, out ppPendingBP); } catch (Exception e) { return EngineUtils.UnexpectedException(e); } return Constants.S_OK; } // Informs a DE that the program specified has been atypically terminated and that the DE should // clean up all references to the program and send a program destroy event. int IDebugEngine2.DestroyProgram(IDebugProgram2 pProgram) { // Tell the SDM that the engine knows that the program is exiting, and that the // engine will send a program destroy. We do this because the Win32 debug api will always // tell us that the process exited, and otherwise we have a race condition. return (AD7_HRESULT.E_PROGRAM_DESTROY_PENDING); } // Gets the GUID of the DE. int IDebugEngine2.GetEngineId(out Guid guidEngine) { guidEngine = new Guid(EngineConstants.EngineId); return Constants.S_OK; } // Removes the list of exceptions the IDE has set for a particular run-time architecture or language. int IDebugEngine2.RemoveAllSetExceptions(ref Guid guidType) { _debuggedProcess?.ExceptionManager.RemoveAllSetExceptions(guidType); return Constants.S_OK; } // Removes the specified exception so it is no longer handled by the debug engine. // The sample engine does not support exceptions in the debuggee so this method is not actually implemented. int IDebugEngine2.RemoveSetException(EXCEPTION_INFO[] pException) { _debuggedProcess?.ExceptionManager.RemoveSetException(ref pException[0]); return Constants.S_OK; } // Specifies how the DE should handle a given exception. // The sample engine does not support exceptions in the debuggee so this method is not actually implemented. int IDebugEngine2.SetException(EXCEPTION_INFO[] pException) { _debuggedProcess?.ExceptionManager.SetException(ref pException[0]); return Constants.S_OK; } // Sets the locale of the DE. // This method is called by the session debug manager (SDM) to propagate the locale settings of the IDE so that // strings returned by the DE are properly localized. The sample engine is not localized so this is not implemented. int IDebugEngine2.SetLocale(ushort wLangID) { return Constants.S_OK; } // A metric is a registry value used to change a debug engine's behavior or to advertise supported functionality. // This method can forward the call to the appropriate form of the Debugging SDK Helpers function, SetMetric. int IDebugEngine2.SetMetric(string pszMetric, object varValue) { if (string.CompareOrdinal(pszMetric, "JustMyCodeStepping") == 0) { string strJustMyCode = varValue.ToString(); bool optJustMyCode; if (string.CompareOrdinal(strJustMyCode, "0") == 0) { optJustMyCode = false; } else if (string.CompareOrdinal(strJustMyCode, "1") == 0) { optJustMyCode = true; } else { return Constants.E_FAIL; } _pollThread.RunOperation(new Operation(() => { _debuggedProcess.MICommandFactory.SetJustMyCode(optJustMyCode); })); return Constants.S_OK; } return Constants.E_NOTIMPL; } // Sets the registry root currently in use by the DE. Different installations of Visual Studio can change where their registry information is stored // This allows the debugger to tell the engine where that location is. int IDebugEngine2.SetRegistryRoot(string registryRoot) { _configStore = new HostConfigurationStore(registryRoot, EngineConstants.EngineId); Logger.EnsureInitialized(_configStore); return Constants.S_OK; } #endregion #region IDebugEngineLaunch2 Members // Determines if a process can be terminated. int IDebugEngineLaunch2.CanTerminateProcess(IDebugProcess2 process) { Debug.Assert(_pollThread != null); Debug.Assert(_engineCallback != null); Debug.Assert(_debuggedProcess != null); AD_PROCESS_ID processId = EngineUtils.GetProcessId(process); if (EngineUtils.ProcIdEquals(processId, _debuggedProcess.Id)) { return Constants.S_OK; } else { return Constants.S_FALSE; } } // Launches a process by means of the debug engine. // Normally, Visual Studio launches a program using the IDebugPortEx2::LaunchSuspended method and then attaches the debugger // to the suspended program. However, there are circumstances in which the debug engine may need to launch a program // (for example, if the debug engine is part of an interpreter and the program being debugged is an interpreted language), // in which case Visual Studio uses the IDebugEngineLaunch2::LaunchSuspended method // The IDebugEngineLaunch2::ResumeProcess method is called to start the process after the process has been successfully launched in a suspended state. int IDebugEngineLaunch2.LaunchSuspended(string pszServer, IDebugPort2 port, string exe, string args, string dir, string env, string options, enum_LAUNCH_FLAGS launchFlags, uint hStdInput, uint hStdOutput, uint hStdError, IDebugEventCallback2 ad7Callback, out IDebugProcess2 process) { Debug.Assert(_pollThread == null); Debug.Assert(_engineCallback == null); Debug.Assert(_debuggedProcess == null); Debug.Assert(_ad7ProgramId == Guid.Empty); process = null; _engineCallback = new EngineCallback(this, ad7Callback); Exception exception; try { // Note: LaunchOptions.GetInstance can be an expensive operation and may push a wait message loop LaunchOptions launchOptions = LaunchOptions.GetInstance(_configStore, exe, args, dir, options, _engineCallback, TargetEngine.Native); // We are being asked to debug a process when we currently aren't debugging anything _pollThread = new WorkerThread(); var cancellationTokenSource = new CancellationTokenSource(); using (cancellationTokenSource) { _pollThread.RunOperation(ResourceStrings.InitializingDebugger, cancellationTokenSource, (HostWaitLoop waitLoop) => { try { _debuggedProcess = new DebuggedProcess(true, launchOptions, _engineCallback, _pollThread, _breakpointManager, this, _configStore); } finally { // If there is an exception from the DebuggeedProcess constructor, it is our responsibility to dispose the DeviceAppLauncher, // otherwise the DebuggedProcess object takes ownership. if (_debuggedProcess == null && launchOptions.DeviceAppLauncher != null) { launchOptions.DeviceAppLauncher.Dispose(); } } _pollThread.PostedOperationErrorEvent += _debuggedProcess.OnPostedOperationError; return _debuggedProcess.Initialize(waitLoop, cancellationTokenSource.Token); }); } EngineUtils.RequireOk(port.GetProcess(_debuggedProcess.Id, out process)); return Constants.S_OK; } catch (Exception e) { exception = e; // Return from the catch block so that we can let the exception unwind - the stack can get kind of big } // If we just return the exception as an HRESULT, we will loose our message, so we instead send up an error event, and then // return E_ABORT. Logger.Flush(); SendStartDebuggingError(exception); Dispose(); return Constants.E_ABORT; } private void SendStartDebuggingError(Exception exception) { if (exception is OperationCanceledException) { return; // don't show a message in this case } string description = EngineUtils.GetExceptionDescription(exception); string message = string.Format(CultureInfo.CurrentCulture, MICoreResources.Error_UnableToStartDebugging, description); var initializationException = exception as MIDebuggerInitializeFailedException; if (initializationException != null) { string outputMessage = string.Join("\r\n", initializationException.OutputLines) + "\r\n"; // NOTE: We can't write to the output window by sending an AD7 event because this may be called before the session create event HostOutputWindow.WriteLaunchError(outputMessage); } _engineCallback.OnErrorImmediate(message); } // Resume a process launched by IDebugEngineLaunch2.LaunchSuspended int IDebugEngineLaunch2.ResumeProcess(IDebugProcess2 process) { Debug.Assert(_pollThread != null); Debug.Assert(_engineCallback != null); Debug.Assert(_debuggedProcess != null); Debug.Assert(_ad7ProgramId == Guid.Empty); try { AD_PROCESS_ID processId = EngineUtils.GetProcessId(process); if (!EngineUtils.ProcIdEquals(processId, _debuggedProcess.Id)) { return Constants.S_FALSE; } // Send a program node to the SDM. This will cause the SDM to turn around and call IDebugEngine2.Attach // which will complete the hookup with AD7 IDebugPort2 port; EngineUtils.RequireOk(process.GetPort(out port)); IDebugDefaultPort2 defaultPort = (IDebugDefaultPort2)port; IDebugPortNotify2 portNotify; EngineUtils.RequireOk(defaultPort.GetPortNotify(out portNotify)); EngineUtils.RequireOk(portNotify.AddProgramNode(new AD7ProgramNode(_debuggedProcess.Id))); if (_ad7ProgramId == Guid.Empty) { Debug.Fail("Unexpected problem -- IDebugEngine2.Attach wasn't called"); return Constants.E_FAIL; } // NOTE: We wait for the program create event to be continued before we really resume the process return Constants.S_OK; } catch (MIException e) { return e.HResult; } catch (Exception e) { return EngineUtils.UnexpectedException(e); } } // This function is used to terminate a process that the SampleEngine launched // The debugger will call IDebugEngineLaunch2::CanTerminateProcess before calling this method. int IDebugEngineLaunch2.TerminateProcess(IDebugProcess2 process) { Debug.Assert(_pollThread != null); Debug.Assert(_engineCallback != null); Debug.Assert(_debuggedProcess != null); AD_PROCESS_ID processId = EngineUtils.GetProcessId(process); if (!EngineUtils.ProcIdEquals(processId, _debuggedProcess.Id)) { return Constants.S_FALSE; } try { _pollThread.RunOperation(() => _debuggedProcess.CmdTerminate()); _debuggedProcess.Terminate(); } catch (ObjectDisposedException) { // Ignore failures caused by the connection already being dead. } return Constants.S_OK; } #endregion #region IDebugProgram2 Members // Determines if a debug engine (DE) can detach from the program. public int CanDetach() { // The sample engine always supports detach return Constants.S_OK; } // The debugger calls CauseBreak when the user clicks on the pause button in VS. The debugger should respond by entering // breakmode. public int CauseBreak() { _pollThread.RunOperation(() => _debuggedProcess.CmdBreak()); return Constants.S_OK; } // Continue is called from the SDM when it wants execution to continue in the debugee // but have stepping state remain. An example is when a tracepoint is executed, // and the debugger does not want to actually enter break mode. public int Continue(IDebugThread2 pThread) { // VS Code currently isn't providing a thread Id in certain cases. Work around this by handling null values. AD7Thread thread = pThread as AD7Thread; _pollThread.RunOperation(() => _debuggedProcess.Continue(thread?.GetDebuggedThread())); return Constants.S_OK; } // Detach is called when debugging is stopped and the process was attached to (as opposed to launched) // or when one of the Detach commands are executed in the UI. public int Detach() { _breakpointManager.ClearBoundBreakpoints(); _pollThread.RunOperation(new Operation(delegate { _debuggedProcess.Detach(); })); return Constants.S_OK; } // Enumerates the code contexts for a given position in a source file. public int EnumCodeContexts(IDebugDocumentPosition2 docPosition, out IEnumDebugCodeContexts2 ppEnum) { string documentName; EngineUtils.CheckOk(docPosition.GetFileName(out documentName)); // Get the location in the document TEXT_POSITION[] startPosition = new TEXT_POSITION[1]; TEXT_POSITION[] endPosition = new TEXT_POSITION[1]; EngineUtils.CheckOk(docPosition.GetRange(startPosition, endPosition)); List<IDebugCodeContext2> codeContexts = new List<IDebugCodeContext2>(); List<ulong> addresses = null; uint line = startPosition[0].dwLine + 1; _debuggedProcess.WorkerThread.RunOperation(async () => { addresses = await DebuggedProcess.StartAddressesForLine(documentName, line); }); if (addresses != null && addresses.Count > 0) { foreach (var a in addresses) { var codeCxt = new AD7MemoryAddress(this, a, null); TEXT_POSITION pos; pos.dwLine = line; pos.dwColumn = 0; MITextPosition textPosition = new MITextPosition(documentName, pos, pos); codeCxt.SetDocumentContext(new AD7DocumentContext(textPosition, codeCxt)); codeContexts.Add(codeCxt); } if (codeContexts.Count > 0) { ppEnum = new AD7CodeContextEnum(codeContexts.ToArray()); return Constants.S_OK; } } ppEnum = null; return Constants.E_FAIL; } // EnumCodePaths is used for the step-into specific feature -- right click on the current statment and decide which // function to step into. This is not something that the SampleEngine supports. public int EnumCodePaths(string hint, IDebugCodeContext2 start, IDebugStackFrame2 frame, int fSource, out IEnumCodePaths2 pathEnum, out IDebugCodeContext2 safetyContext) { pathEnum = null; safetyContext = null; return Constants.E_NOTIMPL; } // EnumModules is called by the debugger when it needs to enumerate the modules in the program. public int EnumModules(out IEnumDebugModules2 ppEnum) { DebuggedModule[] modules = _debuggedProcess.GetModules(); AD7Module[] moduleObjects = new AD7Module[modules.Length]; for (int i = 0; i < modules.Length; i++) { moduleObjects[i] = new AD7Module(modules[i], _debuggedProcess); } ppEnum = new Microsoft.MIDebugEngine.AD7ModuleEnum(moduleObjects); return Constants.S_OK; } // EnumThreads is called by the debugger when it needs to enumerate the threads in the program. public int EnumThreads(out IEnumDebugThreads2 ppEnum) { DebuggedThread[] threads = null; DebuggedProcess.WorkerThread.RunOperation(async () => threads = await DebuggedProcess.ThreadCache.GetThreads()); AD7Thread[] threadObjects = new AD7Thread[threads.Length]; for (int i = 0; i < threads.Length; i++) { Debug.Assert(threads[i].Client != null); threadObjects[i] = (AD7Thread)threads[i].Client; } ppEnum = new Microsoft.MIDebugEngine.AD7ThreadEnum(threadObjects); return Constants.S_OK; } // The properties returned by this method are specific to the program. If the program needs to return more than one property, // then the IDebugProperty2 object returned by this method is a container of additional properties and calling the // IDebugProperty2::EnumChildren method returns a list of all properties. // A program may expose any number and type of additional properties that can be described through the IDebugProperty2 interface. // An IDE might display the additional program properties through a generic property browser user interface. // The sample engine does not support this public int GetDebugProperty(out IDebugProperty2 ppProperty) { throw new NotImplementedException(); } // The debugger calls this when it needs to obtain the IDebugDisassemblyStream2 for a particular code-context. // The sample engine does not support dissassembly so it returns E_NOTIMPL // In order for this to be called, the Disassembly capability must be set in the registry for this Engine public int GetDisassemblyStream(enum_DISASSEMBLY_STREAM_SCOPE dwScope, IDebugCodeContext2 codeContext, out IDebugDisassemblyStream2 disassemblyStream) { disassemblyStream = new AD7DisassemblyStream(this, dwScope, codeContext); return Constants.S_OK; } // This method gets the Edit and Continue (ENC) update for this program. A custom debug engine always returns E_NOTIMPL public int GetENCUpdate(out object update) { // The sample engine does not participate in managed edit & continue. update = null; return Constants.S_OK; } // Gets the name and identifier of the debug engine (DE) running this program. public int GetEngineInfo(out string engineName, out Guid engineGuid) { engineName = ResourceStrings.EngineName; engineGuid = new Guid(EngineConstants.EngineId); return Constants.S_OK; } // The memory bytes as represented by the IDebugMemoryBytes2 object is for the program's image in memory and not any memory // that was allocated when the program was executed. public int GetMemoryBytes(out IDebugMemoryBytes2 ppMemoryBytes) { ppMemoryBytes = this; return Constants.S_OK; } // Gets the name of the program. // The name returned by this method is always a friendly, user-displayable name that describes the program. public int GetName(out string programName) { // The Sample engine uses default transport and doesn't need to customize the name of the program, // so return NULL. programName = null; return Constants.S_OK; } // Gets a GUID for this program. A debug engine (DE) must return the program identifier originally passed to the IDebugProgramNodeAttach2::OnAttach // or IDebugEngine2::Attach methods. This allows identification of the program across debugger components. public int GetProgramId(out Guid guidProgramId) { Debug.Assert(_ad7ProgramId != Guid.Empty); guidProgramId = _ad7ProgramId; return Constants.S_OK; } public int Step(IDebugThread2 pThread, enum_STEPKIND kind, enum_STEPUNIT unit) { AD7Thread thread = (AD7Thread)pThread; _debuggedProcess.WorkerThread.RunOperation(() => _debuggedProcess.Step(thread.GetDebuggedThread().Id, kind, unit)); return Constants.S_OK; } // Terminates the program. public int Terminate() { // Because the sample engine is a native debugger, it implements IDebugEngineLaunch2, and will terminate // the process in IDebugEngineLaunch2.TerminateProcess return Constants.S_OK; } // Writes a dump to a file. public int WriteDump(enum_DUMPTYPE DUMPTYPE, string pszDumpUrl) { // The sample debugger does not support creating or reading mini-dumps. return Constants.E_NOTIMPL; } #endregion #region IDebugProgram3 Members // ExecuteOnThread is called when the SDM wants execution to continue and have // stepping state cleared. public int ExecuteOnThread(IDebugThread2 pThread) { AD7Thread thread = (AD7Thread)pThread; _pollThread.RunOperation(() => _debuggedProcess.Execute(thread.GetDebuggedThread())); return Constants.S_OK; } #endregion #region IDebugEngineProgram2 Members // Stops all threads running in this program. // This method is called when this program is being debugged in a multi-program environment. When a stopping event from some other program // is received, this method is called on this program. The implementation of this method should be asynchronous; // that is, not all threads should be required to be stopped before this method returns. The implementation of this method may be // as simple as calling the IDebugProgram2::CauseBreak method on this program. // // The sample engine only supports debugging native applications and therefore only has one program per-process public int Stop() { throw new NotImplementedException(); } // WatchForExpressionEvaluationOnThread is used to cooperate between two different engines debugging // the same process. The sample engine doesn't cooperate with other engines, so it has nothing // to do here. public int WatchForExpressionEvaluationOnThread(IDebugProgram2 pOriginatingProgram, uint dwTid, uint dwEvalFlags, IDebugEventCallback2 pExprCallback, int fWatch) { return Constants.S_OK; } // WatchForThreadStep is used to cooperate between two different engines debugging the same process. // The sample engine doesn't cooperate with other engines, so it has nothing to do here. public int WatchForThreadStep(IDebugProgram2 pOriginatingProgram, uint dwTid, int fWatch, uint dwFrame) { return Constants.S_OK; } #endregion #region IDebugMemoryBytes2 Members public int GetSize(out ulong pqwSize) { throw new NotImplementedException(); } public int ReadAt(IDebugMemoryContext2 pStartContext, uint dwCount, byte[] rgbMemory, out uint pdwRead, ref uint pdwUnreadable) { pdwUnreadable = 0; AD7MemoryAddress addr = (AD7MemoryAddress)pStartContext; uint bytesRead = 0; int hr = Constants.S_OK; DebuggedProcess.WorkerThread.RunOperation(async () => { bytesRead = await DebuggedProcess.ReadProcessMemory(addr.Address, dwCount, rgbMemory); }); if (bytesRead == uint.MaxValue) { bytesRead = 0; } if (bytesRead < dwCount) // copied from Concord { // assume 4096 sized pages: ARM has 4K or 64K pages uint pageSize = 4096; ulong readEnd = addr.Address + bytesRead; ulong nextPageStart = (readEnd + pageSize - 1) / pageSize * pageSize; if (nextPageStart == readEnd) { nextPageStart = readEnd + pageSize; } // if we have crossed a page boundry - Unreadable = bytes till end of page uint maxUnreadable = dwCount - bytesRead; if (addr.Address + dwCount > nextPageStart) { pdwUnreadable = (uint)Math.Min(maxUnreadable, nextPageStart - readEnd); } else { pdwUnreadable = (uint)Math.Min(maxUnreadable, pageSize); } } pdwRead = bytesRead; return hr; } public int WriteAt(IDebugMemoryContext2 pStartContext, uint dwCount, byte[] rgbMemory) { throw new NotImplementedException(); } #endregion #region IDebugEngine110 public int SetMainThreadSettingsCallback110(IDebugSettingsCallback110 pCallback) { _settingsCallback = pCallback; return Constants.S_OK; } #endregion #region Deprecated interface methods // These methods are not called by the Visual Studio debugger, so they don't need to be implemented int IDebugEngine2.EnumPrograms(out IEnumDebugPrograms2 programs) { Debug.Fail("This function is not called by the debugger"); programs = null; return Constants.E_NOTIMPL; } public int Attach(IDebugEventCallback2 pCallback) { Debug.Fail("This function is not called by the debugger"); return Constants.E_NOTIMPL; } public int GetProcess(out IDebugProcess2 process) { Debug.Fail("This function is not called by the debugger"); process = null; return Constants.E_NOTIMPL; } public int Execute() { Debug.Fail("This function is not called by the debugger."); return Constants.E_NOTIMPL; } #endregion } }
using System; using System.Linq; using NUnit.Framework; using Rhino.Mocks; using StructureMap.Exceptions; using StructureMap.Graph; using StructureMap.Pipeline; namespace StructureMap.Testing.Graph { [TestFixture] public class PluginGraphTester { [Test, ExpectedException(typeof (StructureMapConfigurationException))] public void AssertErrors_throws_StructureMapConfigurationException_if_there_is_an_error() { var graph = new PluginGraph(); graph.Log.RegisterError(400, new ApplicationException("Bad!")); graph.Log.AssertFailures(); } [Test] public void add_type_adds_an_instance_for_type_once_and_only_once() { var graph = new PluginGraph(); graph.AddType(typeof (IThingy), typeof (BigThingy)); var family = graph.Families[typeof (IThingy)]; family.Instances .Single() .ShouldBeOfType<ConstructorInstance>() .PluggedType.ShouldEqual(typeof (BigThingy)); graph.AddType(typeof (IThingy), typeof (BigThingy)); family.Instances.Count().ShouldEqual(1); } [Test] public void all_instances_when_family_has_not_been_created() { var graph = new PluginGraph(); graph.AllInstances(typeof (BigThingy)).Any().ShouldBeFalse(); graph.Families.Has(typeof (BigThingy)).ShouldBeFalse(); } [Test] public void all_instances_when_the_family_already_exists() { var graph = new PluginGraph(); graph.Families.FillDefault(typeof (BigThingy)); graph.AllInstances(typeof (BigThingy)).Any().ShouldBeFalse(); } [Test] public void eject_family_removes_the_family_and_disposes_all_of_its_instances() { var instance1 = new FakeInstance(); var instance2 = new FakeInstance(); var instance3 = new FakeInstance(); var graph = new PluginGraph(); graph.Families[typeof(IThingy)].AddInstance(instance1); graph.Families[typeof(IThingy)].AddInstance(instance2); graph.Families[typeof(IThingy)].AddInstance(instance3); graph.EjectFamily(typeof(IThingy)); instance1.WasDisposed.ShouldBeTrue(); instance2.WasDisposed.ShouldBeTrue(); instance3.WasDisposed.ShouldBeTrue(); graph.Families.Has(typeof (IThingy)); } [Test] public void find_family_by_closing_an_open_interface_that_matches() { PluginGraph graph = PluginGraph.Empty(); graph.Families[typeof (IOpen<>)].SetDefault(new ConfiguredInstance(typeof (Open<>))); graph.Families[typeof (IOpen<string>)].GetDefaultInstance().ShouldBeOfType<ConstructorInstance>() .PluggedType.ShouldEqual(typeof (Open<string>)); } [Test] public void find_family_for_concrete_type_with_default() { PluginGraph graph = PluginGraph.Empty(); graph.Families[typeof (BigThingy)].GetDefaultInstance() .ShouldBeOfType<ConstructorInstance>() .PluggedType.ShouldEqual(typeof (BigThingy)); } [Test] public void find_instance_negative_when_family_does_exist_but_instance_does_not() { var graph = new PluginGraph(); graph.Families[typeof (BigThingy)].AddInstance(new SmartInstance<BigThingy>().Named("red")); graph.FindInstance(typeof (BigThingy), "blue").ShouldBeNull(); } [Test] public void find_instance_negative_when_family_does_not_exist_does_not_create_family() { var graph = new PluginGraph(); graph.FindInstance(typeof (BigThingy), "blue").ShouldBeNull(); graph.Families.Has(typeof (BigThingy)).ShouldBeFalse(); } [Test] public void find_instance_positive() { var graph = new PluginGraph(); SmartInstance<BigThingy> instance = new SmartInstance<BigThingy>().Named("red"); graph.Families[typeof (BigThingy)].AddInstance(instance); graph.FindInstance(typeof (BigThingy), "red").ShouldBeTheSameAs(instance); } [Test] public void find_instance_can_use_missing_instance() { var graph = new PluginGraph(); var instance = new SmartInstance<BigThingy>().Named("red"); graph.Families[typeof (BigThingy)].MissingInstance = instance; graph.FindInstance(typeof (BigThingy), "green") .ShouldBeTheSameAs(instance); } [Test] public void has_default_positive() { var graph = new PluginGraph(); graph.Families[typeof(IThingy)].SetDefault(new SmartInstance<BigThingy>()); graph.HasDefaultForPluginType(typeof (IThingy)); } [Test] public void has_default_when_the_family_has_not_been_created() { var graph = new PluginGraph(); graph.HasDefaultForPluginType(typeof(IThingy)).ShouldBeFalse(); } [Test] public void has_default_with_family_but_no_default() { var graph = new PluginGraph(); graph.Families[typeof(IThingy)].AddInstance(new SmartInstance<BigThingy>()); graph.Families[typeof(IThingy)].AddInstance(new SmartInstance<BigThingy>()); graph.HasDefaultForPluginType(typeof(IThingy)) .ShouldBeFalse(); } [Test] public void has_instance_negative_when_the_family_has_not_been_created() { var graph = new PluginGraph(); graph.HasInstance(typeof(IThingy), "red") .ShouldBeFalse(); } [Test] public void has_instance_negative_with_the_family_already_existing() { var graph = new PluginGraph(); graph.Families[typeof(IThingy)] .AddInstance(new SmartInstance<BigThingy>().Named("blue")); graph.HasInstance(typeof(IThingy), "red") .ShouldBeFalse(); } [Test] public void has_instance_positive() { var graph = new PluginGraph(); graph.Families[typeof(IThingy)] .AddInstance(new SmartInstance<BigThingy>().Named("blue")); graph.HasInstance(typeof(IThingy), "blue") .ShouldBeTrue(); } [Test] public void has_family_false_with_simple() { var graph = PluginGraph.Empty(); graph.HasFamily(typeof(IThingy)).ShouldBeFalse(); } [Test] public void has_family_true_with_simple() { var graph = PluginGraph.Empty(); graph.AddFamily(new PluginFamily(typeof(IThingy))); graph.HasFamily(typeof(IThingy)).ShouldBeTrue(); } [Test] public void has_family_true_with_open_generics() { var graph = PluginGraph.Empty(); graph.Families[typeof(IOpen<>)].SetDefault(new ConstructorInstance(typeof(Open<>))); graph.HasFamily(typeof(IOpen<string>)) .ShouldBeTrue(); } } public class FakeInstance : Instance, IDisposable { public bool WasDisposed; protected override string getDescription() { return "fake"; } public void Dispose() { WasDisposed = true; } } public interface IOpen<T> { } public class Open<T> : IOpen<T> { } //[PluginFamily] public interface IThingy { void Go(); } //[Pluggable("Big")] public class BigThingy : IThingy { #region IThingy Members public void Go() { } #endregion } }
using System; using System.Data; using Csla; using Csla.Data; using SelfLoad.DataAccess; using SelfLoad.DataAccess.ERCLevel; namespace SelfLoad.Business.ERCLevel { /// <summary> /// D05_SubContinent_Child (editable child object).<br/> /// This is a generated base class of <see cref="D05_SubContinent_Child"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="D04_SubContinent"/> collection. /// </remarks> [Serializable] public partial class D05_SubContinent_Child : BusinessBase<D05_SubContinent_Child> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="SubContinent_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> SubContinent_Child_NameProperty = RegisterProperty<string>(p => p.SubContinent_Child_Name, "Sub Continent Child Name"); /// <summary> /// Gets or sets the Sub Continent Child Name. /// </summary> /// <value>The Sub Continent Child Name.</value> public string SubContinent_Child_Name { get { return GetProperty(SubContinent_Child_NameProperty); } set { SetProperty(SubContinent_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="D05_SubContinent_Child"/> object. /// </summary> /// <returns>A reference to the created <see cref="D05_SubContinent_Child"/> object.</returns> internal static D05_SubContinent_Child NewD05_SubContinent_Child() { return DataPortal.CreateChild<D05_SubContinent_Child>(); } /// <summary> /// Factory method. Loads a <see cref="D05_SubContinent_Child"/> object, based on given parameters. /// </summary> /// <param name="subContinent_ID1">The SubContinent_ID1 parameter of the D05_SubContinent_Child to fetch.</param> /// <returns>A reference to the fetched <see cref="D05_SubContinent_Child"/> object.</returns> internal static D05_SubContinent_Child GetD05_SubContinent_Child(int subContinent_ID1) { return DataPortal.FetchChild<D05_SubContinent_Child>(subContinent_ID1); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="D05_SubContinent_Child"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public D05_SubContinent_Child() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="D05_SubContinent_Child"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="D05_SubContinent_Child"/> object from the database, based on given criteria. /// </summary> /// <param name="subContinent_ID1">The Sub Continent ID1.</param> protected void Child_Fetch(int subContinent_ID1) { var args = new DataPortalHookArgs(subContinent_ID1); OnFetchPre(args); using (var dalManager = DalFactorySelfLoad.GetManager()) { var dal = dalManager.GetProvider<ID05_SubContinent_ChildDal>(); var data = dal.Fetch(subContinent_ID1); Fetch(data); } OnFetchPost(args); } private void Fetch(IDataReader data) { using (var dr = new SafeDataReader(data)) { if (dr.Read()) { Fetch(dr); } } } /// <summary> /// Loads a <see cref="D05_SubContinent_Child"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(SubContinent_Child_NameProperty, dr.GetString("SubContinent_Child_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="D05_SubContinent_Child"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(D04_SubContinent parent) { using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(); OnInsertPre(args); var dal = dalManager.GetProvider<ID05_SubContinent_ChildDal>(); using (BypassPropertyChecks) { dal.Insert( parent.SubContinent_ID, SubContinent_Child_Name ); } OnInsertPost(args); } } /// <summary> /// Updates in the database all changes made to the <see cref="D05_SubContinent_Child"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(D04_SubContinent parent) { if (!IsDirty) return; using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(); OnUpdatePre(args); var dal = dalManager.GetProvider<ID05_SubContinent_ChildDal>(); using (BypassPropertyChecks) { dal.Update( parent.SubContinent_ID, SubContinent_Child_Name ); } OnUpdatePost(args); } } /// <summary> /// Self deletes the <see cref="D05_SubContinent_Child"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(D04_SubContinent parent) { using (var dalManager = DalFactorySelfLoad.GetManager()) { var args = new DataPortalHookArgs(); OnDeletePre(args); var dal = dalManager.GetProvider<ID05_SubContinent_ChildDal>(); using (BypassPropertyChecks) { dal.Delete(parent.SubContinent_ID); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Xunit; namespace List_List_CopyToTests { public class List_CopyToTests { [Fact] public static void CopyTo_Simple() { int[] intArr = new int[10]; for (int i = 0; i < 10; i++) intArr[i] = i; List<int> intList = new List<int>(new TestCollection<int>(intArr)); int[] copy = new int[intArr.Length]; intList.CopyTo(copy); for (int i = 0; i < intArr.Length; i++) { Assert.Equal(intArr[i], copy[i]); //"Expect the same contents from original array and the copy." Assert.Equal(intArr[i], intList[i]); //"Expect the same contents from original array and the list." } } [Fact] public static void CopyTo_Simple2() { int[] intArr = new int[10]; for (int i = 0; i < 10; i++) intArr[i] = i; List<int> intList = new List<int>(new TestCollection<int>(intArr)); int[] copy = new int[intArr.Length]; intList.CopyTo(copy, 0); for (int i = 0; i < intArr.Length; i++) { Assert.Equal(intArr[i], copy[i]); //"Expect the same contents from original array and the copy." Assert.Equal(intArr[i], intList[i]); //"Expect the same contents from original array and the list." } } [Fact] public static void CopyTo_Simple3() { int[] intArr = new int[10]; for (int i = 0; i < 10; i++) intArr[i] = i; List<int> intList = new List<int>(new TestCollection<int>(intArr)); int[] copy = new int[intArr.Length]; intList.CopyTo(0, copy, 0, intList.Count); for (int i = 0; i < intArr.Length; i++) { Assert.Equal(intArr[i], copy[i]); //"Expect the same contents from original array and the copy." Assert.Equal(intArr[i], intList[i]); //"Expect the same contents from original array and the list." } } /// <summary> /// Start copying into the middle of the output array. /// </summary> [Fact] public static void CopyTo_Simple2_Middle() { string[] stringArr = new string[10]; for (int i = 0; i < 10; i++) stringArr[i] = "SomeTestString" + i.ToString(); List<string> stringList = new List<string>(new TestCollection<string>(stringArr)); int index = 4; int extra = 10; int totalSize = stringArr.Length + index + extra; string[] copy = new string[totalSize]; stringList.CopyTo(copy, index); for (int i = 0; i < totalSize; i++) { if (i < index) Assert.Null(copy[i]); //"Should be null because nothing has been copied into the array yet." else if (i >= index && i < (stringArr.Length + index)) Assert.Equal(stringArr[i - index], copy[i]); //"Expect the same contents from original array and the copy." else Assert.Null(copy[i]); //"Should be null because nothing has been copied into the array yet." if (i < stringArr.Length) Assert.Equal(stringArr[i], stringList[i]); //"Expect the same contents from original array and the copy." } } [Fact] public static void CopyTo_Empty() { string[] good = new string[10]; new List<string>().CopyTo(good); for (int i = 0; i < good.Length; i++) Assert.Null(good[i]); //"Should have nothing in the array." } [Fact] public static void CopyTo_Empty2() { string[] good = new string[10]; new List<string>().CopyTo(good, 0); for (int i = 0; i < good.Length; i++) Assert.Null(good[i]); //"Should have nothing in the array." } [Fact] public static void CopyTo_Empty3() { string[] good = new string[10]; new List<string>().CopyTo(0, good, 0, 0); for (int i = 0; i < good.Length; i++) Assert.Null(good[i]); //"Should have nothing in the array." } [Fact] public static void CopyTo_3Index() { int[] intArr = new int[10]; for (int i = 0; i < 10; i++) intArr[i] = i; List<int> intList = new List<int>(new TestCollection<int>(intArr)); for (int i = 0; i < 10; i++) { int[] output = new int[intArr.Length + i]; intList.CopyTo(i, output, i, intList.Count - i); for (int j = i; j < intArr.Length; j++) Assert.Equal(intList[j], output[j]); //"Should be equal to the same contents as the list." } string[] stringArr = new string[10]; for (int i = 0; i < 10; i++) stringArr[i] = "StringTest" + i.ToString(); List<string> stringList = new List<string>(new TestCollection<string>(stringArr)); for (int i = 0; i < 10; i++) { string[] output = new string[stringArr.Length]; int startIndex = i; int lastIndex = stringArr.Length - i; stringList.CopyTo(i, output, 0, stringArr.Length - i); for (int j = 0; j < stringArr.Length; j++) { if (j >= lastIndex) Assert.Null(output[j]); //"Should have nothing here, but has value: " + output[j] else Assert.Equal(stringList[j + startIndex], output[j]); //"Should be equal to the same contents as the list." } } } [Fact] public static void CopyTo_3ArrayIndex() { int[] intArr = new int[10]; List<int> intList = new List<int>(new TestCollection<int>(intArr)); // //Second parameter validation tests // for (int i = 0; i < 10; i++) { int[] arr2 = new int[intArr.Length + i]; intList.CopyTo(0, arr2, i, intList.Count); for (int j = i; j < intArr.Length + i; j++) Assert.Equal(intList[j - i], arr2[j]); //"should have equal contents as source list." } } [Fact] public static void CopyTo_3Count() { string[] stringArr = new string[10]; for (int i = 0; i < 10; i++) stringArr[i] = "StringTest" + i.ToString(); List<string> stringList = new List<string>(new TestCollection<string>(stringArr)); for (int i = 0; i < 10; i++) { string[] output = new string[stringArr.Length]; int lastIndex = i; stringList.CopyTo(0, output, 0, i); for (int j = 0; j < stringArr.Length; j++) { if (j >= lastIndex) Assert.Null(output[j]); //"Should have nothing here, but has value: " + output[j] else Assert.Equal(stringList[j], output[j]); //"Should be equal to the same contents as the list." } } } [Fact] public static void CopyTo_Negative() { int[] intArr = new int[10]; for (int i = 0; i < 10; i++) intArr[i] = i; List<int> IntList = new List<int>(new TestCollection<int>(intArr)); Assert.Throws<ArgumentNullException>(() => IntList.CopyTo(null)); //"ArgumentNullException expected on null array." int[] bad = new int[4]; Assert.Throws<ArgumentException>(() => IntList.CopyTo(bad)); //"ArgumentException expected when output array is too small." } [Fact] public static void CopyTo_Negative2() { int[] intArr = new int[10]; List<int> intList = new List<int>(new TestCollection<int>(intArr)); for (int i = 0; i < 10; i++) { int[] copy = new int[intArr.Length + i]; Assert.Throws<ArgumentException>(() => intList.CopyTo(copy, i + 1)); //"ArgumentException expected when output array cannot fit contents + index." } int[] output = new int[intArr.Length]; Assert.Throws<ArgumentOutOfRangeException>(() => intList.CopyTo(output, -1)); //"ArgumentOutOfRangeException expected for negative index." Assert.Throws<ArgumentOutOfRangeException>(() => intList.CopyTo(output, int.MinValue)); //"ArgumentException expected for negative index." Assert.Throws<ArgumentNullException>(() => intList.CopyTo(null, 0)); //"ArgumentNullException expected for null array." int[] bad = new int[4]; Assert.Throws<ArgumentException>(() => intList.CopyTo(bad, 0)); //"ArgumentException expected when output array cannot fit." } [Fact] public static void CopyTo_Negative3() { int[] intArr = new int[10]; List<int> intList = new List<int>(new TestCollection<int>(intArr)); // 1st parameter validation for (int i = 0; i < 10; i++) { int[] output = new int[intArr.Length]; Assert.Throws<ArgumentException>(() => intList.CopyTo(i, output, 0, intList.Count - i + 1)); //"ArgumentException should be thrown if output array cannot fit the list + index" } int[] copy = new int[intArr.Length]; Assert.Throws<ArgumentOutOfRangeException>(() => intList.CopyTo(-1, copy, 0, intList.Count)); //"Should throw ArgumentOutOfRangeException on negative index" Assert.Throws<ArgumentException>(() => intList.CopyTo(int.MinValue, copy, 0, intList.Count)); //"Should throw ArgumentException on negative index" // 2nd parameter validation Assert.Throws<ArgumentNullException>(() => intList.CopyTo(0, null, 0, intArr.Length)); //"ArgumentNullException expected when output is null." // 3rd parameter validation for (int i = 0; i < 10; i++) { int[] arr3 = new int[intArr.Length + i]; Assert.Throws<ArgumentException>(() => intList.CopyTo(0, arr3, i + 1, intList.Count)); //"Should throw ArgumentException if arrayIndex + list cannot fit." } Assert.Throws<ArgumentOutOfRangeException>(() => intList.CopyTo(0, copy, -1, intList.Count)); //"Should throw ArgumentOutOfRangeException on negative index" Assert.Throws<ArgumentOutOfRangeException>(() => intList.CopyTo(0, copy, int.MinValue, intList.Count)); //"Should throw ArgumentOutOfRangeException on negative index" // Fourth parameter validation tests Assert.Throws<ArgumentOutOfRangeException>(() => intList.CopyTo(0, copy, 0, -1)); //"Should throw ArgumentOutOfRangeException on negative count." Assert.Throws<ArgumentOutOfRangeException>(() => intList.CopyTo(0, copy, 0, int.MinValue)); //"Should throw ArgumentOutOfRangeException on negative count." Assert.Throws<ArgumentException>(() => intList.CopyTo(0, copy, 0, int.MaxValue)); //"ArgumentException when count is greater than source List." copy = new int[intArr.Length - 5]; Assert.Throws<ArgumentException>(() => intList.CopyTo(0, copy, 0, intArr.Length)); //"ArgumentException when output array is smaller than input array.." copy = new int[intArr.Length + 3]; Assert.Throws<ArgumentException>(() => intList.CopyTo(0, copy, 0, 11)); //"ArgumentException when count is greater than source List." } } #region Helper Classes /// <summary> /// Helper class that implements ICollection. /// </summary> public class TestCollection<T> : ICollection<T> { /// <summary> /// Expose the Items in Array to give more test flexibility... /// </summary> public readonly T[] m_items; public TestCollection(T[] items) { m_items = items; } public void CopyTo(T[] array, int index) { Array.Copy(m_items, 0, array, index, m_items.Length); } public int Count { get { if (m_items == null) return 0; else return m_items.Length; } } public Object SyncRoot { get { return this; } } public bool IsSynchronized { get { return false; } } public IEnumerator<T> GetEnumerator() { return new TestCollectionEnumerator<T>(this); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new TestCollectionEnumerator<T>(this); } private class TestCollectionEnumerator<T1> : IEnumerator<T1> { private TestCollection<T1> _col; private int _index; public void Dispose() { } public TestCollectionEnumerator(TestCollection<T1> col) { _col = col; _index = -1; } public bool MoveNext() { return (++_index < _col.m_items.Length); } public T1 Current { get { return _col.m_items[_index]; } } Object System.Collections.IEnumerator.Current { get { return _col.m_items[_index]; } } public void Reset() { _index = -1; } } #region Non Implemented methods public void Add(T item) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Contains(T item) { throw new NotSupportedException(); } public bool Remove(T item) { throw new NotSupportedException(); } public bool IsReadOnly { get { throw new NotSupportedException(); } } #endregion } #endregion }
using System; namespace M2SA.AppGenome.Threading.Internal { #region WorkItemFactory class /// <summary> /// /// </summary> public class WorkItemFactory { /// <summary> /// Create a new work item /// </summary> /// <param name="workItemsGroup">The WorkItemsGroup of this workitem</param> /// <param name="wigStartInfo">Work item group start information</param> /// <param name="callback">A callback to execute</param> /// <returns>Returns a work item</returns> public static WorkItem CreateWorkItem( IWorkItemsGroup workItemsGroup, WIGStartInfo wigStartInfo, WorkItemCallback callback) { return CreateWorkItem(workItemsGroup, wigStartInfo, callback, null); } /// <summary> /// Create a new work item /// </summary> /// <param name="workItemsGroup">The WorkItemsGroup of this workitem</param> /// <param name="wigStartInfo">Work item group start information</param> /// <param name="callback">A callback to execute</param> /// <param name="workItemPriority">The priority of the work item</param> /// <returns>Returns a work item</returns> public static WorkItem CreateWorkItem( IWorkItemsGroup workItemsGroup, WIGStartInfo wigStartInfo, WorkItemCallback callback, WorkItemPriority workItemPriority) { return CreateWorkItem(workItemsGroup, wigStartInfo, callback, null, workItemPriority); } /// <summary> /// Create a new work item /// </summary> /// <param name="workItemsGroup">The WorkItemsGroup of this workitem</param> /// <param name="wigStartInfo">Work item group start information</param> /// <param name="workItemInfo">Work item info</param> /// <param name="callback">A callback to execute</param> /// <returns>Returns a work item</returns> public static WorkItem CreateWorkItem( IWorkItemsGroup workItemsGroup, WIGStartInfo wigStartInfo, WorkItemInfo workItemInfo, WorkItemCallback callback) { return CreateWorkItem( workItemsGroup, wigStartInfo, workItemInfo, callback, null); } /// <summary> /// Create a new work item /// </summary> /// <param name="workItemsGroup">The WorkItemsGroup of this workitem</param> /// <param name="wigStartInfo">Work item group start information</param> /// <param name="callback">A callback to execute</param> /// <param name="state"> /// The context object of the work item. Used for passing arguments to the work item. /// </param> /// <returns>Returns a work item</returns> public static WorkItem CreateWorkItem( IWorkItemsGroup workItemsGroup, WIGStartInfo wigStartInfo, WorkItemCallback callback, object state) { ValidateCallback(callback); if (null == wigStartInfo) throw new ArgumentNullException("wigStartInfo"); WorkItemInfo workItemInfo = new WorkItemInfo(); workItemInfo.UseCallerCallContext = wigStartInfo.UseCallerCallContext; workItemInfo.UseCallerHttpContext = wigStartInfo.UseCallerHttpContext; workItemInfo.PostExecuteWorkItemCallback = wigStartInfo.PostExecuteWorkItemCallback; workItemInfo.CallToPostExecute = wigStartInfo.CallToPostExecute; workItemInfo.DisposeOfStateObjects = wigStartInfo.DisposeOfStateObjects; workItemInfo.WorkItemPriority = wigStartInfo.WorkItemPriority; WorkItem workItem = new WorkItem( workItemsGroup, workItemInfo, callback, state); return workItem; } /// <summary> /// Create a new work item /// </summary> /// <param name="workItemsGroup">The work items group</param> /// <param name="wigStartInfo">Work item group start information</param> /// <param name="callback">A callback to execute</param> /// <param name="state"> /// The context object of the work item. Used for passing arguments to the work item. /// </param> /// <param name="workItemPriority">The work item priority</param> /// <returns>Returns a work item</returns> public static WorkItem CreateWorkItem( IWorkItemsGroup workItemsGroup, WIGStartInfo wigStartInfo, WorkItemCallback callback, object state, WorkItemPriority workItemPriority) { ValidateCallback(callback); if (null == wigStartInfo) throw new ArgumentNullException("wigStartInfo"); WorkItemInfo workItemInfo = new WorkItemInfo(); workItemInfo.UseCallerCallContext = wigStartInfo.UseCallerCallContext; workItemInfo.UseCallerHttpContext = wigStartInfo.UseCallerHttpContext; workItemInfo.PostExecuteWorkItemCallback = wigStartInfo.PostExecuteWorkItemCallback; workItemInfo.CallToPostExecute = wigStartInfo.CallToPostExecute; workItemInfo.DisposeOfStateObjects = wigStartInfo.DisposeOfStateObjects; workItemInfo.WorkItemPriority = workItemPriority; WorkItem workItem = new WorkItem( workItemsGroup, workItemInfo, callback, state); return workItem; } /// <summary> /// Create a new work item /// </summary> /// <param name="workItemsGroup">The work items group</param> /// <param name="wigStartInfo">Work item group start information</param> /// <param name="workItemInfo">Work item information</param> /// <param name="callback">A callback to execute</param> /// <param name="state"> /// The context object of the work item. Used for passing arguments to the work item. /// </param> /// <returns>Returns a work item</returns> public static WorkItem CreateWorkItem( IWorkItemsGroup workItemsGroup, WIGStartInfo wigStartInfo, WorkItemInfo workItemInfo, WorkItemCallback callback, object state) { if (null == workItemInfo) throw new ArgumentNullException("workItemInfo"); ValidateCallback(callback); ValidateCallback(workItemInfo.PostExecuteWorkItemCallback); WorkItem workItem = new WorkItem( workItemsGroup, new WorkItemInfo(workItemInfo), callback, state); return workItem; } /// <summary> /// Create a new work item /// </summary> /// <param name="workItemsGroup">The work items group</param> /// <param name="wigStartInfo">Work item group start information</param> /// <param name="callback">A callback to execute</param> /// <param name="state"> /// The context object of the work item. Used for passing arguments to the work item. /// </param> /// <param name="postExecuteWorkItemCallback"> /// A delegate to call after the callback completion /// </param> /// <returns>Returns a work item</returns> public static WorkItem CreateWorkItem( IWorkItemsGroup workItemsGroup, WIGStartInfo wigStartInfo, WorkItemCallback callback, object state, PostExecuteWorkItemCallback postExecuteWorkItemCallback) { ValidateCallback(callback); ValidateCallback(postExecuteWorkItemCallback); if (null == wigStartInfo) throw new ArgumentNullException("wigStartInfo"); WorkItemInfo workItemInfo = new WorkItemInfo(); workItemInfo.UseCallerCallContext = wigStartInfo.UseCallerCallContext; workItemInfo.UseCallerHttpContext = wigStartInfo.UseCallerHttpContext; workItemInfo.PostExecuteWorkItemCallback = postExecuteWorkItemCallback; workItemInfo.CallToPostExecute = wigStartInfo.CallToPostExecute; workItemInfo.DisposeOfStateObjects = wigStartInfo.DisposeOfStateObjects; workItemInfo.WorkItemPriority = wigStartInfo.WorkItemPriority; WorkItem workItem = new WorkItem( workItemsGroup, workItemInfo, callback, state); return workItem; } /// <summary> /// Create a new work item /// </summary> /// <param name="workItemsGroup">The work items group</param> /// <param name="wigStartInfo">Work item group start information</param> /// <param name="callback">A callback to execute</param> /// <param name="state"> /// The context object of the work item. Used for passing arguments to the work item. /// </param> /// <param name="postExecuteWorkItemCallback"> /// A delegate to call after the callback completion /// </param> /// <param name="workItemPriority">The work item priority</param> /// <returns>Returns a work item</returns> public static WorkItem CreateWorkItem( IWorkItemsGroup workItemsGroup, WIGStartInfo wigStartInfo, WorkItemCallback callback, object state, PostExecuteWorkItemCallback postExecuteWorkItemCallback, WorkItemPriority workItemPriority) { ValidateCallback(callback); ValidateCallback(postExecuteWorkItemCallback); if (null == wigStartInfo) throw new ArgumentNullException("wigStartInfo"); WorkItemInfo workItemInfo = new WorkItemInfo(); workItemInfo.UseCallerCallContext = wigStartInfo.UseCallerCallContext; workItemInfo.UseCallerHttpContext = wigStartInfo.UseCallerHttpContext; workItemInfo.PostExecuteWorkItemCallback = postExecuteWorkItemCallback; workItemInfo.CallToPostExecute = wigStartInfo.CallToPostExecute; workItemInfo.DisposeOfStateObjects = wigStartInfo.DisposeOfStateObjects; workItemInfo.WorkItemPriority = workItemPriority; WorkItem workItem = new WorkItem( workItemsGroup, workItemInfo, callback, state); return workItem; } /// <summary> /// Create a new work item /// </summary> /// <param name="workItemsGroup">The work items group</param> /// <param name="wigStartInfo">Work item group start information</param> /// <param name="callback">A callback to execute</param> /// <param name="state"> /// The context object of the work item. Used for passing arguments to the work item. /// </param> /// <param name="postExecuteWorkItemCallback"> /// A delegate to call after the callback completion /// </param> /// <param name="callToPostExecute">Indicates on which cases to call to the post execute callback</param> /// <returns>Returns a work item</returns> public static WorkItem CreateWorkItem( IWorkItemsGroup workItemsGroup, WIGStartInfo wigStartInfo, WorkItemCallback callback, object state, PostExecuteWorkItemCallback postExecuteWorkItemCallback, CallToPostExecute callToPostExecute) { ValidateCallback(callback); ValidateCallback(postExecuteWorkItemCallback); if (null == wigStartInfo) throw new ArgumentNullException("wigStartInfo"); WorkItemInfo workItemInfo = new WorkItemInfo(); workItemInfo.UseCallerCallContext = wigStartInfo.UseCallerCallContext; workItemInfo.UseCallerHttpContext = wigStartInfo.UseCallerHttpContext; workItemInfo.PostExecuteWorkItemCallback = postExecuteWorkItemCallback; workItemInfo.CallToPostExecute = callToPostExecute; workItemInfo.DisposeOfStateObjects = wigStartInfo.DisposeOfStateObjects; workItemInfo.WorkItemPriority = wigStartInfo.WorkItemPriority; WorkItem workItem = new WorkItem( workItemsGroup, workItemInfo, callback, state); return workItem; } /// <summary> /// Create a new work item /// </summary> /// <param name="workItemsGroup">The work items group</param> /// <param name="wigStartInfo">Work item group start information</param> /// <param name="callback">A callback to execute</param> /// <param name="state"> /// The context object of the work item. Used for passing arguments to the work item. /// </param> /// <param name="postExecuteWorkItemCallback"> /// A delegate to call after the callback completion /// </param> /// <param name="callToPostExecute">Indicates on which cases to call to the post execute callback</param> /// <param name="workItemPriority">The work item priority</param> /// <returns>Returns a work item</returns> public static WorkItem CreateWorkItem( IWorkItemsGroup workItemsGroup, WIGStartInfo wigStartInfo, WorkItemCallback callback, object state, PostExecuteWorkItemCallback postExecuteWorkItemCallback, CallToPostExecute callToPostExecute, WorkItemPriority workItemPriority) { if (null == wigStartInfo) throw new ArgumentNullException("wigStartInfo"); ValidateCallback(callback); ValidateCallback(postExecuteWorkItemCallback); WorkItemInfo workItemInfo = new WorkItemInfo(); workItemInfo.UseCallerCallContext = wigStartInfo.UseCallerCallContext; workItemInfo.UseCallerHttpContext = wigStartInfo.UseCallerHttpContext; workItemInfo.PostExecuteWorkItemCallback = postExecuteWorkItemCallback; workItemInfo.CallToPostExecute = callToPostExecute; workItemInfo.WorkItemPriority = workItemPriority; workItemInfo.DisposeOfStateObjects = wigStartInfo.DisposeOfStateObjects; WorkItem workItem = new WorkItem( workItemsGroup, workItemInfo, callback, state); return workItem; } private static void ValidateCallback(Delegate callback) { if (callback != null && callback.GetInvocationList().Length > 1) { throw new NotSupportedException("SmartThreadPool doesn't support delegates chains"); } } } #endregion }
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Diagnostics; using SharpDX; using SharpDX.D3DCompiler; using SharpDX.Direct3D; using SharpDX.Direct3D11; using SharpDX.DXGI; using SharpDX.Windows; using Buffer = SharpDX.Direct3D11.Buffer; using Device = SharpDX.Direct3D11.Device; using MapFlags = SharpDX.Direct3D11.MapFlags; namespace MiniCubeTexure { /// <summary> /// SharpDX MiniCubeTexture Direct3D 11 Sample /// </summary> internal static class Program { [STAThread] private static void Main() { var form = new RenderForm("SharpDX - MiniCubeTexture Direct3D11 Sample"); // SwapChain description var desc = new SwapChainDescription() { BufferCount = 1, ModeDescription = new ModeDescription(form.ClientSize.Width, form.ClientSize.Height, new Rational(60, 1), Format.R8G8B8A8_UNorm), IsWindowed = true, OutputHandle = form.Handle, SampleDescription = new SampleDescription(1, 0), SwapEffect = SwapEffect.Discard, Usage = Usage.RenderTargetOutput }; // Create Device and SwapChain Device device; SwapChain swapChain; Device.CreateWithSwapChain(DriverType.Hardware, DeviceCreationFlags.Debug, desc, out device, out swapChain); var context = device.ImmediateContext; // Ignore all windows events var factory = swapChain.GetParent<Factory>(); factory.MakeWindowAssociation(form.Handle, WindowAssociationFlags.IgnoreAll); // New RenderTargetView from the backbuffer var backBuffer = Texture2D.FromSwapChain<Texture2D>(swapChain, 0); var renderView = new RenderTargetView(device, backBuffer); // Compile Vertex and Pixel shaders var vertexShaderByteCode = ShaderBytecode.CompileFromFile("MiniCubeTexture.fx", "VS", "vs_4_0"); var vertexShader = new VertexShader(device, vertexShaderByteCode); var pixelShaderByteCode = ShaderBytecode.CompileFromFile("MiniCubeTexture.fx", "PS", "ps_4_0"); var pixelShader = new PixelShader(device, pixelShaderByteCode); // Layout from VertexShader input signature var layout = new InputLayout(device, ShaderSignature.GetInputSignature(vertexShaderByteCode), new[] { new InputElement("POSITION", 0, Format.R32G32B32A32_Float, 0, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 16, 0) }); // Instantiate Vertex buiffer from vertex data var vertices = Buffer.Create(device, BindFlags.VertexBuffer, new[] { // 3D coordinates UV Texture coordinates -1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 1.0f, // Front -1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 0.0f, -1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, // BACK 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, // Top -1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, -1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, -1.0f,-1.0f, -1.0f, 1.0f, 1.0f, 0.0f, // Bottom 1.0f,-1.0f, 1.0f, 1.0f, 0.0f, 1.0f, -1.0f,-1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f,-1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 1.0f,-1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f,-1.0f, 1.0f, 1.0f, 0.0f, 1.0f, -1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 1.0f, // Left -1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, -1.0f, -1.0f, -1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 0.0f, // Right 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, -1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, }); // Create Constant Buffer var contantBuffer = new Buffer(device, Utilities.SizeOf<Matrix>(), ResourceUsage.Default, BindFlags.ConstantBuffer, CpuAccessFlags.None, ResourceOptionFlags.None, 0); // Create Depth Buffer & View var depthBuffer = new Texture2D(device, new Texture2DDescription() { Format = Format.D32_Float_S8X24_UInt, ArraySize = 1, MipLevels = 1, Width = form.ClientSize.Width, Height = form.ClientSize.Height, SampleDescription = new SampleDescription(1, 0), Usage = ResourceUsage.Default, BindFlags = BindFlags.DepthStencil, CpuAccessFlags = CpuAccessFlags.None, OptionFlags = ResourceOptionFlags.None }); var depthView = new DepthStencilView(device, depthBuffer); // Load texture and create sampler var texture = Texture2D.FromFile<Texture2D>(device, "GeneticaMortarlessBlocks.jpg"); var textureView = new ShaderResourceView(device, texture); var sampler = new SamplerState(device, new SamplerStateDescription() { Filter = Filter.MinMagMipLinear, AddressU = TextureAddressMode.Wrap, AddressV = TextureAddressMode.Wrap, AddressW = TextureAddressMode.Wrap, BorderColor = Color.Black, ComparisonFunction = Comparison.Never, MaximumAnisotropy = 16, MipLodBias = 0, MinimumLod = 0, MaximumLod = 16, }); // Prepare All the stages context.InputAssembler.InputLayout = layout; context.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; context.InputAssembler.SetVertexBuffers(0, new VertexBufferBinding(vertices, Utilities.SizeOf<Vector4>() + Utilities.SizeOf<Vector2>(), 0)); context.VertexShader.SetConstantBuffer(0, contantBuffer); context.VertexShader.Set(vertexShader); context.Rasterizer.SetViewport(new Viewport(0, 0, form.ClientSize.Width, form.ClientSize.Height, 0.0f, 1.0f)); context.PixelShader.Set(pixelShader); context.PixelShader.SetSampler(0, sampler); context.PixelShader.SetShaderResource(0, textureView); context.OutputMerger.SetTargets(depthView, renderView); // Prepare matrices var view = Matrix.LookAtLH(new Vector3(0, 0, -5), new Vector3(0, 0, 0), Vector3.UnitY); var proj = Matrix.PerspectiveFovLH((float)Math.PI / 4.0f, form.ClientSize.Width / (float)form.ClientSize.Height, 0.1f, 100.0f); var viewProj = Matrix.Multiply(view, proj); // Use clock var clock = new Stopwatch(); clock.Start(); // Main loop RenderLoop.Run(form, () => { var time = clock.ElapsedMilliseconds / 1000.0f; // Clear views context.ClearDepthStencilView(depthView, DepthStencilClearFlags.Depth, 1.0f, 0); context.ClearRenderTargetView(renderView, Color.Black); // Update WorldViewProj Matrix var worldViewProj = Matrix.RotationX(time) * Matrix.RotationY(time * 2) * Matrix.RotationZ(time * .7f) * viewProj; worldViewProj.Transpose(); context.UpdateSubresource(ref worldViewProj, contantBuffer); // Draw the cube context.Draw(36, 0); // Present! swapChain.Present(0, PresentFlags.None); }); // Release all resources vertexShaderByteCode.Dispose(); vertexShader.Dispose(); pixelShaderByteCode.Dispose(); pixelShader.Dispose(); vertices.Dispose(); layout.Dispose(); renderView.Dispose(); backBuffer.Dispose(); context.ClearState(); context.Flush(); device.Dispose(); context.Dispose(); swapChain.Dispose(); factory.Dispose(); } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Globalization; #if NET20 using Medivh.Json.Utilities.LinqBridge; #else using System.Linq; #endif using Medivh.Json.Serialization; namespace Medivh.Json.Utilities { internal static class StringUtils { public const string CarriageReturnLineFeed = "\r\n"; public const string Empty = ""; public const char CarriageReturn = '\r'; public const char LineFeed = '\n'; public const char Tab = '\t'; public static string FormatWith(this string format, IFormatProvider provider, object arg0) { return format.FormatWith(provider, new[] { arg0 }); } public static string FormatWith(this string format, IFormatProvider provider, object arg0, object arg1) { return format.FormatWith(provider, new[] { arg0, arg1 }); } public static string FormatWith(this string format, IFormatProvider provider, object arg0, object arg1, object arg2) { return format.FormatWith(provider, new[] { arg0, arg1, arg2 }); } public static string FormatWith(this string format, IFormatProvider provider, object arg0, object arg1, object arg2, object arg3) { return format.FormatWith(provider, new[] { arg0, arg1, arg2, arg3 }); } private static string FormatWith(this string format, IFormatProvider provider, params object[] args) { // leave this a private to force code to use an explicit overload // avoids stack memory being reserved for the object array ValidationUtils.ArgumentNotNull(format, nameof(format)); return string.Format(provider, format, args); } /// <summary> /// Determines whether the string is all white space. Empty string will return false. /// </summary> /// <param name="s">The string to test whether it is all white space.</param> /// <returns> /// <c>true</c> if the string is all white space; otherwise, <c>false</c>. /// </returns> public static bool IsWhiteSpace(string s) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (s.Length == 0) { return false; } for (int i = 0; i < s.Length; i++) { if (!char.IsWhiteSpace(s[i])) { return false; } } return true; } /// <summary> /// Nulls an empty string. /// </summary> /// <param name="s">The string.</param> /// <returns>Null if the string was null, otherwise the string unchanged.</returns> public static string NullEmptyString(string s) { return (string.IsNullOrEmpty(s)) ? null : s; } public static StringWriter CreateStringWriter(int capacity) { StringBuilder sb = new StringBuilder(capacity); StringWriter sw = new StringWriter(sb, CultureInfo.InvariantCulture); return sw; } public static int? GetLength(string value) { if (value == null) { return null; } else { return value.Length; } } public static void ToCharAsUnicode(char c, char[] buffer) { buffer[0] = '\\'; buffer[1] = 'u'; buffer[2] = MathUtils.IntToHex((c >> 12) & '\x000f'); buffer[3] = MathUtils.IntToHex((c >> 8) & '\x000f'); buffer[4] = MathUtils.IntToHex((c >> 4) & '\x000f'); buffer[5] = MathUtils.IntToHex(c & '\x000f'); } public static TSource ForgivingCaseSensitiveFind<TSource>(this IEnumerable<TSource> source, Func<TSource, string> valueSelector, string testValue) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (valueSelector == null) { throw new ArgumentNullException(nameof(valueSelector)); } var caseInsensitiveResults = source.Where(s => string.Equals(valueSelector(s), testValue, StringComparison.OrdinalIgnoreCase)); if (caseInsensitiveResults.Count() <= 1) { return caseInsensitiveResults.SingleOrDefault(); } else { // multiple results returned. now filter using case sensitivity var caseSensitiveResults = source.Where(s => string.Equals(valueSelector(s), testValue, StringComparison.Ordinal)); return caseSensitiveResults.SingleOrDefault(); } } public static string ToCamelCase(string s) { if (string.IsNullOrEmpty(s)) { return s; } if (!char.IsUpper(s[0])) { return s; } char[] chars = s.ToCharArray(); for (int i = 0; i < chars.Length; i++) { bool hasNext = (i + 1 < chars.Length); if (i > 0 && hasNext && !char.IsUpper(chars[i + 1])) { break; } #if !(DOTNET || PORTABLE) chars[i] = char.ToLower(chars[i], CultureInfo.InvariantCulture); #else chars[i] = char.ToLowerInvariant(chars[i]); #endif } return new string(chars); } public static bool IsHighSurrogate(char c) { #if !(PORTABLE40 || PORTABLE) return char.IsHighSurrogate(c); #else return (c >= 55296 && c <= 56319); #endif } public static bool IsLowSurrogate(char c) { #if !(PORTABLE40 || PORTABLE) return char.IsLowSurrogate(c); #else return (c >= 56320 && c <= 57343); #endif } public static bool StartsWith(this string source, char value) { return (source.Length > 0 && source[0] == value); } public static bool EndsWith(this string source, char value) { return (source.Length > 0 && source[source.Length - 1] == value); } } }
/* * 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.Collections.Specialized; using System.IO; using System.Net; using System.Web; using DotNetOpenId; using DotNetOpenId.Provider; using OpenSim.Framework; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Server.Handlers.Base; using OpenSim.Services.Interfaces; using Nini.Config; using OpenMetaverse; namespace OpenSim.Server.Handlers.Authentication { /// <summary> /// Temporary, in-memory store for OpenID associations /// </summary> public class ProviderMemoryStore : IAssociationStore<AssociationRelyingPartyType> { private class AssociationItem { public AssociationRelyingPartyType DistinguishingFactor; public string Handle; public DateTime Expires; public byte[] PrivateData; } Dictionary<string, AssociationItem> m_store = new Dictionary<string, AssociationItem>(); SortedList<DateTime, AssociationItem> m_sortedStore = new SortedList<DateTime, AssociationItem>(); object m_syncRoot = new object(); #region IAssociationStore<AssociationRelyingPartyType> Members public void StoreAssociation(AssociationRelyingPartyType distinguishingFactor, Association assoc) { AssociationItem item = new AssociationItem(); item.DistinguishingFactor = distinguishingFactor; item.Handle = assoc.Handle; item.Expires = assoc.Expires.ToLocalTime(); item.PrivateData = assoc.SerializePrivateData(); lock (m_syncRoot) { m_store[item.Handle] = item; m_sortedStore[item.Expires] = item; } } public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor) { lock (m_syncRoot) { if (m_sortedStore.Count > 0) { AssociationItem item = m_sortedStore.Values[m_sortedStore.Count - 1]; return Association.Deserialize(item.Handle, item.Expires.ToUniversalTime(), item.PrivateData); } else { return null; } } } public Association GetAssociation(AssociationRelyingPartyType distinguishingFactor, string handle) { AssociationItem item; bool success = false; lock (m_syncRoot) success = m_store.TryGetValue(handle, out item); if (success) return Association.Deserialize(item.Handle, item.Expires.ToUniversalTime(), item.PrivateData); else return null; } public bool RemoveAssociation(AssociationRelyingPartyType distinguishingFactor, string handle) { lock (m_syncRoot) { for (int i = 0; i < m_sortedStore.Values.Count; i++) { AssociationItem item = m_sortedStore.Values[i]; if (item.Handle == handle) { m_sortedStore.RemoveAt(i); break; } } return m_store.Remove(handle); } } public void ClearExpiredAssociations() { lock (m_syncRoot) { List<AssociationItem> itemsCopy = new List<AssociationItem>(m_sortedStore.Values); DateTime now = DateTime.Now; for (int i = 0; i < itemsCopy.Count; i++) { AssociationItem item = itemsCopy[i]; if (item.Expires <= now) { m_sortedStore.RemoveAt(i); m_store.Remove(item.Handle); } } } } #endregion } public class OpenIdStreamHandler : BaseOutputStreamHandler, IStreamHandler { #region HTML /// <summary>Login form used to authenticate OpenID requests</summary> const string LOGIN_PAGE = @"<html> <head><title>OpenSim OpenID Login</title></head> <body> <h3>OpenSim Login</h3> <form method=""post""> <label for=""first"">First Name:</label> <input readonly type=""text"" name=""first"" id=""first"" value=""{0}""/> <label for=""last"">Last Name:</label> <input readonly type=""text"" name=""last"" id=""last"" value=""{1}""/> <label for=""pass"">Password:</label> <input type=""password"" name=""pass"" id=""pass""/> <input type=""submit"" value=""Login""> </form> </body> </html>"; /// <summary>Page shown for a valid OpenID identity</summary> const string OPENID_PAGE = @"<html> <head> <title>{2} {3}</title> <link rel=""openid2.provider openid.server"" href=""{0}://{1}/openid/server/""/> </head> <body>OpenID identifier for {2} {3}</body> </html> "; /// <summary>Page shown for an invalid OpenID identity</summary> const string INVALID_OPENID_PAGE = @"<html><head><title>Identity not found</title></head> <body>Invalid OpenID identity</body></html>"; /// <summary>Page shown if the OpenID endpoint is requested directly</summary> const string ENDPOINT_PAGE = @"<html><head><title>OpenID Endpoint</title></head><body> This is an OpenID server endpoint, not a human-readable resource. For more information, see <a href='http://openid.net/'>http://openid.net/</a>. </body></html>"; #endregion HTML IAuthenticationService m_authenticationService; IUserAccountService m_userAccountService; ProviderMemoryStore m_openidStore = new ProviderMemoryStore(); public override string ContentType { get { return "text/html"; } } /// <summary> /// Constructor /// </summary> public OpenIdStreamHandler( string httpMethod, string path, IUserAccountService userService, IAuthenticationService authService) : base(httpMethod, path, "OpenId", "OpenID stream handler") { m_authenticationService = authService; m_userAccountService = userService; } /// <summary> /// Handles all GET and POST requests for OpenID identifier pages and endpoint /// server communication /// </summary> protected override void ProcessRequest( string path, Stream request, Stream response, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { Uri providerEndpoint = new Uri(String.Format("{0}://{1}{2}", httpRequest.Url.Scheme, httpRequest.Url.Authority, httpRequest.Url.AbsolutePath)); // Defult to returning HTML content httpResponse.ContentType = ContentType; try { NameValueCollection postQuery = HttpUtility.ParseQueryString(new StreamReader(httpRequest.InputStream).ReadToEnd()); NameValueCollection getQuery = HttpUtility.ParseQueryString(httpRequest.Url.Query); NameValueCollection openIdQuery = (postQuery.GetValues("openid.mode") != null ? postQuery : getQuery); OpenIdProvider provider = new OpenIdProvider(m_openidStore, providerEndpoint, httpRequest.Url, openIdQuery); if (provider.Request != null) { if (!provider.Request.IsResponseReady && provider.Request is IAuthenticationRequest) { IAuthenticationRequest authRequest = (IAuthenticationRequest)provider.Request; string[] passwordValues = postQuery.GetValues("pass"); UserAccount account; if (TryGetAccount(new Uri(authRequest.ClaimedIdentifier.ToString()), out account)) { // Check for form POST data if (passwordValues != null && passwordValues.Length == 1) { if (account != null && (m_authenticationService.Authenticate(account.PrincipalID,Util.Md5Hash(passwordValues[0]), 30) != string.Empty)) authRequest.IsAuthenticated = true; else authRequest.IsAuthenticated = false; } else { // Authentication was requested, send the client a login form using (StreamWriter writer = new StreamWriter(response)) writer.Write(String.Format(LOGIN_PAGE, account.FirstName, account.LastName)); return; } } else { // Cannot find an avatar matching the claimed identifier authRequest.IsAuthenticated = false; } } // Add OpenID headers to the response foreach (string key in provider.Request.Response.Headers.Keys) httpResponse.AddHeader(key, provider.Request.Response.Headers[key]); string[] contentTypeValues = provider.Request.Response.Headers.GetValues("Content-Type"); if (contentTypeValues != null && contentTypeValues.Length == 1) httpResponse.ContentType = contentTypeValues[0]; // Set the response code and document body based on the OpenID result httpResponse.StatusCode = (int)provider.Request.Response.Code; response.Write(provider.Request.Response.Body, 0, provider.Request.Response.Body.Length); response.Close(); } else if (httpRequest.Url.AbsolutePath.Contains("/openid/server")) { // Standard HTTP GET was made on the OpenID endpoint, send the client the default error page using (StreamWriter writer = new StreamWriter(response)) writer.Write(ENDPOINT_PAGE); } else { // Try and lookup this avatar UserAccount account; if (TryGetAccount(httpRequest.Url, out account)) { using (StreamWriter writer = new StreamWriter(response)) { // TODO: Print out a full profile page for this avatar writer.Write(String.Format(OPENID_PAGE, httpRequest.Url.Scheme, httpRequest.Url.Authority, account.FirstName, account.LastName)); } } else { // Couldn't parse an avatar name, or couldn't find the avatar in the user server using (StreamWriter writer = new StreamWriter(response)) writer.Write(INVALID_OPENID_PAGE); } } } catch (Exception ex) { httpResponse.StatusCode = (int)HttpStatusCode.InternalServerError; using (StreamWriter writer = new StreamWriter(response)) writer.Write(ex.Message); } } /// <summary> /// Parse a URL with a relative path of the form /users/First_Last and try to /// retrieve the profile matching that avatar name /// </summary> /// <param name="requestUrl">URL to parse for an avatar name</param> /// <param name="profile">Profile data for the avatar</param> /// <returns>True if the parse and lookup were successful, otherwise false</returns> bool TryGetAccount(Uri requestUrl, out UserAccount account) { if (requestUrl.Segments.Length == 3 && requestUrl.Segments[1] == "users/") { // Parse the avatar name from the path string username = requestUrl.Segments[requestUrl.Segments.Length - 1]; string[] name = username.Split('_'); if (name.Length == 2) { account = m_userAccountService.GetUserAccount(UUID.Zero, name[0], name[1]); return (account != null); } } account = null; return false; } } }
// Visual Studio Shared Project // 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.ComponentModel.Design; using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.VisualStudioTools.Navigation; using Microsoft.VisualStudioTools.Project; using Microsoft.VisualStudio; using Microsoft.VisualStudio.ComponentModelHost; using Microsoft.VisualStudio.Editor; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudioTools { public abstract class CommonPackage : Package, IOleComponent { private uint _componentID; private LibraryManager _libraryManager; private IOleComponentManager _compMgr; private static readonly object _commandsLock = new object(); private static readonly Dictionary<Command, MenuCommand> _commands = new Dictionary<Command, MenuCommand>(); #region Language-specific abstracts public abstract Type GetLibraryManagerType(); internal abstract LibraryManager CreateLibraryManager(CommonPackage package); public abstract bool IsRecognizedFile(string filename); // TODO: // public abstract bool TryGetStartupFileAndDirectory(out string filename, out string dir); #endregion internal CommonPackage() { #if DEBUG AppDomain.CurrentDomain.UnhandledException += (sender, e) => { if (e.IsTerminating) { var ex = e.ExceptionObject as Exception; if (ex != null) { Debug.Fail( string.Format("An unhandled exception is about to terminate the process:\n\n{0}", ex.Message), ex.ToString() ); } else { Debug.Fail(string.Format( "An unhandled exception is about to terminate the process:\n\n{0}", e.ExceptionObject )); } } }; #endif } internal static Dictionary<Command, MenuCommand> Commands { get { return _commands; } } internal static object CommandsLock { get { return _commandsLock; } } protected override void Dispose(bool disposing) { try { if (_componentID != 0) { IOleComponentManager mgr = GetService(typeof(SOleComponentManager)) as IOleComponentManager; if (mgr != null) { mgr.FRevokeComponent(_componentID); } _componentID = 0; } if (null != _libraryManager) { _libraryManager.Dispose(); _libraryManager = null; } } finally { base.Dispose(disposing); } } private object CreateService(IServiceContainer container, Type serviceType) { if (GetLibraryManagerType() == serviceType) { return _libraryManager = CreateLibraryManager(this); } return null; } internal void RegisterCommands(IEnumerable<Command> commands, Guid cmdSet) { OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (null != mcs) { lock (_commandsLock) { foreach (var command in commands) { var beforeQueryStatus = command.BeforeQueryStatus; CommandID toolwndCommandID = new CommandID(cmdSet, command.CommandId); OleMenuCommand menuToolWin = new OleMenuCommand(command.DoCommand, toolwndCommandID); if (beforeQueryStatus != null) { menuToolWin.BeforeQueryStatus += beforeQueryStatus; } mcs.AddCommand(menuToolWin); _commands[command] = menuToolWin; } } } } /// <summary> /// Gets the current IWpfTextView that is the active document. /// </summary> /// <returns></returns> public static IWpfTextView GetActiveTextView(System.IServiceProvider serviceProvider) { var monitorSelection = (IVsMonitorSelection)serviceProvider.GetService(typeof(SVsShellMonitorSelection)); if (monitorSelection == null) { return null; } object curDocument; if (ErrorHandler.Failed(monitorSelection.GetCurrentElementValue((uint)VSConstants.VSSELELEMID.SEID_DocumentFrame, out curDocument))) { // TODO: Report error return null; } IVsWindowFrame frame = curDocument as IVsWindowFrame; if (frame == null) { // TODO: Report error return null; } object docView = null; if (ErrorHandler.Failed(frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocView, out docView))) { // TODO: Report error return null; } if (docView is IVsDifferenceCodeWindow) { var diffWindow = (IVsDifferenceCodeWindow)docView; switch (diffWindow.DifferenceViewer.ActiveViewType) { case VisualStudio.Text.Differencing.DifferenceViewType.InlineView: return diffWindow.DifferenceViewer.InlineView; case VisualStudio.Text.Differencing.DifferenceViewType.LeftView: return diffWindow.DifferenceViewer.LeftView; case VisualStudio.Text.Differencing.DifferenceViewType.RightView: return diffWindow.DifferenceViewer.RightView; } return null; } if (docView is IVsCodeWindow) { IVsTextView textView; if (ErrorHandler.Failed(((IVsCodeWindow)docView).GetPrimaryView(out textView))) { // TODO: Report error return null; } var model = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel)); var adapterFactory = model.GetService<IVsEditorAdaptersFactoryService>(); var wpfTextView = adapterFactory.GetWpfTextView(textView); return wpfTextView; } return null; } [Obsolete("ComponentModel should be retrieved from an IServiceProvider")] public static IComponentModel ComponentModel { get { return (IComponentModel)GetGlobalService(typeof(SComponentModel)); } } internal static CommonProjectNode GetStartupProject(System.IServiceProvider serviceProvider) { var buildMgr = (IVsSolutionBuildManager)serviceProvider.GetService(typeof(IVsSolutionBuildManager)); IVsHierarchy hierarchy; if (buildMgr != null && ErrorHandler.Succeeded(buildMgr.get_StartupProject(out hierarchy)) && hierarchy != null) { return hierarchy.GetProject().GetCommonProject(); } return null; } protected override void Initialize() { var container = (IServiceContainer)this; UIThread.EnsureService(this); container.AddService(GetLibraryManagerType(), CreateService, true); var componentManager = _compMgr = (IOleComponentManager)GetService(typeof(SOleComponentManager)); OLECRINFO[] crinfo = new OLECRINFO[1]; crinfo[0].cbSize = (uint)Marshal.SizeOf(typeof(OLECRINFO)); crinfo[0].grfcrf = (uint)_OLECRF.olecrfNeedIdleTime; crinfo[0].grfcadvf = (uint)_OLECADVF.olecadvfModal | (uint)_OLECADVF.olecadvfRedrawOff | (uint)_OLECADVF.olecadvfWarningsOff; crinfo[0].uIdleTimeInterval = 0; ErrorHandler.ThrowOnFailure(componentManager.FRegisterComponent(this, crinfo, out _componentID)); base.Initialize(); } internal static void OpenWebBrowser(string url) { var uri = new Uri(url); Process.Start(new ProcessStartInfo(uri.AbsoluteUri)); return; } internal static void OpenVsWebBrowser(System.IServiceProvider serviceProvider, string url) { serviceProvider.GetUIThread().Invoke(() => { var web = serviceProvider.GetService(typeof(SVsWebBrowsingService)) as IVsWebBrowsingService; if (web == null) { OpenWebBrowser(url); return; } IVsWindowFrame frame; ErrorHandler.ThrowOnFailure(web.Navigate(url, (uint)__VSWBNAVIGATEFLAGS.VSNWB_ForceNew, out frame)); frame.Show(); }); } #region IOleComponent Members public int FContinueMessageLoop(uint uReason, IntPtr pvLoopData, MSG[] pMsgPeeked) { return 1; } public virtual int FDoIdle(uint grfidlef) { if (null != _libraryManager) { _libraryManager.OnIdle(_compMgr); } var onIdle = OnIdle; if (onIdle != null) { onIdle(this, new ComponentManagerEventArgs(_compMgr)); } return 0; } internal event EventHandler<ComponentManagerEventArgs> OnIdle; public int FPreTranslateMessage(MSG[] pMsg) { return 0; } public int FQueryTerminate(int fPromptUser) { return 1; } public int FReserved1(uint dwReserved, uint message, IntPtr wParam, IntPtr lParam) { return 1; } public IntPtr HwndGetWindow(uint dwWhich, uint dwReserved) { return IntPtr.Zero; } public void OnActivationChange(IOleComponent pic, int fSameComponent, OLECRINFO[] pcrinfo, int fHostIsActivating, OLECHOSTINFO[] pchostinfo, uint dwReserved) { } public void OnAppActivate(int fActive, uint dwOtherThreadID) { } public void OnEnterState(uint uStateID, int fEnter) { } public void OnLoseActivation() { } public void Terminate() { } #endregion } class ComponentManagerEventArgs : EventArgs { private readonly IOleComponentManager _compMgr; public ComponentManagerEventArgs(IOleComponentManager compMgr) { _compMgr = compMgr; } public IOleComponentManager ComponentManager { get { return _compMgr; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.Runtime; using System.Security.Authentication.ExtendedProtection; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Security.Tokens; using System.Globalization; namespace System.ServiceModel.Security { /* * See * http://xws/gxa/main/specs/security/security_profiles/SecurityProfiles.doc * for details on security protocols * Concrete implementations are required to me thread safe after * Open() is called; * instances of concrete protocol factories are scoped to a * channel/listener factory; * Each channel/listener factory must have a * SecurityProtocolFactory set on it before open/first use; the * factory instance cannot be changed once the factory is opened * or listening; * security protocol instances are scoped to a channel and will be * created by the Create calls on protocol factories; * security protocol instances are required to be thread-safe. * for typical subclasses, factory wide state and immutable * settings are expected to be on the ProtocolFactory itself while * channel-wide state is maintained internally in each security * protocol instance; * the security protocol instance set on a channel cannot be * changed; however, the protocol instance may change internal * state; this covers RM's SCT renego case; by keeping state * change internal to protocol instances, we get better * coordination with concurrent message security on channels; * the primary pivot in creating a security protocol instance is * initiator (client) vs. responder (server), NOT sender vs * receiver * Create calls for input and reply channels will contain the * listener-wide state (if any) created by the corresponding call * on the factory; */ // Whether we need to add support for targetting different SOAP roles is tracked by 19144 internal abstract class SecurityProtocolFactory : ISecurityCommunicationObject { internal const bool defaultAddTimestamp = true; internal const bool defaultDeriveKeys = true; internal const bool defaultDetectReplays = true; internal const string defaultMaxClockSkewString = "00:05:00"; internal const string defaultReplayWindowString = "00:05:00"; internal static readonly TimeSpan defaultMaxClockSkew = TimeSpan.Parse(defaultMaxClockSkewString, CultureInfo.InvariantCulture); internal static readonly TimeSpan defaultReplayWindow = TimeSpan.Parse(defaultReplayWindowString, CultureInfo.InvariantCulture); internal const int defaultMaxCachedNonces = 900000; internal const string defaultTimestampValidityDurationString = "00:05:00"; internal static readonly TimeSpan defaultTimestampValidityDuration = TimeSpan.Parse(defaultTimestampValidityDurationString, CultureInfo.InvariantCulture); internal const SecurityHeaderLayout defaultSecurityHeaderLayout = SecurityHeaderLayout.Strict; private static ReadOnlyCollection<SupportingTokenAuthenticatorSpecification> s_emptyTokenAuthenticators; private bool _actAsInitiator; private bool _isDuplexReply; private bool _addTimestamp = defaultAddTimestamp; private bool _detectReplays = defaultDetectReplays; private bool _expectIncomingMessages; private bool _expectOutgoingMessages; private SecurityAlgorithmSuite _incomingAlgorithmSuite = SecurityAlgorithmSuite.Default; // per receiver protocol factory lists private ICollection<SupportingTokenAuthenticatorSpecification> _channelSupportingTokenAuthenticatorSpecification; private Dictionary<string, ICollection<SupportingTokenAuthenticatorSpecification>> _scopedSupportingTokenAuthenticatorSpecification; private Dictionary<string, MergedSupportingTokenAuthenticatorSpecification> _mergedSupportingTokenAuthenticatorsMap; private int _maxCachedNonces = defaultMaxCachedNonces; private TimeSpan _maxClockSkew = defaultMaxClockSkew; private NonceCache _nonceCache = null; private SecurityAlgorithmSuite _outgoingAlgorithmSuite = SecurityAlgorithmSuite.Default; private TimeSpan _replayWindow = defaultReplayWindow; private SecurityStandardsManager _standardsManager = SecurityStandardsManager.DefaultInstance; private SecurityTokenManager _securityTokenManager; private SecurityBindingElement _securityBindingElement; private string _requestReplyErrorPropertyName; private NonValidatingSecurityTokenAuthenticator<DerivedKeySecurityToken> _derivedKeyTokenAuthenticator; private TimeSpan _timestampValidityDuration = defaultTimestampValidityDuration; private AuditLogLocation _auditLogLocation; private bool _suppressAuditFailure; private SecurityHeaderLayout _securityHeaderLayout; private AuditLevel _serviceAuthorizationAuditLevel; private AuditLevel _messageAuthenticationAuditLevel; private bool _expectKeyDerivation; private bool _expectChannelBasicTokens; private bool _expectChannelSignedTokens; private bool _expectChannelEndorsingTokens; private bool _expectSupportingTokens; private Uri _listenUri; private MessageSecurityVersion _messageSecurityVersion; private WrapperSecurityCommunicationObject _communicationObject; private Uri _privacyNoticeUri; private int _privacyNoticeVersion; private ExtendedProtectionPolicy _extendedProtectionPolicy; private BufferManager _streamBufferManager = null; protected SecurityProtocolFactory() { _channelSupportingTokenAuthenticatorSpecification = new Collection<SupportingTokenAuthenticatorSpecification>(); _scopedSupportingTokenAuthenticatorSpecification = new Dictionary<string, ICollection<SupportingTokenAuthenticatorSpecification>>(); _communicationObject = new WrapperSecurityCommunicationObject(this); } internal SecurityProtocolFactory(SecurityProtocolFactory factory) : this() { if (factory == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("factory"); } _actAsInitiator = factory._actAsInitiator; _addTimestamp = factory._addTimestamp; _detectReplays = factory._detectReplays; _incomingAlgorithmSuite = factory._incomingAlgorithmSuite; _maxCachedNonces = factory._maxCachedNonces; _maxClockSkew = factory._maxClockSkew; _outgoingAlgorithmSuite = factory._outgoingAlgorithmSuite; _replayWindow = factory._replayWindow; _channelSupportingTokenAuthenticatorSpecification = new Collection<SupportingTokenAuthenticatorSpecification>(new List<SupportingTokenAuthenticatorSpecification>(factory._channelSupportingTokenAuthenticatorSpecification)); _scopedSupportingTokenAuthenticatorSpecification = new Dictionary<string, ICollection<SupportingTokenAuthenticatorSpecification>>(factory._scopedSupportingTokenAuthenticatorSpecification); _standardsManager = factory._standardsManager; _timestampValidityDuration = factory._timestampValidityDuration; _auditLogLocation = factory._auditLogLocation; _suppressAuditFailure = factory._suppressAuditFailure; _serviceAuthorizationAuditLevel = factory._serviceAuthorizationAuditLevel; _messageAuthenticationAuditLevel = factory._messageAuthenticationAuditLevel; if (factory._securityBindingElement != null) { _securityBindingElement = (SecurityBindingElement)factory._securityBindingElement.Clone(); } _securityTokenManager = factory._securityTokenManager; _privacyNoticeUri = factory._privacyNoticeUri; _privacyNoticeVersion = factory._privacyNoticeVersion; _extendedProtectionPolicy = factory._extendedProtectionPolicy; _nonceCache = factory._nonceCache; } protected WrapperSecurityCommunicationObject CommunicationObject { get { return _communicationObject; } } // The ActAsInitiator value is set automatically on Open and // remains unchanged thereafter. ActAsInitiator is true for // the initiator of the message exchange, such as the sender // of a datagram, sender of a request and sender of either leg // of a duplex exchange. public bool ActAsInitiator { get { return _actAsInitiator; } } public BufferManager StreamBufferManager { get { if (_streamBufferManager == null) { _streamBufferManager = BufferManager.CreateBufferManager(0, int.MaxValue); } return _streamBufferManager; } set { _streamBufferManager = value; } } internal bool IsDuplexReply { get { return _isDuplexReply; } set { _isDuplexReply = value; } } public bool AddTimestamp { get { return _addTimestamp; } set { ThrowIfImmutable(); _addTimestamp = value; } } public AuditLogLocation AuditLogLocation { get { return _auditLogLocation; } set { ThrowIfImmutable(); AuditLogLocationHelper.Validate(value); _auditLogLocation = value; } } public bool SuppressAuditFailure { get { return _suppressAuditFailure; } set { ThrowIfImmutable(); _suppressAuditFailure = value; } } public AuditLevel ServiceAuthorizationAuditLevel { get { return _serviceAuthorizationAuditLevel; } set { ThrowIfImmutable(); AuditLevelHelper.Validate(value); _serviceAuthorizationAuditLevel = value; } } public AuditLevel MessageAuthenticationAuditLevel { get { return _messageAuthenticationAuditLevel; } set { ThrowIfImmutable(); AuditLevelHelper.Validate(value); _messageAuthenticationAuditLevel = value; } } public bool DetectReplays { get { return _detectReplays; } set { ThrowIfImmutable(); _detectReplays = value; } } public Uri PrivacyNoticeUri { get { return _privacyNoticeUri; } set { ThrowIfImmutable(); _privacyNoticeUri = value; } } public int PrivacyNoticeVersion { get { return _privacyNoticeVersion; } set { ThrowIfImmutable(); _privacyNoticeVersion = value; } } private static ReadOnlyCollection<SupportingTokenAuthenticatorSpecification> EmptyTokenAuthenticators { get { if (s_emptyTokenAuthenticators == null) { s_emptyTokenAuthenticators = new ReadOnlyCollection<SupportingTokenAuthenticatorSpecification>(new SupportingTokenAuthenticatorSpecification[0]); } return s_emptyTokenAuthenticators; } } internal NonValidatingSecurityTokenAuthenticator<DerivedKeySecurityToken> DerivedKeyTokenAuthenticator { get { return _derivedKeyTokenAuthenticator; } } internal bool ExpectIncomingMessages { get { return _expectIncomingMessages; } } internal bool ExpectOutgoingMessages { get { return _expectOutgoingMessages; } } internal bool ExpectKeyDerivation { get { return _expectKeyDerivation; } set { _expectKeyDerivation = value; } } internal bool ExpectSupportingTokens { get { return _expectSupportingTokens; } set { _expectSupportingTokens = value; } } public SecurityAlgorithmSuite IncomingAlgorithmSuite { get { return _incomingAlgorithmSuite; } set { ThrowIfImmutable(); if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); } _incomingAlgorithmSuite = value; } } protected bool IsReadOnly { get { return this.CommunicationObject.State != CommunicationState.Created; } } public int MaxCachedNonces { get { return _maxCachedNonces; } set { ThrowIfImmutable(); if (value <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value")); } _maxCachedNonces = value; } } public TimeSpan MaxClockSkew { get { return _maxClockSkew; } set { ThrowIfImmutable(); if (value < TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value")); } _maxClockSkew = value; } } public NonceCache NonceCache { get { return _nonceCache; } set { ThrowIfImmutable(); _nonceCache = value; } } public SecurityAlgorithmSuite OutgoingAlgorithmSuite { get { return _outgoingAlgorithmSuite; } set { ThrowIfImmutable(); if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); } _outgoingAlgorithmSuite = value; } } public TimeSpan ReplayWindow { get { return _replayWindow; } set { ThrowIfImmutable(); if (value <= TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", SR.TimeSpanMustbeGreaterThanTimeSpanZero)); } _replayWindow = value; } } public ICollection<SupportingTokenAuthenticatorSpecification> ChannelSupportingTokenAuthenticatorSpecification { get { return _channelSupportingTokenAuthenticatorSpecification; } } public Dictionary<string, ICollection<SupportingTokenAuthenticatorSpecification>> ScopedSupportingTokenAuthenticatorSpecification { get { return _scopedSupportingTokenAuthenticatorSpecification; } } public SecurityBindingElement SecurityBindingElement { get { return _securityBindingElement; } set { ThrowIfImmutable(); if (value != null) { value = (SecurityBindingElement)value.Clone(); } _securityBindingElement = value; } } public SecurityTokenManager SecurityTokenManager { get { return _securityTokenManager; } set { ThrowIfImmutable(); _securityTokenManager = value; } } public virtual bool SupportsDuplex { get { return false; } } public SecurityHeaderLayout SecurityHeaderLayout { get { return _securityHeaderLayout; } set { ThrowIfImmutable(); _securityHeaderLayout = value; } } public virtual bool SupportsReplayDetection { get { return true; } } public virtual bool SupportsRequestReply { get { return true; } } public SecurityStandardsManager StandardsManager { get { return _standardsManager; } set { ThrowIfImmutable(); if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("value")); } _standardsManager = value; } } public TimeSpan TimestampValidityDuration { get { return _timestampValidityDuration; } set { ThrowIfImmutable(); if (value <= TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", SR.TimeSpanMustbeGreaterThanTimeSpanZero)); } _timestampValidityDuration = value; } } public Uri ListenUri { get { return _listenUri; } set { ThrowIfImmutable(); _listenUri = value; } } internal MessageSecurityVersion MessageSecurityVersion { get { return _messageSecurityVersion; } } // ISecurityCommunicationObject members public TimeSpan DefaultOpenTimeout { get { return ServiceDefaults.OpenTimeout; } } public TimeSpan DefaultCloseTimeout { get { return ServiceDefaults.CloseTimeout; } } public IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return new OperationWithTimeoutAsyncResult(this.OnClose, timeout, callback, state); } public IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state) { return new OperationWithTimeoutAsyncResult(this.OnOpen, timeout, callback, state); } public void OnClosed() { } public void OnClosing() { } public void OnEndClose(IAsyncResult result) { OperationWithTimeoutAsyncResult.End(result); } public void OnEndOpen(IAsyncResult result) { OperationWithTimeoutAsyncResult.End(result); } public void OnFaulted() { } public void OnOpened() { } public void OnOpening() { } public virtual void OnAbort() { if (!_actAsInitiator) { foreach (SupportingTokenAuthenticatorSpecification spec in _channelSupportingTokenAuthenticatorSpecification) { SecurityUtils.AbortTokenAuthenticatorIfRequired(spec.TokenAuthenticator); } foreach (string action in _scopedSupportingTokenAuthenticatorSpecification.Keys) { ICollection<SupportingTokenAuthenticatorSpecification> supportingAuthenticators = _scopedSupportingTokenAuthenticatorSpecification[action]; foreach (SupportingTokenAuthenticatorSpecification spec in supportingAuthenticators) { SecurityUtils.AbortTokenAuthenticatorIfRequired(spec.TokenAuthenticator); } } } } public virtual void OnClose(TimeSpan timeout) { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); if (!_actAsInitiator) { foreach (SupportingTokenAuthenticatorSpecification spec in _channelSupportingTokenAuthenticatorSpecification) { SecurityUtils.CloseTokenAuthenticatorIfRequired(spec.TokenAuthenticator, timeoutHelper.RemainingTime()); } foreach (string action in _scopedSupportingTokenAuthenticatorSpecification.Keys) { ICollection<SupportingTokenAuthenticatorSpecification> supportingAuthenticators = _scopedSupportingTokenAuthenticatorSpecification[action]; foreach (SupportingTokenAuthenticatorSpecification spec in supportingAuthenticators) { SecurityUtils.CloseTokenAuthenticatorIfRequired(spec.TokenAuthenticator, timeoutHelper.RemainingTime()); } } } } public virtual object CreateListenerSecurityState() { return null; } public SecurityProtocol CreateSecurityProtocol(EndpointAddress target, Uri via, object listenerSecurityState, bool isReturnLegSecurityRequired, TimeSpan timeout) { ThrowIfNotOpen(); SecurityProtocol securityProtocol = OnCreateSecurityProtocol(target, via, listenerSecurityState, timeout); if (securityProtocol == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new MessageSecurityException(SR.ProtocolFactoryCouldNotCreateProtocol)); } return securityProtocol; } public virtual EndpointIdentity GetIdentityOfSelf() { return null; } public virtual T GetProperty<T>() { if (typeof(T) == typeof(Collection<ISecurityContextSecurityTokenCache>)) { ThrowIfNotOpen(); Collection<ISecurityContextSecurityTokenCache> result = new Collection<ISecurityContextSecurityTokenCache>(); if (_channelSupportingTokenAuthenticatorSpecification != null) { foreach (SupportingTokenAuthenticatorSpecification spec in _channelSupportingTokenAuthenticatorSpecification) { if (spec.TokenAuthenticator is ISecurityContextSecurityTokenCacheProvider) { result.Add(((ISecurityContextSecurityTokenCacheProvider)spec.TokenAuthenticator).TokenCache); } } } return (T)(object)(result); } else { return default(T); } } protected abstract SecurityProtocol OnCreateSecurityProtocol(EndpointAddress target, Uri via, object listenerSecurityState, TimeSpan timeout); private void VerifyTypeUniqueness(ICollection<SupportingTokenAuthenticatorSpecification> supportingTokenAuthenticators) { // its ok to go brute force here since we are dealing with a small number of authenticators foreach (SupportingTokenAuthenticatorSpecification spec in supportingTokenAuthenticators) { Type authenticatorType = spec.TokenAuthenticator.GetType(); int numSkipped = 0; foreach (SupportingTokenAuthenticatorSpecification spec2 in supportingTokenAuthenticators) { Type spec2AuthenticatorType = spec2.TokenAuthenticator.GetType(); if (object.ReferenceEquals(spec, spec2)) { if (numSkipped > 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.MultipleSupportingAuthenticatorsOfSameType, spec.TokenParameters.GetType()))); } ++numSkipped; continue; } else if (authenticatorType.IsAssignableFrom(spec2AuthenticatorType) || spec2AuthenticatorType.IsAssignableFrom(authenticatorType)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.MultipleSupportingAuthenticatorsOfSameType, spec.TokenParameters.GetType()))); } } } } internal IList<SupportingTokenAuthenticatorSpecification> GetSupportingTokenAuthenticators(string action, out bool expectSignedTokens, out bool expectBasicTokens, out bool expectEndorsingTokens) { if (_mergedSupportingTokenAuthenticatorsMap != null && _mergedSupportingTokenAuthenticatorsMap.Count > 0) { if (action != null && _mergedSupportingTokenAuthenticatorsMap.ContainsKey(action)) { MergedSupportingTokenAuthenticatorSpecification mergedSpec = _mergedSupportingTokenAuthenticatorsMap[action]; expectSignedTokens = mergedSpec.ExpectSignedTokens; expectBasicTokens = mergedSpec.ExpectBasicTokens; expectEndorsingTokens = mergedSpec.ExpectEndorsingTokens; return mergedSpec.SupportingTokenAuthenticators; } else if (_mergedSupportingTokenAuthenticatorsMap.ContainsKey(MessageHeaders.WildcardAction)) { MergedSupportingTokenAuthenticatorSpecification mergedSpec = _mergedSupportingTokenAuthenticatorsMap[MessageHeaders.WildcardAction]; expectSignedTokens = mergedSpec.ExpectSignedTokens; expectBasicTokens = mergedSpec.ExpectBasicTokens; expectEndorsingTokens = mergedSpec.ExpectEndorsingTokens; return mergedSpec.SupportingTokenAuthenticators; } } expectSignedTokens = _expectChannelSignedTokens; expectBasicTokens = _expectChannelBasicTokens; expectEndorsingTokens = _expectChannelEndorsingTokens; // in case the channelSupportingTokenAuthenticators is empty return null so that its Count does not get accessed. return (Object.ReferenceEquals(_channelSupportingTokenAuthenticatorSpecification, EmptyTokenAuthenticators)) ? null : (IList<SupportingTokenAuthenticatorSpecification>)_channelSupportingTokenAuthenticatorSpecification; } private void MergeSupportingTokenAuthenticators(TimeSpan timeout) { if (_scopedSupportingTokenAuthenticatorSpecification.Count == 0) { _mergedSupportingTokenAuthenticatorsMap = null; } else { TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); _expectSupportingTokens = true; _mergedSupportingTokenAuthenticatorsMap = new Dictionary<string, MergedSupportingTokenAuthenticatorSpecification>(); foreach (string action in _scopedSupportingTokenAuthenticatorSpecification.Keys) { ICollection<SupportingTokenAuthenticatorSpecification> scopedAuthenticators = _scopedSupportingTokenAuthenticatorSpecification[action]; if (scopedAuthenticators == null || scopedAuthenticators.Count == 0) { continue; } Collection<SupportingTokenAuthenticatorSpecification> mergedAuthenticators = new Collection<SupportingTokenAuthenticatorSpecification>(); bool expectSignedTokens = _expectChannelSignedTokens; bool expectBasicTokens = _expectChannelBasicTokens; bool expectEndorsingTokens = _expectChannelEndorsingTokens; foreach (SupportingTokenAuthenticatorSpecification spec in _channelSupportingTokenAuthenticatorSpecification) { mergedAuthenticators.Add(spec); } foreach (SupportingTokenAuthenticatorSpecification spec in scopedAuthenticators) { SecurityUtils.OpenTokenAuthenticatorIfRequired(spec.TokenAuthenticator, timeoutHelper.RemainingTime()); mergedAuthenticators.Add(spec); if (spec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.Endorsing || spec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.SignedEndorsing) { if (spec.TokenParameters.RequireDerivedKeys && !spec.TokenParameters.HasAsymmetricKey) { _expectKeyDerivation = true; } } SecurityTokenAttachmentMode mode = spec.SecurityTokenAttachmentMode; if (mode == SecurityTokenAttachmentMode.SignedEncrypted || mode == SecurityTokenAttachmentMode.Signed || mode == SecurityTokenAttachmentMode.SignedEndorsing) { expectSignedTokens = true; if (mode == SecurityTokenAttachmentMode.SignedEncrypted) { expectBasicTokens = true; } } if (mode == SecurityTokenAttachmentMode.Endorsing || mode == SecurityTokenAttachmentMode.SignedEndorsing) { expectEndorsingTokens = true; } } VerifyTypeUniqueness(mergedAuthenticators); MergedSupportingTokenAuthenticatorSpecification mergedSpec = new MergedSupportingTokenAuthenticatorSpecification(); mergedSpec.SupportingTokenAuthenticators = mergedAuthenticators; mergedSpec.ExpectBasicTokens = expectBasicTokens; mergedSpec.ExpectEndorsingTokens = expectEndorsingTokens; mergedSpec.ExpectSignedTokens = expectSignedTokens; _mergedSupportingTokenAuthenticatorsMap.Add(action, mergedSpec); } } } protected RecipientServiceModelSecurityTokenRequirement CreateRecipientSecurityTokenRequirement() { RecipientServiceModelSecurityTokenRequirement requirement = new RecipientServiceModelSecurityTokenRequirement(); requirement.SecurityBindingElement = _securityBindingElement; requirement.SecurityAlgorithmSuite = this.IncomingAlgorithmSuite; requirement.ListenUri = _listenUri; requirement.MessageSecurityVersion = this.MessageSecurityVersion.SecurityTokenVersion; requirement.Properties[ServiceModelSecurityTokenRequirement.ExtendedProtectionPolicy] = _extendedProtectionPolicy; return requirement; } private RecipientServiceModelSecurityTokenRequirement CreateRecipientSecurityTokenRequirement(SecurityTokenParameters parameters, SecurityTokenAttachmentMode attachmentMode) { RecipientServiceModelSecurityTokenRequirement requirement = CreateRecipientSecurityTokenRequirement(); requirement.KeyUsage = SecurityKeyUsage.Signature; requirement.Properties[ServiceModelSecurityTokenRequirement.MessageDirectionProperty] = MessageDirection.Input; requirement.Properties[ServiceModelSecurityTokenRequirement.SupportingTokenAttachmentModeProperty] = attachmentMode; requirement.Properties[ServiceModelSecurityTokenRequirement.ExtendedProtectionPolicy] = _extendedProtectionPolicy; return requirement; } private void AddSupportingTokenAuthenticators(SupportingTokenParameters supportingTokenParameters, bool isOptional, IList<SupportingTokenAuthenticatorSpecification> authenticatorSpecList) { for (int i = 0; i < supportingTokenParameters.Endorsing.Count; ++i) { SecurityTokenRequirement requirement = this.CreateRecipientSecurityTokenRequirement(supportingTokenParameters.Endorsing[i], SecurityTokenAttachmentMode.Endorsing); try { System.IdentityModel.Selectors.SecurityTokenResolver resolver; System.IdentityModel.Selectors.SecurityTokenAuthenticator authenticator = this.SecurityTokenManager.CreateSecurityTokenAuthenticator(requirement, out resolver); SupportingTokenAuthenticatorSpecification authenticatorSpec = new SupportingTokenAuthenticatorSpecification(authenticator, resolver, SecurityTokenAttachmentMode.Endorsing, supportingTokenParameters.Endorsing[i], isOptional); authenticatorSpecList.Add(authenticatorSpec); } catch (Exception e) { if (!isOptional || Fx.IsFatal(e)) { throw; } } } for (int i = 0; i < supportingTokenParameters.SignedEndorsing.Count; ++i) { SecurityTokenRequirement requirement = this.CreateRecipientSecurityTokenRequirement(supportingTokenParameters.SignedEndorsing[i], SecurityTokenAttachmentMode.SignedEndorsing); try { System.IdentityModel.Selectors.SecurityTokenResolver resolver; System.IdentityModel.Selectors.SecurityTokenAuthenticator authenticator = this.SecurityTokenManager.CreateSecurityTokenAuthenticator(requirement, out resolver); SupportingTokenAuthenticatorSpecification authenticatorSpec = new SupportingTokenAuthenticatorSpecification(authenticator, resolver, SecurityTokenAttachmentMode.SignedEndorsing, supportingTokenParameters.SignedEndorsing[i], isOptional); authenticatorSpecList.Add(authenticatorSpec); } catch (Exception e) { if (!isOptional || Fx.IsFatal(e)) { throw; } } } for (int i = 0; i < supportingTokenParameters.SignedEncrypted.Count; ++i) { SecurityTokenRequirement requirement = this.CreateRecipientSecurityTokenRequirement(supportingTokenParameters.SignedEncrypted[i], SecurityTokenAttachmentMode.SignedEncrypted); try { System.IdentityModel.Selectors.SecurityTokenResolver resolver; System.IdentityModel.Selectors.SecurityTokenAuthenticator authenticator = this.SecurityTokenManager.CreateSecurityTokenAuthenticator(requirement, out resolver); SupportingTokenAuthenticatorSpecification authenticatorSpec = new SupportingTokenAuthenticatorSpecification(authenticator, resolver, SecurityTokenAttachmentMode.SignedEncrypted, supportingTokenParameters.SignedEncrypted[i], isOptional); authenticatorSpecList.Add(authenticatorSpec); } catch (Exception e) { if (!isOptional || Fx.IsFatal(e)) { throw; } } } for (int i = 0; i < supportingTokenParameters.Signed.Count; ++i) { SecurityTokenRequirement requirement = this.CreateRecipientSecurityTokenRequirement(supportingTokenParameters.Signed[i], SecurityTokenAttachmentMode.Signed); try { System.IdentityModel.Selectors.SecurityTokenResolver resolver; System.IdentityModel.Selectors.SecurityTokenAuthenticator authenticator = this.SecurityTokenManager.CreateSecurityTokenAuthenticator(requirement, out resolver); SupportingTokenAuthenticatorSpecification authenticatorSpec = new SupportingTokenAuthenticatorSpecification(authenticator, resolver, SecurityTokenAttachmentMode.Signed, supportingTokenParameters.Signed[i], isOptional); authenticatorSpecList.Add(authenticatorSpec); } catch (Exception e) { if (!isOptional || Fx.IsFatal(e)) { throw; } } } } public virtual void OnOpen(TimeSpan timeout) { if (this.SecurityBindingElement == null) { this.OnPropertySettingsError("SecurityBindingElement", true); } if (this.SecurityTokenManager == null) { this.OnPropertySettingsError("SecurityTokenManager", true); } _messageSecurityVersion = _standardsManager.MessageSecurityVersion; TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); _expectOutgoingMessages = this.ActAsInitiator || this.SupportsRequestReply; _expectIncomingMessages = !this.ActAsInitiator || this.SupportsRequestReply; if (!_actAsInitiator) { AddSupportingTokenAuthenticators(_securityBindingElement.EndpointSupportingTokenParameters, false, (IList<SupportingTokenAuthenticatorSpecification>)_channelSupportingTokenAuthenticatorSpecification); // validate the token authenticator types and create a merged map if needed. if (!_channelSupportingTokenAuthenticatorSpecification.IsReadOnly) { if (_channelSupportingTokenAuthenticatorSpecification.Count == 0) { _channelSupportingTokenAuthenticatorSpecification = EmptyTokenAuthenticators; } else { _expectSupportingTokens = true; foreach (SupportingTokenAuthenticatorSpecification tokenAuthenticatorSpec in _channelSupportingTokenAuthenticatorSpecification) { SecurityUtils.OpenTokenAuthenticatorIfRequired(tokenAuthenticatorSpec.TokenAuthenticator, timeoutHelper.RemainingTime()); if (tokenAuthenticatorSpec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.Endorsing || tokenAuthenticatorSpec.SecurityTokenAttachmentMode == SecurityTokenAttachmentMode.SignedEndorsing) { if (tokenAuthenticatorSpec.TokenParameters.RequireDerivedKeys && !tokenAuthenticatorSpec.TokenParameters.HasAsymmetricKey) { _expectKeyDerivation = true; } } SecurityTokenAttachmentMode mode = tokenAuthenticatorSpec.SecurityTokenAttachmentMode; if (mode == SecurityTokenAttachmentMode.SignedEncrypted || mode == SecurityTokenAttachmentMode.Signed || mode == SecurityTokenAttachmentMode.SignedEndorsing) { _expectChannelSignedTokens = true; if (mode == SecurityTokenAttachmentMode.SignedEncrypted) { _expectChannelBasicTokens = true; } } if (mode == SecurityTokenAttachmentMode.Endorsing || mode == SecurityTokenAttachmentMode.SignedEndorsing) { _expectChannelEndorsingTokens = true; } } _channelSupportingTokenAuthenticatorSpecification = new ReadOnlyCollection<SupportingTokenAuthenticatorSpecification>((Collection<SupportingTokenAuthenticatorSpecification>)_channelSupportingTokenAuthenticatorSpecification); } } VerifyTypeUniqueness(_channelSupportingTokenAuthenticatorSpecification); MergeSupportingTokenAuthenticators(timeoutHelper.RemainingTime()); } if (this.DetectReplays) { if (!this.SupportsReplayDetection) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("DetectReplays", SR.Format(SR.SecurityProtocolCannotDoReplayDetection, this)); } if (this.MaxClockSkew == TimeSpan.MaxValue || this.ReplayWindow == TimeSpan.MaxValue) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.NoncesCachedInfinitely)); } // If DetectReplays is true and nonceCache is null then use the default InMemoryNonceCache. if (_nonceCache == null) { // The nonce needs to be cached for replayWindow + 2*clockSkew to eliminate replays _nonceCache = new InMemoryNonceCache(this.ReplayWindow + this.MaxClockSkew + this.MaxClockSkew, this.MaxCachedNonces); } } _derivedKeyTokenAuthenticator = new NonValidatingSecurityTokenAuthenticator<DerivedKeySecurityToken>(); } public void Open(bool actAsInitiator, TimeSpan timeout) { _actAsInitiator = actAsInitiator; _communicationObject.Open(timeout); } public IAsyncResult BeginOpen(bool actAsInitiator, TimeSpan timeout, AsyncCallback callback, object state) { _actAsInitiator = actAsInitiator; return this.CommunicationObject.BeginOpen(timeout, callback, state); } public void EndOpen(IAsyncResult result) { this.CommunicationObject.EndOpen(result); } public void Close(bool aborted, TimeSpan timeout) { if (aborted) { this.CommunicationObject.Abort(); } else { this.CommunicationObject.Close(timeout); } } public IAsyncResult BeginClose(TimeSpan timeout, AsyncCallback callback, object state) { return this.CommunicationObject.BeginClose(timeout, callback, state); } public void EndClose(IAsyncResult result) { this.CommunicationObject.EndClose(result); } internal void Open(string propertyName, bool requiredForForwardDirection, SecurityTokenAuthenticator authenticator, TimeSpan timeout) { if (authenticator != null) { SecurityUtils.OpenTokenAuthenticatorIfRequired(authenticator, timeout); } else { OnPropertySettingsError(propertyName, requiredForForwardDirection); } } internal void Open(string propertyName, bool requiredForForwardDirection, SecurityTokenProvider provider, TimeSpan timeout) { if (provider != null) { SecurityUtils.OpenTokenProviderIfRequired(provider, timeout); } else { OnPropertySettingsError(propertyName, requiredForForwardDirection); } } internal void OnPropertySettingsError(string propertyName, bool requiredForForwardDirection) { if (requiredForForwardDirection) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException( SR.Format(SR.PropertySettingErrorOnProtocolFactory, propertyName, this), propertyName)); } else if (_requestReplyErrorPropertyName == null) { _requestReplyErrorPropertyName = propertyName; } } private void ThrowIfReturnDirectionSecurityNotSupported() { if (_requestReplyErrorPropertyName != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException( SR.Format(SR.PropertySettingErrorOnProtocolFactory, _requestReplyErrorPropertyName, this), _requestReplyErrorPropertyName)); } } internal void ThrowIfImmutable() { _communicationObject.ThrowIfDisposedOrImmutable(); } private void ThrowIfNotOpen() { _communicationObject.ThrowIfNotOpened(); } } internal struct MergedSupportingTokenAuthenticatorSpecification { public Collection<SupportingTokenAuthenticatorSpecification> SupportingTokenAuthenticators; public bool ExpectSignedTokens; public bool ExpectEndorsingTokens; public bool ExpectBasicTokens; } }
// 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.Globalization; using System.Numerics; using Xunit; namespace System.Tests { public partial class Int64Tests { [Fact] public static void Ctor_Empty() { var i = new long(); Assert.Equal(0, i); } [Fact] public static void Ctor_Value() { long i = 41; Assert.Equal(41, i); } [Fact] public static void MaxValue() { Assert.Equal(0x7FFFFFFFFFFFFFFF, long.MaxValue); } [Fact] public static void MinValue() { Assert.Equal(unchecked((long)0x8000000000000000), long.MinValue); } [Theory] [InlineData((long)234, (long)234, 0)] [InlineData((long)234, long.MinValue, 1)] [InlineData((long)234, (long)-123, 1)] [InlineData((long)234, (long)0, 1)] [InlineData((long)234, (long)123, 1)] [InlineData((long)234, (long)456, -1)] [InlineData((long)234, long.MaxValue, -1)] [InlineData((long)-234, (long)-234, 0)] [InlineData((long)-234, (long)234, -1)] [InlineData((long)-234, (long)-432, 1)] [InlineData((long)234, null, 1)] public void CompareTo_Other_ReturnsExpected(long i, object value, int expected) { if (value is long longValue) { Assert.Equal(expected, Math.Sign(i.CompareTo(longValue))); } Assert.Equal(expected, Math.Sign(i.CompareTo(value))); } [Theory] [InlineData("a")] [InlineData(234)] public void CompareTo_ObjectNotLong_ThrowsArgumentException(object value) { AssertExtensions.Throws<ArgumentException>(null, () => ((long)123).CompareTo(value)); } [Theory] [InlineData((long)789, (long)789, true)] [InlineData((long)789, (long)-789, false)] [InlineData((long)789, (long)0, false)] [InlineData((long)0, (long)0, true)] [InlineData((long)-789, (long)-789, true)] [InlineData((long)-789, (long)789, false)] [InlineData((long)789, null, false)] [InlineData((long)789, "789", false)] [InlineData((long)789, 789, false)] public static void Equals(long i1, object obj, bool expected) { if (obj is long) { long i2 = (long)obj; Assert.Equal(expected, i1.Equals(i2)); Assert.Equal(expected, i1.GetHashCode().Equals(i2.GetHashCode())); } Assert.Equal(expected, i1.Equals(obj)); } [Fact] public void GetTypeCode_Invoke_ReturnsInt64() { Assert.Equal(TypeCode.Int64, ((long)1).GetTypeCode()); } public static IEnumerable<object[]> ToString_TestData() { foreach (NumberFormatInfo defaultFormat in new[] { null, NumberFormatInfo.CurrentInfo }) { yield return new object[] { long.MinValue, "G", defaultFormat, "-9223372036854775808" }; yield return new object[] { (long)-4567, "G", defaultFormat, "-4567" }; yield return new object[] { (long)0, "G", defaultFormat, "0" }; yield return new object[] { (long)4567, "G", defaultFormat, "4567" }; yield return new object[] { long.MaxValue, "G", defaultFormat, "9223372036854775807" }; yield return new object[] { (long)4567, "D", defaultFormat, "4567" }; yield return new object[] { long.MaxValue, "D99", defaultFormat, "000000000000000000000000000000000000000000000000000000000000000000000000000000009223372036854775807" }; yield return new object[] { (long)0x2468, "x", defaultFormat, "2468" }; yield return new object[] { (long)2468, "N", defaultFormat, string.Format("{0:N}", 2468.00) }; } var customFormat = new NumberFormatInfo() { NegativeSign = "#", NumberDecimalSeparator = "~", NumberGroupSeparator = "*", PositiveSign = "&", NumberDecimalDigits = 2, PercentSymbol = "@", PercentGroupSeparator = ",", PercentDecimalSeparator = ".", PercentDecimalDigits = 5 }; yield return new object[] { (long)-2468, "N", customFormat, "#2*468~00" }; yield return new object[] { (long)2468, "N", customFormat, "2*468~00" }; yield return new object[] { (long)123, "E", customFormat, "1~230000E&002" }; yield return new object[] { (long)123, "F", customFormat, "123~00" }; yield return new object[] { (long)123, "P", customFormat, "12,300.00000 @" }; } [Theory] [MemberData(nameof(ToString_TestData))] public static void ToString(long i, string format, IFormatProvider provider, string expected) { // Format is case insensitive string upperFormat = format.ToUpperInvariant(); string lowerFormat = format.ToLowerInvariant(); string upperExpected = expected.ToUpperInvariant(); string lowerExpected = expected.ToLowerInvariant(); bool isDefaultProvider = (provider == null || provider == NumberFormatInfo.CurrentInfo); if (string.IsNullOrEmpty(format) || format.ToUpperInvariant() == "G") { if (isDefaultProvider) { Assert.Equal(upperExpected, i.ToString()); Assert.Equal(upperExpected, i.ToString((IFormatProvider)null)); } Assert.Equal(upperExpected, i.ToString(provider)); } if (isDefaultProvider) { Assert.Equal(upperExpected, i.ToString(upperFormat)); Assert.Equal(lowerExpected, i.ToString(lowerFormat)); Assert.Equal(upperExpected, i.ToString(upperFormat, null)); Assert.Equal(lowerExpected, i.ToString(lowerFormat, null)); } Assert.Equal(upperExpected, i.ToString(upperFormat, provider)); Assert.Equal(lowerExpected, i.ToString(lowerFormat, provider)); } [Fact] public static void ToString_InvalidFormat_ThrowsFormatException() { long i = 123; Assert.Throws<FormatException>(() => i.ToString("Y")); // Invalid format Assert.Throws<FormatException>(() => i.ToString("Y", null)); // Invalid format } public static IEnumerable<object[]> Parse_Valid_TestData() { // Reuse all Int32 test data foreach (object[] objs in Int32Tests.Parse_Valid_TestData()) { bool unsigned = (((NumberStyles)objs[1]) & NumberStyles.HexNumber) == NumberStyles.HexNumber; yield return new object[] { objs[0], objs[1], objs[2], unsigned ? (long)(uint)(int)objs[3] : (long)(int)objs[3] }; } // All lengths decimal foreach (bool neg in new[] { false, true }) { string s = neg ? "-" : ""; long result = 0; for (int i = 1; i <= 19; i++) { result = (result * 10) + (i % 10); s += (i % 10).ToString(); yield return new object[] { s, NumberStyles.Integer, null, neg ? result * -1 : result }; } } // All lengths hexadecimal { string s = ""; long result = 0; for (int i = 1; i <= 16; i++) { result = (result * 16) + (i % 16); s += (i % 16).ToString("X"); yield return new object[] { s, NumberStyles.HexNumber, null, result }; } } // And test boundary conditions for Int64 yield return new object[] { "-9223372036854775808", NumberStyles.Integer, null, long.MinValue }; yield return new object[] { "9223372036854775807", NumberStyles.Integer, null, long.MaxValue }; yield return new object[] { " -9223372036854775808 ", NumberStyles.Integer, null, long.MinValue }; yield return new object[] { " +9223372036854775807 ", NumberStyles.Integer, null, long.MaxValue }; yield return new object[] { "7FFFFFFFFFFFFFFF", NumberStyles.HexNumber, null, long.MaxValue }; yield return new object[] { "8000000000000000", NumberStyles.HexNumber, null, long.MinValue }; yield return new object[] { "FFFFFFFFFFFFFFFF", NumberStyles.HexNumber, null, -1L }; yield return new object[] { " FFFFFFFFFFFFFFFF ", NumberStyles.HexNumber, null, -1L }; } [Theory] [MemberData(nameof(Parse_Valid_TestData))] public static void Parse_Valid(string value, NumberStyles style, IFormatProvider provider, long expected) { long result; // Default style and provider if (style == NumberStyles.Integer && provider == null) { Assert.True(long.TryParse(value, out result)); Assert.Equal(expected, result); Assert.Equal(expected, long.Parse(value)); } // Default provider if (provider == null) { Assert.Equal(expected, long.Parse(value, style)); // Substitute default NumberFormatInfo Assert.True(long.TryParse(value, style, new NumberFormatInfo(), out result)); Assert.Equal(expected, result); Assert.Equal(expected, long.Parse(value, style, new NumberFormatInfo())); } // Default style if (style == NumberStyles.Integer) { Assert.Equal(expected, long.Parse(value, provider)); } // Full overloads Assert.True(long.TryParse(value, style, provider, out result)); Assert.Equal(expected, result); Assert.Equal(expected, long.Parse(value, style, provider)); } public static IEnumerable<object[]> Parse_Invalid_TestData() { // Reuse all int test data, except for those that wouldn't overflow long. foreach (object[] objs in Int32Tests.Parse_Invalid_TestData()) { if ((Type)objs[3] == typeof(OverflowException) && (!BigInteger.TryParse((string)objs[0], out BigInteger bi) || (bi >= long.MinValue && bi <= long.MaxValue))) { continue; } yield return objs; } } [Theory] [MemberData(nameof(Parse_Invalid_TestData))] public static void Parse_Invalid(string value, NumberStyles style, IFormatProvider provider, Type exceptionType) { long result; // Default style and provider if (style == NumberStyles.Integer && provider == null) { Assert.False(long.TryParse(value, out result)); Assert.Equal(default, result); Assert.Throws(exceptionType, () => long.Parse(value)); } // Default provider if (provider == null) { Assert.Throws(exceptionType, () => long.Parse(value, style)); // Substitute default NumberFormatInfo Assert.False(long.TryParse(value, style, new NumberFormatInfo(), out result)); Assert.Equal(default, result); Assert.Throws(exceptionType, () => long.Parse(value, style, new NumberFormatInfo())); } // Default style if (style == NumberStyles.Integer) { Assert.Throws(exceptionType, () => long.Parse(value, provider)); } // Full overloads Assert.False(long.TryParse(value, style, provider, out result)); Assert.Equal(default, result); Assert.Throws(exceptionType, () => long.Parse(value, style, provider)); } [Theory] [InlineData(NumberStyles.HexNumber | NumberStyles.AllowParentheses, null)] [InlineData(unchecked((NumberStyles)0xFFFFFC00), "style")] public static void TryParse_InvalidNumberStyle_ThrowsArgumentException(NumberStyles style, string paramName) { long result = 0; AssertExtensions.Throws<ArgumentException>(paramName, () => long.TryParse("1", style, null, out result)); Assert.Equal(default(long), result); AssertExtensions.Throws<ArgumentException>(paramName, () => long.Parse("1", style)); AssertExtensions.Throws<ArgumentException>(paramName, () => long.Parse("1", style, null)); } } }
// // LiteServ.cs // // Authors: // Jed Foss-Alfke <jed.foss-alfke@couchbase.com> // Jim Borden <jim.borden@couchbase.com> // // Copyright (c) 2015 Couchbase, Inc All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.IO; using System.Net; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using Couchbase.Lite; using Couchbase.Lite.Store; using Couchbase.Lite.Auth; using Couchbase.Lite.Listener; using Couchbase.Lite.Listener.Tcp; using Newtonsoft.Json; namespace Listener { public static class ListenerShared { private const int DefaultPort = 59840; public static void StartListener() { // INTERNAL API CouchbaseLiteRouter.InsecureMode = true; // INTERNAL API var alternateDir = default(string); var pullUrl = default(Uri); var pushUrl = default(Uri); var portToUse = DefaultPort; var readOnly = false; var requiresAuth = false; var createTarget = false; var continuous = false; var userName = default(string); var password = default(string); var useSSL = false; var sslCertPath = default(string); var sslCertPass = default(string); var storageType = "SQLite"; var passwordMap = new Dictionary<string, string>(); var revsLimit = 0; View.Compiler = new JSViewCompiler(); Database.FilterCompiler = new JSFilterCompiler(); string json; using (var httpListener = new HttpListener()) { try { httpListener.Prefixes.Add($"http://*:{DefaultPort}/test/"); httpListener.Start(); } catch (HttpListenerException e) { Console.Error.WriteLine("Error setting up parameter listener: {0}", e); return; } var context = httpListener.GetContext(); var reader = new StreamReader(context.Request.InputStream); json = reader.ReadToEnd(); } Dictionary<string, object> optionsDict = JsonConvert.DeserializeObject<Dictionary<string, object>>(json); foreach (var option in optionsDict) { switch (option.Key) { case "dir": alternateDir = (string)option.Value; break; case "port": portToUse = Convert.ToInt32(option.Value); break; case "readonly": readOnly = (bool)option.Value; break; case "auth": requiresAuth = (bool)option.Value; break; case "push": pushUrl = new Uri((string)option.Value); break; case "pull": pullUrl = new Uri((string)option.Value); break; case "create-target": createTarget = (bool)option.Value; break; case "continuous": continuous = (bool)option.Value; break; case "user": userName = (string)option.Value; break; case "password": password = (string)option.Value; break; case "revs_limit": revsLimit = Convert.ToInt32(option.Value); break; case "ssl": useSSL = (bool)option.Value; break; case "sslcert": sslCertPath = (string)option.Value; break; case "sslpass": sslCertPass = (string)option.Value; break; case "storage": storageType = (string)option.Value; break; case "dbpassword": RegisterPassword(passwordMap, (string)option.Value); break; default: Console.Error.WriteLine("Unrecognized argument {0}, ignoring...", option.Key); break; } } Couchbase.Lite.Storage.ForestDB.Plugin.Register(); Couchbase.Lite.Storage.SQLCipher.Plugin.Register(); var manager = alternateDir != null ? new Manager(new DirectoryInfo(alternateDir), ManagerOptions.Default) : Manager.SharedInstance; manager.StorageType = storageType; if (revsLimit > 0) { // Note: Internal API (used for testing) manager.DefaultMaxRevTreeDepth = revsLimit; } if (passwordMap.Count > 0) { foreach (var entry in passwordMap) { #pragma warning disable 618 manager.RegisterEncryptionKey(entry.Key, new SymmetricKey(entry.Value)); #pragma warning restore 618 } } var tcpOptions = CouchbaseLiteTcpOptions.Default | CouchbaseLiteTcpOptions.AllowBasicAuth; var sslCert = default(X509Certificate2); if (useSSL) { tcpOptions |= CouchbaseLiteTcpOptions.UseTLS; if (sslCertPath != null) { if (!File.Exists(sslCertPath)) { Console.Error.WriteLine("No file exists at given path for SSL cert ({0})", sslCertPath); return; } try { sslCert = new X509Certificate2(sslCertPath, sslCertPass); } catch (Exception e) { Console.Error.WriteLine("Error reading SSL cert ({0}), {1}", sslCertPath, e); return; } } } var replicator = default(Replication); if (pushUrl != null || pullUrl != null) { replicator = SetupReplication(manager, continuous, createTarget, pushUrl ?? pullUrl, pullUrl != null, userName, password); if (replicator == null) { return; } } CouchbaseLiteServiceListener listener = new CouchbaseLiteTcpListener(manager, (ushort)portToUse, tcpOptions, sslCert); listener.ReadOnly = readOnly; if (requiresAuth) { var random = new Random(); var generatedPassword = random.Next().ToString(); listener.SetPasswords(new Dictionary<string, string> { { "cbl", generatedPassword } }); Console.WriteLine("Auth required: user='cbl', password='{0}'", generatedPassword); } listener.Start(); Console.WriteLine("LISTENING..."); } private static Replication SetupReplication(Manager manager, bool continuous, bool createTarget, Uri remoteUri, bool isPull, string user, string password) { if (remoteUri == null) { return null; } var databaseName = remoteUri.Segments.Last(); var authenticator = default(IAuthenticator); if (user != null && password != null) { Console.WriteLine("Setting session credentials for user '{0}'", user); authenticator = AuthenticatorFactory.CreateBasicAuthenticator(user, password); } if (isPull) { Console.WriteLine("Pulling from <{0}> --> {1}", remoteUri, databaseName); } else { Console.WriteLine("Pushing {0} --> <{1}>", databaseName, remoteUri); } var db = manager.GetExistingDatabase(databaseName); if (isPull && db == null) { db = manager.GetDatabase(databaseName); } if (db == null) { Console.Error.WriteLine("Couldn't open database {0}", databaseName); return null; } var repl = isPull ? db.CreatePullReplication(remoteUri) : db.CreatePushReplication(remoteUri); repl.Continuous = continuous; repl.CreateTarget = createTarget; repl.Authenticator = authenticator; repl.Changed += (sender, e) => { Console.WriteLine("*** Replicator status changed ({0} {1}/{2}) ***", e.Status, e.CompletedChangesCount, e.ChangesCount); if (e.LastError != null) { Console.Error.WriteLine("*** Replicator reported error ***", e); } else if (e.Status == ReplicationStatus.Stopped) { Console.WriteLine("*** Replicator finished ***"); } }; repl.Start(); return repl; } private static void RegisterPassword(IDictionary<string, string> collection, string unparsed) { var userAndPass = unparsed.Split('='); if (userAndPass.Length != 2) { throw new ArgumentException($"Invalid entry for dbpassword ({unparsed}), must be in " + "the format <name>=<password>"); } collection[userAndPass[0]] = userAndPass[1]; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime; using System.Runtime.InteropServices; using Debug = Internal.Runtime.CompilerHelpers.StartupDebug; namespace Internal.Runtime.CompilerHelpers { [McgIntrinsics] public static partial class StartupCodeHelpers { /// <summary> /// Initial module array allocation used when adding modules dynamically. /// </summary> private const int InitialModuleCount = 8; /// <summary> /// Table of logical modules. Only the first s_moduleCount elements of the array are in use. /// </summary> private static TypeManagerHandle[] s_modules; /// <summary> /// Number of valid elements in the logical module table. /// </summary> private static int s_moduleCount; [NativeCallable(EntryPoint = "InitializeModules", CallingConvention = CallingConvention.Cdecl)] internal static unsafe void InitializeModules(IntPtr osModule, IntPtr* pModuleHeaders, int count, IntPtr* pClasslibFunctions, int nClasslibFunctions) { RuntimeImports.RhpRegisterOsModule(osModule); TypeManagerHandle[] modules = CreateTypeManagers(osModule, pModuleHeaders, count, pClasslibFunctions, nClasslibFunctions); for (int i = 0; i < modules.Length; i++) { InitializeGlobalTablesForModule(modules[i], i); } // We are now at a stage where we can use GC statics - publish the list of modules // so that the eager constructors can access it. if (s_modules != null) { for (int i = 0; i < modules.Length; i++) { AddModule(modules[i]); } } else { s_modules = modules; s_moduleCount = modules.Length; } // These two loops look funny but it's important to initialize the global tables before running // the first class constructor to prevent them calling into another uninitialized module for (int i = 0; i < modules.Length; i++) { InitializeEagerClassConstructorsForModule(modules[i]); } } /// <summary> /// Return the number of registered logical modules; optionally copy them into an array. /// </summary> /// <param name="outputModules">Array to copy logical modules to, null = only return logical module count</param> internal static int GetLoadedModules(TypeManagerHandle[] outputModules) { if (outputModules != null) { int copyLimit = (s_moduleCount < outputModules.Length ? s_moduleCount : outputModules.Length); for (int copyIndex = 0; copyIndex < copyLimit; copyIndex++) { outputModules[copyIndex] = s_modules[copyIndex]; } } return s_moduleCount; } private static void AddModule(TypeManagerHandle newModuleHandle) { if (s_modules == null || s_moduleCount >= s_modules.Length) { // Reallocate logical module array int newModuleLength = 2 * s_moduleCount; if (newModuleLength < InitialModuleCount) { newModuleLength = InitialModuleCount; } TypeManagerHandle[] newModules = new TypeManagerHandle[newModuleLength]; for (int copyIndex = 0; copyIndex < s_moduleCount; copyIndex++) { newModules[copyIndex] = s_modules[copyIndex]; } s_modules = newModules; } s_modules[s_moduleCount] = newModuleHandle; s_moduleCount++; } private static unsafe TypeManagerHandle[] CreateTypeManagers(IntPtr osModule, IntPtr* pModuleHeaders, int count, IntPtr* pClasslibFunctions, int nClasslibFunctions) { // Count the number of modules so we can allocate an array to hold the TypeManager objects. // At this stage of startup, complex collection classes will not work. int moduleCount = 0; for (int i = 0; i < count; i++) { // The null pointers are sentinel values and padding inserted as side-effect of // the section merging. (The global static constructors section used by C++ has // them too.) if (pModuleHeaders[i] != IntPtr.Zero) moduleCount++; } TypeManagerHandle[] modules = new TypeManagerHandle[moduleCount]; int moduleIndex = 0; for (int i = 0; i < count; i++) { if (pModuleHeaders[i] != IntPtr.Zero) { modules[moduleIndex] = RuntimeImports.RhpCreateTypeManager(osModule, pModuleHeaders[i], pClasslibFunctions, nClasslibFunctions); moduleIndex++; } } return modules; } /// <summary> /// Each managed module linked into the final binary may have its own global tables for strings, /// statics, etc that need initializing. InitializeGlobalTables walks through the modules /// and offers each a chance to initialize its global tables. /// </summary> private static unsafe void InitializeGlobalTablesForModule(TypeManagerHandle typeManager, int moduleIndex) { // Configure the module indirection cell with the newly created TypeManager. This allows EETypes to find // their interface dispatch map tables. int length; TypeManagerSlot* section = (TypeManagerSlot*)RuntimeImports.RhGetModuleSection(typeManager, ReadyToRunSectionType.TypeManagerIndirection, out length); section->TypeManager = typeManager; section->ModuleIndex = moduleIndex; // Initialize Mrt import address tables IntPtr mrtImportSection = RuntimeImports.RhGetModuleSection(typeManager, ReadyToRunSectionType.ImportAddressTables, out length); if (mrtImportSection != IntPtr.Zero) { Debug.Assert(length % IntPtr.Size == 0); InitializeImports(mrtImportSection, length); } #if !PROJECTN // Initialize statics if any are present IntPtr staticsSection = RuntimeImports.RhGetModuleSection(typeManager, ReadyToRunSectionType.GCStaticRegion, out length); if (staticsSection != IntPtr.Zero) { Debug.Assert(length % IntPtr.Size == 0); InitializeStatics(staticsSection, length); } #endif // Initialize frozen object segment with GC present IntPtr frozenObjectSection = RuntimeImports.RhGetModuleSection(typeManager, ReadyToRunSectionType.FrozenObjectRegion, out length); if (frozenObjectSection != IntPtr.Zero) { Debug.Assert(length % IntPtr.Size == 0); InitializeFrozenObjectSegment(frozenObjectSection, length); } } private static unsafe void InitializeFrozenObjectSegment(IntPtr segmentStart, int length) { if (!RuntimeImports.RhpRegisterFrozenSegment(segmentStart, length)) { // This should only happen if we ran out of memory. RuntimeExceptionHelpers.FailFast("Failed to register frozen object segment."); } } private static unsafe void InitializeEagerClassConstructorsForModule(TypeManagerHandle typeManager) { int length; // Run eager class constructors if any are present IntPtr eagerClassConstructorSection = RuntimeImports.RhGetModuleSection(typeManager, ReadyToRunSectionType.EagerCctor, out length); if (eagerClassConstructorSection != IntPtr.Zero) { Debug.Assert(length % IntPtr.Size == 0); RunEagerClassConstructors(eagerClassConstructorSection, length); } } private static void Call(System.IntPtr pfn) { } private static unsafe void RunEagerClassConstructors(IntPtr cctorTableStart, int length) { IntPtr cctorTableEnd = (IntPtr)((byte*)cctorTableStart + length); for (IntPtr* tab = (IntPtr*)cctorTableStart; tab < (IntPtr*)cctorTableEnd; tab++) { Call(*tab); } } [StructLayout(LayoutKind.Sequential)] unsafe struct MrtExportsV1 { public int ExportsVersion; // Currently only version 1 is supported public int SymbolsCount; public int FirstDataItemAsRelativePointer; // Index 1 } [StructLayout(LayoutKind.Sequential)] unsafe struct MrtImportsV1 { public int ImportVersion; // Currently only version 1 is supported public int ImportCount; // Count of imports public MrtExportsV1** ExportTable; // Pointer to pointer to Export table public IntPtr FirstImportEntry; } private static unsafe void InitializeImports(IntPtr importsRegionStart, int length) { IntPtr importsRegionEnd = (IntPtr)((byte*)importsRegionStart + length); for (MrtImportsV1** importTablePtr = (MrtImportsV1**)importsRegionStart; importTablePtr < (MrtImportsV1**)importsRegionEnd; importTablePtr++) { MrtImportsV1* importTable = *importTablePtr; if (importTable->ImportVersion != 1) RuntimeExceptionHelpers.FailFast("Mrt Import table version"); MrtExportsV1* exportTable = *importTable->ExportTable; if (exportTable->ExportsVersion != 1) RuntimeExceptionHelpers.FailFast("Mrt Export table version"); if (importTable->ImportCount < 0) { RuntimeExceptionHelpers.FailFast("Mrt Import Count"); } int* firstExport = &exportTable->FirstDataItemAsRelativePointer; IntPtr* firstImport = &importTable->FirstImportEntry; for (int import = 0; import < importTable->ImportCount; import++) { // Get 1 based ordinal from import table int importOrdinal = (int)firstImport[import]; if ((importOrdinal < 1) || (importOrdinal > exportTable->SymbolsCount)) RuntimeExceptionHelpers.FailFast("Mrt import ordinal"); // Get entry in export table int* exportTableEntry = &firstExport[importOrdinal - 1]; // Get pointer from export table int relativeOffsetFromExportTableEntry = *exportTableEntry; byte* actualPointer = ((byte*)exportTableEntry) + relativeOffsetFromExportTableEntry + sizeof(int); // Update import table with imported value firstImport[import] = new IntPtr(actualPointer); } } } #if !PROJECTN private static unsafe void InitializeStatics(IntPtr gcStaticRegionStart, int length) { IntPtr gcStaticRegionEnd = (IntPtr)((byte*)gcStaticRegionStart + length); for (IntPtr* block = (IntPtr*)gcStaticRegionStart; block < (IntPtr*)gcStaticRegionEnd; block++) { // Gc Static regions can be shared by modules linked together during compilation. To ensure each // is initialized once, the static region pointer is stored with lowest bit set in the image. // The first time we initialize the static region its pointer is replaced with an object reference // whose lowest bit is no longer set. IntPtr* pBlock = (IntPtr*)*block; long blockAddr = (*pBlock).ToInt64(); if ((blockAddr & GCStaticRegionConstants.Uninitialized) == GCStaticRegionConstants.Uninitialized) { object obj = RuntimeImports.RhNewObject(new EETypePtr(new IntPtr(blockAddr & ~GCStaticRegionConstants.Mask))); if ((blockAddr & GCStaticRegionConstants.HasPreInitializedData) == GCStaticRegionConstants.HasPreInitializedData) { // The next pointer is preinitialized data blob that contains preinitialized static GC fields, // which are pointer relocs to GC objects in frozen segment. // It actually has all GC fields including non-preinitialized fields and we simply copy over the // entire blob to this object, overwriting everything. IntPtr pPreInitDataAddr = *(pBlock + 1); RuntimeImports.RhBulkMoveWithWriteBarrier(ref obj.GetRawData(), ref *(byte *)pPreInitDataAddr, obj.GetRawDataSize()); } *pBlock = RuntimeImports.RhHandleAlloc(obj, GCHandleType.Normal); } } } #endif // !PROJECTN } [StructLayout(LayoutKind.Sequential)] internal unsafe struct TypeManagerSlot { public TypeManagerHandle TypeManager; public int ModuleIndex; } }
/* * 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> /// OrderPaymentCreditCard /// </summary> [DataContract] public partial class OrderPaymentCreditCard : IEquatable<OrderPaymentCreditCard>, IValidatableObject { /// <summary> /// Card type /// </summary> /// <value>Card type</value> [JsonConverter(typeof(StringEnumConverter))] public enum CardTypeEnum { /// <summary> /// Enum AMEX for value: AMEX /// </summary> [EnumMember(Value = "AMEX")] AMEX = 1, /// <summary> /// Enum DinersClub for value: Diners Club /// </summary> [EnumMember(Value = "Diners Club")] DinersClub = 2, /// <summary> /// Enum Discover for value: Discover /// </summary> [EnumMember(Value = "Discover")] Discover = 3, /// <summary> /// Enum JCB for value: JCB /// </summary> [EnumMember(Value = "JCB")] JCB = 4, /// <summary> /// Enum MasterCard for value: MasterCard /// </summary> [EnumMember(Value = "MasterCard")] MasterCard = 5, /// <summary> /// Enum VISA for value: VISA /// </summary> [EnumMember(Value = "VISA")] VISA = 6 } /// <summary> /// Card type /// </summary> /// <value>Card type</value> [DataMember(Name="card_type", EmitDefaultValue=false)] public CardTypeEnum? CardType { get; set; } /// <summary> /// Initializes a new instance of the <see cref="OrderPaymentCreditCard" /> class. /// </summary> /// <param name="cardAuthTicket">Card authorization ticket.</param> /// <param name="cardAuthorizationAmount">Card authorization amount.</param> /// <param name="cardAuthorizationDts">Card authorization date/time.</param> /// <param name="cardAuthorizationReferenceNumber">Card authorization reference number.</param> /// <param name="cardExpirationMonth">Card expiration month (1-12).</param> /// <param name="cardExpirationYear">Card expiration year (Four digit year).</param> /// <param name="cardNumber">Card number (masked to last 4).</param> /// <param name="cardNumberToken">Card number token from hosted fields used to update the card number.</param> /// <param name="cardNumberTruncated">True if the card has been truncated.</param> /// <param name="cardType">Card type.</param> /// <param name="cardVerificationNumberToken">Card verification number token from hosted fields, only for import/insert of new orders, completely ignored for updates, and always null/empty for queries.</param> public OrderPaymentCreditCard(string cardAuthTicket = default(string), decimal? cardAuthorizationAmount = default(decimal?), string cardAuthorizationDts = default(string), string cardAuthorizationReferenceNumber = default(string), int? cardExpirationMonth = default(int?), int? cardExpirationYear = default(int?), string cardNumber = default(string), string cardNumberToken = default(string), bool? cardNumberTruncated = default(bool?), CardTypeEnum? cardType = default(CardTypeEnum?), string cardVerificationNumberToken = default(string)) { this.CardAuthTicket = cardAuthTicket; this.CardAuthorizationAmount = cardAuthorizationAmount; this.CardAuthorizationDts = cardAuthorizationDts; this.CardAuthorizationReferenceNumber = cardAuthorizationReferenceNumber; this.CardExpirationMonth = cardExpirationMonth; this.CardExpirationYear = cardExpirationYear; this.CardNumber = cardNumber; this.CardNumberToken = cardNumberToken; this.CardNumberTruncated = cardNumberTruncated; this.CardType = cardType; this.CardVerificationNumberToken = cardVerificationNumberToken; } /// <summary> /// Card authorization ticket /// </summary> /// <value>Card authorization ticket</value> [DataMember(Name="card_auth_ticket", EmitDefaultValue=false)] public string CardAuthTicket { get; set; } /// <summary> /// Card authorization amount /// </summary> /// <value>Card authorization amount</value> [DataMember(Name="card_authorization_amount", EmitDefaultValue=false)] public decimal? CardAuthorizationAmount { get; set; } /// <summary> /// Card authorization date/time /// </summary> /// <value>Card authorization date/time</value> [DataMember(Name="card_authorization_dts", EmitDefaultValue=false)] public string CardAuthorizationDts { get; set; } /// <summary> /// Card authorization reference number /// </summary> /// <value>Card authorization reference number</value> [DataMember(Name="card_authorization_reference_number", EmitDefaultValue=false)] public string CardAuthorizationReferenceNumber { get; set; } /// <summary> /// Card expiration month (1-12) /// </summary> /// <value>Card expiration month (1-12)</value> [DataMember(Name="card_expiration_month", EmitDefaultValue=false)] public int? CardExpirationMonth { get; set; } /// <summary> /// Card expiration year (Four digit year) /// </summary> /// <value>Card expiration year (Four digit year)</value> [DataMember(Name="card_expiration_year", EmitDefaultValue=false)] public int? CardExpirationYear { get; set; } /// <summary> /// Card number (masked to last 4) /// </summary> /// <value>Card number (masked to last 4)</value> [DataMember(Name="card_number", EmitDefaultValue=false)] public string CardNumber { get; set; } /// <summary> /// Card number token from hosted fields used to update the card number /// </summary> /// <value>Card number token from hosted fields used to update the card number</value> [DataMember(Name="card_number_token", EmitDefaultValue=false)] public string CardNumberToken { get; set; } /// <summary> /// True if the card has been truncated /// </summary> /// <value>True if the card has been truncated</value> [DataMember(Name="card_number_truncated", EmitDefaultValue=false)] public bool? CardNumberTruncated { get; set; } /// <summary> /// Card verification number token from hosted fields, only for import/insert of new orders, completely ignored for updates, and always null/empty for queries /// </summary> /// <value>Card verification number token from hosted fields, only for import/insert of new orders, completely ignored for updates, and always null/empty for queries</value> [DataMember(Name="card_verification_number_token", EmitDefaultValue=false)] public string CardVerificationNumberToken { 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 OrderPaymentCreditCard {\n"); sb.Append(" CardAuthTicket: ").Append(CardAuthTicket).Append("\n"); sb.Append(" CardAuthorizationAmount: ").Append(CardAuthorizationAmount).Append("\n"); sb.Append(" CardAuthorizationDts: ").Append(CardAuthorizationDts).Append("\n"); sb.Append(" CardAuthorizationReferenceNumber: ").Append(CardAuthorizationReferenceNumber).Append("\n"); sb.Append(" CardExpirationMonth: ").Append(CardExpirationMonth).Append("\n"); sb.Append(" CardExpirationYear: ").Append(CardExpirationYear).Append("\n"); sb.Append(" CardNumber: ").Append(CardNumber).Append("\n"); sb.Append(" CardNumberToken: ").Append(CardNumberToken).Append("\n"); sb.Append(" CardNumberTruncated: ").Append(CardNumberTruncated).Append("\n"); sb.Append(" CardType: ").Append(CardType).Append("\n"); sb.Append(" CardVerificationNumberToken: ").Append(CardVerificationNumberToken).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 OrderPaymentCreditCard); } /// <summary> /// Returns true if OrderPaymentCreditCard instances are equal /// </summary> /// <param name="input">Instance of OrderPaymentCreditCard to be compared</param> /// <returns>Boolean</returns> public bool Equals(OrderPaymentCreditCard input) { if (input == null) return false; return ( this.CardAuthTicket == input.CardAuthTicket || (this.CardAuthTicket != null && this.CardAuthTicket.Equals(input.CardAuthTicket)) ) && ( this.CardAuthorizationAmount == input.CardAuthorizationAmount || (this.CardAuthorizationAmount != null && this.CardAuthorizationAmount.Equals(input.CardAuthorizationAmount)) ) && ( this.CardAuthorizationDts == input.CardAuthorizationDts || (this.CardAuthorizationDts != null && this.CardAuthorizationDts.Equals(input.CardAuthorizationDts)) ) && ( this.CardAuthorizationReferenceNumber == input.CardAuthorizationReferenceNumber || (this.CardAuthorizationReferenceNumber != null && this.CardAuthorizationReferenceNumber.Equals(input.CardAuthorizationReferenceNumber)) ) && ( this.CardExpirationMonth == input.CardExpirationMonth || (this.CardExpirationMonth != null && this.CardExpirationMonth.Equals(input.CardExpirationMonth)) ) && ( this.CardExpirationYear == input.CardExpirationYear || (this.CardExpirationYear != null && this.CardExpirationYear.Equals(input.CardExpirationYear)) ) && ( this.CardNumber == input.CardNumber || (this.CardNumber != null && this.CardNumber.Equals(input.CardNumber)) ) && ( this.CardNumberToken == input.CardNumberToken || (this.CardNumberToken != null && this.CardNumberToken.Equals(input.CardNumberToken)) ) && ( this.CardNumberTruncated == input.CardNumberTruncated || (this.CardNumberTruncated != null && this.CardNumberTruncated.Equals(input.CardNumberTruncated)) ) && ( this.CardType == input.CardType || (this.CardType != null && this.CardType.Equals(input.CardType)) ) && ( this.CardVerificationNumberToken == input.CardVerificationNumberToken || (this.CardVerificationNumberToken != null && this.CardVerificationNumberToken.Equals(input.CardVerificationNumberToken)) ); } /// <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.CardAuthTicket != null) hashCode = hashCode * 59 + this.CardAuthTicket.GetHashCode(); if (this.CardAuthorizationAmount != null) hashCode = hashCode * 59 + this.CardAuthorizationAmount.GetHashCode(); if (this.CardAuthorizationDts != null) hashCode = hashCode * 59 + this.CardAuthorizationDts.GetHashCode(); if (this.CardAuthorizationReferenceNumber != null) hashCode = hashCode * 59 + this.CardAuthorizationReferenceNumber.GetHashCode(); if (this.CardExpirationMonth != null) hashCode = hashCode * 59 + this.CardExpirationMonth.GetHashCode(); if (this.CardExpirationYear != null) hashCode = hashCode * 59 + this.CardExpirationYear.GetHashCode(); if (this.CardNumber != null) hashCode = hashCode * 59 + this.CardNumber.GetHashCode(); if (this.CardNumberToken != null) hashCode = hashCode * 59 + this.CardNumberToken.GetHashCode(); if (this.CardNumberTruncated != null) hashCode = hashCode * 59 + this.CardNumberTruncated.GetHashCode(); if (this.CardType != null) hashCode = hashCode * 59 + this.CardType.GetHashCode(); if (this.CardVerificationNumberToken != null) hashCode = hashCode * 59 + this.CardVerificationNumberToken.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) { yield break; } } }
#region License /*---------------------------------------------------------------------------------*\ Distributed under the terms of an MIT-style license: The MIT License Copyright (c) 2006-2010 Stephen M. McKamey 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 License using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; #if WINDOWS_STORE using TP = System.Reflection.TypeInfo; #else using TP = System.Type; #endif namespace Pathfinding.Serialization.JsonFx { /// <summary> /// Writes data as full ECMAScript objects, rather than the limited set of JSON objects. /// </summary> public class EcmaScriptWriter : JsonWriter { #region Constants private static readonly DateTime EcmaScriptEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc); private const string EcmaScriptDateCtor1 = "new Date({0})"; private const string EcmaScriptDateCtor7 = "new Date({0:0000},{1},{2},{3},{4},{5},{6})"; private const string EmptyRegExpLiteral = "(?:)"; private const char RegExpLiteralDelim = '/'; private const char OperatorCharEscape = '\\'; private const string NamespaceDelim = "."; private static readonly char[] NamespaceDelims = { '.' }; private const string RootDeclarationDebug = @" /* namespace {1} */ var {0};"; private const string RootDeclaration = @"var {0};"; private const string NamespaceCheck = @"if(""undefined""===typeof {0}){{{0}={{}};}}"; private const string NamespaceCheckDebug = @" if (""undefined"" === typeof {0}) {{ {0} = {{}}; }}"; private static readonly IList<string> BrowserObjects = new List<string>(new string[] { "console", "document", "event", "frames", "history", "location", "navigator", "opera", "screen", "window" }); #endregion Constants #region Init /// <summary> /// Ctor /// </summary> /// <param name="output">TextWriter for writing</param> public EcmaScriptWriter(TextWriter output) : base(output) { } /// <summary> /// Ctor /// </summary> /// <param name="output">Stream for writing</param> public EcmaScriptWriter(Stream output) : base(output) { } /// <summary> /// Ctor /// </summary> /// <param name="output">File name for writing</param> public EcmaScriptWriter(string outputFileName) : base(outputFileName) { } /// <summary> /// Ctor /// </summary> /// <param name="output">StringBuilder for appending</param> public EcmaScriptWriter(StringBuilder output) : base(output) { } #endregion Init #region Static Methods /// <summary> /// A helper method for serializing an object to EcmaScript /// </summary> /// <param name="value"></param> /// <returns></returns> public static new string Serialize(object value) { StringBuilder output = new StringBuilder(); using (EcmaScriptWriter writer = new EcmaScriptWriter(output)) { writer.Write(value); } return output.ToString(); } /// <summary> /// Returns a block of script for ensuring that a namespace is declared. /// </summary> /// <param name="writer">the output writer</param> /// <param name="ident">the namespace to ensure</param> /// <param name="namespaces">list of namespaces already emitted</param> /// <param name="debug">determines if should emit pretty-printed</param> /// <returns>if was a nested identifier</returns> public static bool WriteNamespaceDeclaration(TextWriter writer, string ident, List<string> namespaces, bool isDebug) { if (String.IsNullOrEmpty(ident)) { return false; } if (namespaces == null) { namespaces = new List<string>(); } string[] nsParts = ident.Split(EcmaScriptWriter.NamespaceDelims, StringSplitOptions.RemoveEmptyEntries); string ns = nsParts[0]; bool isNested = false; for (int i=0; i<nsParts.Length-1; i++) { isNested = true; if (i > 0) { ns += EcmaScriptWriter.NamespaceDelim; ns += nsParts[i]; } if (namespaces.Contains(ns) || EcmaScriptWriter.BrowserObjects.Contains(ns)) { // don't emit multiple checks for same namespace continue; } // make note that we've emitted this namespace before namespaces.Add(ns); if (i == 0) { if (isDebug) { writer.Write(EcmaScriptWriter.RootDeclarationDebug, ns, String.Join(NamespaceDelim, nsParts, 0, nsParts.Length-1)); } else { writer.Write(EcmaScriptWriter.RootDeclaration, ns); } } if (isDebug) { writer.WriteLine(EcmaScriptWriter.NamespaceCheckDebug, ns); } else { writer.Write(EcmaScriptWriter.NamespaceCheck, ns); } } if (isDebug && isNested) { writer.WriteLine(); } return isNested; } #endregion Static Methods #region Writer Methods /// <summary> /// Writes dates as ECMAScript Date constructors /// </summary> /// <param name="value"></param> public override void Write(DateTime value) { EcmaScriptWriter.WriteEcmaScriptDate(this, value); } /// <summary> /// Writes out all Single values including NaN, Infinity, -Infinity /// </summary> /// <param name="value">Single</param> public override void Write(float value) { this.TextWriter.Write(value.ToString("r")); } /// <summary> /// Writes out all Double values including NaN, Infinity, -Infinity /// </summary> /// <param name="value">Double</param> public override void Write(double value) { this.TextWriter.Write(value.ToString("r")); } protected override void Write(object value, bool isProperty) { if (value is Regex) { if (isProperty && this.Settings.PrettyPrint) { this.TextWriter.Write(' '); } EcmaScriptWriter.WriteEcmaScriptRegExp(this, (Regex)value); return; } base.Write(value, isProperty); } protected override void WriteObjectPropertyName(string name) { if (EcmaScriptIdentifier.IsValidIdentifier(name, false)) { // write out without quoting this.TextWriter.Write(name); } else { // write out as an escaped string base.WriteObjectPropertyName(name); } } public static void WriteEcmaScriptDate(JsonWriter writer, DateTime value) { if (value.Kind == DateTimeKind.Unspecified) { // unknown timezones serialize directly to become browser-local writer.TextWriter.Write( EcmaScriptWriter.EcmaScriptDateCtor7, value.Year, // yyyy value.Month-1, // 0-11 value.Day, // 1-31 value.Hour, // 0-23 value.Minute, // 0-60 value.Second, // 0-60 value.Millisecond); // 0-999 return; } if (value.Kind == DateTimeKind.Local) { // convert server-local to UTC value = value.ToUniversalTime(); } // find the time since Jan 1, 1970 TimeSpan duration = value.Subtract(EcmaScriptWriter.EcmaScriptEpoch); // get the total milliseconds long ticks = (long)duration.TotalMilliseconds; // write out as a Date constructor writer.TextWriter.Write( EcmaScriptWriter.EcmaScriptDateCtor1, ticks); } /// <summary> /// Outputs a .NET Regex as an ECMAScript RegExp literal. /// Defaults to global matching off. /// </summary> /// <param name="writer"></param> /// <param name="regex"></param> /// <remarks> /// http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf /// </remarks> public static void WriteEcmaScriptRegExp(JsonWriter writer, Regex regex) { EcmaScriptWriter.WriteEcmaScriptRegExp(writer, regex, false); } /// <summary> /// Outputs a .NET Regex as an ECMAScript RegExp literal. /// </summary> /// <param name="writer"></param> /// <param name="regex"></param> /// <param name="isGlobal"></param> /// <remarks> /// http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf /// </remarks> public static void WriteEcmaScriptRegExp(JsonWriter writer, Regex regex, bool isGlobal) { if (regex == null) { writer.TextWriter.Write(JsonReader.LiteralNull); return; } // Regex.ToString() returns the original pattern string pattern = regex.ToString(); if (String.IsNullOrEmpty(pattern)) { // must output something otherwise becomes a code comment pattern = EcmaScriptWriter.EmptyRegExpLiteral; } string modifiers = isGlobal ? "g" : ""; switch (regex.Options & (RegexOptions.IgnoreCase|RegexOptions.Multiline)) { case RegexOptions.IgnoreCase: { modifiers += "i"; break; } case RegexOptions.Multiline: { modifiers += "m"; break; } case RegexOptions.IgnoreCase|RegexOptions.Multiline: { modifiers += "im"; break; } } writer.TextWriter.Write(EcmaScriptWriter.RegExpLiteralDelim); int length = pattern.Length; int start = 0; for (int i = start; i < length; i++) { switch (pattern[i]) { case EcmaScriptWriter.RegExpLiteralDelim: { writer.TextWriter.Write(pattern.Substring(start, i - start)); start = i + 1; writer.TextWriter.Write(EcmaScriptWriter.OperatorCharEscape); writer.TextWriter.Write(pattern[i]); break; } } } writer.TextWriter.Write(pattern.Substring(start, length - start)); writer.TextWriter.Write(EcmaScriptWriter.RegExpLiteralDelim); writer.TextWriter.Write(modifiers); } #endregion Writer Methods } }
// 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.Collections.ObjectModel; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Xml; using Microsoft.Build.Construction; using Microsoft.Build.Evaluation; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Interpreter; using Microsoft.VisualStudio.Language.Intellisense; using Task = System.Threading.Tasks.Task; namespace Microsoft.PythonTools.Project.ImportWizard { internal class ImportSettings : DependencyObject { private readonly IServiceProvider _site; private readonly IInterpreterRegistryService _service; private bool _isAutoGeneratedProjectPath; private static readonly PythonInterpreterView _defaultInterpreter = new PythonInterpreterView( "(Global default or an auto-detected virtual environment)", String.Empty, null ); private static readonly IList<ProjectCustomization> _projectCustomizations = new [] { BottleProjectCustomization.Instance, DjangoProjectCustomization.Instance, FlaskProjectCustomization.Instance, GenericWebProjectCustomization.Instance, UwpProjectCustomization.Instance }; public ImportSettings(IServiceProvider site, IInterpreterRegistryService service) { _site = site; _service = service; if (_service != null) { AvailableInterpreters = new ObservableCollection<PythonInterpreterView>( Enumerable.Repeat(_defaultInterpreter, 1) .Concat(_service.Configurations.Select(fact => new PythonInterpreterView(fact))) ); } else { AvailableInterpreters = new ObservableCollection<PythonInterpreterView>(); AvailableInterpreters.Add(_defaultInterpreter); } SelectedInterpreter = AvailableInterpreters[0]; TopLevelPythonFiles = new BulkObservableCollection<string>(); Customization = _projectCustomizations.First(); Filters = "*.pyw;*.txt;*.htm;*.html;*.css;*.djt;*.js;*.ini;*.png;*.jpg;*.gif;*.bmp;*.ico;*.svg"; } private static string MakeSafePath(string path) { if (string.IsNullOrEmpty(path)) { return null; } var safePath = path.Trim(' ', '"'); if (PathUtils.IsValidPath(safePath)) { return safePath; } return null; } public string ProjectPath { get { return MakeSafePath((string)GetValue(ProjectPathProperty)); } set { SetValue(ProjectPathProperty, value); } } public string SourcePath { get { return MakeSafePath((string)GetValue(SourcePathProperty)); } set { SetValue(SourcePathProperty, value); } } public string Filters { get { return (string)GetValue(FiltersProperty); } set { SetValue(FiltersProperty, value); } } public string SearchPaths { get { return (string)GetValue(SearchPathsProperty); } set { SetValue(SearchPathsProperty, value); } } public ObservableCollection<PythonInterpreterView> AvailableInterpreters { get { return (ObservableCollection<PythonInterpreterView>)GetValue(AvailableInterpretersProperty); } set { SetValue(AvailableInterpretersPropertyKey, value); } } public PythonInterpreterView SelectedInterpreter { get { return (PythonInterpreterView)GetValue(SelectedInterpreterProperty); } set { SetValue(SelectedInterpreterProperty, value); } } public ObservableCollection<string> TopLevelPythonFiles { get { return (ObservableCollection<string>)GetValue(TopLevelPythonFilesProperty); } private set { SetValue(TopLevelPythonFilesPropertyKey, value); } } public string StartupFile { get { return (string)GetValue(StartupFileProperty); } set { SetValue(StartupFileProperty, value); } } public IEnumerable<ProjectCustomization> SupportedProjectCustomizations { get { return _projectCustomizations; } } public bool UseCustomization { get { return (bool)GetValue(UseCustomizationProperty); } set { SetValue(UseCustomizationProperty, value); } } public ProjectCustomization Customization { get { return (ProjectCustomization)GetValue(CustomizationProperty); } set { SetValue(CustomizationProperty, value); } } public bool DetectVirtualEnv { get { return (bool)GetValue(DetectVirtualEnvProperty); } set { SetValue(DetectVirtualEnvProperty, value); } } public static readonly DependencyProperty ProjectPathProperty = DependencyProperty.Register("ProjectPath", typeof(string), typeof(ImportSettings), new PropertyMetadata(ProjectPath_Updated)); public static readonly DependencyProperty SourcePathProperty = DependencyProperty.Register("SourcePath", typeof(string), typeof(ImportSettings), new PropertyMetadata()); public static readonly DependencyProperty FiltersProperty = DependencyProperty.Register("Filters", typeof(string), typeof(ImportSettings), new PropertyMetadata()); public static readonly DependencyProperty SearchPathsProperty = DependencyProperty.Register("SearchPaths", typeof(string), typeof(ImportSettings), new PropertyMetadata(RecalculateIsValid)); private static readonly DependencyPropertyKey AvailableInterpretersPropertyKey = DependencyProperty.RegisterReadOnly("AvailableInterpreters", typeof(ObservableCollection<PythonInterpreterView>), typeof(ImportSettings), new PropertyMetadata()); public static readonly DependencyProperty AvailableInterpretersProperty = AvailableInterpretersPropertyKey.DependencyProperty; public static readonly DependencyProperty SelectedInterpreterProperty = DependencyProperty.Register("SelectedInterpreter", typeof(PythonInterpreterView), typeof(ImportSettings), new PropertyMetadata(RecalculateIsValid)); private static readonly DependencyPropertyKey TopLevelPythonFilesPropertyKey = DependencyProperty.RegisterReadOnly("TopLevelPythonFiles", typeof(ObservableCollection<string>), typeof(ImportSettings), new PropertyMetadata()); public static readonly DependencyProperty TopLevelPythonFilesProperty = TopLevelPythonFilesPropertyKey.DependencyProperty; public static readonly DependencyProperty StartupFileProperty = DependencyProperty.Register("StartupFile", typeof(string), typeof(ImportSettings), new PropertyMetadata()); public static readonly DependencyProperty UseCustomizationProperty = DependencyProperty.Register("UseCustomization", typeof(bool), typeof(ImportSettings), new PropertyMetadata(false)); public static readonly DependencyProperty CustomizationProperty = DependencyProperty.Register("Customization", typeof(ProjectCustomization), typeof(ImportSettings), new PropertyMetadata()); public static readonly DependencyProperty DetectVirtualEnvProperty = DependencyProperty.Register("DetectVirtualEnv", typeof(bool), typeof(ImportSettings), new PropertyMetadata(true)); public bool IsValid { get { return (bool)GetValue(IsValidProperty); } private set { SetValue(IsValidPropertyKey, value); } } private static void RecalculateIsValid(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (!d.Dispatcher.CheckAccess()) { var t = d.Dispatcher.BeginInvoke((Action)(() => RecalculateIsValid(d, e))); return; } var s = d as ImportSettings; if (s == null) { d.SetValue(IsValidPropertyKey, false); return; } s.UpdateIsValid(); } internal void UpdateIsValid() { SetValue(IsValidPropertyKey, PathUtils.IsValidPath(SourcePath) && PathUtils.IsValidPath(ProjectPath) && Directory.Exists(SourcePath) && SelectedInterpreter != null && AvailableInterpreters.Contains(SelectedInterpreter) ); } internal void SetInitialSourcePath(string path) { SourcePath = path; } internal void SetInitialProjectPath(string path) { ProjectPath = path; _isAutoGeneratedProjectPath = true; } internal async Task UpdateSourcePathAsync() { UpdateIsValid(); if (PathUtils.IsValidPath(SourcePath) && (string.IsNullOrEmpty(ProjectPath) || _isAutoGeneratedProjectPath)) { ProjectPath = PathUtils.GetAvailableFilename(SourcePath, Path.GetFileName(SourcePath), ".pyproj"); _isAutoGeneratedProjectPath = true; } var fileList = await GetCandidateStartupFiles(SourcePath, Filters).ConfigureAwait(true); var tlpf = TopLevelPythonFiles as BulkObservableCollection<string>; if (tlpf != null) { tlpf.Clear(); tlpf.AddRange(fileList); } else { TopLevelPythonFiles.Clear(); foreach (var file in fileList) { TopLevelPythonFiles.Add(file); } } StartupFile = SelectDefaultStartupFile(fileList, StartupFile); } internal static string SelectDefaultStartupFile(IList<string> fileList, string currentSelection) { return string.IsNullOrEmpty(currentSelection) || !fileList.Contains(currentSelection) ? fileList.FirstOrDefault() : currentSelection; } internal static async Task<IList<string>> GetCandidateStartupFiles( string sourcePath, string filters ) { if (Directory.Exists(sourcePath)) { return await Task.Run(() => { var files = PathUtils.EnumerateFiles(sourcePath, "*.py", recurse: false); // Also include *.pyw files if they were in the filter list foreach (var pywFilters in filters .Split(';') .Where(filter => filter.TrimEnd().EndsWith(".pyw", StringComparison.OrdinalIgnoreCase)) ) { files = files.Concat(PathUtils.EnumerateFiles(sourcePath, pywFilters, recurse: false)); } return files.Select(f => Path.GetFileName(f)).ToList(); }); } else { return new string[0]; } } private static void ProjectPath_Updated(DependencyObject d, DependencyPropertyChangedEventArgs e) { var self = d as ImportSettings; if (self != null) { self._isAutoGeneratedProjectPath = false; } RecalculateIsValid(d, e); } private static readonly DependencyPropertyKey IsValidPropertyKey = DependencyProperty.RegisterReadOnly("IsValid", typeof(bool), typeof(ImportSettings), new PropertyMetadata(false)); public static readonly DependencyProperty IsValidProperty = IsValidPropertyKey.DependencyProperty; private static XmlWriter GetDefaultWriter(string projectPath) { var settings = new XmlWriterSettings { CloseOutput = true, Encoding = Encoding.UTF8, Indent = true, IndentChars = " ", NewLineChars = Environment.NewLine, NewLineOnAttributes = false }; var dir = Path.GetDirectoryName(projectPath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } return XmlWriter.Create(projectPath, settings); } public bool ProjectFileExists { get { return File.Exists(ProjectPath); } } public async Task<string> CreateRequestedProjectAsync() { await UpdateSourcePathAsync().HandleAllExceptions(_site); string projectPath = ProjectPath; string sourcePath = SourcePath; string filters = Filters; string searchPaths = string.Join(";", (SearchPaths ?? "").Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Select(p => PathUtils.GetRelativeDirectoryPath(SourcePath, p))); string startupFile = StartupFile; PythonInterpreterView selectedInterpreter = SelectedInterpreter; ProjectCustomization projectCustomization = UseCustomization ? Customization : null; bool detectVirtualEnv = DetectVirtualEnv; return await Task.Run(() => { bool success = false; try { Directory.CreateDirectory(Path.GetDirectoryName(projectPath)); using (var writer = new StreamWriter(projectPath, false, Encoding.UTF8)) { WriteProjectXml( _service, writer, projectPath, sourcePath, filters, searchPaths, startupFile, selectedInterpreter, projectCustomization, detectVirtualEnv ); } success = true; return projectPath; } finally { if (!success) { try { File.Delete(projectPath); } catch { // Try and avoid leaving stray files, but it does // not matter much if we do. } } } }); } internal static void WriteProjectXml( IInterpreterRegistryService service, TextWriter writer, string projectPath, string sourcePath, string filters, string searchPaths, string startupFile, PythonInterpreterView selectedInterpreter, ProjectCustomization customization, bool detectVirtualEnv ) { var projectHome = PathUtils.GetRelativeDirectoryPath(Path.GetDirectoryName(projectPath), sourcePath); var project = ProjectRootElement.Create(); project.DefaultTargets = "Build"; project.ToolsVersion = "4.0"; var globals = project.AddPropertyGroup(); globals.AddProperty("Configuration", "Debug").Condition = " '$(Configuration)' == '' "; globals.AddProperty("SchemaVersion", "2.0"); globals.AddProperty("ProjectGuid", Guid.NewGuid().ToString("B")); globals.AddProperty("ProjectHome", projectHome); if (PathUtils.IsValidPath(startupFile)) { globals.AddProperty("StartupFile", startupFile); } else { globals.AddProperty("StartupFile", ""); } globals.AddProperty("SearchPath", searchPaths); globals.AddProperty("WorkingDirectory", "."); globals.AddProperty("OutputPath", "."); globals.AddProperty("ProjectTypeGuids", "{888888a0-9f3d-457c-b088-3a5042f75d52}"); globals.AddProperty("LaunchProvider", DefaultLauncherProvider.DefaultLauncherName); var interpreterId = globals.AddProperty(PythonConstants.InterpreterId, ""); if (selectedInterpreter != null && !String.IsNullOrWhiteSpace(selectedInterpreter.Id)) { interpreterId.Value = selectedInterpreter.Id; } // VS requires property groups with conditions for Debug // and Release configurations or many COMExceptions are // thrown. var debugGroup = project.AddPropertyGroup(); var releaseGroup = project.AddPropertyGroup(); debugGroup.Condition = "'$(Configuration)' == 'Debug'"; releaseGroup.Condition = "'$(Configuration)' == 'Release'"; var folders = new HashSet<string>(); var virtualEnvPaths = detectVirtualEnv ? new List<string>() : null; foreach (var unescapedFile in EnumerateAllFiles(sourcePath, filters, virtualEnvPaths)) { var file = ProjectCollection.Escape(unescapedFile); var ext = Path.GetExtension(file); var fileType = "Content"; if (PythonConstants.FileExtension.Equals(ext, StringComparison.OrdinalIgnoreCase) || PythonConstants.WindowsFileExtension.Equals(ext, StringComparison.OrdinalIgnoreCase)) { fileType = "Compile"; } folders.Add(Path.GetDirectoryName(file)); project.AddItem(fileType, file); } foreach (var folder in folders.Where(s => !string.IsNullOrWhiteSpace(s)).OrderBy(s => s)) { project.AddItem("Folder", folder); } if (selectedInterpreter != null && !String.IsNullOrWhiteSpace(selectedInterpreter.Id)) { project.AddItem( MSBuildConstants.InterpreterReferenceItem, selectedInterpreter.Id ); } if (virtualEnvPaths != null && virtualEnvPaths.Any() && service != null) { foreach (var path in virtualEnvPaths) { var id = MSBuildProjectInterpreterFactoryProvider.GetInterpreterId("$(MSBuildProjectFullPath)", Path.GetFileName(sourcePath)); var config = VirtualEnv.FindInterpreterConfiguration(id, path, service); if (config != null) { AddVirtualEnvironment(project, sourcePath, config); if (string.IsNullOrEmpty(interpreterId.Value)) { interpreterId.Value = id; } } } } var imports = project.AddPropertyGroup(); imports.AddProperty("VisualStudioVersion", "10.0").Condition = " '$(VisualStudioVersion)' == '' "; (customization ?? DefaultProjectCustomization.Instance).Process( project, new Dictionary<string, ProjectPropertyGroupElement> { { "Globals", globals }, { "Imports", imports }, { "Debug", debugGroup }, { "Release", releaseGroup } } ); project.Save(writer); } private static ProjectItemElement AddVirtualEnvironment( ProjectRootElement project, string sourcePath, InterpreterConfiguration config ) { var prefixPath = config.PrefixPath ?? string.Empty; var interpreterPath = string.IsNullOrEmpty(config.InterpreterPath) ? string.Empty : PathUtils.GetRelativeFilePath(prefixPath, config.InterpreterPath); var windowInterpreterPath = string.IsNullOrEmpty(config.WindowsInterpreterPath) ? string.Empty : PathUtils.GetRelativeFilePath(prefixPath, config.WindowsInterpreterPath); var libraryPath = string.IsNullOrEmpty(config.LibraryPath) ? string.Empty : PathUtils.GetRelativeDirectoryPath(prefixPath, config.LibraryPath); prefixPath = PathUtils.GetRelativeDirectoryPath(sourcePath, prefixPath); return project.AddItem( MSBuildConstants.InterpreterItem, prefixPath, new Dictionary<string, string> { { MSBuildConstants.IdKey, Path.GetFileName(sourcePath) }, { MSBuildConstants.DescriptionKey, config.Description }, { MSBuildConstants.BaseInterpreterKey, config.Id }, { MSBuildConstants.InterpreterPathKey, interpreterPath }, { MSBuildConstants.WindowsPathKey, windowInterpreterPath }, { MSBuildConstants.LibraryPathKey, libraryPath }, { MSBuildConstants.VersionKey, config.Version.ToString() }, { MSBuildConstants.ArchitectureKey, config.Architecture.ToString() }, { MSBuildConstants.PathEnvVarKey, config.PathEnvironmentVariable } } ); } private static IEnumerable<string> UnwindDirectory(string source) { var dir = PathUtils.TrimEndSeparator(source); yield return dir; int lastBackslash = dir.LastIndexOf('\\'); while (lastBackslash > 0) { dir = dir.Remove(lastBackslash); yield return dir; lastBackslash = dir.LastIndexOf('\\'); } } private static IEnumerable<string> EnumerateAllFiles( string source, string filters, List<string> virtualEnvPaths ) { var files = new HashSet<string>(StringComparer.OrdinalIgnoreCase); var patterns = filters.Split(';').Concat(new[] { "*.py" }).Select(p => p.Trim()).ToArray(); var directories = new List<string>() { source }; var skipDirectories = new HashSet<string>(StringComparer.OrdinalIgnoreCase); directories.AddRange(PathUtils.EnumerateDirectories(source)); foreach (var dir in directories) { if (UnwindDirectory(dir).Any(skipDirectories.Contains)) { continue; } try { if (virtualEnvPaths != null) { var origPrefix = DerivedInterpreterFactory.GetOrigPrefixPath(dir); if (!string.IsNullOrEmpty(origPrefix)) { virtualEnvPaths.Add(dir); skipDirectories.Add(PathUtils.TrimEndSeparator(dir)); continue; } } foreach (var filter in patterns) { files.UnionWith(PathUtils.EnumerateFiles(dir, filter, recurse: false)); } } catch (UnauthorizedAccessException) { } } return files .Where(path => path.StartsWith(source)) .Select(path => path.Substring(source.Length).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)) .Distinct(StringComparer.OrdinalIgnoreCase); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Net; using System.Text; using Microsoft.Rest.Generator.ClientModel; using Microsoft.Rest.Generator.Logging; using Microsoft.Rest.Generator.Utilities; using Microsoft.Rest.Modeler.Swagger.Model; using Microsoft.Rest.Modeler.Swagger.Properties; using ParameterLocation = Microsoft.Rest.Modeler.Swagger.Model.ParameterLocation; namespace Microsoft.Rest.Modeler.Swagger { /// <summary> /// The builder for building swagger operations into client model methods. /// </summary> public class OperationBuilder { private IList<string> _effectiveProduces; private SwaggerModeler _swaggerModeler; private Operation _operation; private const string APP_JSON_MIME = "application/json"; public OperationBuilder(Operation operation, SwaggerModeler swaggerModeler) { if (operation == null) { throw new ArgumentNullException("operation"); } if (swaggerModeler == null) { throw new ArgumentNullException("swaggerModeler"); } this._operation = operation; this._swaggerModeler = swaggerModeler; this._effectiveProduces = operation.Produces ?? swaggerModeler.ServiceDefinition.Produces; } public Method BuildMethod(HttpMethod httpMethod, string url, string methodName, string methodGroup) { EnsureUniqueMethodName(methodName, methodGroup); var method = new Method { HttpMethod = httpMethod, Url = url, Name = methodName }; method.ContentType = APP_JSON_MIME; string produce = _effectiveProduces.FirstOrDefault(s => s.StartsWith(APP_JSON_MIME, StringComparison.OrdinalIgnoreCase)); if (!string.IsNullOrEmpty(produce)) { method.ContentType = produce; } if (method.ContentType.IndexOf("charset=", StringComparison.OrdinalIgnoreCase) == -1) { // Enable UTF-8 charset method.ContentType += "; charset=utf-8"; } method.Description = _operation.Description; method.Summary = _operation.Summary; // Service parameters if (_operation.Parameters != null) { foreach (var swaggerParameter in DeduplicateParameters(_operation.Parameters)) { var parameter = ((ParameterBuilder) swaggerParameter.GetBuilder(_swaggerModeler)).Build(); method.Parameters.Add(parameter); StringBuilder parameterName = new StringBuilder(parameter.Name); parameterName = CollectionFormatBuilder.OnBuildMethodParameter(method, swaggerParameter, parameterName); if (swaggerParameter.In == ParameterLocation.Header) { method.RequestHeaders[swaggerParameter.Name] = string.Format(CultureInfo.InvariantCulture, "{{{0}}}", parameterName); } } } // Response format var typesList = new List<Stack<IType>>(); _operation.Responses.ForEach(response => { if (string.Equals(response.Key, "default", StringComparison.OrdinalIgnoreCase)) { TryBuildDefaultResponse(methodName, response.Value, method); } else { if ( !(TryBuildResponse(methodName, response.Key.ToHttpStatusCode(), response.Value, method, typesList) || TryBuildStreamResponse(response.Key.ToHttpStatusCode(), response.Value, method, typesList) || TryBuildEmptyResponse(methodName, response.Key.ToHttpStatusCode(), response.Value, method, typesList))) { throw new InvalidOperationException( string.Format(CultureInfo.InvariantCulture, Resources.UnsupportedMimeTypeForResponseBody, methodName, response.Key)); } } }); method.ReturnType = BuildMethodReturnType(typesList); if (method.Responses.Count == 0 && method.DefaultResponse != null) { method.ReturnType = method.DefaultResponse; } // Copy extensions _operation.Extensions.ForEach(extention => method.Extensions.Add(extention.Key, extention.Value)); return method; } private static IEnumerable<SwaggerParameter> DeduplicateParameters(IEnumerable<SwaggerParameter> parameters) { return parameters .Select(s => { // if parameter with the same name exists in Body and Path/Query then we need to give it a unique name if (s.In == ParameterLocation.Body) { string newName = s.Name; while (parameters.Any(t => t.In != ParameterLocation.Body && string.Equals(t.Name, newName, StringComparison.OrdinalIgnoreCase))) { newName += "Body"; } s.Name = newName; } // if parameter with same name exists in Query and Path, make Query one required if (s.In == ParameterLocation.Query && parameters.Any(t => t.In == ParameterLocation.Path && string.Equals(t.Name, s.Name, StringComparison.OrdinalIgnoreCase))) { s.IsRequired = true; } return s; }); } private static void BuildMethodReturnTypeStack(IType type, List<Stack<IType>> types) { var typeStack = new Stack<IType>(); typeStack.Push(type); types.Add(typeStack); } private IType BuildMethodReturnType(List<Stack<IType>> types) { IType baseType = PrimaryType.Object; // Return null if no response is specified if (types.Count == 0) { return null; } // Return first if only one return type if (types.Count == 1) { return types.First().Pop(); } // BuildParameter up type inheritance tree types.ForEach(typeStack => { IType type = typeStack.Peek(); while (!Equals(type, baseType)) { if (type is CompositeType && _swaggerModeler.ExtendedTypes.ContainsKey(type.Name)) { type = _swaggerModeler.GeneratedTypes[_swaggerModeler.ExtendedTypes[type.Name]]; } else { type = baseType; } typeStack.Push(type); } }); // Eliminate commonly shared base classes while (!types.First().IsNullOrEmpty()) { IType currentType = types.First().Peek(); foreach (var typeStack in types) { IType t = typeStack.Pop(); if (!Equals(t, currentType)) { return baseType; } } baseType = currentType; } return baseType; } private bool TryBuildStreamResponse(HttpStatusCode responseStatusCode, Response response, Method method, List<Stack<IType>> types) { bool handled = false; if (SwaggerOperationProducesNotEmpty()) { if (response.Schema != null) { IType serviceType = response.Schema.GetBuilder(_swaggerModeler) .BuildServiceType(response.Schema.Reference.StripDefinitionPath()); Debug.Assert(serviceType != null); BuildMethodReturnTypeStack(serviceType, types); var compositeType = serviceType as CompositeType; if (compositeType != null) { VerifyFirstPropertyIsByteArray(compositeType); } method.Responses[responseStatusCode] = serviceType; handled = true; } } return handled; } private void VerifyFirstPropertyIsByteArray(CompositeType serviceType) { var referenceKey = serviceType.Name; var responseType = _swaggerModeler.GeneratedTypes[referenceKey]; var property = responseType.Properties.FirstOrDefault(p => p.Type == PrimaryType.ByteArray); if (property == null) { throw new KeyNotFoundException( "Please specify a field with type of System.Byte[] to deserialize the file contents to"); } } private bool TryBuildResponse(string methodName, HttpStatusCode responseStatusCode, Response response, Method method, List<Stack<IType>> types) { bool handled = false; IType serviceType; if (SwaggerOperationProducesJson()) { if (TryBuildResponseBody(methodName, response, s => GenerateResponseObjectName(s, responseStatusCode), out serviceType)) { method.Responses[responseStatusCode] = serviceType; BuildMethodReturnTypeStack(serviceType, types); handled = true; } } return handled; } private bool TryBuildEmptyResponse(string methodName, HttpStatusCode responseStatusCode, Response response, Method method, List<Stack<IType>> types) { bool handled = false; if (response.Schema == null) { method.Responses[responseStatusCode] = null; handled = true; } else { if (_operation.Produces.IsNullOrEmpty()) { method.Responses[responseStatusCode] = PrimaryType.Object; BuildMethodReturnTypeStack(PrimaryType.Object, types); handled = true; } var unwrapedSchemaProperties = _swaggerModeler.Resolver.Unwrap(response.Schema).Properties; if (unwrapedSchemaProperties != null && unwrapedSchemaProperties.Any()) { Logger.LogWarning(Resources.NoProduceOperationWithBody, methodName); } } return handled; } private void TryBuildDefaultResponse(string methodName, Response response, Method method) { IType errorModel = null; if (SwaggerOperationProducesJson()) { if (TryBuildResponseBody(methodName, response, s => GenerateErrorModelName(s), out errorModel)) { method.DefaultResponse = errorModel; } } } private bool TryBuildResponseBody(string methodName, Response response, Func<string, string> typeNamer, out IType responseType) { bool handled = false; responseType = null; if (SwaggerOperationProducesJson()) { if (response.Schema != null) { string referenceKey; if (response.Schema.Reference != null) { referenceKey = response.Schema.Reference.StripDefinitionPath(); response.Schema.Reference = referenceKey; } else { referenceKey = typeNamer(methodName); } responseType = response.Schema.GetBuilder(_swaggerModeler).BuildServiceType(referenceKey); handled = true; } } return handled; } private bool SwaggerOperationProducesJson() { return _effectiveProduces != null && _effectiveProduces.Any(s => s.StartsWith(APP_JSON_MIME, StringComparison.OrdinalIgnoreCase)); } private bool SwaggerOperationProducesNotEmpty() { return _effectiveProduces != null && _effectiveProduces.Any(); } private void EnsureUniqueMethodName(string methodName, string methodGroup) { string serviceOperationPrefix = ""; if (methodGroup != null) { serviceOperationPrefix = methodGroup + "_"; } if (_swaggerModeler.ServiceClient.Methods.Any(m => m.Group == methodGroup && m.Name == methodName)) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, Resources.DuplicateOperationIdException, serviceOperationPrefix + methodName)); } } private static string GenerateResponseObjectName(string methodName, HttpStatusCode responseStatusCode) { return string.Format(CultureInfo.InvariantCulture, "{0}{1}Response", methodName, responseStatusCode); } private static string GenerateErrorModelName(string methodName) { return string.Format(CultureInfo.InvariantCulture, "{0}ErrorModel", methodName); } } }
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 Uno.Web.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; } } }
/* * 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> /// TransactionEmail /// </summary> [DataContract] public partial class TransactionEmail : IEquatable<TransactionEmail>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="TransactionEmail" /> class. /// </summary> /// <param name="content">Actual template contents.</param> /// <param name="espDomainUuid">The uuid of the sending domain.</param> /// <param name="espFriendlyName">Friendly from that will appear in customer email clients..</param> /// <param name="espUser">The username of the sending email. This is not the full email. Only the username which is everything before the @ sign..</param> /// <param name="fileExists">An internal identifier used to aid in retrieving templates from the filesystem..</param> /// <param name="fileName">File name.</param> /// <param name="group">Group.</param> /// <param name="handlebarVariables">Handlebar Variables available for email template.</param> /// <param name="invalid">Invalid will be true if the template cannot compile.</param> /// <param name="lastModified">Last modified timestamp.</param> /// <param name="libraryItemOid">If this item was ever added to the Code Library, this is the oid for that library item, or 0 if never added before. This value is used to determine if a library item should be inserted or updated..</param> /// <param name="options">Options that help govern how and when this template is used.</param> /// <param name="path">directory path where template is stored in file system.</param> /// <param name="size">Size of file in friendly description.</param> /// <param name="storeFrontFsDirectoryOid">Internal identifier used to store and retrieve template from filesystem.</param> /// <param name="storeFrontFsFileOid">Internal identifier used to store and retrieve template from filesystem.</param> /// <param name="subject">Subject.</param> /// <param name="syntaxErrors">Any syntax errors contained within the tempalate.</param> /// <param name="templatePathRelativePath">Internal value used to locate the template in the filesystem.</param> /// <param name="themeRelativePath">Theme relative path in the filesystem..</param> public TransactionEmail(string content = default(string), string espDomainUuid = default(string), string espFriendlyName = default(string), string espUser = default(string), bool? fileExists = default(bool?), string fileName = default(string), string group = default(string), List<string> handlebarVariables = default(List<string>), bool? invalid = default(bool?), string lastModified = default(string), int? libraryItemOid = default(int?), List<TransactionEmailOption> options = default(List<TransactionEmailOption>), string path = default(string), string size = default(string), int? storeFrontFsDirectoryOid = default(int?), int? storeFrontFsFileOid = default(int?), string subject = default(string), string syntaxErrors = default(string), string templatePathRelativePath = default(string), string themeRelativePath = default(string)) { this.Content = content; this.EspDomainUuid = espDomainUuid; this.EspFriendlyName = espFriendlyName; this.EspUser = espUser; this.FileExists = fileExists; this.FileName = fileName; this.Group = group; this.HandlebarVariables = handlebarVariables; this.Invalid = invalid; this.LastModified = lastModified; this.LibraryItemOid = libraryItemOid; this.Options = options; this.Path = path; this.Size = size; this.StoreFrontFsDirectoryOid = storeFrontFsDirectoryOid; this.StoreFrontFsFileOid = storeFrontFsFileOid; this.Subject = subject; this.SyntaxErrors = syntaxErrors; this.TemplatePathRelativePath = templatePathRelativePath; this.ThemeRelativePath = themeRelativePath; } /// <summary> /// Actual template contents /// </summary> /// <value>Actual template contents</value> [DataMember(Name="content", EmitDefaultValue=false)] public string Content { get; set; } /// <summary> /// The uuid of the sending domain /// </summary> /// <value>The uuid of the sending domain</value> [DataMember(Name="esp_domain_uuid", EmitDefaultValue=false)] public string EspDomainUuid { get; set; } /// <summary> /// Friendly from that will appear in customer email clients. /// </summary> /// <value>Friendly from that will appear in customer email clients.</value> [DataMember(Name="esp_friendly_name", EmitDefaultValue=false)] public string EspFriendlyName { get; set; } /// <summary> /// The username of the sending email. This is not the full email. Only the username which is everything before the @ sign. /// </summary> /// <value>The username of the sending email. This is not the full email. Only the username which is everything before the @ sign.</value> [DataMember(Name="esp_user", EmitDefaultValue=false)] public string EspUser { get; set; } /// <summary> /// An internal identifier used to aid in retrieving templates from the filesystem. /// </summary> /// <value>An internal identifier used to aid in retrieving templates from the filesystem.</value> [DataMember(Name="file_exists", EmitDefaultValue=false)] public bool? FileExists { get; set; } /// <summary> /// File name /// </summary> /// <value>File name</value> [DataMember(Name="file_name", EmitDefaultValue=false)] public string FileName { get; set; } /// <summary> /// Group /// </summary> /// <value>Group</value> [DataMember(Name="group", EmitDefaultValue=false)] public string Group { get; set; } /// <summary> /// Handlebar Variables available for email template /// </summary> /// <value>Handlebar Variables available for email template</value> [DataMember(Name="handlebar_variables", EmitDefaultValue=false)] public List<string> HandlebarVariables { get; set; } /// <summary> /// Invalid will be true if the template cannot compile /// </summary> /// <value>Invalid will be true if the template cannot compile</value> [DataMember(Name="invalid", EmitDefaultValue=false)] public bool? Invalid { get; set; } /// <summary> /// Last modified timestamp /// </summary> /// <value>Last modified timestamp</value> [DataMember(Name="last_modified", EmitDefaultValue=false)] public string LastModified { get; set; } /// <summary> /// If this item was ever added to the Code Library, this is the oid for that library item, or 0 if never added before. This value is used to determine if a library item should be inserted or updated. /// </summary> /// <value>If this item was ever added to the Code Library, this is the oid for that library item, or 0 if never added before. This value is used to determine if a library item should be inserted or updated.</value> [DataMember(Name="library_item_oid", EmitDefaultValue=false)] public int? LibraryItemOid { get; set; } /// <summary> /// Options that help govern how and when this template is used /// </summary> /// <value>Options that help govern how and when this template is used</value> [DataMember(Name="options", EmitDefaultValue=false)] public List<TransactionEmailOption> Options { get; set; } /// <summary> /// directory path where template is stored in file system /// </summary> /// <value>directory path where template is stored in file system</value> [DataMember(Name="path", EmitDefaultValue=false)] public string Path { get; set; } /// <summary> /// Size of file in friendly description /// </summary> /// <value>Size of file in friendly description</value> [DataMember(Name="size", EmitDefaultValue=false)] public string Size { get; set; } /// <summary> /// Internal identifier used to store and retrieve template from filesystem /// </summary> /// <value>Internal identifier used to store and retrieve template from filesystem</value> [DataMember(Name="store_front_fs_directory_oid", EmitDefaultValue=false)] public int? StoreFrontFsDirectoryOid { get; set; } /// <summary> /// Internal identifier used to store and retrieve template from filesystem /// </summary> /// <value>Internal identifier used to store and retrieve template from filesystem</value> [DataMember(Name="store_front_fs_file_oid", EmitDefaultValue=false)] public int? StoreFrontFsFileOid { get; set; } /// <summary> /// Subject /// </summary> /// <value>Subject</value> [DataMember(Name="subject", EmitDefaultValue=false)] public string Subject { get; set; } /// <summary> /// Any syntax errors contained within the tempalate /// </summary> /// <value>Any syntax errors contained within the tempalate</value> [DataMember(Name="syntax_errors", EmitDefaultValue=false)] public string SyntaxErrors { get; set; } /// <summary> /// Internal value used to locate the template in the filesystem /// </summary> /// <value>Internal value used to locate the template in the filesystem</value> [DataMember(Name="template_path_relative_path", EmitDefaultValue=false)] public string TemplatePathRelativePath { get; set; } /// <summary> /// Theme relative path in the filesystem. /// </summary> /// <value>Theme relative path in the filesystem.</value> [DataMember(Name="theme_relative_path", EmitDefaultValue=false)] public string ThemeRelativePath { 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 TransactionEmail {\n"); sb.Append(" Content: ").Append(Content).Append("\n"); sb.Append(" EspDomainUuid: ").Append(EspDomainUuid).Append("\n"); sb.Append(" EspFriendlyName: ").Append(EspFriendlyName).Append("\n"); sb.Append(" EspUser: ").Append(EspUser).Append("\n"); sb.Append(" FileExists: ").Append(FileExists).Append("\n"); sb.Append(" FileName: ").Append(FileName).Append("\n"); sb.Append(" Group: ").Append(Group).Append("\n"); sb.Append(" HandlebarVariables: ").Append(HandlebarVariables).Append("\n"); sb.Append(" Invalid: ").Append(Invalid).Append("\n"); sb.Append(" LastModified: ").Append(LastModified).Append("\n"); sb.Append(" LibraryItemOid: ").Append(LibraryItemOid).Append("\n"); sb.Append(" Options: ").Append(Options).Append("\n"); sb.Append(" Path: ").Append(Path).Append("\n"); sb.Append(" Size: ").Append(Size).Append("\n"); sb.Append(" StoreFrontFsDirectoryOid: ").Append(StoreFrontFsDirectoryOid).Append("\n"); sb.Append(" StoreFrontFsFileOid: ").Append(StoreFrontFsFileOid).Append("\n"); sb.Append(" Subject: ").Append(Subject).Append("\n"); sb.Append(" SyntaxErrors: ").Append(SyntaxErrors).Append("\n"); sb.Append(" TemplatePathRelativePath: ").Append(TemplatePathRelativePath).Append("\n"); sb.Append(" ThemeRelativePath: ").Append(ThemeRelativePath).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 TransactionEmail); } /// <summary> /// Returns true if TransactionEmail instances are equal /// </summary> /// <param name="input">Instance of TransactionEmail to be compared</param> /// <returns>Boolean</returns> public bool Equals(TransactionEmail input) { if (input == null) return false; return ( this.Content == input.Content || (this.Content != null && this.Content.Equals(input.Content)) ) && ( this.EspDomainUuid == input.EspDomainUuid || (this.EspDomainUuid != null && this.EspDomainUuid.Equals(input.EspDomainUuid)) ) && ( this.EspFriendlyName == input.EspFriendlyName || (this.EspFriendlyName != null && this.EspFriendlyName.Equals(input.EspFriendlyName)) ) && ( this.EspUser == input.EspUser || (this.EspUser != null && this.EspUser.Equals(input.EspUser)) ) && ( this.FileExists == input.FileExists || (this.FileExists != null && this.FileExists.Equals(input.FileExists)) ) && ( this.FileName == input.FileName || (this.FileName != null && this.FileName.Equals(input.FileName)) ) && ( this.Group == input.Group || (this.Group != null && this.Group.Equals(input.Group)) ) && ( this.HandlebarVariables == input.HandlebarVariables || this.HandlebarVariables != null && this.HandlebarVariables.SequenceEqual(input.HandlebarVariables) ) && ( this.Invalid == input.Invalid || (this.Invalid != null && this.Invalid.Equals(input.Invalid)) ) && ( this.LastModified == input.LastModified || (this.LastModified != null && this.LastModified.Equals(input.LastModified)) ) && ( this.LibraryItemOid == input.LibraryItemOid || (this.LibraryItemOid != null && this.LibraryItemOid.Equals(input.LibraryItemOid)) ) && ( this.Options == input.Options || this.Options != null && this.Options.SequenceEqual(input.Options) ) && ( this.Path == input.Path || (this.Path != null && this.Path.Equals(input.Path)) ) && ( this.Size == input.Size || (this.Size != null && this.Size.Equals(input.Size)) ) && ( this.StoreFrontFsDirectoryOid == input.StoreFrontFsDirectoryOid || (this.StoreFrontFsDirectoryOid != null && this.StoreFrontFsDirectoryOid.Equals(input.StoreFrontFsDirectoryOid)) ) && ( this.StoreFrontFsFileOid == input.StoreFrontFsFileOid || (this.StoreFrontFsFileOid != null && this.StoreFrontFsFileOid.Equals(input.StoreFrontFsFileOid)) ) && ( this.Subject == input.Subject || (this.Subject != null && this.Subject.Equals(input.Subject)) ) && ( this.SyntaxErrors == input.SyntaxErrors || (this.SyntaxErrors != null && this.SyntaxErrors.Equals(input.SyntaxErrors)) ) && ( this.TemplatePathRelativePath == input.TemplatePathRelativePath || (this.TemplatePathRelativePath != null && this.TemplatePathRelativePath.Equals(input.TemplatePathRelativePath)) ) && ( this.ThemeRelativePath == input.ThemeRelativePath || (this.ThemeRelativePath != null && this.ThemeRelativePath.Equals(input.ThemeRelativePath)) ); } /// <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.Content != null) hashCode = hashCode * 59 + this.Content.GetHashCode(); if (this.EspDomainUuid != null) hashCode = hashCode * 59 + this.EspDomainUuid.GetHashCode(); if (this.EspFriendlyName != null) hashCode = hashCode * 59 + this.EspFriendlyName.GetHashCode(); if (this.EspUser != null) hashCode = hashCode * 59 + this.EspUser.GetHashCode(); if (this.FileExists != null) hashCode = hashCode * 59 + this.FileExists.GetHashCode(); if (this.FileName != null) hashCode = hashCode * 59 + this.FileName.GetHashCode(); if (this.Group != null) hashCode = hashCode * 59 + this.Group.GetHashCode(); if (this.HandlebarVariables != null) hashCode = hashCode * 59 + this.HandlebarVariables.GetHashCode(); if (this.Invalid != null) hashCode = hashCode * 59 + this.Invalid.GetHashCode(); if (this.LastModified != null) hashCode = hashCode * 59 + this.LastModified.GetHashCode(); if (this.LibraryItemOid != null) hashCode = hashCode * 59 + this.LibraryItemOid.GetHashCode(); if (this.Options != null) hashCode = hashCode * 59 + this.Options.GetHashCode(); if (this.Path != null) hashCode = hashCode * 59 + this.Path.GetHashCode(); if (this.Size != null) hashCode = hashCode * 59 + this.Size.GetHashCode(); if (this.StoreFrontFsDirectoryOid != null) hashCode = hashCode * 59 + this.StoreFrontFsDirectoryOid.GetHashCode(); if (this.StoreFrontFsFileOid != null) hashCode = hashCode * 59 + this.StoreFrontFsFileOid.GetHashCode(); if (this.Subject != null) hashCode = hashCode * 59 + this.Subject.GetHashCode(); if (this.SyntaxErrors != null) hashCode = hashCode * 59 + this.SyntaxErrors.GetHashCode(); if (this.TemplatePathRelativePath != null) hashCode = hashCode * 59 + this.TemplatePathRelativePath.GetHashCode(); if (this.ThemeRelativePath != null) hashCode = hashCode * 59 + this.ThemeRelativePath.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) { yield break; } } }
using System; using System.Data; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; using System.Text; using Epi.Analysis; using Epi.Windows.Dialogs; using Epi.Windows.Analysis; using Epi.Data.Services; using VariableCollection = Epi.Collections.NamedObjectCollection<Epi.IVariable>; namespace Epi.Windows.Analysis.Dialogs { /// <summary> /// Dialog for Frequency command /// </summary> public partial class FrequencyDialog : CommandDesignDialog { #region Private Fields private Project currentProject; private string SetClauses = null; private string strWeightVar = ""; #endregion #region Constructor /// <summary> /// Default constructor - NOT TO BE USED FOR INSTANTIATION /// </summary> [Obsolete("Use of default constructor not allowed", true)] public FrequencyDialog() { InitializeComponent(); } /// <summary> /// Constructor for the Frequency dialog /// </summary> /// <param name="frm"></param> public FrequencyDialog(Epi.Windows.Analysis.Forms.AnalysisMainForm frm) : base(frm) { InitializeComponent(); Construct(); } private void Construct() { if (!this.DesignMode) // designer throws an error { this.btnOK.Click += new System.EventHandler(this.btnOK_Click); this.btnSaveOnly.Click += new System.EventHandler(this.btnSaveOnly_Click); } //IProjectHost host = Module.GetService(typeof(IProjectHost)) as IProjectHost; //if (host == null) //{ // throw new GeneralException("No project is hosted by service provider."); //} //// get project reference //Project project = host.CurrentProject; //if (project == null) //{ // //A native DB has been read, no longer need to show error message // //throw new GeneralException("You must first open a project."); // //MessageBox.Show("You must first open a project."); // //this.Close(); //} //else //{ // currentProject = project; //} } #endregion Constructors #region Protected Methods /// <summary> /// Generates the command text /// </summary> protected override void GenerateCommand() { StringBuilder command = new StringBuilder(); command.Append(CommandNames.FREQ); command.Append(StringLiterals.SPACE); if (this.cbxAllExcept.Checked) { command.Append(StringLiterals.STAR); command.Append(StringLiterals.SPACE); command.Append(CommandNames.EXCEPT); command.Append(StringLiterals.SPACE); } if (this.lbxVariables.Items.Count > 0) { foreach (string item in lbxVariables.Items) { command.Append(FieldNameNeedsBrackets(item) ? Util.InsertInSquareBrackets(item) : item); command.Append(StringLiterals.SPACE); } } else { command.Append(StringLiterals.STAR); command.Append(StringLiterals.SPACE); } if (lbxStratifyBy.Items.Count > 0) { command.Append(CommandNames.STRATAVAR); command.Append(StringLiterals.EQUAL); foreach (string item in lbxStratifyBy.Items) { command.Append(FieldNameNeedsBrackets(item) ? Util.InsertInSquareBrackets(item) : item); command.Append(StringLiterals.SPACE); } } if (cmbWeight.Text != string.Empty) { command.Append(CommandNames.WEIGHTVAR); command.Append(StringLiterals.EQUAL); command.Append(FieldNameNeedsBrackets(cmbWeight.Text) ? Util.InsertInSquareBrackets(cmbWeight.Text) : cmbWeight.Text); command.Append(StringLiterals.SPACE); } if (txtOutput.Text != string.Empty) { command.Append(CommandNames.OUTTABLE); command.Append(StringLiterals.EQUAL); command.Append(txtOutput.Text.ToString()); command.Append(StringLiterals.SPACE); } /* if (!string.IsNullOrEmpty(this.SetClauses)) { command.Append(this.SetClauses); command.Append(StringLiterals.SPACE); }*/ CommandText = command.ToString(); } /// <summary> /// Output Table /// </summary> protected void OutputTable() { } /// <summary> /// Validates user input /// </summary> /// <returns>True/False depending upon whether error messages were found</returns> protected override bool ValidateInput() { base.ValidateInput(); if (this.cbxAllExcept.Checked && this.lbxVariables.Items.Count == 0) { ErrorMessages.Add(SharedStrings.SELECT_EXCLUSION_VARIABLES); } if (this.lbxVariables.Items.Count == 0) { if (this.cmbVariables.Text.Equals("")) { ErrorMessages.Add(SharedStrings.SELECT_VARIABLE); } } //if (!string.IsNullOrEmpty(txtOutput.Text.Trim())) //{ // currentProject.CollectedData.TableExists(txtOutput.Text.Trim()); // ErrorMessages.Add(SharedStrings.TABLE_EXISTS_OUTPUT); //} return (ErrorMessages.Count == 0); } #endregion //Protected Methods #region Private methods //private void LoadVariables(ComboBox cmb, DataTable tbl, bool numericOnly) //{ // String cn = ColumnNames.NAME; // String dt = ColumnNames.DATA_TYPE; // string s; // foreach (DataRow row in tbl.Rows) // { // if (!numericOnly || (Int32.Parse(row[dt].ToString()) == (Int32)DataType.Number)) // { // s = row[cn].ToString(); // if (s != ColumnNames.REC_STATUS && s != ColumnNames.UNIQUE_KEY) // { // cmb.Items.Add(row[cn].ToString()); // } // } // } //} #endregion #region Public Methods /// <summary> /// Sets enabled property of OK and Save Only /// </summary> public override void CheckForInputSufficiency() { bool inputValid = ValidateInput(); btnOK.Enabled = inputValid; btnSaveOnly.Enabled = inputValid; } #endregion Public Methods #region Event Handlers private void btnClear_Click(object sender, System.EventArgs e) { cmbVariables.Items.Clear(); cmbStratifyBy.Items.Clear(); cmbWeight.Items.Clear(); cbxAllExcept.Checked = false; lbxVariables.Items.Clear(); lbxStratifyBy.Items.Clear(); cmbWeight.Text = string.Empty; txtOutput.Text = string.Empty; cmbStratifyBy.Text = string.Empty; FrequencyDialog_Load(this, null); CheckForInputSufficiency(); } /// <summary> /// Handles the SelectedIndexChanged event /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbVariables_SelectedIndexChanged(object sender, EventArgs e) { if (cmbVariables.Text != StringLiterals.STAR) { string s = cmbVariables.Text; lbxVariables.Items.Add(s); cmbStratifyBy.Items.Remove(s); cmbVariables.Items.Remove(s); cmbWeight.Items.Remove(s); this.cbxAllExcept.Enabled = true; } else { this.cbxAllExcept.Checked = false; this.cbxAllExcept.Enabled = false; } CheckForInputSufficiency(); } /// <summary> /// Handles the SelectedIndexChanged event /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void cmbStratifyBy_SelectedIndexChanged(object sender, EventArgs e) { if (cmbStratifyBy.Text != StringLiterals.SPACE) { string s = cmbStratifyBy.Text; lbxStratifyBy.Items.Add(s); cmbStratifyBy.Items.Remove(s); cmbVariables.Items.Remove(s); cmbWeight.Items.Remove(s); } } /// <summary> /// Handles the Attach Event for the form, fills all of the dialogs with a list of variables. /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void FrequencyDialog_Load(object sender, EventArgs e) { VariableType scopeWord = VariableType.DataSource | VariableType.DataSourceRedefined | VariableType.Standard | VariableType.Global; FillVariableCombo(cmbVariables, scopeWord); cmbVariables.Items.Add("*"); if (cmbVariables.Items[0].ToString().Equals("*")) { cmbVariables.SelectedIndex = 0; } FillVariableCombo(cmbStratifyBy, scopeWord); cmbStratifyBy.SelectedIndex = -1; FillWeightVariableCombo(cmbWeight, scopeWord); cmbWeight.SelectedIndex = -1; } /// <summary> /// Handles the Selected Index Change event for lbxVariables. /// Moves the variable name back to the comboboxes /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void lbxVariables_SelectedIndexChanged(object sender, EventArgs e) { if (lbxVariables.SelectedIndex >= 0) // prevent the remove below from re-entering { string s = lbxVariables.SelectedItem.ToString(); cmbVariables.Items.Add(s); cmbStratifyBy.Items.Add(s); cmbWeight.Items.Add(s); lbxVariables.Items.Remove(s); } CheckForInputSufficiency(); } /// <summary> /// Handles the Selected Index Change event for lbxStratifyBy. /// Moves the variable name back to the comboboxes /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> private void lbxStratifyBy_SelectedIndexChanged(object sender, EventArgs e) { if (lbxStratifyBy.SelectedIndex >= 0) // prevent the remove below from re-entering { string s = this.lbxStratifyBy.SelectedItem.ToString(); cmbVariables.Items.Add(s); cmbStratifyBy.Items.Add(s); cmbWeight.Items.Add(s); lbxStratifyBy.Items.Remove(s); } } private void btnSettings_Click(object sender, EventArgs e) { SetDialog SD = new SetDialog(mainForm); SD.isDialogMode = true; SD.ShowDialog(); SetClauses = SD.CommandText; SD.Close(); } private void cmbWeight_SelectedIndexChanged(object sender, EventArgs e) { //Get the old variable chosen that was saved to the txt string. string strOld = strWeightVar; string strNew = cmbWeight.Text; //make sure it isn't "" or the same as the new variable picked. if ((strOld.Length != 0) && (strOld != strNew)) { //add the former variable chosen back into the other lists cmbVariables.Items.Add(strOld); cmbStratifyBy.Items.Add(strOld); } //record the new variable and remove it from the other lists strWeightVar = strNew; cmbVariables.Items.Remove(strNew); cmbStratifyBy.Items.Remove(strNew); } private void cmbWeight_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Delete) { //SelectedIndexChanged will add the var back to the other DDLs cmbWeight.Text = ""; cmbWeight.SelectedIndex = -1; } } /// <summary> /// Opens a process to show the related help topic /// </summary> /// <param name="sender">Object that fired the event.</param> /// <param name="e">.NET supplied event args.</param> protected override void btnHelp_Click(object sender, System.EventArgs e) { System.Diagnostics.Process.Start("http://www.cdc.gov/epiinfo/user-guide/command-reference/analysis-commands-freq.html"); } #endregion //Event Handlers } }
// 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. // Zip Spec here: http://www.pkware.com/documents/casestudies/APPNOTE.TXT using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Text; namespace System.IO.Compression { public class ZipArchive : IDisposable { private Stream _archiveStream; private ZipArchiveEntry _archiveStreamOwner; private BinaryReader _archiveReader; private ZipArchiveMode _mode; private List<ZipArchiveEntry> _entries; private ReadOnlyCollection<ZipArchiveEntry> _entriesCollection; private Dictionary<string, ZipArchiveEntry> _entriesDictionary; private bool _readEntries; private bool _leaveOpen; private long _centralDirectoryStart; //only valid after ReadCentralDirectory private bool _isDisposed; private uint _numberOfThisDisk; //only valid after ReadCentralDirectory private long _expectedNumberOfEntries; private Stream _backingStream; private byte[] _archiveComment; private Encoding _entryNameEncoding; #if DEBUG_FORCE_ZIP64 public bool _forceZip64; #endif /// <summary> /// Initializes a new instance of ZipArchive on the given stream for reading. /// </summary> /// <exception cref="ArgumentException">The stream is already closed or does not support reading.</exception> /// <exception cref="ArgumentNullException">The stream is null.</exception> /// <exception cref="InvalidDataException">The contents of the stream could not be interpreted as a Zip archive.</exception> /// <param name="stream">The stream containing the archive to be read.</param> public ZipArchive(Stream stream) : this(stream, ZipArchiveMode.Read, leaveOpen: false, entryNameEncoding: null) { } /// <summary> /// Initializes a new instance of ZipArchive on the given stream in the specified mode. /// </summary> /// <exception cref="ArgumentException">The stream is already closed. -or- mode is incompatible with the capabilities of the stream.</exception> /// <exception cref="ArgumentNullException">The stream is null.</exception> /// <exception cref="ArgumentOutOfRangeException">mode specified an invalid value.</exception> /// <exception cref="InvalidDataException">The contents of the stream could not be interpreted as a Zip file. -or- mode is Update and an entry is missing from the archive or is corrupt and cannot be read. -or- mode is Update and an entry is too large to fit into memory.</exception> /// <param name="stream">The input or output stream.</param> /// <param name="mode">See the description of the ZipArchiveMode enum. Read requires the stream to support reading, Create requires the stream to support writing, and Update requires the stream to support reading, writing, and seeking.</param> public ZipArchive(Stream stream, ZipArchiveMode mode) : this(stream, mode, leaveOpen: false, entryNameEncoding: null) { } /// <summary> /// Initializes a new instance of ZipArchive on the given stream in the specified mode, specifying whether to leave the stream open. /// </summary> /// <exception cref="ArgumentException">The stream is already closed. -or- mode is incompatible with the capabilities of the stream.</exception> /// <exception cref="ArgumentNullException">The stream is null.</exception> /// <exception cref="ArgumentOutOfRangeException">mode specified an invalid value.</exception> /// <exception cref="InvalidDataException">The contents of the stream could not be interpreted as a Zip file. -or- mode is Update and an entry is missing from the archive or is corrupt and cannot be read. -or- mode is Update and an entry is too large to fit into memory.</exception> /// <param name="stream">The input or output stream.</param> /// <param name="mode">See the description of the ZipArchiveMode enum. Read requires the stream to support reading, Create requires the stream to support writing, and Update requires the stream to support reading, writing, and seeking.</param> /// <param name="leaveOpen">true to leave the stream open upon disposing the ZipArchive, otherwise false.</param> public ZipArchive(Stream stream, ZipArchiveMode mode, bool leaveOpen) : this(stream, mode, leaveOpen, entryNameEncoding: null) { } /// <summary> /// Initializes a new instance of ZipArchive on the given stream in the specified mode, specifying whether to leave the stream open. /// </summary> /// <exception cref="ArgumentException">The stream is already closed. -or- mode is incompatible with the capabilities of the stream.</exception> /// <exception cref="ArgumentNullException">The stream is null.</exception> /// <exception cref="ArgumentOutOfRangeException">mode specified an invalid value.</exception> /// <exception cref="InvalidDataException">The contents of the stream could not be interpreted as a Zip file. -or- mode is Update and an entry is missing from the archive or is corrupt and cannot be read. -or- mode is Update and an entry is too large to fit into memory.</exception> /// <param name="stream">The input or output stream.</param> /// <param name="mode">See the description of the ZipArchiveMode enum. Read requires the stream to support reading, Create requires the stream to support writing, and Update requires the stream to support reading, writing, and seeking.</param> /// <param name="leaveOpen">true to leave the stream open upon disposing the ZipArchive, otherwise false.</param> /// <param name="entryNameEncoding">The encoding to use when reading or writing entry names in this ZipArchive. /// /// <para>NOTE: Specifying this parameter to values other than <c>null</c> is discouraged. /// However, this may be necessary for interoperability with ZIP archive tools and libraries that do not correctly support /// UTF-8 encoding for entry names.<br /> /// This value is used as follows:</para> /// <para><strong>Reading (opening) ZIP archive files:</strong></para> /// <para>If <c>entryNameEncoding</c> is not specified (<c>== null</c>):</para> /// <list> /// <item>For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header is <em>not</em> set, /// use the current system default code page (<c>Encoding.Default</c>) in order to decode the entry name.</item> /// <item>For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header <em>is</em> set, /// use UTF-8 (<c>Encoding.UTF8</c>) in order to decode the entry name.</item> /// </list> /// <para>If <c>entryNameEncoding</c> is specified (<c>!= null</c>):</para> /// <list> /// <item>For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header is <em>not</em> set, /// use the specified <c>entryNameEncoding</c> in order to decode the entry name.</item> /// <item>For entries where the language encoding flag (EFS) in the general purpose bit flag of the local file header <em>is</em> set, /// use UTF-8 (<c>Encoding.UTF8</c>) in order to decode the entry name.</item> /// </list> /// <para><strong>Writing (saving) ZIP archive files:</strong></para> /// <para>If <c>entryNameEncoding</c> is not specified (<c>== null</c>):</para> /// <list> /// <item>For entry names that contain characters outside the ASCII range, /// the language encoding flag (EFS) will be set in the general purpose bit flag of the local file header, /// and UTF-8 (<c>Encoding.UTF8</c>) will be used in order to encode the entry name into bytes.</item> /// <item>For entry names that do not contain characters outside the ASCII range, /// the language encoding flag (EFS) will not be set in the general purpose bit flag of the local file header, /// and the current system default code page (<c>Encoding.Default</c>) will be used to encode the entry names into bytes.</item> /// </list> /// <para>If <c>entryNameEncoding</c> is specified (<c>!= null</c>):</para> /// <list> /// <item>The specified <c>entryNameEncoding</c> will always be used to encode the entry names into bytes. /// The language encoding flag (EFS) in the general purpose bit flag of the local file header will be set if and only /// if the specified <c>entryNameEncoding</c> is a UTF-8 encoding.</item> /// </list> /// <para>Note that Unicode encodings other than UTF-8 may not be currently used for the <c>entryNameEncoding</c>, /// otherwise an <see cref="ArgumentException"/> is thrown.</para> /// </param> /// <exception cref="ArgumentException">If a Unicode encoding other than UTF-8 is specified for the <code>entryNameEncoding</code>.</exception> public ZipArchive(Stream stream, ZipArchiveMode mode, bool leaveOpen, Encoding entryNameEncoding) { if (stream == null) throw new ArgumentNullException(nameof(stream)); EntryNameEncoding = entryNameEncoding; Init(stream, mode, leaveOpen); } /// <summary> /// The collection of entries that are currently in the ZipArchive. This may not accurately represent the actual entries that are present in the underlying file or stream. /// </summary> /// <exception cref="NotSupportedException">The ZipArchive does not support reading.</exception> /// <exception cref="ObjectDisposedException">The ZipArchive has already been closed.</exception> /// <exception cref="InvalidDataException">The Zip archive is corrupt and the entries cannot be retrieved.</exception> public ReadOnlyCollection<ZipArchiveEntry> Entries { get { if (_mode == ZipArchiveMode.Create) throw new NotSupportedException(SR.EntriesInCreateMode); ThrowIfDisposed(); EnsureCentralDirectoryRead(); return _entriesCollection; } } /// <summary> /// The ZipArchiveMode that the ZipArchive was initialized with. /// </summary> public ZipArchiveMode Mode { get { return _mode; } } /// <summary> /// Creates an empty entry in the Zip archive with the specified entry name. /// There are no restrictions on the names of entries. /// The last write time of the entry is set to the current time. /// If an entry with the specified name already exists in the archive, a second entry will be created that has an identical name. /// Since no <code>CompressionLevel</code> is specified, the default provided by the implementation of the underlying compression /// algorithm will be used; the <code>ZipArchive</code> will not impose its own default. /// (Currently, the underlying compression algorithm is provided by the <code>System.IO.Compression.DeflateStream</code> class.) /// </summary> /// <exception cref="ArgumentException">entryName is a zero-length string.</exception> /// <exception cref="ArgumentNullException">entryName is null.</exception> /// <exception cref="NotSupportedException">The ZipArchive does not support writing.</exception> /// <exception cref="ObjectDisposedException">The ZipArchive has already been closed.</exception> /// <param name="entryName">A path relative to the root of the archive, indicating the name of the entry to be created.</param> /// <returns>A wrapper for the newly created file entry in the archive.</returns> public ZipArchiveEntry CreateEntry(string entryName) { return DoCreateEntry(entryName, null); } /// <summary> /// Creates an empty entry in the Zip archive with the specified entry name. There are no restrictions on the names of entries. The last write time of the entry is set to the current time. If an entry with the specified name already exists in the archive, a second entry will be created that has an identical name. /// </summary> /// <exception cref="ArgumentException">entryName is a zero-length string.</exception> /// <exception cref="ArgumentNullException">entryName is null.</exception> /// <exception cref="NotSupportedException">The ZipArchive does not support writing.</exception> /// <exception cref="ObjectDisposedException">The ZipArchive has already been closed.</exception> /// <param name="entryName">A path relative to the root of the archive, indicating the name of the entry to be created.</param> /// <param name="compressionLevel">The level of the compression (speed/memory vs. compressed size trade-off).</param> /// <returns>A wrapper for the newly created file entry in the archive.</returns> public ZipArchiveEntry CreateEntry(string entryName, CompressionLevel compressionLevel) { return DoCreateEntry(entryName, compressionLevel); } /// <summary> /// Releases the unmanaged resources used by ZipArchive and optionally finishes writing the archive and releases the managed resources. /// </summary> /// <param name="disposing">true to finish writing the archive and release unmanaged and managed resources, false to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (disposing && !_isDisposed) { try { switch (_mode) { case ZipArchiveMode.Read: break; case ZipArchiveMode.Create: case ZipArchiveMode.Update: default: Debug.Assert(_mode == ZipArchiveMode.Update || _mode == ZipArchiveMode.Create); WriteFile(); break; } } finally { CloseStreams(); _isDisposed = true; } } } /// <summary> /// Finishes writing the archive and releases all resources used by the ZipArchive object, unless the object was constructed with leaveOpen as true. Any streams from opened entries in the ZipArchive still open will throw exceptions on subsequent writes, as the underlying streams will have been closed. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Retrieves a wrapper for the file entry in the archive with the specified name. Names are compared using ordinal comparison. If there are multiple entries in the archive with the specified name, the first one found will be returned. /// </summary> /// <exception cref="ArgumentException">entryName is a zero-length string.</exception> /// <exception cref="ArgumentNullException">entryName is null.</exception> /// <exception cref="NotSupportedException">The ZipArchive does not support reading.</exception> /// <exception cref="ObjectDisposedException">The ZipArchive has already been closed.</exception> /// <exception cref="InvalidDataException">The Zip archive is corrupt and the entries cannot be retrieved.</exception> /// <param name="entryName">A path relative to the root of the archive, identifying the desired entry.</param> /// <returns>A wrapper for the file entry in the archive. If no entry in the archive exists with the specified name, null will be returned.</returns> public ZipArchiveEntry GetEntry(string entryName) { if (entryName == null) throw new ArgumentNullException(nameof(entryName)); if (_mode == ZipArchiveMode.Create) throw new NotSupportedException(SR.EntriesInCreateMode); EnsureCentralDirectoryRead(); ZipArchiveEntry result; _entriesDictionary.TryGetValue(entryName, out result); return result; } internal BinaryReader ArchiveReader => _archiveReader; internal Stream ArchiveStream => _archiveStream; internal uint NumberOfThisDisk => _numberOfThisDisk; internal Encoding EntryNameEncoding { get { return _entryNameEncoding; } private set { // value == null is fine. This means the user does not want to overwrite default encoding picking logic. // The Zip file spec [http://www.pkware.com/documents/casestudies/APPNOTE.TXT] specifies a bit in the entry header // (specifically: the language encoding flag (EFS) in the general purpose bit flag of the local file header) that // basically says: UTF8 (1) or CP437 (0). But in reality, tools replace CP437 with "something else that is not UTF8". // For instance, the Windows Shell Zip tool takes "something else" to mean "the local system codepage". // We default to the same behaviour, but we let the user explicitly specify the encoding to use for cases where they // understand their use case well enough. // Since the definition of acceptable encodings for the "something else" case is in reality by convention, it is not // immediately clear, whether non-UTF8 Unicode encodings are acceptable. To determine that we would need to survey // what is currently being done in the field, but we do not have the time for it right now. // So, we artificially disallow non-UTF8 Unicode encodings for now to make sure we are not creating a compat burden // for something other tools do not support. If we realise in future that "something else" should include non-UTF8 // Unicode encodings, we can remove this restriction. if (value != null && (value.Equals(Encoding.BigEndianUnicode) || value.Equals(Encoding.Unicode) #if FEATURE_UTF32 || value.Equals(Encoding.UTF32) #endif // FEATURE_UTF32 #if FEATURE_UTF7 || value.Equals(Encoding.UTF7) #endif // FEATURE_UTF7 )) { throw new ArgumentException(SR.EntryNameEncodingNotSupported, nameof(EntryNameEncoding)); } _entryNameEncoding = value; } } private ZipArchiveEntry DoCreateEntry(string entryName, CompressionLevel? compressionLevel) { if (entryName == null) throw new ArgumentNullException(nameof(entryName)); if (string.IsNullOrEmpty(entryName)) throw new ArgumentException(SR.CannotBeEmpty, nameof(entryName)); if (_mode == ZipArchiveMode.Read) throw new NotSupportedException(SR.CreateInReadMode); ThrowIfDisposed(); ZipArchiveEntry entry = compressionLevel.HasValue ? new ZipArchiveEntry(this, entryName, compressionLevel.Value) : new ZipArchiveEntry(this, entryName); AddEntry(entry); return entry; } internal void AcquireArchiveStream(ZipArchiveEntry entry) { // if a previous entry had held the stream but never wrote anything, we write their local header for them if (_archiveStreamOwner != null) { if (!_archiveStreamOwner.EverOpenedForWrite) { _archiveStreamOwner.WriteAndFinishLocalEntry(); } else { throw new IOException(SR.CreateModeCreateEntryWhileOpen); } } _archiveStreamOwner = entry; } private void AddEntry(ZipArchiveEntry entry) { _entries.Add(entry); string entryName = entry.FullName; if (!_entriesDictionary.ContainsKey(entryName)) { _entriesDictionary.Add(entryName, entry); } } [Conditional("DEBUG")] internal void DebugAssertIsStillArchiveStreamOwner(ZipArchiveEntry entry) => Debug.Assert(_archiveStreamOwner == entry); internal void ReleaseArchiveStream(ZipArchiveEntry entry) { Debug.Assert(_archiveStreamOwner == entry); _archiveStreamOwner = null; } internal void RemoveEntry(ZipArchiveEntry entry) { _entries.Remove(entry); _entriesDictionary.Remove(entry.FullName); } internal void ThrowIfDisposed() { if (_isDisposed) throw new ObjectDisposedException(GetType().ToString()); } private void CloseStreams() { if (!_leaveOpen) { _archiveStream.Dispose(); _backingStream?.Dispose(); _archiveReader?.Dispose(); } else { // if _backingStream isn't null, that means we assigned the original stream they passed // us to _backingStream (which they requested we leave open), and _archiveStream was // the temporary copy that we needed if (_backingStream != null) _archiveStream.Dispose(); } } private void EnsureCentralDirectoryRead() { if (!_readEntries) { ReadCentralDirectory(); _readEntries = true; } } private void Init(Stream stream, ZipArchiveMode mode, bool leaveOpen) { Stream extraTempStream = null; try { _backingStream = null; // check stream against mode switch (mode) { case ZipArchiveMode.Create: if (!stream.CanWrite) throw new ArgumentException(SR.CreateModeCapabilities); break; case ZipArchiveMode.Read: if (!stream.CanRead) throw new ArgumentException(SR.ReadModeCapabilities); if (!stream.CanSeek) { _backingStream = stream; extraTempStream = stream = new MemoryStream(); _backingStream.CopyTo(stream); stream.Seek(0, SeekOrigin.Begin); } break; case ZipArchiveMode.Update: if (!stream.CanRead || !stream.CanWrite || !stream.CanSeek) throw new ArgumentException(SR.UpdateModeCapabilities); break; default: // still have to throw this, because stream constructor doesn't do mode argument checks throw new ArgumentOutOfRangeException(nameof(mode)); } _mode = mode; if (mode == ZipArchiveMode.Create && !stream.CanSeek) _archiveStream = new PositionPreservingWriteOnlyStreamWrapper(stream); else _archiveStream = stream; _archiveStreamOwner = null; if (mode == ZipArchiveMode.Create) _archiveReader = null; else _archiveReader = new BinaryReader(_archiveStream); _entries = new List<ZipArchiveEntry>(); _entriesCollection = new ReadOnlyCollection<ZipArchiveEntry>(_entries); _entriesDictionary = new Dictionary<string, ZipArchiveEntry>(); _readEntries = false; _leaveOpen = leaveOpen; _centralDirectoryStart = 0; // invalid until ReadCentralDirectory _isDisposed = false; _numberOfThisDisk = 0; // invalid until ReadCentralDirectory _archiveComment = null; switch (mode) { case ZipArchiveMode.Create: _readEntries = true; break; case ZipArchiveMode.Read: ReadEndOfCentralDirectory(); break; case ZipArchiveMode.Update: default: Debug.Assert(mode == ZipArchiveMode.Update); if (_archiveStream.Length == 0) { _readEntries = true; } else { ReadEndOfCentralDirectory(); EnsureCentralDirectoryRead(); foreach (ZipArchiveEntry entry in _entries) { entry.ThrowIfNotOpenable(needToUncompress: false, needToLoadIntoMemory: true); } } break; } } catch { if (extraTempStream != null) extraTempStream.Dispose(); throw; } } private void ReadCentralDirectory() { try { // assume ReadEndOfCentralDirectory has been called and has populated _centralDirectoryStart _archiveStream.Seek(_centralDirectoryStart, SeekOrigin.Begin); long numberOfEntries = 0; //read the central directory ZipCentralDirectoryFileHeader currentHeader; bool saveExtraFieldsAndComments = Mode == ZipArchiveMode.Update; while (ZipCentralDirectoryFileHeader.TryReadBlock(_archiveReader, saveExtraFieldsAndComments, out currentHeader)) { AddEntry(new ZipArchiveEntry(this, currentHeader)); numberOfEntries++; } if (numberOfEntries != _expectedNumberOfEntries) throw new InvalidDataException(SR.NumEntriesWrong); } catch (EndOfStreamException ex) { throw new InvalidDataException(SR.Format(SR.CentralDirectoryInvalid, ex)); } } // This function reads all the EOCD stuff it needs to find the offset to the start of the central directory // This offset gets put in _centralDirectoryStart and the number of this disk gets put in _numberOfThisDisk // Also does some verification that this isn't a split/spanned archive // Also checks that offset to CD isn't out of bounds private void ReadEndOfCentralDirectory() { try { // This seeks backwards almost to the beginning of the EOCD, one byte after where the signature would be // located if the EOCD had the minimum possible size (no file zip comment) _archiveStream.Seek(-ZipEndOfCentralDirectoryBlock.SizeOfBlockWithoutSignature, SeekOrigin.End); // If the EOCD has the minimum possible size (no zip file comment), then exactly the previous 4 bytes will contain the signature // But if the EOCD has max possible size, the signature should be found somewhere in the previous 64K + 4 bytes if (!ZipHelper.SeekBackwardsToSignature(_archiveStream, ZipEndOfCentralDirectoryBlock.SignatureConstant, ZipEndOfCentralDirectoryBlock.ZipFileCommentMaxLength + ZipEndOfCentralDirectoryBlock.SignatureSize)) throw new InvalidDataException(SR.EOCDNotFound); long eocdStart = _archiveStream.Position; // read the EOCD ZipEndOfCentralDirectoryBlock eocd; bool eocdProper = ZipEndOfCentralDirectoryBlock.TryReadBlock(_archiveReader, out eocd); Debug.Assert(eocdProper); // we just found this using the signature finder, so it should be okay if (eocd.NumberOfThisDisk != eocd.NumberOfTheDiskWithTheStartOfTheCentralDirectory) throw new InvalidDataException(SR.SplitSpanned); _numberOfThisDisk = eocd.NumberOfThisDisk; _centralDirectoryStart = eocd.OffsetOfStartOfCentralDirectoryWithRespectToTheStartingDiskNumber; if (eocd.NumberOfEntriesInTheCentralDirectory != eocd.NumberOfEntriesInTheCentralDirectoryOnThisDisk) throw new InvalidDataException(SR.SplitSpanned); _expectedNumberOfEntries = eocd.NumberOfEntriesInTheCentralDirectory; // only bother saving the comment if we are in update mode if (_mode == ZipArchiveMode.Update) _archiveComment = eocd.ArchiveComment; TryReadZip64EndOfCentralDirectory(eocd, eocdStart); if (_centralDirectoryStart > _archiveStream.Length) { throw new InvalidDataException(SR.FieldTooBigOffsetToCD); } } catch (EndOfStreamException ex) { throw new InvalidDataException(SR.CDCorrupt, ex); } catch (IOException ex) { throw new InvalidDataException(SR.CDCorrupt, ex); } } // Tries to find the Zip64 End of Central Directory Locator, then the Zip64 End of Central Directory, assuming the // End of Central Directory block has already been found, as well as the location in the stream where the EOCD starts. private void TryReadZip64EndOfCentralDirectory(ZipEndOfCentralDirectoryBlock eocd, long eocdStart) { // Only bother looking for the Zip64-EOCD stuff if we suspect it is needed because some value is FFFFFFFFF // because these are the only two values we need, we only worry about these // if we don't find the Zip64-EOCD, we just give up and try to use the original values if (eocd.NumberOfThisDisk == ZipHelper.Mask16Bit || eocd.OffsetOfStartOfCentralDirectoryWithRespectToTheStartingDiskNumber == ZipHelper.Mask32Bit || eocd.NumberOfEntriesInTheCentralDirectory == ZipHelper.Mask16Bit) { // Read Zip64 End of Central Directory Locator // This seeks forwards almost to the beginning of the Zip64-EOCDL, one byte after where the signature would be located _archiveStream.Seek(eocdStart - Zip64EndOfCentralDirectoryLocator.SizeOfBlockWithoutSignature, SeekOrigin.Begin); // Exactly the previous 4 bytes should contain the Zip64-EOCDL signature // if we don't find it, assume it doesn't exist and use data from normal EOCD if (ZipHelper.SeekBackwardsToSignature(_archiveStream, Zip64EndOfCentralDirectoryLocator.SignatureConstant, Zip64EndOfCentralDirectoryLocator.SignatureSize)) { Debug.Assert(_archiveReader != null); // use locator to get to Zip64-EOCD Zip64EndOfCentralDirectoryLocator locator; bool zip64eocdLocatorProper = Zip64EndOfCentralDirectoryLocator.TryReadBlock(_archiveReader, out locator); Debug.Assert(zip64eocdLocatorProper); // we just found this using the signature finder, so it should be okay if (locator.OffsetOfZip64EOCD > long.MaxValue) throw new InvalidDataException(SR.FieldTooBigOffsetToZip64EOCD); long zip64EOCDOffset = (long)locator.OffsetOfZip64EOCD; _archiveStream.Seek(zip64EOCDOffset, SeekOrigin.Begin); // Read Zip64 End of Central Directory Record Zip64EndOfCentralDirectoryRecord record; if (!Zip64EndOfCentralDirectoryRecord.TryReadBlock(_archiveReader, out record)) throw new InvalidDataException(SR.Zip64EOCDNotWhereExpected); _numberOfThisDisk = record.NumberOfThisDisk; if (record.NumberOfEntriesTotal > long.MaxValue) throw new InvalidDataException(SR.FieldTooBigNumEntries); if (record.OffsetOfCentralDirectory > long.MaxValue) throw new InvalidDataException(SR.FieldTooBigOffsetToCD); if (record.NumberOfEntriesTotal != record.NumberOfEntriesOnThisDisk) throw new InvalidDataException(SR.SplitSpanned); _expectedNumberOfEntries = (long)record.NumberOfEntriesTotal; _centralDirectoryStart = (long)record.OffsetOfCentralDirectory; } } } private void WriteFile() { // if we are in create mode, we always set readEntries to true in Init // if we are in update mode, we call EnsureCentralDirectoryRead, which sets readEntries to true Debug.Assert(_readEntries); if (_mode == ZipArchiveMode.Update) { List<ZipArchiveEntry> markedForDelete = new List<ZipArchiveEntry>(); foreach (ZipArchiveEntry entry in _entries) { if (!entry.LoadLocalHeaderExtraFieldAndCompressedBytesIfNeeded()) markedForDelete.Add(entry); } foreach (ZipArchiveEntry entry in markedForDelete) entry.Delete(); _archiveStream.Seek(0, SeekOrigin.Begin); _archiveStream.SetLength(0); } foreach (ZipArchiveEntry entry in _entries) { entry.WriteAndFinishLocalEntry(); } long startOfCentralDirectory = _archiveStream.Position; foreach (ZipArchiveEntry entry in _entries) { entry.WriteCentralDirectoryFileHeader(); } long sizeOfCentralDirectory = _archiveStream.Position - startOfCentralDirectory; WriteArchiveEpilogue(startOfCentralDirectory, sizeOfCentralDirectory); } // writes eocd, and if needed, zip 64 eocd, zip64 eocd locator // should only throw an exception in extremely exceptional cases because it is called from dispose private void WriteArchiveEpilogue(long startOfCentralDirectory, long sizeOfCentralDirectory) { // determine if we need Zip 64 if (startOfCentralDirectory >= uint.MaxValue || sizeOfCentralDirectory >= uint.MaxValue || _entries.Count >= ZipHelper.Mask16Bit #if DEBUG_FORCE_ZIP64 || _forceZip64 #endif ) { // if we need zip 64, write zip 64 eocd and locator long zip64EOCDRecordStart = _archiveStream.Position; Zip64EndOfCentralDirectoryRecord.WriteBlock(_archiveStream, _entries.Count, startOfCentralDirectory, sizeOfCentralDirectory); Zip64EndOfCentralDirectoryLocator.WriteBlock(_archiveStream, zip64EOCDRecordStart); } // write normal eocd ZipEndOfCentralDirectoryBlock.WriteBlock(_archiveStream, _entries.Count, startOfCentralDirectory, sizeOfCentralDirectory, _archiveComment); } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Umbraco.Core; using Umbraco.Core.Configuration; using Umbraco.Core.IO; using Umbraco.Core.Models; using umbraco.BasePages; using umbraco.cms.businesslogic; using umbraco.cms.businesslogic.datatype; using umbraco.cms.businesslogic.propertytype; using umbraco.cms.businesslogic.web; using umbraco.interfaces; using umbraco.uicontrols; using Content = umbraco.cms.businesslogic.Content; using ContentType = umbraco.cms.businesslogic.ContentType; using Media = umbraco.cms.businesslogic.media.Media; using Property = umbraco.cms.businesslogic.property.Property; using StylesheetProperty = umbraco.cms.businesslogic.web.StylesheetProperty; namespace umbraco.controls { public class ContentControlLoadEventArgs : CancelEventArgs { } /// <summary> /// Summary description for ContentControl. /// </summary> public class ContentControl : TabView { internal Dictionary<string, IDataType> DataTypes = new Dictionary<string, IDataType>(); private readonly Content _content; private UmbracoEnsuredPage _prntpage; public event EventHandler SaveAndPublish; public event EventHandler SaveToPublish; public event EventHandler Save; private readonly publishModes _canPublish = publishModes.NoPublish; public TabPage tpProp; public bool DoesPublish = false; public TextBox NameTxt = new TextBox(); public PlaceHolder NameTxtHolder = new PlaceHolder(); public RequiredFieldValidator NameTxtValidator = new RequiredFieldValidator(); private readonly CustomValidator _nameTxtCustomValidator = new CustomValidator(); private static readonly string UmbracoPath = SystemDirectories.Umbraco; public Pane PropertiesPane = new Pane(); // zb-00036 #29889 : load it only once List<ContentType.TabI> _virtualTabs; //default to true! private bool _savePropertyDataWhenInvalid = true; private ContentType _contentType; public Content ContentObject { get { return _content; } } /// <summary> /// This property controls whether the content property values are persisted even if validation /// fails. If set to false, then the values will not be persisted. /// </summary> /// <remarks> /// This is required because when we are editing content we should be persisting invalid values to the database /// as this makes it easier for editors to come back and fix up their changes before they publish. Of course we /// don't publish if the page is invalid. In the case of media and members, we don't want to persist the values /// to the database when the page is invalid because there is no published state. /// Relates to: http://issues.umbraco.org/issue/U4-227 /// </remarks> public bool SavePropertyDataWhenInvalid { get { return _savePropertyDataWhenInvalid; } set { _savePropertyDataWhenInvalid = value; } } [Obsolete("This is no longer used and will be removed from the codebase in future versions")] private string _errorMessage = ""; [Obsolete("This is no longer used and will be removed from the codebase in future versions")] public string ErrorMessage { set { _errorMessage = value; } } [Obsolete("This is no longer used and will be removed from the codebase in future versions")] protected void standardSaveAndPublishHandler(object sender, EventArgs e) { } /// <summary> /// Constructor to set default properties. /// </summary> /// <param name="c"></param> /// <param name="CanPublish"></param> /// <param name="Id"></param> /// <remarks> /// This method used to create all of the child controls too which is BAD since /// the page hasn't started initializing yet. Control IDs were not being named /// correctly, etc... I've moved the child control setup/creation to the CreateChildControls /// method where they are suposed to be. /// </remarks> public ContentControl(Content c, publishModes CanPublish, string Id) { ID = Id; this._canPublish = CanPublish; _content = c; Width = 350; Height = 350; _prntpage = (UmbracoEnsuredPage)Page; // zb-00036 #29889 : load it only once if (_virtualTabs == null) _virtualTabs = _content.ContentType.getVirtualTabs.ToList(); foreach (ContentType.TabI t in _virtualTabs) { TabPage tp = NewTabPage(t.Caption); AddSaveAndPublishButtons(ref tp); } } /// <summary> /// Create and setup all of the controls child controls. /// </summary> protected override void CreateChildControls() { base.CreateChildControls(); _prntpage = (UmbracoEnsuredPage)Page; int i = 0; Hashtable inTab = new Hashtable(); // zb-00036 #29889 : load it only once if (_virtualTabs == null) _virtualTabs = _content.ContentType.getVirtualTabs.ToList(); if(_contentType == null) _contentType = ContentType.GetContentType(_content.ContentType.Id); foreach (ContentType.TabI tab in _virtualTabs) { var tabPage = this.Panels[i] as TabPage; if (tabPage == null) { throw new ArgumentException("Unable to load tab \"" + tab.Caption + "\""); } tabPage.Style.Add("text-align", "center"); //Legacy vs New API loading of PropertyTypes if (_contentType.ContentTypeItem != null) { LoadPropertyTypes(_contentType.ContentTypeItem, tabPage, inTab, tab.Id, tab.Caption); } else { LoadPropertyTypes(tab, tabPage, inTab); } i++; } // Add property pane tpProp = NewTabPage(ui.Text("general", "properties")); AddSaveAndPublishButtons(ref tpProp); tpProp.Controls.Add( new LiteralControl("<div id=\"errorPane_" + tpProp.ClientID + "\" style=\"display: none; text-align: left; color: red;width: 100%; border: 1px solid red; background-color: #FCDEDE\"><div><b>There were errors - data has not been saved!</b><br/></div></div>")); //if the property is not in a tab, add it to the general tab var props = _content.GenericProperties; foreach (Property p in props.OrderBy(x => x.PropertyType.SortOrder)) { if (inTab[p.PropertyType.Id.ToString()] == null) AddControlNew(p, tpProp, ui.Text("general", "properties")); } } /// <summary> /// Loades PropertyTypes by Tab/PropertyGroup using the new API. /// </summary> /// <param name="contentType"></param> /// <param name="tabPage"></param> /// <param name="inTab"></param> /// <param name="tabId"></param> /// <param name="tabCaption"></param> private void LoadPropertyTypes(IContentTypeComposition contentType, TabPage tabPage, Hashtable inTab, int tabId, string tabCaption) { var propertyGroups = contentType.CompositionPropertyGroups.Where(x => x.Id == tabId || x.ParentId == tabId); var propertyTypeAliases = propertyGroups.SelectMany(x => x.PropertyTypes.OrderBy(y => y.SortOrder).Select(y => new Tuple<int, string, int>(y.Id, y.Alias, y.SortOrder))); foreach (var items in propertyTypeAliases) { var property = _content.getProperty(items.Item2); if (property != null) { AddControlNew(property, tabPage, tabCaption); if (!inTab.ContainsKey(items.Item1.ToString(CultureInfo.InvariantCulture))) inTab.Add(items.Item1.ToString(CultureInfo.InvariantCulture), true); } else { throw new ArgumentNullException( string.Format( "Property {0} ({1}) on Content Type {2} could not be retrieved for Document {3} on Tab Page {4}. To fix this problem, delete the property and recreate it.", items.Item2, items.Item1, _content.ContentType.Alias, _content.Id, tabCaption)); } } } /// <summary> /// Loades PropertyTypes by Tab using the Legacy API. /// </summary> /// <param name="tab"></param> /// <param name="tabPage"></param> /// <param name="inTab"></param> private void LoadPropertyTypes(ContentType.TabI tab, TabPage tabPage, Hashtable inTab) { // Iterate through the property types and add them to the tab // zb-00036 #29889 : fix property types getter to get the right set of properties // ge : had a bit of a corrupt db and got weird NRE errors so rewrote this to catch the error and rethrow with detail var propertyTypes = tab.GetPropertyTypes(_content.ContentType.Id); foreach (var propertyType in propertyTypes.OrderBy(x => x.SortOrder)) { var property = _content.getProperty(propertyType); if (property != null && tabPage != null) { AddControlNew(property, tabPage, tab.Caption); // adding this check, as we occasionally get an already in dictionary error, though not sure why if (!inTab.ContainsKey(propertyType.Id.ToString(CultureInfo.InvariantCulture))) inTab.Add(propertyType.Id.ToString(CultureInfo.InvariantCulture), true); } else { throw new ArgumentNullException( string.Format( "Property {0} ({1}) on Content Type {2} could not be retrieved for Document {3} on Tab Page {4}. To fix this problem, delete the property and recreate it.", propertyType.Alias, propertyType.Id, _content.ContentType.Alias, _content.Id, tab.Caption)); } } } /// <summary> /// Initializes the control and ensures child controls are setup /// </summary> /// <param name="e"></param> protected override void OnInit(EventArgs e) { base.OnInit(e); EnsureChildControls(); // Add extras for the property tabpage. . ContentControlLoadEventArgs contentcontrolEvent = new ContentControlLoadEventArgs(); FireBeforeContentControlLoad(contentcontrolEvent); if (!contentcontrolEvent.Cancel) { NameTxt.ID = "NameTxt"; if (!Page.IsPostBack) { NameTxt.Text = _content.Text; } // Name validation NameTxtValidator.ControlToValidate = NameTxt.ID; _nameTxtCustomValidator.ControlToValidate = NameTxt.ID; string[] errorVars = { ui.Text("name") }; NameTxtValidator.ErrorMessage = " " + ui.Text("errorHandling", "errorMandatoryWithoutTab", errorVars) + "<br/>"; NameTxtValidator.EnableClientScript = false; NameTxtValidator.Display = ValidatorDisplay.Dynamic; _nameTxtCustomValidator.EnableClientScript = false; _nameTxtCustomValidator.Display = ValidatorDisplay.Dynamic; _nameTxtCustomValidator.ServerValidate += NameTxtCustomValidatorServerValidate; _nameTxtCustomValidator.ValidateEmptyText = false; NameTxtHolder.Controls.Add(NameTxt); NameTxtHolder.Controls.Add(NameTxtValidator); NameTxtHolder.Controls.Add(_nameTxtCustomValidator); PropertiesPane.addProperty(ui.Text("general", "name"), NameTxtHolder); Literal ltt = new Literal(); ltt.Text = _content.User.Name; PropertiesPane.addProperty(ui.Text("content", "createBy"), ltt); ltt = new Literal(); ltt.Text = _content.CreateDateTime.ToString(); PropertiesPane.addProperty(ui.Text("content", "createDate"), ltt); ltt = new Literal(); ltt.Text = _content.Id.ToString(); PropertiesPane.addProperty("Id", ltt); if (_content is Media) { PropertiesPane.addProperty(ui.Text("content", "mediatype"), new LiteralControl(_content.ContentType.Alias)); } tpProp.Controls.AddAt(0, PropertiesPane); tpProp.Style.Add("text-align", "center"); } } /// <summary> /// Custom validates the content name field /// </summary> /// <param name="source"></param> /// <param name="args"></param> /// <remarks> /// We need to ensure people are not entering XSS attacks on this field /// http://issues.umbraco.org/issue/U4-485 /// /// This doesn't actually 'validate' but changes the text field value and strips html /// </remarks> void NameTxtCustomValidatorServerValidate(object source, ServerValidateEventArgs args) { NameTxt.Text = NameTxt.Text.StripHtml(); args.IsValid = true; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); ContentControlLoadEventArgs contentcontrolEvent = new ContentControlLoadEventArgs(); FireAfterContentControlLoad(contentcontrolEvent); } /// <summary> /// Sets the name (text) and values on the data types of the document /// </summary> private void SetNameAndDataTypeValues() { //we only continue saving anything if: // SavePropertyDataWhenInvalid == true // OR if the page is actually valid. if (SavePropertyDataWhenInvalid || Page.IsValid) { foreach (var property in DataTypes) { var defaultData = property.Value.Data as DefaultData; if (defaultData != null) { defaultData.PropertyTypeAlias = property.Key; defaultData.NodeId = _content.Id; } property.Value.DataEditor.Save(); } //don't update if the name is empty if (!NameTxt.Text.IsNullOrWhiteSpace()) { _content.Text = NameTxt.Text; } } } private void SaveClick(object sender, ImageClickEventArgs e) { SetNameAndDataTypeValues(); if (Save != null) { Save(this, new EventArgs()); } } private void DoSaveAndPublish(object sender, ImageClickEventArgs e) { DoesPublish = true; SetNameAndDataTypeValues(); //NOTE: This is only here to keep backwards compatibility. // see: http://issues.umbraco.org/issue/U4-1660 Save(this, new EventArgs()); if (SaveAndPublish != null) { SaveAndPublish(this, new EventArgs()); } } private void DoSaveToPublish(object sender, ImageClickEventArgs e) { SaveClick(sender, e); if (SaveToPublish != null) { SaveToPublish(this, new EventArgs()); } } private void AddSaveAndPublishButtons(ref TabPage tp) { MenuImageButton menuSave = tp.Menu.NewImageButton(); menuSave.ID = tp.ID + "_save"; menuSave.ImageUrl = UmbracoPath + "/images/editor/save.gif"; menuSave.Click += new ImageClickEventHandler(SaveClick); menuSave.OnClickCommand = "invokeSaveHandlers();"; menuSave.AltText = ui.Text("buttons", "save"); if (_canPublish == publishModes.Publish) { MenuImageButton menuPublish = tp.Menu.NewImageButton(); menuPublish.ID = tp.ID + "_publish"; menuPublish.ImageUrl = UmbracoPath + "/images/editor/saveAndPublish.gif"; menuPublish.OnClickCommand = "invokeSaveHandlers();"; menuPublish.Click += new ImageClickEventHandler(DoSaveAndPublish); menuPublish.AltText = ui.Text("buttons", "saveAndPublish"); } else if (_canPublish == publishModes.SendToPublish) { MenuImageButton menuToPublish = tp.Menu.NewImageButton(); menuToPublish.ID = tp.ID + "_topublish"; menuToPublish.ImageUrl = UmbracoPath + "/images/editor/saveToPublish.gif"; menuToPublish.OnClickCommand = "invokeSaveHandlers();"; menuToPublish.Click += new ImageClickEventHandler(DoSaveToPublish); menuToPublish.AltText = ui.Text("buttons", "saveToPublish"); } } private void AddControlNew(Property p, TabPage tp, string cap) { IDataType dt = p.PropertyType.DataTypeDefinition.DataType; //check that property editor has been set for the data type used by this property if (dt != null) { dt.DataEditor.Editor.ID = string.Format("prop_{0}", p.PropertyType.Alias); dt.Data.PropertyId = p.Id; //Add the DataType to an internal dictionary, which will be used to call the save method on the IDataEditor //and to retrieve the value from IData in editContent.aspx.cs, so that it can be set on the legacy Document class. DataTypes.Add(p.PropertyType.Alias, dt); // check for buttons IDataFieldWithButtons df1 = dt.DataEditor.Editor as IDataFieldWithButtons; if (df1 != null) { ((Control)df1).ID = p.PropertyType.Alias; if (df1.MenuIcons.Length > 0) tp.Menu.InsertSplitter(); // Add buttons int c = 0; bool atEditHtml = false; bool atSplitter = false; foreach (object o in df1.MenuIcons) { try { MenuIconI m = (MenuIconI)o; MenuIconI mi = tp.Menu.NewIcon(); mi.ImageURL = m.ImageURL; mi.OnClickCommand = m.OnClickCommand; mi.AltText = m.AltText; mi.ID = tp.ID + "_" + m.ID; if (m.ID == "html") atEditHtml = true; else atEditHtml = false; atSplitter = false; } catch { tp.Menu.InsertSplitter(); atSplitter = true; } // Testing custom styles in editor if (atSplitter && atEditHtml && dt.DataEditor.TreatAsRichTextEditor) { DropDownList ddl = tp.Menu.NewDropDownList(); ddl.Style.Add("margin-bottom", "5px"); ddl.Items.Add(ui.Text("buttons", "styleChoose")); ddl.ID = tp.ID + "_editorStyle"; if (StyleSheet.GetAll().Length > 0) { foreach (StyleSheet s in StyleSheet.GetAll()) { foreach (StylesheetProperty sp in s.Properties) { ddl.Items.Add(new ListItem(sp.Text, sp.Alias)); } } } ddl.Attributes.Add("onChange", "addStyle(this, '" + p.PropertyType.Alias + "');"); atEditHtml = false; } c++; } } // check for element additions IMenuElement menuElement = dt.DataEditor.Editor as IMenuElement; if (menuElement != null) { // add separator tp.Menu.InsertSplitter(); // add the element tp.Menu.NewElement(menuElement.ElementName, menuElement.ElementIdPreFix + p.Id.ToString(), menuElement.ElementClass, menuElement.ExtraMenuWidth); } Pane pp = new Pane(); Control holder = new Control(); holder.Controls.Add(dt.DataEditor.Editor); if (p.PropertyType.DataTypeDefinition.DataType.DataEditor.ShowLabel) { string caption = p.PropertyType.Name; if (p.PropertyType.Description != null && p.PropertyType.Description != String.Empty) switch (UmbracoConfig.For.UmbracoSettings().Content.PropertyContextHelpOption) { case "icon": caption += " <img src=\"" + this.ResolveUrl(SystemDirectories.Umbraco) + "/images/help.png\" class=\"umbPropertyContextHelp\" alt=\"" + p.PropertyType.Description + "\" title=\"" + p.PropertyType.Description + "\" />"; break; case "text": caption += "<br /><small>" + umbraco.library.ReplaceLineBreaks(p.PropertyType.Description) + "</small>"; break; } pp.addProperty(caption, holder); } else pp.addProperty(holder); // Validation if (p.PropertyType.Mandatory) { try { var rq = new RequiredFieldValidator { ControlToValidate = dt.DataEditor.Editor.ID, CssClass = "error" }; rq.Style.Add(HtmlTextWriterStyle.Display, "block"); rq.Style.Add(HtmlTextWriterStyle.Padding, "2px"); var component = dt.DataEditor.Editor; // holder.FindControl(rq.ControlToValidate); var attribute = (ValidationPropertyAttribute)TypeDescriptor.GetAttributes(component)[typeof(ValidationPropertyAttribute)]; PropertyDescriptor pd = null; if (attribute != null) { pd = TypeDescriptor.GetProperties(component, null)[attribute.Name]; } if (pd != null) { rq.EnableClientScript = false; rq.Display = ValidatorDisplay.Dynamic; string[] errorVars = { p.PropertyType.Name, cap }; rq.ErrorMessage = ui.Text("errorHandling", "errorMandatory", errorVars) + "<br/>"; holder.Controls.AddAt(0, rq); } } catch (Exception valE) { HttpContext.Current.Trace.Warn("contentControl", "EditorControl (" + dt.DataTypeName + ") does not support validation", valE); } } // RegExp Validation if (p.PropertyType.ValidationRegExp != "") { try { var rv = new RegularExpressionValidator { ControlToValidate = dt.DataEditor.Editor.ID, CssClass = "error" }; rv.Style.Add(HtmlTextWriterStyle.Display, "block"); rv.Style.Add(HtmlTextWriterStyle.Padding, "2px"); var component = dt.DataEditor.Editor; // holder.FindControl(rq.ControlToValidate); var attribute = (ValidationPropertyAttribute)TypeDescriptor.GetAttributes(component)[typeof(ValidationPropertyAttribute)]; PropertyDescriptor pd = null; if (attribute != null) { pd = TypeDescriptor.GetProperties(component, null)[attribute.Name]; } if (pd != null) { rv.ValidationExpression = p.PropertyType.ValidationRegExp; rv.EnableClientScript = false; rv.Display = ValidatorDisplay.Dynamic; string[] errorVars = { p.PropertyType.Name, cap }; rv.ErrorMessage = ui.Text("errorHandling", "errorRegExp", errorVars) + "<br/>"; holder.Controls.AddAt(0, rv); } } catch (Exception valE) { HttpContext.Current.Trace.Warn("contentControl", "EditorControl (" + dt.DataTypeName + ") does not support validation", valE); } } // This is once again a nasty nasty hack to fix gui when rendering wysiwygeditor if (dt.DataEditor.TreatAsRichTextEditor) { tp.Controls.Add(dt.DataEditor.Editor); } else { Panel ph = new Panel(); ph.Attributes.Add("style", "padding: 0; position: relative;"); // NH 4.7.1, latest styles added to support CP item: 30363 ph.Controls.Add(pp); tp.Controls.Add(ph); } } else { var ph = new Panel(); var pp = new Pane(); var missingPropertyEditorLabel = new Literal { Text = ui.Text("errors", "missingPropertyEditorErrorMessage") }; pp.addProperty(p.PropertyType.Name, missingPropertyEditorLabel); ph.Attributes.Add("style", "padding: 0; position: relative;"); ph.Controls.Add(pp); tp.Controls.Add(ph); } } public enum publishModes { Publish, SendToPublish, NoPublish } // EVENTS public delegate void BeforeContentControlLoadEventHandler(ContentControl contentControl, ContentControlLoadEventArgs e); public delegate void AfterContentControlLoadEventHandler(ContentControl contentControl, ContentControlLoadEventArgs e); /// <summary> /// Occurs when [before content control load]. /// </summary> public static event BeforeContentControlLoadEventHandler BeforeContentControlLoad; /// <summary> /// Fires the before content control load. /// </summary> /// <param name="e">The <see cref="umbraco.controls.ContentControlLoadEventArgs"/> instance containing the event data.</param> protected virtual void FireBeforeContentControlLoad(ContentControlLoadEventArgs e) { if (BeforeContentControlLoad != null) BeforeContentControlLoad(this, e); } /// <summary> /// Occurs when [before content control load]. /// </summary> public static event AfterContentControlLoadEventHandler AfterContentControlLoad; /// <summary> /// Fires the before content control load. /// </summary> /// <param name="e">The <see cref="umbraco.controls.ContentControlLoadEventArgs"/> instance containing the event data.</param> protected virtual void FireAfterContentControlLoad(ContentControlLoadEventArgs e) { if (AfterContentControlLoad != null) AfterContentControlLoad(this, e); } } }
// 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.Diagnostics; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { [ComVisible(true)] [ComDefaultInterface(typeof(EnvDTE80.CodeFunction2))] public sealed partial class CodeAccessorFunction : AbstractCodeElement, EnvDTE.CodeFunction, EnvDTE80.CodeFunction2 { internal static EnvDTE.CodeFunction Create(CodeModelState state, AbstractCodeMember parent, MethodKind kind) { var newElement = new CodeAccessorFunction(state, parent, kind); return (EnvDTE.CodeFunction)ComAggregate.CreateAggregatedObject(newElement); } private readonly ParentHandle<AbstractCodeMember> _parentHandle; private readonly MethodKind _kind; private CodeAccessorFunction(CodeModelState state, AbstractCodeMember parent, MethodKind kind) : base(state, parent.FileCodeModel) { Debug.Assert(kind == MethodKind.EventAdd || kind == MethodKind.EventRaise || kind == MethodKind.EventRemove || kind == MethodKind.PropertyGet || kind == MethodKind.PropertySet); _parentHandle = new ParentHandle<AbstractCodeMember>(parent); _kind = kind; } private AbstractCodeMember ParentMember { get { return _parentHandle.Value; } } private bool IsPropertyAccessor() { return _kind == MethodKind.PropertyGet || _kind == MethodKind.PropertySet; } internal override SyntaxNode LookupNode() { var parentNode = _parentHandle.Value.LookupNode(); if (parentNode == null) { throw Exceptions.ThrowEFail(); } SyntaxNode accessorNode; if (!CodeModelService.TryGetAccessorNode(parentNode, _kind, out accessorNode)) { throw Exceptions.ThrowEFail(); } return accessorNode; } public override EnvDTE.vsCMElement Kind { get { return EnvDTE.vsCMElement.vsCMElementFunction; } } public override object Parent { get { return _parentHandle.Value; } } public override EnvDTE.CodeElements Children { get { return EmptyCollection.Create(this.State, this); } } protected override string GetName() { return this.ParentMember.Name; } protected override void SetName(string value) { this.ParentMember.Name = value; } protected override string GetFullName() { return this.ParentMember.FullName; } public EnvDTE.CodeElements Attributes { get { return AttributeCollection.Create(this.State, this); } } public EnvDTE.vsCMAccess Access { get { var node = LookupNode(); return CodeModelService.GetAccess(node); } set { UpdateNode(FileCodeModel.UpdateAccess, value); } } public bool CanOverride { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } public string Comment { get { throw Exceptions.ThrowEFail(); } set { throw Exceptions.ThrowEFail(); } } public string DocComment { get { return string.Empty; } set { throw Exceptions.ThrowENotImpl(); } } public EnvDTE.vsCMFunction FunctionKind { get { var methodSymbol = LookupSymbol() as IMethodSymbol; if (methodSymbol == null) { throw Exceptions.ThrowEUnexpected(); } return CodeModelService.GetFunctionKind(methodSymbol); } } public bool IsGeneric { get { if (IsPropertyAccessor()) { return ((CodeProperty)this.ParentMember).IsGeneric; } else { return ((CodeEvent)this.ParentMember).IsGeneric; } } } public EnvDTE80.vsCMOverrideKind OverrideKind { get { if (IsPropertyAccessor()) { return ((CodeProperty)this.ParentMember).OverrideKind; } else { return ((CodeEvent)this.ParentMember).OverrideKind; } } set { if (IsPropertyAccessor()) { ((CodeProperty)this.ParentMember).OverrideKind = value; } else { ((CodeEvent)this.ParentMember).OverrideKind = value; } } } public bool IsOverloaded { get { return false; } } public bool IsShared { get { if (IsPropertyAccessor()) { return ((CodeProperty)this.ParentMember).IsShared; } else { return ((CodeEvent)this.ParentMember).IsShared; } } set { if (IsPropertyAccessor()) { ((CodeProperty)this.ParentMember).IsShared = value; } else { ((CodeEvent)this.ParentMember).IsShared = value; } } } public bool MustImplement { get { if (IsPropertyAccessor()) { return ((CodeProperty)this.ParentMember).MustImplement; } else { return ((CodeEvent)this.ParentMember).MustImplement; } } set { if (IsPropertyAccessor()) { ((CodeProperty)this.ParentMember).MustImplement = value; } else { ((CodeEvent)this.ParentMember).MustImplement = value; } } } public EnvDTE.CodeElements Overloads { get { throw Exceptions.ThrowEFail(); } } public EnvDTE.CodeElements Parameters { get { if (IsPropertyAccessor()) { return ((CodeProperty)this.ParentMember).Parameters; } throw Exceptions.ThrowEFail(); } } public EnvDTE.CodeTypeRef Type { get { if (IsPropertyAccessor()) { return ((CodeProperty)this.ParentMember).Type; } throw Exceptions.ThrowEFail(); } set { throw Exceptions.ThrowEFail(); } } public EnvDTE.CodeAttribute AddAttribute(string name, string value, object position) { // TODO(DustinCa): Check VB throw Exceptions.ThrowEFail(); } public EnvDTE.CodeParameter AddParameter(string name, object type, object position) { // TODO(DustinCa): Check VB throw Exceptions.ThrowEFail(); } public void RemoveParameter(object element) { // TODO(DustinCa): Check VB throw Exceptions.ThrowEFail(); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core { using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Runtime; using System.Threading; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache.Affinity; using Apache.Ignite.Core.Client; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Cache.Affinity; using Apache.Ignite.Core.Impl.Client; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Handle; using Apache.Ignite.Core.Impl.Log; using Apache.Ignite.Core.Impl.Memory; using Apache.Ignite.Core.Impl.Unmanaged; using Apache.Ignite.Core.Impl.Unmanaged.Jni; using Apache.Ignite.Core.Lifecycle; using Apache.Ignite.Core.Log; using Apache.Ignite.Core.Resource; using BinaryReader = Apache.Ignite.Core.Impl.Binary.BinaryReader; using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils; /// <summary> /// This class defines a factory for the main Ignite API. /// <p/> /// Use <see cref="Start()"/> method to start Ignite with default configuration. /// <para/> /// All members are thread-safe and may be used concurrently from multiple threads. /// </summary> public static class Ignition { /// <summary> /// Default configuration section name. /// </summary> public const string ConfigurationSectionName = "igniteConfiguration"; /// <summary> /// Default configuration section name. /// </summary> public const string ClientConfigurationSectionName = "igniteClientConfiguration"; /** */ private static readonly object SyncRoot = new object(); /** GC warning flag. */ private static int _gcWarn; /** */ private static readonly IDictionary<NodeKey, Ignite> Nodes = new Dictionary<NodeKey, Ignite>(); /** Current DLL name. */ private static readonly string IgniteDllName = Path.GetFileName(Assembly.GetExecutingAssembly().Location); /** Startup info. */ [ThreadStatic] private static Startup _startup; /** Client mode flag. */ [ThreadStatic] private static bool _clientMode; /// <summary> /// Static initializer. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")] static Ignition() { AppDomain.CurrentDomain.DomainUnload += CurrentDomain_DomainUnload; } /// <summary> /// Gets or sets a value indicating whether Ignite should be started in client mode. /// Client nodes cannot hold data in caches. /// </summary> public static bool ClientMode { get { return _clientMode; } set { _clientMode = value; } } /// <summary> /// Starts Ignite with default configuration. By default this method will /// use Ignite configuration defined in <c>{IGNITE_HOME}/config/default-config.xml</c> /// configuration file. If such file is not found, then all system defaults will be used. /// </summary> /// <returns>Started Ignite.</returns> public static IIgnite Start() { return Start(new IgniteConfiguration()); } /// <summary> /// Starts all grids specified within given Spring XML configuration file. If Ignite with given name /// is already started, then exception is thrown. In this case all instances that may /// have been started so far will be stopped too. /// </summary> /// <param name="springCfgPath">Spring XML configuration file path or URL. Note, that the path can be /// absolute or relative to IGNITE_HOME.</param> /// <returns>Started Ignite. If Spring configuration contains multiple Ignite instances, then the 1st /// found instance is returned.</returns> public static IIgnite Start(string springCfgPath) { return Start(new IgniteConfiguration {SpringConfigUrl = springCfgPath}); } /// <summary> /// Reads <see cref="IgniteConfiguration"/> from application configuration /// <see cref="IgniteConfigurationSection"/> with <see cref="ConfigurationSectionName"/> /// name and starts Ignite. /// </summary> /// <returns>Started Ignite.</returns> public static IIgnite StartFromApplicationConfiguration() { // ReSharper disable once IntroduceOptionalParameters.Global return StartFromApplicationConfiguration(ConfigurationSectionName); } /// <summary> /// Reads <see cref="IgniteConfiguration"/> from application configuration /// <see cref="IgniteConfigurationSection"/> with specified name and starts Ignite. /// </summary> /// <param name="sectionName">Name of the section.</param> /// <returns>Started Ignite.</returns> public static IIgnite StartFromApplicationConfiguration(string sectionName) { IgniteArgumentCheck.NotNullOrEmpty(sectionName, "sectionName"); var section = ConfigurationManager.GetSection(sectionName) as IgniteConfigurationSection; if (section == null) throw new ConfigurationErrorsException(string.Format("Could not find {0} with name '{1}'", typeof(IgniteConfigurationSection).Name, sectionName)); if (section.IgniteConfiguration == null) throw new ConfigurationErrorsException( string.Format("{0} with name '{1}' is defined in <configSections>, " + "but not present in configuration.", typeof(IgniteConfigurationSection).Name, sectionName)); return Start(section.IgniteConfiguration); } /// <summary> /// Reads <see cref="IgniteConfiguration" /> from application configuration /// <see cref="IgniteConfigurationSection" /> with specified name and starts Ignite. /// </summary> /// <param name="sectionName">Name of the section.</param> /// <param name="configPath">Path to the configuration file.</param> /// <returns>Started Ignite.</returns> public static IIgnite StartFromApplicationConfiguration(string sectionName, string configPath) { var section = GetConfigurationSection<IgniteConfigurationSection>(sectionName, configPath); if (section.IgniteConfiguration == null) { throw new ConfigurationErrorsException( string.Format("{0} with name '{1}' in file '{2}' is defined in <configSections>, " + "but not present in configuration.", typeof(IgniteConfigurationSection).Name, sectionName, configPath)); } return Start(section.IgniteConfiguration); } /// <summary> /// Gets the configuration section. /// </summary> private static T GetConfigurationSection<T>(string sectionName, string configPath) where T : class { IgniteArgumentCheck.NotNullOrEmpty(sectionName, "sectionName"); IgniteArgumentCheck.NotNullOrEmpty(configPath, "configPath"); var fileMap = GetConfigMap(configPath); var config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); var section = config.GetSection(sectionName) as T; if (section == null) { throw new ConfigurationErrorsException( string.Format("Could not find {0} with name '{1}' in file '{2}'", typeof(T).Name, sectionName, configPath)); } return section; } /// <summary> /// Gets the configuration file map. /// </summary> private static ExeConfigurationFileMap GetConfigMap(string fileName) { var fullFileName = Path.GetFullPath(fileName); if (!File.Exists(fullFileName)) throw new ConfigurationErrorsException("Specified config file does not exist: " + fileName); return new ExeConfigurationFileMap { ExeConfigFilename = fullFileName }; } /// <summary> /// Starts Ignite with given configuration. /// </summary> /// <returns>Started Ignite.</returns> public static IIgnite Start(IgniteConfiguration cfg) { IgniteArgumentCheck.NotNull(cfg, "cfg"); cfg = new IgniteConfiguration(cfg); // Create a copy so that config can be modified and reused. lock (SyncRoot) { // 0. Init logger var log = cfg.Logger ?? new JavaLogger(); log.Debug("Starting Ignite.NET " + Assembly.GetExecutingAssembly().GetName().Version); // 1. Check GC settings. CheckServerGc(cfg, log); // 2. Create context. JvmDll.Load(cfg.JvmDllPath, log); var cbs = IgniteManager.CreateJvmContext(cfg, log); var env = cbs.Jvm.AttachCurrentThread(); log.Debug("JVM started."); var gridName = cfg.IgniteInstanceName; if (cfg.AutoGenerateIgniteInstanceName) { gridName = (gridName ?? "ignite-instance-") + Guid.NewGuid(); } // 3. Create startup object which will guide us through the rest of the process. _startup = new Startup(cfg, cbs); PlatformJniTarget interopProc = null; try { // 4. Initiate Ignite start. UU.IgnitionStart(env, cfg.SpringConfigUrl, gridName, ClientMode, cfg.Logger != null, cbs.IgniteId, cfg.RedirectJavaConsoleOutput); // 5. At this point start routine is finished. We expect STARTUP object to have all necessary data. var node = _startup.Ignite; interopProc = (PlatformJniTarget)node.InteropProcessor; var javaLogger = log as JavaLogger; if (javaLogger != null) { javaLogger.SetIgnite(node); } // 6. On-start callback (notify lifecycle components). node.OnStart(); Nodes[new NodeKey(_startup.Name)] = node; return node; } catch (Exception ex) { // 1. Perform keys cleanup. string name = _startup.Name; if (name != null) { NodeKey key = new NodeKey(name); if (Nodes.ContainsKey(key)) Nodes.Remove(key); } // 2. Stop Ignite node if it was started. if (interopProc != null) UU.IgnitionStop(gridName, true); // 3. Throw error further (use startup error if exists because it is more precise). if (_startup.Error != null) { // Wrap in a new exception to preserve original stack trace. throw new IgniteException("Failed to start Ignite.NET, check inner exception for details", _startup.Error); } var jex = ex as JavaException; if (jex == null) { throw; } throw ExceptionUtils.GetException(null, jex); } finally { var ignite = _startup.Ignite; _startup = null; if (ignite != null) { ignite.ProcessorReleaseStart(); } } } } /// <summary> /// Check whether GC is set to server mode. /// </summary> /// <param name="cfg">Configuration.</param> /// <param name="log">Log.</param> private static void CheckServerGc(IgniteConfiguration cfg, ILogger log) { if (!cfg.SuppressWarnings && !GCSettings.IsServerGC && Interlocked.CompareExchange(ref _gcWarn, 1, 0) == 0) log.Warn("GC server mode is not enabled, this could lead to less " + "than optimal performance on multi-core machines (to enable see " + "http://msdn.microsoft.com/en-us/library/ms229357(v=vs.110).aspx)."); } /// <summary> /// Prepare callback invoked from Java. /// </summary> /// <param name="inStream">Input stream with data.</param> /// <param name="outStream">Output stream.</param> /// <param name="handleRegistry">Handle registry.</param> /// <param name="log">Log.</param> internal static void OnPrepare(PlatformMemoryStream inStream, PlatformMemoryStream outStream, HandleRegistry handleRegistry, ILogger log) { try { BinaryReader reader = BinaryUtils.Marshaller.StartUnmarshal(inStream); PrepareConfiguration(reader, outStream, log); PrepareLifecycleHandlers(reader, outStream, handleRegistry); PrepareAffinityFunctions(reader, outStream); outStream.SynchronizeOutput(); } catch (Exception e) { _startup.Error = e; throw; } } /// <summary> /// Prepare configuration. /// </summary> /// <param name="reader">Reader.</param> /// <param name="outStream">Response stream.</param> /// <param name="log">Log.</param> private static void PrepareConfiguration(BinaryReader reader, PlatformMemoryStream outStream, ILogger log) { // 1. Load assemblies. IgniteConfiguration cfg = _startup.Configuration; LoadAssemblies(cfg.Assemblies); ICollection<string> cfgAssembllies; BinaryConfiguration binaryCfg; BinaryUtils.ReadConfiguration(reader, out cfgAssembllies, out binaryCfg); LoadAssemblies(cfgAssembllies); // 2. Create marshaller only after assemblies are loaded. if (cfg.BinaryConfiguration == null) cfg.BinaryConfiguration = binaryCfg; _startup.Marshaller = new Marshaller(cfg.BinaryConfiguration, log); // 3. Send configuration details to Java cfg.Validate(log); // Use system marshaller. cfg.Write(BinaryUtils.Marshaller.StartMarshal(outStream), ClientSocket.CurrentProtocolVersion); } /// <summary> /// Prepare lifecycle handlers. /// </summary> /// <param name="reader">Reader.</param> /// <param name="outStream">Output stream.</param> /// <param name="handleRegistry">Handle registry.</param> private static void PrepareLifecycleHandlers(IBinaryRawReader reader, IBinaryStream outStream, HandleRegistry handleRegistry) { IList<LifecycleHandlerHolder> beans = new List<LifecycleHandlerHolder> { new LifecycleHandlerHolder(new InternalLifecycleHandler()) // add internal bean for events }; // 1. Read beans defined in Java. int cnt = reader.ReadInt(); for (int i = 0; i < cnt; i++) beans.Add(new LifecycleHandlerHolder(CreateObject<ILifecycleHandler>(reader))); // 2. Append beans defined in local configuration. ICollection<ILifecycleHandler> nativeBeans = _startup.Configuration.LifecycleHandlers; if (nativeBeans != null) { foreach (ILifecycleHandler nativeBean in nativeBeans) beans.Add(new LifecycleHandlerHolder(nativeBean)); } // 3. Write bean pointers to Java stream. outStream.WriteInt(beans.Count); foreach (LifecycleHandlerHolder bean in beans) outStream.WriteLong(handleRegistry.AllocateCritical(bean)); // 4. Set beans to STARTUP object. _startup.LifecycleHandlers = beans; } /// <summary> /// Prepares the affinity functions. /// </summary> private static void PrepareAffinityFunctions(BinaryReader reader, PlatformMemoryStream outStream) { var cnt = reader.ReadInt(); var writer = reader.Marshaller.StartMarshal(outStream); for (var i = 0; i < cnt; i++) { var objHolder = new ObjectInfoHolder(reader); AffinityFunctionSerializer.Write(writer, objHolder.CreateInstance<IAffinityFunction>(), objHolder); } } /// <summary> /// Creates an object and sets the properties. /// </summary> /// <param name="reader">Reader.</param> /// <returns>Resulting object.</returns> private static T CreateObject<T>(IBinaryRawReader reader) { return IgniteUtils.CreateInstance<T>(reader.ReadString(), reader.ReadDictionaryAsGeneric<string, object>()); } /// <summary> /// Kernal start callback. /// </summary> /// <param name="interopProc">Interop processor.</param> /// <param name="stream">Stream.</param> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "PlatformJniTarget is passed further")] internal static void OnStart(GlobalRef interopProc, IBinaryStream stream) { try { // 1. Read data and leave critical state ASAP. BinaryReader reader = BinaryUtils.Marshaller.StartUnmarshal(stream); // ReSharper disable once PossibleInvalidOperationException var name = reader.ReadString(); // 2. Set ID and name so that Start() method can use them later. _startup.Name = name; if (Nodes.ContainsKey(new NodeKey(name))) throw new IgniteException("Ignite with the same name already started: " + name); _startup.Ignite = new Ignite(_startup.Configuration, _startup.Name, new PlatformJniTarget(interopProc, _startup.Marshaller), _startup.Marshaller, _startup.LifecycleHandlers, _startup.Callbacks); } catch (Exception e) { // 5. Preserve exception to throw it later in the "Start" method and throw it further // to abort startup in Java. _startup.Error = e; throw; } } /// <summary> /// Load assemblies. /// </summary> /// <param name="assemblies">Assemblies.</param> private static void LoadAssemblies(IEnumerable<string> assemblies) { if (assemblies != null) { foreach (string s in assemblies) { // 1. Try loading as directory. if (Directory.Exists(s)) { string[] files = Directory.GetFiles(s, "*.dll"); #pragma warning disable 0168 foreach (string dllPath in files) { if (!SelfAssembly(dllPath)) { try { Assembly.LoadFile(dllPath); } catch (BadImageFormatException) { // No-op. } } } #pragma warning restore 0168 continue; } // 2. Try loading using full-name. try { Assembly assembly = Assembly.Load(s); if (assembly != null) continue; } catch (Exception e) { if (!(e is FileNotFoundException || e is FileLoadException)) throw new IgniteException("Failed to load assembly: " + s, e); } // 3. Try loading using file path. try { Assembly assembly = Assembly.LoadFrom(s); // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (assembly != null) continue; } catch (Exception e) { if (!(e is FileNotFoundException || e is FileLoadException)) throw new IgniteException("Failed to load assembly: " + s, e); } // 4. Not found, exception. throw new IgniteException("Failed to load assembly: " + s); } } } /// <summary> /// Whether assembly points to Ignite binary. /// </summary> /// <param name="assembly">Assembly to check..</param> /// <returns><c>True</c> if this is one of GG assemblies.</returns> private static bool SelfAssembly(string assembly) { return assembly.EndsWith(IgniteDllName, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Gets a named Ignite instance. If Ignite name is <c>null</c> or empty string, /// then default no-name Ignite will be returned. Note that caller of this method /// should not assume that it will return the same instance every time. /// <p /> /// Note that single process can run multiple Ignite instances and every Ignite instance (and its /// node) can belong to a different grid. Ignite name defines what grid a particular Ignite /// instance (and correspondingly its node) belongs to. /// </summary> /// <param name="name">Ignite name to which requested Ignite instance belongs. If <c>null</c>, /// then Ignite instance belonging to a default no-name Ignite will be returned.</param> /// <returns> /// An instance of named grid. /// </returns> /// <exception cref="IgniteException">When there is no Ignite instance with specified name.</exception> public static IIgnite GetIgnite(string name) { var ignite = TryGetIgnite(name); if (ignite == null) throw new IgniteException("Ignite instance was not properly started or was already stopped: " + name); return ignite; } /// <summary> /// Gets the default Ignite instance with null name, or an instance with any name when there is only one. /// <para /> /// Note that caller of this method should not assume that it will return the same instance every time. /// </summary> /// <returns>Default Ignite instance.</returns> /// <exception cref="IgniteException">When there is no matching Ignite instance.</exception> public static IIgnite GetIgnite() { lock (SyncRoot) { if (Nodes.Count == 0) { throw new IgniteException("Failed to get default Ignite instance: " + "there are no instances started."); } if (Nodes.Count == 1) { return Nodes.Single().Value; } Ignite result; if (Nodes.TryGetValue(new NodeKey(null), out result)) { return result; } throw new IgniteException(string.Format("Failed to get default Ignite instance: " + "there are {0} instances started, and none of them has null name.", Nodes.Count)); } } /// <summary> /// Gets all started Ignite instances. /// </summary> /// <returns>All Ignite instances.</returns> public static ICollection<IIgnite> GetAll() { lock (SyncRoot) { return Nodes.Values.ToArray(); } } /// <summary> /// Gets a named Ignite instance, or <c>null</c> if none found. If Ignite name is <c>null</c> or empty string, /// then default no-name Ignite will be returned. Note that caller of this method /// should not assume that it will return the same instance every time. /// <p/> /// Note that single process can run multiple Ignite instances and every Ignite instance (and its /// node) can belong to a different grid. Ignite name defines what grid a particular Ignite /// instance (and correspondingly its node) belongs to. /// </summary> /// <param name="name">Ignite name to which requested Ignite instance belongs. If <c>null</c>, /// then Ignite instance belonging to a default no-name Ignite will be returned. /// </param> /// <returns>An instance of named grid, or null.</returns> public static IIgnite TryGetIgnite(string name) { lock (SyncRoot) { Ignite result; return !Nodes.TryGetValue(new NodeKey(name), out result) ? null : result; } } /// <summary> /// Gets the default Ignite instance with null name, or an instance with any name when there is only one. /// Returns null when there are no Ignite instances started, or when there are more than one, /// and none of them has null name. /// </summary> /// <returns>An instance of default no-name grid, or null.</returns> public static IIgnite TryGetIgnite() { lock (SyncRoot) { if (Nodes.Count == 1) { return Nodes.Single().Value; } return TryGetIgnite(null); } } /// <summary> /// Stops named grid. If <c>cancel</c> flag is set to <c>true</c> then /// all jobs currently executing on local node will be interrupted. If /// grid name is <c>null</c>, then default no-name Ignite will be stopped. /// </summary> /// <param name="name">Grid name. If <c>null</c>, then default no-name Ignite will be stopped.</param> /// <param name="cancel">If <c>true</c> then all jobs currently executing will be cancelled /// by calling <c>ComputeJob.cancel</c>method.</param> /// <returns><c>true</c> if named Ignite instance was indeed found and stopped, <c>false</c> /// othwerwise (the instance with given <c>name</c> was not found).</returns> public static bool Stop(string name, bool cancel) { lock (SyncRoot) { NodeKey key = new NodeKey(name); Ignite node; if (!Nodes.TryGetValue(key, out node)) return false; node.Stop(cancel); Nodes.Remove(key); GC.Collect(); return true; } } /// <summary> /// Stops <b>all</b> started grids. If <c>cancel</c> flag is set to <c>true</c> then /// all jobs currently executing on local node will be interrupted. /// </summary> /// <param name="cancel">If <c>true</c> then all jobs currently executing will be cancelled /// by calling <c>ComputeJob.Cancel()</c> method.</param> public static void StopAll(bool cancel) { lock (SyncRoot) { while (Nodes.Count > 0) { var entry = Nodes.First(); entry.Value.Stop(cancel); Nodes.Remove(entry.Key); } } GC.Collect(); } /// <summary> /// Connects Ignite lightweight (thin) client to an Ignite node. /// <para /> /// Thin client connects to an existing Ignite node with a socket and does not start JVM in process. /// </summary> /// <param name="clientConfiguration">The client configuration.</param> /// <returns>Ignite client instance.</returns> public static IIgniteClient StartClient(IgniteClientConfiguration clientConfiguration) { IgniteArgumentCheck.NotNull(clientConfiguration, "clientConfiguration"); return new IgniteClient(clientConfiguration); } /// <summary> /// Reads <see cref="IgniteClientConfiguration"/> from application configuration /// <see cref="IgniteClientConfigurationSection"/> with <see cref="ClientConfigurationSectionName"/> /// name and connects Ignite lightweight (thin) client to an Ignite node. /// <para /> /// Thin client connects to an existing Ignite node with a socket and does not start JVM in process. /// </summary> /// <returns>Ignite client instance.</returns> public static IIgniteClient StartClient() { // ReSharper disable once IntroduceOptionalParameters.Global return StartClient(ClientConfigurationSectionName); } /// <summary> /// Reads <see cref="IgniteClientConfiguration" /> from application configuration /// <see cref="IgniteClientConfigurationSection" /> with specified name and connects /// Ignite lightweight (thin) client to an Ignite node. /// <para /> /// Thin client connects to an existing Ignite node with a socket and does not start JVM in process. /// </summary> /// <param name="sectionName">Name of the configuration section.</param> /// <returns>Ignite client instance.</returns> public static IIgniteClient StartClient(string sectionName) { IgniteArgumentCheck.NotNullOrEmpty(sectionName, "sectionName"); var section = ConfigurationManager.GetSection(sectionName) as IgniteClientConfigurationSection; if (section == null) { throw new ConfigurationErrorsException(string.Format("Could not find {0} with name '{1}'.", typeof(IgniteClientConfigurationSection).Name, sectionName)); } if (section.IgniteClientConfiguration == null) { throw new ConfigurationErrorsException( string.Format("{0} with name '{1}' is defined in <configSections>, " + "but not present in configuration.", typeof(IgniteClientConfigurationSection).Name, sectionName)); } return StartClient(section.IgniteClientConfiguration); } /// <summary> /// Reads <see cref="IgniteConfiguration" /> from application configuration /// <see cref="IgniteConfigurationSection" /> with specified name and starts Ignite. /// </summary> /// <param name="sectionName">Name of the section.</param> /// <param name="configPath">Path to the configuration file.</param> /// <returns>Started Ignite.</returns> public static IIgniteClient StartClient(string sectionName, string configPath) { var section = GetConfigurationSection<IgniteClientConfigurationSection>(sectionName, configPath); if (section.IgniteClientConfiguration == null) { throw new ConfigurationErrorsException( string.Format("{0} with name '{1}' in file '{2}' is defined in <configSections>, " + "but not present in configuration.", typeof(IgniteClientConfigurationSection).Name, sectionName, configPath)); } return StartClient(section.IgniteClientConfiguration); } /// <summary> /// Handles the DomainUnload event of the CurrentDomain control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private static void CurrentDomain_DomainUnload(object sender, EventArgs e) { // If we don't stop Ignite.NET on domain unload, // we end up with broken instances in Java (invalid callbacks, etc). // IIS, in particular, is known to unload and reload domains within the same process. StopAll(true); } /// <summary> /// Grid key. Workaround for non-null key requirement in Dictionary. /// </summary> private class NodeKey { /** */ private readonly string _name; /// <summary> /// Initializes a new instance of the <see cref="NodeKey"/> class. /// </summary> /// <param name="name">The name.</param> internal NodeKey(string name) { _name = name; } /** <inheritdoc /> */ public override bool Equals(object obj) { var other = obj as NodeKey; return other != null && Equals(_name, other._name); } /** <inheritdoc /> */ public override int GetHashCode() { return _name == null ? 0 : _name.GetHashCode(); } } /// <summary> /// Value object to pass data between .Net methods during startup bypassing Java. /// </summary> private class Startup { /// <summary> /// Constructor. /// </summary> /// <param name="cfg">Configuration.</param> /// <param name="cbs"></param> internal Startup(IgniteConfiguration cfg, UnmanagedCallbacks cbs) { Configuration = cfg; Callbacks = cbs; } /// <summary> /// Configuration. /// </summary> internal IgniteConfiguration Configuration { get; private set; } /// <summary> /// Gets unmanaged callbacks. /// </summary> internal UnmanagedCallbacks Callbacks { get; private set; } /// <summary> /// Lifecycle handlers. /// </summary> internal IList<LifecycleHandlerHolder> LifecycleHandlers { get; set; } /// <summary> /// Node name. /// </summary> internal string Name { get; set; } /// <summary> /// Marshaller. /// </summary> internal Marshaller Marshaller { get; set; } /// <summary> /// Start error. /// </summary> internal Exception Error { get; set; } /// <summary> /// Gets or sets the ignite. /// </summary> internal Ignite Ignite { get; set; } } /// <summary> /// Internal handler for event notification. /// </summary> private class InternalLifecycleHandler : ILifecycleHandler { /** */ #pragma warning disable 649 // unused field [InstanceResource] private readonly IIgnite _ignite; /** <inheritdoc /> */ public void OnLifecycleEvent(LifecycleEventType evt) { if (evt == LifecycleEventType.BeforeNodeStop && _ignite != null) ((Ignite) _ignite).BeforeNodeStop(); } } } }
#if !UNITY_WINRT || UNITY_EDITOR || (UNITY_WP8 && !UNITY_WP_8_1) #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json.Utilities; using System.Collections; using System.Globalization; namespace Newtonsoft.Json.Linq { /// <summary> /// Contains the LINQ to JSON extension methods. /// </summary> public static class LinqExtensions { /// <summary> /// Returns a collection of tokens that contains the ancestors of every token in the source collection. /// </summary> /// <typeparam name="T">The type of the objects in source, constrained to <see cref="JToken"/>.</typeparam> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the ancestors of every node in the source collection.</returns> public static IJEnumerable<JToken> Ancestors<T>(this IEnumerable<T> source) where T : JToken { ValidationUtils.ArgumentNotNull(source, "source"); return source.SelectMany(j => j.Ancestors()).AsJEnumerable(); } //public static IEnumerable<JObject> AncestorsAndSelf<T>(this IEnumerable<T> source) where T : JObject //{ // ValidationUtils.ArgumentNotNull(source, "source"); // return source.SelectMany(j => j.AncestorsAndSelf()); //} /// <summary> /// Returns a collection of tokens that contains the descendants of every token in the source collection. /// </summary> /// <typeparam name="T">The type of the objects in source, constrained to <see cref="JContainer"/>.</typeparam> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the descendants of every node in the source collection.</returns> public static IJEnumerable<JToken> Descendants<T>(this IEnumerable<T> source) where T : JContainer { ValidationUtils.ArgumentNotNull(source, "source"); return source.SelectMany(j => j.Descendants()).AsJEnumerable(); } //TODO //public static IEnumerable<JObject> DescendantsAndSelf<T>(this IEnumerable<T> source) where T : JContainer //{ // ValidationUtils.ArgumentNotNull(source, "source"); // return source.SelectMany(j => j.DescendantsAndSelf()); //} /// <summary> /// Returns a collection of child properties of every object in the source collection. /// </summary> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JObject"/> that contains the source collection.</param> /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JProperty"/> that contains the properties of every object in the source collection.</returns> public static IJEnumerable<JProperty> Properties(this IEnumerable<JObject> source) { ValidationUtils.ArgumentNotNull(source, "source"); return source.SelectMany(d => d.Properties()).AsJEnumerable(); } /// <summary> /// Returns a collection of child values of every object in the source collection with the given key. /// </summary> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <param name="key">The token key.</param> /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the values of every node in the source collection with the given key.</returns> public static IJEnumerable<JToken> Values(this IEnumerable<JToken> source, object key) { return Values<JToken, JToken>(source, key).AsJEnumerable(); } /// <summary> /// Returns a collection of child values of every object in the source collection. /// </summary> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the values of every node in the source collection.</returns> public static IJEnumerable<JToken> Values(this IEnumerable<JToken> source) { return source.Values(null); } /// <summary> /// Returns a collection of converted child values of every object in the source collection with the given key. /// </summary> /// <typeparam name="U">The type to convert the values to.</typeparam> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <param name="key">The token key.</param> /// <returns>An <see cref="IEnumerable{T}"/> that contains the converted values of every node in the source collection with the given key.</returns> public static IEnumerable<U> Values<U>(this IEnumerable<JToken> source, object key) { return Values<JToken, U>(source, key); } /// <summary> /// Returns a collection of converted child values of every object in the source collection. /// </summary> /// <typeparam name="U">The type to convert the values to.</typeparam> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <returns>An <see cref="IEnumerable{T}"/> that contains the converted values of every node in the source collection.</returns> public static IEnumerable<U> Values<U>(this IEnumerable<JToken> source) { return Values<JToken, U>(source, null); } /// <summary> /// Converts the value. /// </summary> /// <typeparam name="U">The type to convert the value to.</typeparam> /// <param name="value">A <see cref="JToken"/> cast as a <see cref="IEnumerable{T}"/> of <see cref="JToken"/>.</param> /// <returns>A converted value.</returns> public static U Value<U>(this IEnumerable<JToken> value) { return value.Value<JToken, U>(); } /// <summary> /// Converts the value. /// </summary> /// <typeparam name="T">The source collection type.</typeparam> /// <typeparam name="U">The type to convert the value to.</typeparam> /// <param name="value">A <see cref="JToken"/> cast as a <see cref="IEnumerable{T}"/> of <see cref="JToken"/>.</param> /// <returns>A converted value.</returns> public static U Value<T, U>(this IEnumerable<T> value) where T : JToken { ValidationUtils.ArgumentNotNull(value, "source"); JToken token = value as JToken; if (token == null) throw new ArgumentException("Source value must be a JToken."); return token.Convert<JToken, U>(); } internal static IEnumerable<U> Values<T, U>(this IEnumerable<T> source, object key) where T : JToken { ValidationUtils.ArgumentNotNull(source, "source"); foreach (JToken token in source) { if (key == null) { if (token is JValue) { yield return Convert<JValue, U>((JValue)token); } else { foreach (JToken t in token.Children()) { yield return t.Convert<JToken, U>(); ; } } } else { JToken value = token[key]; if (value != null) yield return value.Convert<JToken, U>(); } } yield break; } //TODO //public static IEnumerable<T> InDocumentOrder<T>(this IEnumerable<T> source) where T : JObject; //public static IEnumerable<JToken> Children<T>(this IEnumerable<T> source) where T : JToken //{ // ValidationUtils.ArgumentNotNull(source, "source"); // return source.SelectMany(c => c.Children()); //} /// <summary> /// Returns a collection of child tokens of every array in the source collection. /// </summary> /// <typeparam name="T">The source collection type.</typeparam> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the values of every node in the source collection.</returns> public static IJEnumerable<JToken> Children<T>(this IEnumerable<T> source) where T : JToken { return Children<T, JToken>(source).AsJEnumerable(); } /// <summary> /// Returns a collection of converted child tokens of every array in the source collection. /// </summary> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <typeparam name="U">The type to convert the values to.</typeparam> /// <typeparam name="T">The source collection type.</typeparam> /// <returns>An <see cref="IEnumerable{T}"/> that contains the converted values of every node in the source collection.</returns> public static IEnumerable<U> Children<T, U>(this IEnumerable<T> source) where T : JToken { ValidationUtils.ArgumentNotNull(source, "source"); return source.SelectMany(c => c.Children()).Convert<JToken, U>(); } internal static IEnumerable<U> Convert<T, U>(this IEnumerable<T> source) where T : JToken { ValidationUtils.ArgumentNotNull(source, "source"); foreach (JToken token in source) { yield return Convert<JToken, U>(token); } } internal static U Convert<T, U>(this T token) where T : JToken { if (token == null) return default(U); if (token is U // don't want to cast JValue to its interfaces, want to get the internal value && typeof(U) != typeof(IComparable) && typeof(U) != typeof(IFormattable)) { // HACK return (U)(object)token; } else { JValue value = token as JValue; if (value == null) throw new InvalidCastException("Cannot cast {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, token.GetType(), typeof(T))); if (value.Value is U) return (U)value.Value; Type targetType = typeof(U); if (ReflectionUtils.IsNullableType(targetType)) { if (value.Value == null) return default(U); targetType = Nullable.GetUnderlyingType(targetType); } return (U)System.Convert.ChangeType(value.Value, targetType, CultureInfo.InvariantCulture); } } //public static void Remove<T>(this IEnumerable<T> source) where T : JContainer; /// <summary> /// Returns the input typed as <see cref="IJEnumerable{T}"/>. /// </summary> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <returns>The input typed as <see cref="IJEnumerable{T}"/>.</returns> public static IJEnumerable<JToken> AsJEnumerable(this IEnumerable<JToken> source) { return source.AsJEnumerable<JToken>(); } /// <summary> /// Returns the input typed as <see cref="IJEnumerable{T}"/>. /// </summary> /// <typeparam name="T">The source collection type.</typeparam> /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param> /// <returns>The input typed as <see cref="IJEnumerable{T}"/>.</returns> public static IJEnumerable<T> AsJEnumerable<T>(this IEnumerable<T> source) where T : JToken { if (source == null) return null; else if (source is IJEnumerable<T>) return (IJEnumerable<T>)source; else return new JEnumerable<T>(source); } } } #endif
using System; using System.Text; using WalletWasabi.BitcoinCore.Configuration; using Xunit; namespace WalletWasabi.Tests.UnitTests.BitcoinCore { public class ConfigTests { [Fact] public void RemovesEmptyDuplications() { var configStringBuilder = new StringBuilder("foo=bar"); configStringBuilder.Append(Environment.NewLine); configStringBuilder.Append(Environment.NewLine); configStringBuilder.Append(Environment.NewLine); configStringBuilder.Append("bar=bar"); var config = new CoreConfig(); config.AddOrUpdate(configStringBuilder.ToString()); var expectedConfig = @"foo = bar bar = bar "; Assert.Equal(expectedConfig, config.ToString()); } [Fact] public void CanParse() { var testConfig = @"foo=buz foo = bar"; testConfig += Environment.NewLine; testConfig += Environment.NewLine; testConfig += Environment.NewLine; testConfig += @" foo = bar foo bar = buz quxx too =1 foo bar #qoo=boo"; var coreConfig = new CoreConfig(); coreConfig.AddOrUpdate(testConfig); var expectedConfig = @"foo = bar foo bar = buz quxx too = 1 foo bar #qoo=boo "; Assert.Equal(expectedConfig, coreConfig.ToString()); var configDic = coreConfig.ToDictionary(); Assert.True(configDic.TryGetValue("foo", out var v1)); Assert.True(configDic.TryGetValue("too", out var v2)); Assert.False(configDic.TryGetValue("qoo", out _)); Assert.False(configDic.TryGetValue("bar", out _)); Assert.True(configDic.TryGetValue("foo bar", out var v3)); Assert.Equal("bar", v1); Assert.Equal("1", v2); Assert.Equal("buz quxx", v3); var coreConfig2 = new CoreConfig(); coreConfig2.AddOrUpdate(testConfig); var configDic2 = coreConfig2.ToDictionary(); Assert.True(configDic2.TryGetValue("foo", out var v1_2)); Assert.True(configDic2.TryGetValue("too", out var v2_2)); Assert.False(configDic2.TryGetValue("qoo", out _)); Assert.False(configDic2.TryGetValue("bar", out _)); Assert.True(configDic2.TryGetValue("foo bar", out var v3_3)); Assert.Equal("bar", v1_2); Assert.Equal("1", v2_2); Assert.Equal("buz quxx", v3_3); var add1 = "moo=1"; var add2 = "foo=bar"; var add3 = "too=0"; coreConfig.AddOrUpdate(add1); coreConfig2.AddOrUpdate(add1); coreConfig.AddOrUpdate(add2); coreConfig2.AddOrUpdate(add2); coreConfig.AddOrUpdate(add3); coreConfig2.AddOrUpdate(add3); configDic = coreConfig.ToDictionary(); configDic2 = coreConfig2.ToDictionary(); Assert.True(configDic.TryGetValue("moo", out var mooValue)); Assert.True(configDic.TryGetValue("foo", out var fooValue)); Assert.True(configDic.TryGetValue("too", out var tooValue)); Assert.Equal("1", mooValue); Assert.Equal("bar", fooValue); Assert.Equal("0", tooValue); Assert.True(configDic2.TryGetValue("moo", out mooValue)); Assert.True(configDic2.TryGetValue("foo", out fooValue)); Assert.True(configDic2.TryGetValue("too", out tooValue)); Assert.Equal("1", mooValue); Assert.Equal("bar", fooValue); Assert.Equal("0", tooValue); expectedConfig = @"foo = bar foo bar = buz quxx foo bar #qoo=boo moo = 1 too = 0 "; Assert.Equal(expectedConfig, coreConfig.ToString()); var expectedConfig2 = @"foo = bar foo bar = buz quxx foo bar #qoo=boo moo = 1 too = 0 "; Assert.Equal(expectedConfig2, coreConfig2.ToString()); } [Fact] public void KeepsOrder() { var testConfig = @"foo=bar buz=qux"; var coreConfig = new CoreConfig(); coreConfig.AddOrUpdate(testConfig); var expectedConfig = @"foo = bar buz = qux "; Assert.Equal(expectedConfig, coreConfig.ToString()); var add1 = "foo=bar"; coreConfig.AddOrUpdate(add1); Assert.Equal(expectedConfig, coreConfig.ToString()); } [Fact] public void HandlesSections() { var testConfig = @"qux=1 [main] foo=1 bar=1 [test] foo=2 bar=2 [regtest] foo=3 bar=4 [main] buz=1 test.buz=2"; var coreConfig = new CoreConfig(); coreConfig.AddOrUpdate(testConfig); var expectedConfig = @"qux = 1 main.foo = 1 main.bar = 1 test.foo = 2 test.bar = 2 regtest.foo = 3 regtest.bar = 4 main.buz = 1 test.buz = 2 "; Assert.Equal(expectedConfig, coreConfig.ToString()); } } }
using System; using System.Collections.Generic; using System.Xml; namespace SIL.Xml { public class XmlHelpers { public static void AddOrUpdateAttribute(XmlNode node, string attributeName, string value) { AddOrUpdateAttribute(node, attributeName, value, null); } public static void AddOrUpdateAttribute(XmlNode node, string attributeName, string value, IComparer<XmlNode> nodeOrderComparer) { XmlNode attr = node.Attributes.GetNamedItem(attributeName); if (attr == null) { attr = GetDocument(node).CreateAttribute(attributeName); if (nodeOrderComparer == null) { node.Attributes.SetNamedItem(attr); } else { InsertNodeUsingDefinedOrder(node, attr, nodeOrderComparer); } } attr.Value = value; } public static XmlNode GetOrCreateElement(XmlNode node, string xpathNotIncludingElement, string elementName, string nameSpace, XmlNamespaceManager nameSpaceManager) { return GetOrCreateElement(node, xpathNotIncludingElement, elementName, nameSpace, nameSpaceManager, null); } public static XmlNode GetOrCreateElement(XmlNode node, string xpathNotIncludingElement, string elementName, string nameSpace, XmlNamespaceManager nameSpaceManager, IComparer<XmlNode> nodeOrderComparer) { //enhance: if the parent path isn't found, strip of the last piece and recurse, //so that the path will always be created if needed. XmlNode parentNode = node.SelectSingleNode(xpathNotIncludingElement,nameSpaceManager); if (parentNode == null) { throw new ApplicationException(string.Format("The path {0} could not be found", xpathNotIncludingElement)); } string prefix = ""; if (!String.IsNullOrEmpty(nameSpace)) { prefix = nameSpace + ":"; } XmlNode n = parentNode.SelectSingleNode(prefix+elementName,nameSpaceManager); if (n == null) { if (!String.IsNullOrEmpty(nameSpace)) { n = GetDocument(node).CreateElement(nameSpace, elementName, nameSpaceManager.LookupNamespace(nameSpace)); } else { n = GetDocument(node).CreateElement(elementName); } if (nodeOrderComparer == null) { parentNode.AppendChild(n); } else { XmlNode insertAfterNode = null; foreach (XmlNode childNode in parentNode.ChildNodes) { if (childNode.NodeType != XmlNodeType.Element) { continue; } if (nodeOrderComparer.Compare(n, childNode) < 0) { break; } insertAfterNode = childNode; } parentNode.InsertAfter(n, insertAfterNode); } } return n; } public static void RemoveElement(XmlNode node, string xpath, XmlNamespaceManager nameSpaceManager) { XmlNode found = node.SelectSingleNode(xpath, nameSpaceManager); if (found != null) { found.ParentNode.RemoveChild(found); } } private static XmlDocument GetDocument(XmlNode nodeOrDoc) { if (nodeOrDoc is XmlDocument) { return (XmlDocument)nodeOrDoc; } else { return nodeOrDoc.OwnerDocument; } } /// <summary> /// Get an optional attribute value from an XmlNode. /// </summary> /// <param name="node">The XmlNode to look in.</param> /// <param name="attrName">The attribute to find.</param> /// <param name="defaultValue"></param> /// <returns>The value of the attribute, or the default value, if the attribute dismissing</returns> public static bool GetOptionalBooleanAttributeValue(XmlNode node, string attrName, bool defaultValue) { return GetBooleanAttributeValue(GetOptionalAttributeValue(node, attrName, defaultValue ? "true" : "false")); } /// <summary> /// Returns true if value of attrName is 'true' or 'yes' (case ignored) /// </summary> /// <param name="node">The XmlNode to look in.</param> /// <param name="attrName">The optional attribute to find.</param> /// <returns></returns> public static bool GetBooleanAttributeValue(XmlNode node, string attrName) { return GetBooleanAttributeValue(GetOptionalAttributeValue(node, attrName)); } /// <summary> /// Returns true if sValue is 'true' or 'yes' (case ignored) /// </summary> public static bool GetBooleanAttributeValue(string sValue) { return (sValue != null && (sValue.ToLower().Equals("true") || sValue.ToLower().Equals("yes"))); } /// <summary> /// Deprecated: use GetOptionalAttributeValue instead. /// </summary> /// <param name="node"></param> /// <param name="attrName"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static string GetAttributeValue(XmlNode node, string attrName, string defaultValue) { return GetOptionalAttributeValue(node, attrName, defaultValue); } /// <summary> /// Get an optional attribute value from an XmlNode. /// </summary> /// <param name="node">The XmlNode to look in.</param> /// <param name="attrName">The attribute to find.</param> /// <returns>The value of the attribute, or null, if not found.</returns> public static string GetAttributeValue(XmlNode node, string attrName) { return GetOptionalAttributeValue(node, attrName); } /// <summary> /// Get an optional attribute value from an XmlNode. /// </summary> /// <param name="node">The XmlNode to look in.</param> /// <param name="attrName">The attribute to find.</param> /// <returns>The value of the attribute, or null, if not found.</returns> public static string GetOptionalAttributeValue(XmlNode node, string attrName) { return GetOptionalAttributeValue(node, attrName, null); } /// <summary> /// Get an optional attribute value from an XmlNode. /// </summary> /// <param name="node">The XmlNode to look in.</param> /// <param name="attrName">The attribute to find.</param> /// <param name="defaultString">value to return when optional attribute not specified</param> /// <returns>The value of the attribute, or null, if not found.</returns> public static string GetOptionalAttributeValue(XmlNode node, string attrName, string defaultString) { if (node != null && node.Attributes != null) { XmlAttribute xa = node.Attributes[attrName]; if (xa != null) return xa.Value; } return defaultString; } public static void InsertNodeUsingDefinedOrder(XmlNode parent, XmlNode newChild, IComparer<XmlNode> nodeOrderComparer) { if (newChild.NodeType == XmlNodeType.Attribute) { XmlAttribute insertAfterNode = null; foreach (XmlAttribute childNode in parent.Attributes) { if (nodeOrderComparer.Compare(newChild, childNode) < 0) { break; } insertAfterNode = childNode; } parent.Attributes.InsertAfter((XmlAttribute)newChild, insertAfterNode); } else { XmlNode insertAfterNode = null; foreach (XmlNode childNode in parent.ChildNodes) { if (nodeOrderComparer.Compare(newChild, childNode) < 0) { break; } insertAfterNode = childNode; } parent.InsertAfter(newChild, insertAfterNode); } } public static bool FindNextElementInSequence(XmlReader reader, string name, Comparison<string> comparison) { while (!reader.EOF && reader.NodeType != XmlNodeType.EndElement && (reader.NodeType != XmlNodeType.Element || comparison(name, reader.Name) > 0)) { switch (reader.NodeType) { case XmlNodeType.Attribute: case XmlNodeType.Element: reader.Skip(); break; default: reader.Read(); break; } } // Element name comparison returns the order of elements. It is possible that we passed where the element would have been without // finding it. So, use string comparison to determine whether we found it or not. return !reader.EOF && reader.NodeType == XmlNodeType.Element && name.Equals(reader.Name); } public static bool FindNextElementInSequence(XmlReader reader, string name, string nameSpace, Comparison<string> comparison) { while (FindNextElementInSequence(reader, name, comparison)) { if (reader.NamespaceURI == nameSpace) { return true; } reader.Skip(); } return false; } /// <summary> /// Finds and reads the EndElement with the specified name /// </summary> /// <param name="reader"></param> /// <param name="name"></param> /// REVIEW Hasso 2013.12: This method--and all of our XmlReader code, really--is fragile. Since we don't expect LDML files to be unwieldily /// large, we could afford to refactor all this using XElement, which would pay off in the long run. public static void ReadEndElement(XmlReader reader, string name) { while (!reader.EOF && (reader.NodeType != XmlNodeType.EndElement || !name.Equals(reader.Name))) { reader.Read(); } if (!reader.EOF) { reader.ReadEndElement(); } } } }
// 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 CultureInfo = System.Globalization.CultureInfo; using System.Security; using System.Security.Policy; using System.IO; using StringBuilder = System.Text.StringBuilder; using System.Configuration.Assemblies; using StackCrawlMark = System.Threading.StackCrawlMark; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Threading; using System.Diagnostics.Contracts; namespace System.Reflection { [Serializable] internal class RuntimeAssembly : Assembly { #if FEATURE_APPX // The highest byte is the flags and the lowest 3 bytes are // the cached ctor token of [DynamicallyInvocableAttribute]. private enum ASSEMBLY_FLAGS : uint { ASSEMBLY_FLAGS_UNKNOWN = 0x00000000, ASSEMBLY_FLAGS_INITIALIZED = 0x01000000, ASSEMBLY_FLAGS_FRAMEWORK = 0x02000000, ASSEMBLY_FLAGS_TOKEN_MASK = 0x00FFFFFF, } #endif // FEATURE_APPX private const uint COR_E_LOADING_REFERENCE_ASSEMBLY = 0x80131058U; internal RuntimeAssembly() { throw new NotSupportedException(); } #region private data members private event ModuleResolveEventHandler _ModuleResolve; private string m_fullname; private object m_syncRoot; // Used to keep collectible types alive and as the syncroot for reflection.emit private IntPtr m_assembly; // slack for ptr datum on unmanaged side #if FEATURE_APPX private ASSEMBLY_FLAGS m_flags; #endif #endregion #if FEATURE_APPX private ASSEMBLY_FLAGS Flags { get { if ((m_flags & ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_INITIALIZED) == 0) { ASSEMBLY_FLAGS flags = ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_UNKNOWN | ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_FRAMEWORK; m_flags = flags | ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_INITIALIZED; } return m_flags; } } #endif // FEATURE_APPX internal object SyncRoot { get { if (m_syncRoot == null) { Interlocked.CompareExchange<object>(ref m_syncRoot, new object(), null); } return m_syncRoot; } } public override event ModuleResolveEventHandler ModuleResolve { add { _ModuleResolve += value; } remove { _ModuleResolve -= value; } } private const String s_localFilePrefix = "file:"; [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetCodeBase(RuntimeAssembly assembly, bool copiedName, StringHandleOnStack retString); internal String GetCodeBase(bool copiedName) { String codeBase = null; GetCodeBase(GetNativeHandle(), copiedName, JitHelpers.GetStringHandleOnStack(ref codeBase)); return codeBase; } public override String CodeBase { get { String codeBase = GetCodeBase(false); return codeBase; } } internal RuntimeAssembly GetNativeHandle() { return this; } // If the assembly is copied before it is loaded, the codebase will be set to the // actual file loaded if copiedName is true. If it is false, then the original code base // is returned. public override AssemblyName GetName(bool copiedName) { AssemblyName an = new AssemblyName(); String codeBase = GetCodeBase(copiedName); an.Init(GetSimpleName(), GetPublicKey(), null, // public key token GetVersion(), GetLocale(), GetHashAlgorithm(), AssemblyVersionCompatibility.SameMachine, codeBase, GetFlags() | AssemblyNameFlags.PublicKey, null); // strong name key pair PortableExecutableKinds pek; ImageFileMachine ifm; Module manifestModule = ManifestModule; if (manifestModule != null) { if (manifestModule.MDStreamVersion > 0x10000) { ManifestModule.GetPEKind(out pek, out ifm); an.SetProcArchIndex(pek, ifm); } } return an; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetFullName(RuntimeAssembly assembly, StringHandleOnStack retString); public override String FullName { get { // If called by Object.ToString(), return val may be NULL. if (m_fullname == null) { string s = null; GetFullName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref s)); Interlocked.CompareExchange<string>(ref m_fullname, s, null); } return m_fullname; } } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetEntryPoint(RuntimeAssembly assembly, ObjectHandleOnStack retMethod); public override MethodInfo EntryPoint { get { IRuntimeMethodInfo methodHandle = null; GetEntryPoint(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref methodHandle)); if (methodHandle == null) return null; return (MethodInfo)RuntimeType.GetMethodBase(methodHandle); } } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetType(RuntimeAssembly assembly, String name, bool throwOnError, bool ignoreCase, ObjectHandleOnStack type, ObjectHandleOnStack keepAlive); public override Type GetType(String name, bool throwOnError, bool ignoreCase) { // throw on null strings regardless of the value of "throwOnError" if (name == null) throw new ArgumentNullException(nameof(name)); RuntimeType type = null; Object keepAlive = null; GetType(GetNativeHandle(), name, throwOnError, ignoreCase, JitHelpers.GetObjectHandleOnStack(ref type), JitHelpers.GetObjectHandleOnStack(ref keepAlive)); GC.KeepAlive(keepAlive); return type; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetExportedTypes(RuntimeAssembly assembly, ObjectHandleOnStack retTypes); public override Type[] GetExportedTypes() { Type[] types = null; GetExportedTypes(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref types)); return types; } public override IEnumerable<TypeInfo> DefinedTypes { get { List<RuntimeType> rtTypes = new List<RuntimeType>(); RuntimeModule[] modules = GetModulesInternal(true, false); for (int i = 0; i < modules.Length; i++) { rtTypes.AddRange(modules[i].GetDefinedTypes()); } return rtTypes.ToArray(); } } // Load a resource based on the NameSpace of the type. [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public override Stream GetManifestResourceStream(Type type, String name) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return GetManifestResourceStream(type, name, false, ref stackMark); } [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public override Stream GetManifestResourceStream(String name) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return GetManifestResourceStream(name, ref stackMark, false); } // ISerializable implementation public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); UnitySerializationHolder.GetUnitySerializationInfo(info, UnitySerializationHolder.AssemblyUnity, this.FullName, this); } public override Module ManifestModule { get { // We don't need to return the "external" ModuleBuilder because // it is meant to be read-only return RuntimeAssembly.GetManifestModule(GetNativeHandle()); } } public override Object[] GetCustomAttributes(bool inherit) { return CustomAttribute.GetCustomAttributes(this, typeof(object) as RuntimeType); } public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType); } public override bool IsDefined(Type attributeType, bool inherit) { if (attributeType == null) throw new ArgumentNullException(nameof(attributeType)); Contract.EndContractBlock(); RuntimeType attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType; if (attributeRuntimeType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType)); return CustomAttribute.IsDefined(this, attributeRuntimeType); } public override IList<CustomAttributeData> GetCustomAttributesData() { return CustomAttributeData.GetCustomAttributesInternal(this); } [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod internal static RuntimeAssembly InternalLoadFrom(String assemblyFile, Evidence securityEvidence, byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, bool forIntrospection, ref StackCrawlMark stackMark) { if (assemblyFile == null) throw new ArgumentNullException(nameof(assemblyFile)); Contract.EndContractBlock(); AssemblyName an = new AssemblyName(); an.CodeBase = assemblyFile; an.SetHashControl(hashValue, hashAlgorithm); // The stack mark is used for MDA filtering return InternalLoadAssemblyName(an, securityEvidence, null, ref stackMark, true /*thrownOnFileNotFound*/, forIntrospection); } // Wrapper function to wrap the typical use of InternalLoad. internal static RuntimeAssembly InternalLoad(String assemblyString, Evidence assemblySecurity, ref StackCrawlMark stackMark, bool forIntrospection) { return InternalLoad(assemblyString, assemblySecurity, ref stackMark, IntPtr.Zero, forIntrospection); } [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod internal static RuntimeAssembly InternalLoad(String assemblyString, Evidence assemblySecurity, ref StackCrawlMark stackMark, IntPtr pPrivHostBinder, bool forIntrospection) { RuntimeAssembly assembly; AssemblyName an = CreateAssemblyName(assemblyString, forIntrospection, out assembly); if (assembly != null) { // The assembly was returned from ResolveAssemblyEvent return assembly; } return InternalLoadAssemblyName(an, assemblySecurity, null, ref stackMark, pPrivHostBinder, true /*thrownOnFileNotFound*/, forIntrospection); } // Creates AssemblyName. Fills assembly if AssemblyResolve event has been raised. internal static AssemblyName CreateAssemblyName( String assemblyString, bool forIntrospection, out RuntimeAssembly assemblyFromResolveEvent) { if (assemblyString == null) throw new ArgumentNullException(nameof(assemblyString)); Contract.EndContractBlock(); if ((assemblyString.Length == 0) || (assemblyString[0] == '\0')) throw new ArgumentException(SR.Format_StringZeroLength); if (forIntrospection) AppDomain.CheckReflectionOnlyLoadSupported(); AssemblyName an = new AssemblyName(); an.Name = assemblyString; an.nInit(out assemblyFromResolveEvent, forIntrospection, true); return an; } // Wrapper function to wrap the typical use of InternalLoadAssemblyName. internal static RuntimeAssembly InternalLoadAssemblyName( AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, ref StackCrawlMark stackMark, bool throwOnFileNotFound, bool forIntrospection, IntPtr ptrLoadContextBinder = default(IntPtr)) { return InternalLoadAssemblyName(assemblyRef, assemblySecurity, reqAssembly, ref stackMark, IntPtr.Zero, true /*throwOnError*/, forIntrospection, ptrLoadContextBinder); } internal static RuntimeAssembly InternalLoadAssemblyName( AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, ref StackCrawlMark stackMark, IntPtr pPrivHostBinder, bool throwOnFileNotFound, bool forIntrospection, IntPtr ptrLoadContextBinder = default(IntPtr)) { if (assemblyRef == null) throw new ArgumentNullException(nameof(assemblyRef)); Contract.EndContractBlock(); if (assemblyRef.CodeBase != null) { AppDomain.CheckLoadFromSupported(); } assemblyRef = (AssemblyName)assemblyRef.Clone(); if (!forIntrospection && (assemblyRef.ProcessorArchitecture != ProcessorArchitecture.None)) { // PA does not have a semantics for by-name binds for execution assemblyRef.ProcessorArchitecture = ProcessorArchitecture.None; } String codeBase = VerifyCodeBase(assemblyRef.CodeBase); return nLoad(assemblyRef, codeBase, assemblySecurity, reqAssembly, ref stackMark, pPrivHostBinder, throwOnFileNotFound, forIntrospection, ptrLoadContextBinder); } // These are the framework assemblies that does reflection invocation // on behalf of user code. We allow framework code to invoke non-W8P // framework APIs but don't want user code to gain that privilege // through these assemblies. So we blaklist them. private static string[] s_unsafeFrameworkAssemblyNames = new string[] { "System.Reflection.Context", "Microsoft.VisualBasic" }; #if FEATURE_APPX internal bool IsFrameworkAssembly() { ASSEMBLY_FLAGS flags = Flags; return (flags & ASSEMBLY_FLAGS.ASSEMBLY_FLAGS_FRAMEWORK) != 0; } #endif [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern RuntimeAssembly _nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, ref StackCrawlMark stackMark, IntPtr pPrivHostBinder, bool throwOnFileNotFound, bool forIntrospection, bool suppressSecurityChecks, IntPtr ptrLoadContextBinder); private static RuntimeAssembly nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, ref StackCrawlMark stackMark, IntPtr pPrivHostBinder, bool throwOnFileNotFound, bool forIntrospection, IntPtr ptrLoadContextBinder = default(IntPtr)) { return _nLoad(fileName, codeBase, assemblySecurity, locationHint, ref stackMark, pPrivHostBinder, throwOnFileNotFound, forIntrospection, true /* suppressSecurityChecks */, ptrLoadContextBinder); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool IsReflectionOnly(RuntimeAssembly assembly); public override bool ReflectionOnly { get { return IsReflectionOnly(GetNativeHandle()); } } // Returns the module in this assembly with name 'name' [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetModule(RuntimeAssembly assembly, String name, ObjectHandleOnStack retModule); public override Module GetModule(String name) { Module retModule = null; GetModule(GetNativeHandle(), name, JitHelpers.GetObjectHandleOnStack(ref retModule)); return retModule; } // Returns the file in the File table of the manifest that matches the // given name. (Name should not include path.) public override FileStream GetFile(String name) { RuntimeModule m = (RuntimeModule)GetModule(name); if (m == null) return null; return new FileStream(m.GetFullyQualifiedName(), FileMode.Open, FileAccess.Read, FileShare.Read, FileStream.DefaultBufferSize, false); } public override FileStream[] GetFiles(bool getResourceModules) { Module[] m = GetModules(getResourceModules); FileStream[] fs = new FileStream[m.Length]; for (int i = 0; i < fs.Length; i++) { fs[i] = new FileStream(((RuntimeModule)m[i]).GetFullyQualifiedName(), FileMode.Open, FileAccess.Read, FileShare.Read, FileStream.DefaultBufferSize, false); } return fs; } // Returns the names of all the resources [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern String[] GetManifestResourceNames(RuntimeAssembly assembly); // Returns the names of all the resources public override String[] GetManifestResourceNames() { return GetManifestResourceNames(GetNativeHandle()); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetExecutingAssembly(StackCrawlMarkHandle stackMark, ObjectHandleOnStack retAssembly); internal static RuntimeAssembly GetExecutingAssembly(ref StackCrawlMark stackMark) { RuntimeAssembly retAssembly = null; GetExecutingAssembly(JitHelpers.GetStackCrawlMarkHandle(ref stackMark), JitHelpers.GetObjectHandleOnStack(ref retAssembly)); return retAssembly; } // Returns the names of all the resources [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern AssemblyName[] GetReferencedAssemblies(RuntimeAssembly assembly); public override AssemblyName[] GetReferencedAssemblies() { return GetReferencedAssemblies(GetNativeHandle()); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern int GetManifestResourceInfo(RuntimeAssembly assembly, String resourceName, ObjectHandleOnStack assemblyRef, StringHandleOnStack retFileName, StackCrawlMarkHandle stackMark); [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public override ManifestResourceInfo GetManifestResourceInfo(String resourceName) { RuntimeAssembly retAssembly = null; String fileName = null; StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; int location = GetManifestResourceInfo(GetNativeHandle(), resourceName, JitHelpers.GetObjectHandleOnStack(ref retAssembly), JitHelpers.GetStringHandleOnStack(ref fileName), JitHelpers.GetStackCrawlMarkHandle(ref stackMark)); if (location == -1) return null; return new ManifestResourceInfo(retAssembly, fileName, (ResourceLocation)location); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetLocation(RuntimeAssembly assembly, StringHandleOnStack retString); public override String Location { get { String location = null; GetLocation(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref location)); return location; } } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetImageRuntimeVersion(RuntimeAssembly assembly, StringHandleOnStack retString); public override String ImageRuntimeVersion { get { String s = null; GetImageRuntimeVersion(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref s)); return s; } } public override bool GlobalAssemblyCache { get { return false; } } public override Int64 HostContext { get { return 0; } } private static String VerifyCodeBase(String codebase) { if (codebase == null) return null; int len = codebase.Length; if (len == 0) return null; int j = codebase.IndexOf(':'); // Check to see if the url has a prefix if ((j != -1) && (j + 2 < len) && ((codebase[j + 1] == '/') || (codebase[j + 1] == '\\')) && ((codebase[j + 2] == '/') || (codebase[j + 2] == '\\'))) return codebase; #if PLATFORM_WINDOWS else if ((len > 2) && (codebase[0] == '\\') && (codebase[1] == '\\')) return "file://" + codebase; else return "file:///" + Path.GetFullPath(codebase); #else else return "file://" + Path.GetFullPath(codebase); #endif // PLATFORM_WINDOWS } internal Stream GetManifestResourceStream( Type type, String name, bool skipSecurityCheck, ref StackCrawlMark stackMark) { StringBuilder sb = new StringBuilder(); if (type == null) { if (name == null) throw new ArgumentNullException(nameof(type)); } else { String nameSpace = type.Namespace; if (nameSpace != null) { sb.Append(nameSpace); if (name != null) sb.Append(Type.Delimiter); } } if (name != null) sb.Append(name); return GetManifestResourceStream(sb.ToString(), ref stackMark, skipSecurityCheck); } // GetResource will return a pointer to the resources in memory. [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static unsafe extern byte* GetResource(RuntimeAssembly assembly, String resourceName, out ulong length, StackCrawlMarkHandle stackMark, bool skipSecurityCheck); internal unsafe Stream GetManifestResourceStream(String name, ref StackCrawlMark stackMark, bool skipSecurityCheck) { ulong length = 0; byte* pbInMemoryResource = GetResource(GetNativeHandle(), name, out length, JitHelpers.GetStackCrawlMarkHandle(ref stackMark), skipSecurityCheck); if (pbInMemoryResource != null) { //Console.WriteLine("Creating an unmanaged memory stream of length "+length); if (length > Int64.MaxValue) throw new NotImplementedException(SR.NotImplemented_ResourcesLongerThanInt64Max); return new UnmanagedMemoryStream(pbInMemoryResource, (long)length, (long)length, FileAccess.Read); } //Console.WriteLine("GetManifestResourceStream: Blob "+name+" not found..."); return null; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetVersion(RuntimeAssembly assembly, out int majVer, out int minVer, out int buildNum, out int revNum); internal Version GetVersion() { int majorVer, minorVer, build, revision; GetVersion(GetNativeHandle(), out majorVer, out minorVer, out build, out revision); return new Version(majorVer, minorVer, build, revision); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetLocale(RuntimeAssembly assembly, StringHandleOnStack retString); internal CultureInfo GetLocale() { String locale = null; GetLocale(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref locale)); if (locale == null) return CultureInfo.InvariantCulture; return new CultureInfo(locale); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool FCallIsDynamic(RuntimeAssembly assembly); public override bool IsDynamic { get { return FCallIsDynamic(GetNativeHandle()); } } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetSimpleName(RuntimeAssembly assembly, StringHandleOnStack retSimpleName); internal String GetSimpleName() { string name = null; GetSimpleName(GetNativeHandle(), JitHelpers.GetStringHandleOnStack(ref name)); return name; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static AssemblyHashAlgorithm GetHashAlgorithm(RuntimeAssembly assembly); private AssemblyHashAlgorithm GetHashAlgorithm() { return GetHashAlgorithm(GetNativeHandle()); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static AssemblyNameFlags GetFlags(RuntimeAssembly assembly); private AssemblyNameFlags GetFlags() { return GetFlags(GetNativeHandle()); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern void GetPublicKey(RuntimeAssembly assembly, ObjectHandleOnStack retPublicKey); internal byte[] GetPublicKey() { byte[] publicKey = null; GetPublicKey(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref publicKey)); return publicKey; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private extern static bool IsAllSecurityTransparent(RuntimeAssembly assembly); // Is everything introduced by this assembly transparent internal bool IsAllSecurityTransparent() { return IsAllSecurityTransparent(GetNativeHandle()); } // This method is called by the VM. private RuntimeModule OnModuleResolveEvent(String moduleName) { ModuleResolveEventHandler moduleResolve = _ModuleResolve; if (moduleResolve == null) return null; Delegate[] ds = moduleResolve.GetInvocationList(); int len = ds.Length; for (int i = 0; i < len; i++) { RuntimeModule ret = (RuntimeModule)((ModuleResolveEventHandler)ds[i])(this, new ResolveEventArgs(moduleName, this)); if (ret != null) return ret; } return null; } [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public override Assembly GetSatelliteAssembly(CultureInfo culture) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return InternalGetSatelliteAssembly(culture, null, ref stackMark); } // Useful for binding to a very specific version of a satellite assembly [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod public override Assembly GetSatelliteAssembly(CultureInfo culture, Version version) { StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; return InternalGetSatelliteAssembly(culture, version, ref stackMark); } [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod internal Assembly InternalGetSatelliteAssembly(CultureInfo culture, Version version, ref StackCrawlMark stackMark) { if (culture == null) throw new ArgumentNullException(nameof(culture)); Contract.EndContractBlock(); String name = GetSimpleName() + ".resources"; return InternalGetSatelliteAssembly(name, culture, version, true, ref stackMark); } [System.Security.DynamicSecurityMethod] // Methods containing StackCrawlMark local var has to be marked DynamicSecurityMethod internal RuntimeAssembly InternalGetSatelliteAssembly(String name, CultureInfo culture, Version version, bool throwOnFileNotFound, ref StackCrawlMark stackMark) { AssemblyName an = new AssemblyName(); an.SetPublicKey(GetPublicKey()); an.Flags = GetFlags() | AssemblyNameFlags.PublicKey; if (version == null) an.Version = GetVersion(); else an.Version = version; an.CultureInfo = culture; an.Name = name; RuntimeAssembly retAssembly = nLoad(an, null, null, this, ref stackMark, IntPtr.Zero, throwOnFileNotFound, false); if (retAssembly == this || (retAssembly == null && throwOnFileNotFound)) { throw new FileNotFoundException(String.Format(culture, SR.IO_FileNotFound_FileName, an.Name)); } return retAssembly; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetModules(RuntimeAssembly assembly, bool loadIfNotFound, bool getResourceModules, ObjectHandleOnStack retModuleHandles); private RuntimeModule[] GetModulesInternal(bool loadIfNotFound, bool getResourceModules) { RuntimeModule[] modules = null; GetModules(GetNativeHandle(), loadIfNotFound, getResourceModules, JitHelpers.GetObjectHandleOnStack(ref modules)); return modules; } public override Module[] GetModules(bool getResourceModules) { return GetModulesInternal(true, getResourceModules); } public override Module[] GetLoadedModules(bool getResourceModules) { return GetModulesInternal(false, getResourceModules); } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern RuntimeModule GetManifestModule(RuntimeAssembly assembly); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern int GetToken(RuntimeAssembly assembly); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.returnType.properties.property001.property001 { public class Test { private class MyClass { public dynamic Foo { get { dynamic d = new object(); return d; } } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { MyClass mc = new MyClass(); dynamic d = mc.Foo; if (d != null) return 0; return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.returnType.properties.property002.property002 { public class Test { private class MyClass { public static dynamic Foo { get { dynamic d = new object(); return d; } } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = MyClass.Foo; if (d != null) return 0; return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.returnType.properties.property003.property003 { public class Test { private class MyClass<T> { public static dynamic Foo { get { dynamic d = default(T); return d; } } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = MyClass<float>.Foo; if ((float)d != 0f) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.returnType.properties.property004.property004 { public class Test { private class MyClass<T> { public dynamic Foo { get { dynamic d = default(T); return d; } } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { MyClass<decimal> mc = new MyClass<decimal>(); dynamic d = mc.Foo; if ((decimal)d == 0m) return 0; return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.returnType.properties.property005.property005 { public class Test { private class MyClass<T> { public int x; public dynamic Foo { set { x = (int)value; } } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { MyClass<decimal> mc = new MyClass<decimal>(); mc.Foo = 3; if (mc.x != 3) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.returnType.properties.property006.property006 { public class Test { private class MyClass<T> { public static float f; public static dynamic Foo { get { return f; } set { f = (float)value; } } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = 3f; MyClass<float>.Foo = d; if (MyClass<float>.f != 3f) return 1; d = MyClass<float>.Foo; if ((float)d != 3f) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.returnType.properties.property007.property007 { public class Test { private class MyClass { public decimal dec; public dynamic Foo { get { return dec; } set { dec = value; } } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { MyClass mc = new MyClass(); dynamic d = 3m; mc.Foo = d; if (mc.dec != 3m) return 1; d = mc.Foo; if ((decimal)d != 3m) return 1; return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.returnType.properties.property008.property008 { public class Test { private class MyClass { public static string s; public static dynamic Foo { get { return s; } set { s = value; } } } [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic dd = "string"; MyClass.Foo = dd; if (MyClass.s != "string") return 1; dynamic d = MyClass.Foo; if (d != "string") return 1; return 0; } } // </Code> }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** ** ** Purpose: Managed ACL wrapper for Win32 mutexes. ** ** ===========================================================*/ using System; using System.Collections; using System.Security.Principal; using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System.Runtime.InteropServices; using System.Threading; namespace System.Security.AccessControl { // Derive this list of values from winnt.h and MSDN docs: // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/synchronization_object_security_and_access_rights.asp // In order to call ReleaseMutex, you must have an ACL granting you // MUTEX_MODIFY_STATE rights (0x0001). The other interesting value // in a Mutex's ACL is MUTEX_ALL_ACCESS (0x1F0001). // You need SYNCHRONIZE to be able to open a handle to a mutex. [Flags] public enum MutexRights { Modify = 0x000001, Delete = 0x010000, ReadPermissions = 0x020000, ChangePermissions = 0x040000, TakeOwnership = 0x080000, Synchronize = 0x100000, // SYNCHRONIZE FullControl = 0x1F0001 } public sealed class MutexAccessRule : AccessRule { // Constructor for creating access rules for registry objects public MutexAccessRule(IdentityReference identity, MutexRights eventRights, AccessControlType type) : this(identity, (int)eventRights, false, InheritanceFlags.None, PropagationFlags.None, type) { } public MutexAccessRule(String identity, MutexRights eventRights, AccessControlType type) : this(new NTAccount(identity), (int)eventRights, false, InheritanceFlags.None, PropagationFlags.None, type) { } // // Internal constructor to be called by public constructors // and the access rule factory methods of {File|Folder}Security // internal MutexAccessRule( IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) : base( identity, accessMask, isInherited, inheritanceFlags, propagationFlags, type) { } public MutexRights MutexRights { get { return (MutexRights)base.AccessMask; } } } public sealed class MutexAuditRule : AuditRule { public MutexAuditRule(IdentityReference identity, MutexRights eventRights, AuditFlags flags) : this(identity, (int)eventRights, false, InheritanceFlags.None, PropagationFlags.None, flags) { } /* // Not in the spec public MutexAuditRule(string identity, MutexRights eventRights, AuditFlags flags) : this(new NTAccount(identity), (int) eventRights, false, InheritanceFlags.None, PropagationFlags.None, flags) { } */ internal MutexAuditRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) : base(identity, accessMask, isInherited, inheritanceFlags, propagationFlags, flags) { } public MutexRights MutexRights { get { return (MutexRights)base.AccessMask; } } } public sealed class MutexSecurity : NativeObjectSecurity { public MutexSecurity() : base(true, ResourceType.KernelObject) { } [System.Security.SecuritySafeCritical] // auto-generated public MutexSecurity(String name, AccessControlSections includeSections) : base(true, ResourceType.KernelObject, name, includeSections, _HandleErrorCode, null) { // Let the underlying ACL API's demand unmanaged code permission. } [System.Security.SecurityCritical] // auto-generated internal MutexSecurity(SafeWaitHandle handle, AccessControlSections includeSections) : base(true, ResourceType.KernelObject, handle, includeSections, _HandleErrorCode, null) { // Let the underlying ACL API's demand unmanaged code permission. } [System.Security.SecurityCritical] // auto-generated private static Exception _HandleErrorCode(int errorCode, string name, SafeHandle handle, object context) { System.Exception exception = null; switch (errorCode) { case Interop.Errors.ERROR_INVALID_NAME: case Interop.Errors.ERROR_INVALID_HANDLE: case Interop.Errors.ERROR_FILE_NOT_FOUND: if ((name != null) && (name.Length != 0)) exception = new WaitHandleCannotBeOpenedException(SR.Format(SR.WaitHandleCannotBeOpenedException_InvalidHandle, name)); else exception = new WaitHandleCannotBeOpenedException(); break; default: break; } return exception; } public override AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) { return new MutexAccessRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, type); } public override AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) { return new MutexAuditRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, flags); } internal AccessControlSections GetAccessControlSectionsFromChanges() { AccessControlSections persistRules = AccessControlSections.None; if (AccessRulesModified) persistRules = AccessControlSections.Access; if (AuditRulesModified) persistRules |= AccessControlSections.Audit; if (OwnerModified) persistRules |= AccessControlSections.Owner; if (GroupModified) persistRules |= AccessControlSections.Group; return persistRules; } [System.Security.SecurityCritical] // auto-generated internal void Persist(SafeWaitHandle handle) { // Let the underlying ACL API's demand unmanaged code. WriteLock(); try { AccessControlSections persistSections = GetAccessControlSectionsFromChanges(); if (persistSections == AccessControlSections.None) return; // Don't need to persist anything. base.Persist(handle, persistSections); OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false; } finally { WriteUnlock(); } } public void AddAccessRule(MutexAccessRule rule) { base.AddAccessRule(rule); } public void SetAccessRule(MutexAccessRule rule) { base.SetAccessRule(rule); } public void ResetAccessRule(MutexAccessRule rule) { base.ResetAccessRule(rule); } public bool RemoveAccessRule(MutexAccessRule rule) { return base.RemoveAccessRule(rule); } public void RemoveAccessRuleAll(MutexAccessRule rule) { base.RemoveAccessRuleAll(rule); } public void RemoveAccessRuleSpecific(MutexAccessRule rule) { base.RemoveAccessRuleSpecific(rule); } public void AddAuditRule(MutexAuditRule rule) { base.AddAuditRule(rule); } public void SetAuditRule(MutexAuditRule rule) { base.SetAuditRule(rule); } public bool RemoveAuditRule(MutexAuditRule rule) { return base.RemoveAuditRule(rule); } public void RemoveAuditRuleAll(MutexAuditRule rule) { base.RemoveAuditRuleAll(rule); } public void RemoveAuditRuleSpecific(MutexAuditRule rule) { base.RemoveAuditRuleSpecific(rule); } public override Type AccessRightType { get { return typeof(MutexRights); } } public override Type AccessRuleType { get { return typeof(MutexAccessRule); } } public override Type AuditRuleType { get { return typeof(MutexAuditRule); } } } }
// // Body.cs // // Author: // Zachary Gramana <zack@xamarin.com> // // Copyright (c) 2014 Xamarin Inc // Copyright (c) 2014 .NET Foundation // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // Copyright (c) 2014 Couchbase, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. // using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using Sharpen; namespace Couchbase.Lite { /// <summary> /// A request/response/document body, stored as either JSON, IDictionary&gt;String,Object&gt;, or IList&gt;object&gt; /// </summary> public sealed class Body { #region Variables private IEnumerable<byte> _json; private object _jsonObject; #endregion #region Constructors /// <summary> /// Constructor /// </summary> /// <param name="json">An enumerable collection of bytes storing JSON</param> public Body(IEnumerable<Byte> json) { _json = json; } /// <summary> /// Constructor /// </summary> /// <param name="properties">An IDictionary containing the properties and objects to serialize</param> public Body(IDictionary<string, object> properties) { _jsonObject = properties; } /// <summary> /// Constructor /// </summary> /// <param name="array">An IList containing a list of objects to serialize</param> public Body(IList<object> array) { _jsonObject = array; } #endregion #region Public Methods /// <summary> /// Determines whether this instance is valid JSON. /// </summary> /// <returns><c>true</c> if this instance is valid JSON; otherwise, <c>false</c>.</returns> public bool IsValidJSON() { if (_jsonObject == null) { if (_json == null) { throw new InvalidOperationException("Both object and json are null for this body: " + this); } try { _jsonObject = Manager.GetObjectMapper().ReadValue<object>(_json); } catch (IOException) { } } return _jsonObject != null; } /// <summary> /// Returns a serialized JSON byte enumerable object containing the properties /// of this object. /// </summary> /// <returns>JSON bytes</returns> public IEnumerable<byte> AsJson() { if (_json == null) { LazyLoadJsonFromObject(); } return _json; } /// <summary> /// Returns a serialized JSON byte enumerable object containing the properties /// of this object in human readable form. /// </summary> /// <returns>JSON bytes</returns> public IEnumerable<Byte> AsPrettyJson() { object properties = AsObject(); if (properties != null) { ObjectWriter writer = Manager.GetObjectMapper().WriterWithDefaultPrettyPrinter(); try { _json = writer.WriteValueAsBytes(properties); } catch (IOException e) { throw new InvalidDataException("The array or dictionary stored is corrupt", e); } } return AsJson(); } /// <summary> /// Returns a serialized JSON string containing the properties /// of this object /// </summary> /// <returns>JSON string</returns> public string AsJSONString() { return Encoding.UTF8.GetString(AsJson().ToArray()); } /// <summary> /// Gets the deserialized object containing the properties of the JSON /// </summary> /// <returns>The deserialized object (either IDictionary or IList)</returns> public object AsObject() { if (_jsonObject == null) { LazyLoadObjectFromJson(); } return _jsonObject; } /// <summary> /// Gets the properties from this object /// </summary> /// <returns>The properties contained in the object</returns> public IDictionary<string, object> GetProperties() { var currentObj = AsObject(); return currentObj.AsDictionary<string, object>(); } /// <summary> /// Determines whether this instance has value the specified key. /// </summary> /// <returns><c>true</c> if this instance has value for the specified key; otherwise, <c>false</c>.</returns> /// <param name="key">The key to check</param> public bool HasValueForKey(string key) { return GetProperties().ContainsKey(key); } /// <summary> /// Gets the property for the given key /// </summary> /// <returns>The property for the given key</returns> /// <param name="key">Key.</param> public object GetPropertyForKey(string key) { IDictionary<string, object> theProperties = GetProperties(); if (theProperties == null) { return null; } return theProperties.Get(key); } /// <summary> /// Gets the cast property for the given key, or uses the default value if not found /// </summary> /// <returns>The property for key, cast to T</returns> /// <param name="key">The key to search for</param> /// <param name="defaultVal">The value to use if the key is not found</param> /// <typeparam name="T">The type to cast to</typeparam> public T GetPropertyForKey<T>(string key, T defaultVal = default(T)) { IDictionary<string, object> theProperties = GetProperties(); if (theProperties == null) { return defaultVal; } return theProperties.GetCast<T>(key, defaultVal); } /// <summary> /// Tries the get property for key and cast it to T /// </summary> /// <returns><c>true</c>, if the property was found and cast, <c>false</c> otherwise.</returns> /// <param name="key">The key to search for</param> /// <param name="val">The cast value, if successful</param> /// <typeparam name="T">The type to cast to</typeparam> public bool TryGetPropertyForKey<T>(string key, out T val) { val = default(T); IDictionary<string, object> theProperties = GetProperties(); if (theProperties == null) { return false; } object valueObj; if (!theProperties.TryGetValue(key, out valueObj)) { return false; } return ExtensionMethods.TryCast<T>(valueObj, out val); } #endregion #region Private Methods // Attempt to serialize _jsonObject private void LazyLoadJsonFromObject() { if (_jsonObject == null) { throw new InvalidOperationException("Both json and object are null for this body: " + this); } try { _json = Manager.GetObjectMapper().WriteValueAsBytes(_jsonObject); } catch (IOException e) { throw new InvalidDataException("The array or dictionary stored is corrupt", e); } } // Attempt to deserialize /json private void LazyLoadObjectFromJson() { if (_json == null) { throw new InvalidOperationException("Both object and json are null for this body: " + this); } try { _jsonObject = Manager.GetObjectMapper().ReadValue<IDictionary<string,object>>(_json); } catch (IOException e) { throw new InvalidDataException("The JSON stored is corrupt", e); } } #endregion } }
using System; using System.Drawing; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.Windows.Forms; namespace m { /// <summary> /// Summary description for EditCounterForm. /// </summary> public class CountersForm : System.Windows.Forms.Form { private System.Windows.Forms.Label label1; private System.Windows.Forms.Button buttonOk; private System.Windows.Forms.Button buttonCancel; private System.Windows.Forms.ListBox listBox1; private System.Windows.Forms.Button buttonNew; private System.Windows.Forms.Button buttonModify; private System.Windows.Forms.Button buttonDelete; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public CountersForm(string strTitle, string strCurrent, StringCollection strc) { // // Required for Windows Form Designer support // InitializeComponent(); // foreach (string str in strc) listBox1.Items.Add(str); listBox1.SelectedIndex = strCurrent == "" ? -1 : listBox1.Items.IndexOf(strCurrent); Text = strTitle; label1.Text = label1.Text.Replace("$1", strTitle); } public Counter GetSelectedCounter() { if (listBox1.SelectedIndex == -1) return null; CounterManager ctrm = ((LevelDoc)DocManager.GetActiveDocument(typeof(LevelDoc))).CounterManager; return ctrm[(string)listBox1.SelectedItem]; } static public Counter DoModal(string strTitle, string strCurrent, StringCollection strc) { CountersForm frm = new CountersForm(strTitle, strCurrent, strc); DialogResult res = frm.ShowDialog(); if (res == DialogResult.Cancel) return null; return frm.GetSelectedCounter(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.buttonOk = new System.Windows.Forms.Button(); this.buttonCancel = new System.Windows.Forms.Button(); this.listBox1 = new System.Windows.Forms.ListBox(); this.buttonNew = new System.Windows.Forms.Button(); this.buttonModify = new System.Windows.Forms.Button(); this.buttonDelete = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.Location = new System.Drawing.Point(8, 8); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(160, 16); this.label1.TabIndex = 0; this.label1.Text = "Choose one $1:"; // // buttonOk // this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK; this.buttonOk.Location = new System.Drawing.Point(184, 8); this.buttonOk.Name = "buttonOk"; this.buttonOk.TabIndex = 2; this.buttonOk.Text = "OK"; this.buttonOk.Click += new System.EventHandler(this.buttonOk_Click); // // buttonCancel // this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonCancel.Location = new System.Drawing.Point(184, 40); this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.TabIndex = 2; this.buttonCancel.Text = "Cancel"; this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click); // // listBox1 // this.listBox1.Location = new System.Drawing.Point(8, 24); this.listBox1.Name = "listBox1"; this.listBox1.Size = new System.Drawing.Size(168, 173); this.listBox1.Sorted = true; this.listBox1.TabIndex = 3; this.listBox1.DoubleClick += new System.EventHandler(this.listBox1_DoubleClick); // // buttonNew // this.buttonNew.Location = new System.Drawing.Point(184, 96); this.buttonNew.Name = "buttonNew"; this.buttonNew.TabIndex = 4; this.buttonNew.Text = "New..."; this.buttonNew.Click += new System.EventHandler(this.buttonNew_Click); // // buttonModify // this.buttonModify.Location = new System.Drawing.Point(184, 128); this.buttonModify.Name = "buttonModify"; this.buttonModify.TabIndex = 5; this.buttonModify.Text = "Modify..."; this.buttonModify.Click += new System.EventHandler(this.buttonModify_Click); // // buttonDelete // this.buttonDelete.Location = new System.Drawing.Point(184, 160); this.buttonDelete.Name = "buttonDelete"; this.buttonDelete.TabIndex = 6; this.buttonDelete.Text = "Delete"; this.buttonDelete.Click += new System.EventHandler(this.buttonDelete_Click); // // CountersForm // this.AcceptButton = this.buttonOk; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.CancelButton = this.buttonCancel; this.ClientSize = new System.Drawing.Size(266, 208); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.buttonDelete, this.buttonModify, this.buttonNew, this.listBox1, this.buttonOk, this.label1, this.buttonCancel}); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "CountersForm"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "EditCounterForm"; this.ResumeLayout(false); } #endregion private void buttonOk_Click(object sender, System.EventArgs e) { DialogResult = DialogResult.OK; } private void buttonCancel_Click(object sender, System.EventArgs e) { DialogResult = DialogResult.Cancel; } private void listBox1_DoubleClick(object sender, System.EventArgs e) { DialogResult = DialogResult.OK; } private void buttonNew_Click(object sender, System.EventArgs e) { string str = EditStringForm.DoModal("New Counter", "New Counter name:", null); if (str != null) { CounterManager ctrm = ((LevelDoc)DocManager.GetActiveDocument(typeof(LevelDoc))).CounterManager; if (ctrm[str] == null) { ctrm.AddCounter(new Counter(str)); int i = listBox1.Items.Add(str); listBox1.SelectedIndex = i; // UNDONE: doc is modified } } } private void buttonModify_Click(object sender, System.EventArgs e) { string str = (string)listBox1.SelectedItem; if (str == null) return; CounterManager ctrm = ((LevelDoc)DocManager.GetActiveDocument(typeof(LevelDoc))).CounterManager; Counter ctr = ctrm[str]; string strNew = EditStringForm.DoModal("Modify Counter", "New Counter name:", str); if (strNew == null) return; if (strNew != str) { ctr.Name = strNew; listBox1.Items.Remove(str); int i = listBox1.Items.Add(strNew); listBox1.SelectedIndex = i; // UNDONE: doc is modified } } private void buttonDelete_Click(object sender, System.EventArgs e) { string str = (string)listBox1.SelectedItem; if (str == null) return; CounterManager ctrm = ((LevelDoc)DocManager.GetActiveDocument(typeof(LevelDoc))).CounterManager; Counter ctr = ctrm[str]; ctrm.RemoveCounter(ctr); listBox1.Items.Remove(str); // UNDONE: doc is modified } } }
using System; using System.Collections.Generic; using Gtk; using Moscrif.IDE.Devices; using Moscrif.IDE.Controls; using Moscrif.IDE.Workspace; using Moscrif.IDE.Components; using Moscrif.IDE.Task; using MessageDialogs = Moscrif.IDE.Controls.MessageDialog; using Moscrif.IDE.Iface.Entities; using Moscrif.IDE.Option; using Moscrif.IDE.Iface; namespace Moscrif.IDE.Controls { public partial class PublishDialog : Gtk.Dialog { private Notebook notebook; private Project project; private CheckButton chbOpenOutputDirectory; private CheckButton chbSignApp; private CheckButton chbIncludeAllResolution; private CheckButton chbDebugLog; protected virtual void OnButtonOkClicked (object sender, System.EventArgs e) { if (MainClass.Settings.ClearConsoleBeforRuning) MainClass.MainWindow.OutputConsole.Clear(); if(MainClass.Workspace.SignApp){ LoggUser vc = new LoggUser(); if((MainClass.User == null)||(string.IsNullOrEmpty(MainClass.User.Token))){ LoginRegisterDialog ld = new LoginRegisterDialog(this); int res = ld.Run(); if (res == (int)Gtk.ResponseType.Cancel){ ld.Destroy(); return; } ld.Destroy(); return; } if(!vc.Ping(MainClass.User.Token)){ MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("invalid_login_f1"), "", Gtk.MessageType.Error,this); md.ShowDialog(); LoginRegisterDialog ld = new LoginRegisterDialog(this); int res = ld.Run(); if (res == (int)Gtk.ResponseType.Cancel){ ld.Destroy(); return; } ld.Destroy(); return; } } List<CombinePublish> list =project.ProjectUserSetting.CombinePublish.FindAll(x=>x.IsSelected==true); if(list==null || list.Count<1){ MessageDialogs md = new MessageDialogs(MessageDialogs.DialogButtonType.Ok, MainClass.Languages.Translate("pleas_select_application"), "", Gtk.MessageType.Error,this); md.ShowDialog(); return; } RunPublishTask(list); this.Respond(ResponseType.Ok); } private void ShowLogin(){ LoginRegisterDialog ld = new LoginRegisterDialog(this); int res = ld.Run(); if (res == (int)Gtk.ResponseType.Cancel){ ld.Destroy(); return; } ld.Destroy(); return; } public PublishDialog() { project = MainClass.Workspace.ActualProject; this.TransientFor = MainClass.MainWindow; this.Build(); btnResetMatrix.Label = MainClass.Languages.Translate("reset_matrix"); this.Title = MainClass.Languages.Translate("publish_title" , project.ProjectName); if(project.ProjectUserSetting.CombinePublish == null || project.ProjectUserSetting.CombinePublish.Count==0){ project.GeneratePublishCombination(); } if(project.DevicesSettings == null || project.DevicesSettings.Count == 0) project.GenerateDevices(); foreach (Rule rl in MainClass.Settings.Platform.Rules){ if( (rl.Tag == -1 ) && !MainClass.Settings.ShowUnsupportedDevices) continue; if( (rl.Tag == -2 ) && !MainClass.Settings.ShowDebugDevices) continue; Device dvc = project.DevicesSettings.Find(x => x.TargetPlatformId == rl.Id); if (dvc == null) { Console.WriteLine("generate device -{0}",rl.Id); dvc = new Device(); dvc.TargetPlatformId = rl.Id; dvc.PublishPropertisMask = project.GeneratePublishPropertisMask(rl.Id); project.DevicesSettings.Add(dvc); } } project.Save(); notebook = new Notebook(); GenerateNotebookPages(); this.vbox2.PackStart(notebook,true,true,0);//PackEnd VBox vbox1 = new VBox(); chbOpenOutputDirectory = new CheckButton( MainClass.Languages.Translate("open_open_directory_after_publish")); chbOpenOutputDirectory.Toggled += new EventHandler(OnChbOpenOutputDirectoryToggled); chbIncludeAllResolution = new CheckButton( MainClass.Languages.Translate("include_all_resolution")); chbIncludeAllResolution.Active = project.IncludeAllResolution; chbIncludeAllResolution.Sensitive = false; chbIncludeAllResolution.Toggled+= delegate { project.IncludeAllResolution =chbIncludeAllResolution.Active; }; vbox1.PackStart(chbIncludeAllResolution,false,false,0); vbox1.PackEnd(chbOpenOutputDirectory,false,false,0); chbDebugLog = new Gtk.CheckButton(MainClass.Languages.Translate("debug_log_publish")); //MainClass.Settings.LogPublish =false; chbDebugLog.Active = MainClass.Settings.LogPublish; chbDebugLog.Toggled+= delegate { MainClass.Settings.LogPublish = chbDebugLog.Active; }; vbox1.PackEnd(chbDebugLog,false,false,0); this.vbox2.PackEnd(vbox1,false,false,0); //this.vbox2.PackEnd(chbOpenOutputDirectory,false,false,0);// chbSignApp= new CheckButton( MainClass.Languages.Translate("sign_app")); chbSignApp.Toggled += new EventHandler(OnChbSignAppToggled); chbSignApp.Sensitive = true;//MainClass.Settings.SignAllow; //this.vbox2.PackEnd(chbSignApp,false,false,0);// VBox hbox = new VBox(); hbox.PackStart(chbSignApp,false,false,0); this.vbox2.PackEnd(hbox,false,false,0); this.ShowAll(); int cpage = project.ProjectUserSetting.PublishPage; notebook.SwitchPage += delegate(object o, SwitchPageArgs args) { project.ProjectUserSetting.PublishPage = notebook.CurrentPage; NotebookLabel nl = (NotebookLabel)notebook.GetTabLabel(notebook.CurrentPageWidget); chbIncludeAllResolution.Sensitive = false; if(nl.Tag == null) return; Device d = project.DevicesSettings.Find(x=>(int)x.Devicetype==(int)nl.Tag); if(d!=null){ if(d.Includes != null){ if(d.Includes.Skin!=null){ if(!String.IsNullOrEmpty(d.Includes.Skin.Name)) chbIncludeAllResolution.Sensitive = true; } } } }; chbOpenOutputDirectory.Active = MainClass.Settings.OpenOutputAfterPublish; chbSignApp.Active = MainClass.Workspace.SignApp; notebook.CurrentPage =cpage; buttonOk.GrabFocus(); } private void GenerateNotebookPages(){ string platformName = MainClass.Settings.Platform.Name; foreach(Rule rl in MainClass.Settings.Platform.Rules){ bool iOsNoMac = false; if( (rl.Tag == -1 ) && !MainClass.Settings.ShowUnsupportedDevices) continue; if( (rl.Tag == -2 ) && !MainClass.Settings.ShowDebugDevices) continue; bool validDevice = true; if(!Device.CheckDevice(rl.Specific) ){ Tool.Logger.Debug("Invalid Device " + rl.Specific); validDevice = false; } ScrolledWindow sw= new ScrolledWindow(); sw.ShadowType = ShadowType.EtchedOut; TreeView tvList = new TreeView(); List<CombinePublish> lcp = project.ProjectUserSetting.CombinePublish.FindAll(x=> x.combineRule.FindIndex(y=>y.ConditionName==platformName && y.RuleId == rl.Id) >-1); List<CombinePublish> lcpDennied = new List<CombinePublish>(); string deviceName = rl.Name; int deviceTyp = rl.Id; ListStore ls = new ListStore(typeof(bool),typeof(string),typeof(CombinePublish),typeof(string),typeof(bool)); string ico="empty.png"; switch (deviceTyp) { case (int)DeviceType.Android_1_6:{ ico = "android.png"; break;} case (int)DeviceType.Android_2_2:{ ico = "android.png"; break;} case (int)DeviceType.Bada_1_0: case (int)DeviceType.Bada_1_1: case (int)DeviceType.Bada_1_2: case (int)DeviceType.Bada_2_0:{ ico = "bada.png"; break;} case (int)DeviceType.Symbian_9_4:{ ico = "symbian.png"; break;} case (int)DeviceType.iOS_5_0:{ ico = "apple.png"; if(!MainClass.Platform.IsMac){ iOsNoMac = true; } break; } case (int)DeviceType.PocketPC_2003SE: case (int)DeviceType.WindowsMobile_5: case (int)DeviceType.WindowsMobile_6:{ ico = "windows.png"; break;} case (int)DeviceType.Windows:{ ico = "win32.png"; break;} case (int)DeviceType.MacOs:{ ico = "macos.png"; break;} } List<CombinePublish> tmp = lcp.FindAll(x=>x.IsSelected == true); NotebookLabel nl = new NotebookLabel(ico,String.Format("{0} ({1})",deviceName,tmp.Count )); nl.Tag=deviceTyp; if(iOsNoMac){ Label lbl=new Label(MainClass.Languages.Translate("ios_available_Mac")); Pango.FontDescription customFont = Pango.FontDescription.FromString(MainClass.Settings.ConsoleTaskFont); customFont.Weight = Pango.Weight.Bold; lbl.ModifyFont(customFont); notebook.AppendPage(lbl, nl); continue; } if(!validDevice){ Label lbl=new Label(MainClass.Languages.Translate("publish_tool_missing")); Pango.FontDescription customFont = Pango.FontDescription.FromString(MainClass.Settings.ConsoleTaskFont); customFont.Weight = Pango.Weight.Bold; lbl.ModifyFont(customFont); notebook.AppendPage(lbl, nl); continue; } ; CellRendererToggle crt = new CellRendererToggle(); crt.Activatable = true; crt.Sensitive = true; tvList.AppendColumn ("", crt, "active", 0); Gtk.CellRendererText fileNameRenderer = new Gtk.CellRendererText(); Gtk.CellRendererText collumnResolRenderer = new Gtk.CellRendererText(); tvList.AppendColumn(MainClass.Languages.Translate("file_name"),fileNameRenderer, "text", 1); tvList.AppendColumn(MainClass.Languages.Translate("resolution_f1"), collumnResolRenderer, "text", 1); tvList.Columns[1].SetCellDataFunc(fileNameRenderer, new Gtk.TreeCellDataFunc(RenderCombine)); tvList.Columns[2].SetCellDataFunc(collumnResolRenderer, new Gtk.TreeCellDataFunc(RenderResolution)); // povolene resolution pre danu platformu PlatformResolution listPR = MainClass.Settings.PlatformResolutions.Find(x=>x.IdPlatform ==deviceTyp); Device dvc = project.DevicesSettings.Find(x=>x.TargetPlatformId ==deviceTyp); string stringTheme = ""; List<System.IO.DirectoryInfo> themeResolution = new List<System.IO.DirectoryInfo>(); // resolution z adresara themes po novom if((project.NewSkin) && (dvc != null)){ Skin skin =dvc.Includes.Skin; if((skin != null) && ( !String.IsNullOrEmpty(skin.Name)) && (!String.IsNullOrEmpty(skin.Theme)) ){ string skinDir = System.IO.Path.Combine(MainClass.Workspace.RootDirectory, MainClass.Settings.SkinDir); stringTheme = System.IO.Path.Combine(skinDir,skin.Name); stringTheme = System.IO.Path.Combine(stringTheme, "themes"); stringTheme = System.IO.Path.Combine(stringTheme, skin.Theme); if (System.IO.Directory.Exists(stringTheme)){ System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(stringTheme); themeResolution = new List<System.IO.DirectoryInfo>(di.GetDirectories()); } } } crt.Toggled += delegate(object o, ToggledArgs args) { TreeIter iter; if (ls.GetIter (out iter, new TreePath(args.Path))) { bool old = (bool) ls.GetValue(iter,0); CombinePublish cp =(CombinePublish) ls.GetValue(iter,2); cp.IsSelected = !old; ls.SetValue(iter,0,!old); List<CombinePublish> tmp2 = lcp.FindAll(x=>x.IsSelected == true); nl.SetLabel (String.Format("{0} ({1})",deviceName,tmp2.Count )); //if(dvc == null) return; //if(dvc.Includes == null) return; if(dvc.Includes.Skin == null) return; if(String.IsNullOrEmpty(dvc.Includes.Skin.Name) || String.IsNullOrEmpty(dvc.Includes.Skin.Theme)) return; if(cp.IsSelected){ // Najdem ake je rozlisenie v danej combinacii CombineCondition cc = cp.combineRule.Find(x=>x.ConditionId == MainClass.Settings.Resolution.Id); if(cc == null) return; /// nema ziadne rozlisenie v combinacii int indxResol = themeResolution.FindIndex(x=>x.Name.ToLower() == cc.RuleName.ToLower()); if(indxResol<0){ // theme chyba prislusne rozlisenie string error =String.Format("Invalid {0} Skin and {1} Theme, using in {2}. Missing resolutions: {3}. ",dvc.Includes.Skin.Name,dvc.Includes.Skin.Theme,deviceName,cc.RuleName.ToLower()); MainClass.MainWindow.OutputConsole.WriteError(error+"\n"); List<string> lst = new List<string>(); lst.Add(error); MainClass.MainWindow.ErrorWritte("","",lst); } } } }; int cntOfAdded = 0; foreach (CombinePublish cp in lcp){ bool isValid = cp.IsSelected; if (!validDevice) isValid = false; // Najdem ake je rozlisenie v danej combinacii CombineCondition cc = cp.combineRule.Find(x=>x.ConditionId == MainClass.Settings.Resolution.Id); if(cc == null) continue; /// nema ziadne rozlisenie v combinacii int indx = MainClass.Settings.Resolution.Rules.FindIndex(x=> x.Id == cc.RuleId ); if(indx<0) continue; /// rozlisenie pouzite v danej combinacii nexistuje if(cc!= null){ bool isValidResolution = false; //ak nema definovane ziadne povolenia, tak povolene su vsetky if((listPR==null) || (listPR.AllowResolution == null) || (listPR.AllowResolution.Count<1)){ isValidResolution = true; } else { isValidResolution = listPR.IsValidResolution(cc.RuleId); } if(isValidResolution){ // po novom vyhodom aj tie ktore niesu v adresaru themes - pokial je thema definovana if((project.NewSkin) && (themeResolution.Count > 0)){ //cntResolution = 0; int indxResol = themeResolution.FindIndex(x=>x.Name.ToLower() == cc.RuleName.ToLower()); if(indxResol>-1){ ls.AppendValues(isValid,cp.ProjectName,cp,cp.ProjectName,true); cntOfAdded++; } else { lcpDennied.Add(cp); } } else { ls.AppendValues(isValid,cp.ProjectName,cp,cp.ProjectName,true); cntOfAdded++; } } else { lcpDennied.Add(cp); } } //} } // pridam tie zakazane, ktore su vybrate na publish foreach (CombinePublish cp in lcpDennied){ if(cp.IsSelected){ ls.AppendValues(cp.IsSelected,cp.ProjectName,cp,cp.ProjectName,false); cntOfAdded++; } } if(cntOfAdded == 0){ MainClass.MainWindow.OutputConsole.WriteError(String.Format("Missing publish settings for {0}.\n",deviceName)); } bool showAll = false; tvList.ButtonReleaseEvent += delegate(object o, ButtonReleaseEventArgs args){ if (args.Event.Button == 3) { TreeSelection ts = tvList.Selection; Gtk.TreePath[] selRow = ts.GetSelectedRows(); if(selRow.Length<1){ TreeIter tiFirst= new TreeIter(); ls.GetIterFirst(out tiFirst); tvList.Selection.SelectIter(tiFirst); selRow = ts.GetSelectedRows(); } if(selRow.Length<1) return; Gtk.TreePath tp = selRow[0]; TreeIter ti = new TreeIter(); ls.GetIter(out ti,tp); CombinePublish combinePublish= (CombinePublish)ls.GetValue(ti,2); if(combinePublish!=null){ Menu popupMenu = new Menu(); if(!showAll){ MenuItem miShowDenied = new MenuItem( MainClass.Languages.Translate("show_denied" )); miShowDenied.Activated+= delegate(object sender, EventArgs e) { // odoberem zakazane, ktore sa zobrazuju kedze su zaceknute na publish List<TreeIter> lst= new List<TreeIter>(); ls.Foreach((model, path, iterr) => { bool cp =(bool) ls.GetValue(iterr,4); bool selected =(bool) ls.GetValue(iterr,0); if(!cp && selected){ lst.Add(iterr); } return false; }); foreach(TreeIter ti2 in lst){ TreeIter ti3 =ti2; ls.Remove(ref ti3); } // pridam zakazane if( (lcpDennied==null) || (lcpDennied.Count<1)) return; foreach (CombinePublish cp in lcpDennied){ ls.AppendValues(cp.IsSelected,cp.ProjectName,cp,cp.ProjectName,false); } showAll = true; }; popupMenu.Append(miShowDenied); } else { MenuItem miHideDenied = new MenuItem( MainClass.Languages.Translate("hide_denied" )); miHideDenied.Activated+= delegate(object sender, EventArgs e) { List<TreeIter> lst= new List<TreeIter>(); ls.Foreach((model, path, iterr) => { bool cp =(bool) ls.GetValue(iterr,4); bool selected =(bool) ls.GetValue(iterr,0); if(!cp && !selected){ lst.Add(iterr); } return false; }); foreach(TreeIter ti2 in lst){ TreeIter ti3 =ti2; ls.Remove(ref ti3); } showAll = false; }; popupMenu.Append(miHideDenied); } popupMenu.Append(new SeparatorMenuItem()); MenuItem miCheckAll = new MenuItem( MainClass.Languages.Translate("check_all" )); miCheckAll.Activated+= delegate(object sender, EventArgs e) { int cnt = 0; ls.Foreach((model, path, iterr) => { CombinePublish cp =(CombinePublish) ls.GetValue(iterr,2); cp.IsSelected = true; ls.SetValue(iterr,0,true); cnt ++; return false; }); nl.SetLabel (String.Format("{0} ({1})",deviceName,cnt )); }; popupMenu.Append(miCheckAll); MenuItem miUnCheckAll = new MenuItem( MainClass.Languages.Translate("uncheck_all" )); miUnCheckAll.Activated+= delegate(object sender, EventArgs e) { ls.Foreach((model, path, iterr) => { CombinePublish cp =(CombinePublish) ls.GetValue(iterr,2); cp.IsSelected = false; ls.SetValue(iterr,0,false); return false; }); nl.SetLabel (String.Format("{0} ({1})",deviceName,0 )); }; popupMenu.Append(miUnCheckAll); popupMenu.Append(new SeparatorMenuItem()); MenuItem mi = new MenuItem( MainClass.Languages.Translate("publis_only_this",combinePublish.ProjectName.Replace("_","__") )); mi.Activated+= delegate(object sender, EventArgs e) { List<CombinePublish> lst = new List<CombinePublish>(); lst.Add(combinePublish); RunPublishTask(lst); this.Respond(ResponseType.Ok); }; popupMenu.Append(mi); MenuItem miD = new MenuItem(MainClass.Languages.Translate("publis_this_device",deviceName)); miD.Activated+= delegate(object sender, EventArgs e) { RunPublishTask(lcp); this.Respond(ResponseType.Ok); }; popupMenu.Append(miD); popupMenu.Popup(); popupMenu.ShowAll(); } } }; tvList.Model = ls; if (!validDevice) tvList.Sensitive = false; sw.Add(tvList); notebook.AppendPage(sw, nl); } } private void RenderResolution(Gtk.TreeViewColumn column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter) { CombinePublish cp = (CombinePublish) model.GetValue (iter, 2); bool type = (bool) model.GetValue (iter, 4); // Najdem ake je rozlisenie v danej combinacii CombineCondition cc = cp.combineRule.Find(x=>x.ConditionId == MainClass.Settings.Resolution.Id); if(cc == null) return; Rule rl = MainClass.Settings.Resolution.Rules.Find(x=>x.Id == cc.RuleId); if(rl == null) { return; } if(cc == null) return; /// nema ziadne rozlisenie v combinacii Pango.FontDescription fd = new Pango.FontDescription(); (cell as Gtk.CellRendererText).Text =String.Format("{0}x{1}",rl.Width,rl.Height); if (!type) { fd.Style = Pango.Style.Italic; } else { fd.Style = Pango.Style.Normal; } (cell as Gtk.CellRendererText).FontDesc = fd; } private void RenderCombine(Gtk.TreeViewColumn column, Gtk.CellRenderer cell, Gtk.TreeModel model, Gtk.TreeIter iter) { bool type = (bool) model.GetValue (iter, 4); Pango.FontDescription fd = new Pango.FontDescription(); if (!type) { fd.Style = Pango.Style.Italic; } else { fd.Style = Pango.Style.Normal; } (cell as Gtk.CellRendererText).FontDesc = fd; //(cell as Gtk.CellRendererText).Text = type; } private void RunPublishTask(List<CombinePublish> list){ LoggingInfo log = new LoggingInfo(); log.LoggWebThread(LoggingInfo.ActionId.IDEEnd,project.ProjectName); if((!MainClass.Workspace.SignApp) ){ TaskList tlpublish = new TaskList(); tlpublish.TasksList = new System.Collections.Generic.List<Moscrif.IDE.Task.ITask>(); PublishTask pt = new PublishTask(); pt.ParentWindow = this; pt.Initialize(list); tlpublish.TasksList.Add(pt); MainClass.MainWindow.RunTaskList(tlpublish,true); } else { if(MainClass.User == null){ LoginRegisterDialog ld = new LoginRegisterDialog(this); int res = ld.Run(); if (res == (int)Gtk.ResponseType.Cancel){ ld.Destroy(); return; } ld.Destroy(); } TaskList tl = new TaskList(); tl.TasksList = new System.Collections.Generic.List<Moscrif.IDE.Task.ITask>(); SignPublishTask ct = new SignPublishTask(); ct.Initialize(list); ct.ParentWindow = this; tl.TasksList.Add(ct ); MainClass.MainWindow.RunTaskList(tl,false); } } protected virtual void OnChbSignAppToggled (object sender, System.EventArgs e) { MainClass.Workspace.SignApp = chbSignApp.Active; } protected virtual void OnChbOpenOutputDirectoryToggled (object sender, System.EventArgs e) { MainClass.Settings.OpenOutputAfterPublish = chbOpenOutputDirectory.Active; } protected void OnButton12Clicked (object sender, System.EventArgs e) { project.GeneratePublishCombination(); int page = notebook.NPages; for (int i = page ; i>=0 ;i--){ notebook.RemovePage(i); } GenerateNotebookPages(); notebook.ShowAll(); } } }
// // Client.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.Net; using System.Net.NetworkInformation; using Mono.Ssdp.Internal; namespace Mono.Ssdp { public class Client : IDisposable { public static bool StrictProtocol { get; set; } private bool disposed; private readonly object mutex = new object(); private NotifyListener notify_listener; private Dictionary<string, Browser> browsers; private readonly NetworkInterfaceInfo network_interface_info; internal NetworkInterfaceInfo NetworkInterfaceInfo { get { return network_interface_info; } } private readonly TimeoutDispatcher dispatcher = new TimeoutDispatcher (); internal TimeoutDispatcher Dispatcher { get { return dispatcher; } } private ServiceCache service_cache; internal ServiceCache ServiceCache { get { lock (service_cache) { return service_cache; } } } public bool Started { get; private set; } public event EventHandler<ServiceArgs> ServiceAdded; public event EventHandler<ServiceArgs> ServiceUpdated; public event EventHandler<ServiceArgs> ServiceRemoved; public Client () : this (null) { } public Client (NetworkInterface networkInterface) { network_interface_info = NetworkInterfaceInfo.GetNetworkInterfaceInfo (networkInterface); service_cache = new ServiceCache (this); notify_listener = new NotifyListener (this); browsers = new Dictionary<string, Browser> (); } public void Start () { Start (true); } public void Start (bool startBrowsers) { lock (mutex) { CheckDisposed (); if (Started) { throw new InvalidOperationException ("The Client is already started."); } Started = true; notify_listener.Start (); if (startBrowsers) { foreach (var browser in browsers.Values) { if (!browser.Started) { browser.Start (); } } } } } public void Stop () { Stop (true); } public void Stop (bool stopBrowsers) { lock (mutex) { CheckDisposed (); Started = false; notify_listener.Stop (); if (stopBrowsers) { foreach (var browser in browsers.Values) { browser.Stop (); } } } } public Browser BrowseAll () { return BrowseAll (true); } public Browser BrowseAll (bool autoStart) { return Browse (Protocol.SsdpAll, autoStart); } public Browser Browse (string serviceType) { return Browse (serviceType, true); } public Browser Browse (string serviceType, bool autoStart) { lock (mutex) { CheckDisposed (); Browser browser; if (browsers.TryGetValue (serviceType, out browser)) { if (!browser.Started && autoStart) { browser.Start (); } return browser; } browser = new Browser (this, serviceType); browsers.Add (serviceType, browser); if (autoStart) { browser.Start (); } return browser; } } internal void RemoveBrowser (Browser browser) { lock (mutex) { foreach (var entry in browsers) { if (entry.Value == browser) { browsers.Remove (entry.Key); return; } } } } internal bool ServiceTypeRegistered (string serviceType) { lock (mutex) { return serviceType != null && browsers != null && (browsers.ContainsKey (serviceType) || browsers.ContainsKey (Protocol.SsdpAll)); } } internal void CacheServiceAdded (Service service) { OnServiceAdded (service); } internal void CacheServiceUpdated (Service service) { OnServiceUpdated (service); } internal void CacheServiceRemoved (string usn) { OnServiceRemoved (usn); } protected virtual void OnServiceAdded (Service service) { var handler = ServiceAdded; if (handler != null) { handler (this, new ServiceArgs (ServiceOperation.Added, service)); } } protected virtual void OnServiceUpdated (Service service) { var handler = ServiceUpdated; if (handler != null) { handler (this, new ServiceArgs (ServiceOperation.Updated, service)); } } protected virtual void OnServiceRemoved (string usn) { var handler = ServiceRemoved; if (handler != null) { handler (this, new ServiceArgs (usn)); } } private void CheckDisposed () { if (disposed) { throw new ObjectDisposedException ("Client has been Disposed"); } } public void Dispose () { lock (mutex) { if (disposed) { return; } notify_listener.Stop (); foreach (var browser in browsers.Values) { browser.Dispose (false); } browsers.Clear (); service_cache.Dispose (); service_cache = null; notify_listener = null; browsers = null; disposed = true; } } } }
namespace YAF.Lucene.Net.QueryParsers.Classic { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ public static class RegexpToken { /// <summary>End of File. </summary> public const int EOF = 0; /// <summary>RegularExpression Id. </summary> public const int NUM_CHAR = 1; // LUCENENET specific: removed leading underscore to make CLS compliant /// <summary>RegularExpression Id. </summary> public const int ESCAPED_CHAR = 2; // LUCENENET specific: removed leading underscore to make CLS compliant /// <summary>RegularExpression Id. </summary> public const int TERM_START_CHAR = 3; // LUCENENET specific: removed leading underscore to make CLS compliant /// <summary>RegularExpression Id. </summary> public const int TERM_CHAR = 4; // LUCENENET specific: removed leading underscore to make CLS compliant /// <summary>RegularExpression Id. </summary> public const int WHITESPACE = 5; // LUCENENET specific: removed leading underscore to make CLS compliant /// <summary>RegularExpression Id. </summary> public const int QUOTED_CHAR = 6; // LUCENENET specific: removed leading underscore to make CLS compliant /// <summary>RegularExpression Id. </summary> public const int AND = 8; /// <summary>RegularExpression Id. </summary> public const int OR = 9; /// <summary>RegularExpression Id. </summary> public const int NOT = 10; /// <summary>RegularExpression Id. </summary> public const int PLUS = 11; /// <summary>RegularExpression Id. </summary> public const int MINUS = 12; /// <summary>RegularExpression Id. </summary> public const int BAREOPER = 13; /// <summary>RegularExpression Id. </summary> public const int LPAREN = 14; /// <summary>RegularExpression Id. </summary> public const int RPAREN = 15; /// <summary>RegularExpression Id. </summary> public const int COLON = 16; /// <summary>RegularExpression Id. </summary> public const int STAR = 17; /// <summary>RegularExpression Id. </summary> public const int CARAT = 18; /// <summary>RegularExpression Id. </summary> public const int QUOTED = 19; /// <summary>RegularExpression Id. </summary> public const int TERM = 20; /// <summary>RegularExpression Id. </summary> public const int FUZZY_SLOP = 21; /// <summary>RegularExpression Id. </summary> public const int PREFIXTERM = 22; /// <summary>RegularExpression Id. </summary> public const int WILDTERM = 23; /// <summary>RegularExpression Id. </summary> public const int REGEXPTERM = 24; /// <summary>RegularExpression Id. </summary> public const int RANGEIN_START = 25; /// <summary>RegularExpression Id. </summary> public const int RANGEEX_START = 26; /// <summary>RegularExpression Id. </summary> public const int NUMBER = 27; /// <summary>RegularExpression Id. </summary> public const int RANGE_TO = 28; /// <summary>RegularExpression Id. </summary> public const int RANGEIN_END = 29; /// <summary>RegularExpression Id. </summary> public const int RANGEEX_END = 30; /// <summary>RegularExpression Id. </summary> public const int RANGE_QUOTED = 31; /// <summary>RegularExpression Id. </summary> public const int RANGE_GOOP = 32; } public static class LexicalToken { /// <summary>Lexical state.</summary> public const int Boost = 0; /// <summary>Lexical state.</summary> public const int Range = 1; /// <summary>Lexical state.</summary> public const int DEFAULT = 2; } // NOTE: In Java, this was an interface. However, in // .NET we cannot define constants in an interface. // So, instead we are making it a static class so it // can be shared between classes with different base classes. // public interface QueryParserConstants /// <summary> Token literal values and constants. /// Generated by org.javacc.parser.OtherFilesGen#start() /// </summary> public static class QueryParserConstants { ///// <summary>End of File. </summary> //public const int EndOfFileToken = 0; ///// <summary>RegularExpression Id. </summary> //public const int NumCharToken = 1; ///// <summary>RegularExpression Id. </summary> //public const int EscapedCharToken = 2; ///// <summary>RegularExpression Id. </summary> //public const int TermStartCharToken = 3; ///// <summary>RegularExpression Id. </summary> //public const int TermCharToken = 4; ///// <summary>RegularExpression Id. </summary> //public const int WhitespaceToken = 5; ///// <summary>RegularExpression Id. </summary> //public const int QuotedCharToken = 6; ///// <summary>RegularExpression Id. </summary> //public const int AndToken = 8; ///// <summary>RegularExpression Id. </summary> //public const int OrToken = 9; ///// <summary>RegularExpression Id. </summary> //public const int NotToken = 10; ///// <summary>RegularExpression Id. </summary> //public const int PlusToken = 11; ///// <summary>RegularExpression Id. </summary> //public const int MinusToken = 12; ///// <summary>RegularExpression Id. </summary> //public const int BareOperToken = 13; ///// <summary>RegularExpression Id. </summary> //public const int LParanToken = 14; ///// <summary>RegularExpression Id. </summary> //public const int RParenToken = 15; ///// <summary>RegularExpression Id. </summary> //public const int ColonToken = 16; ///// <summary>RegularExpression Id. </summary> //public const int StarToken = 17; ///// <summary>RegularExpression Id. </summary> //public const int CaratToken = 18; ///// <summary>RegularExpression Id. </summary> //public const int QuotedToken = 19; ///// <summary>RegularExpression Id. </summary> //public const int TermToken = 20; ///// <summary>RegularExpression Id. </summary> //public const int FuzzySlopToken = 21; ///// <summary>RegularExpression Id. </summary> //public const int PrefixTermToken = 22; ///// <summary>RegularExpression Id. </summary> //public const int WildTermToken = 23; ///// <summary>RegularExpression Id. </summary> //public const int RegExpTermToken = 24; ///// <summary>RegularExpression Id. </summary> //public const int RangeInStartToken = 25; ///// <summary>RegularExpression Id. </summary> //public const int RangeExStartToken = 26; ///// <summary>RegularExpression Id. </summary> //public const int NumberToken = 27; ///// <summary>RegularExpression Id. </summary> //public const int RangeToToken = 28; ///// <summary>RegularExpression Id. </summary> //public const int RangeInEndToken = 29; ///// <summary>RegularExpression Id. </summary> //public const int RangeExEndToken = 30; ///// <summary>RegularExpression Id. </summary> //public const int RangeQuotedToken = 31; ///// <summary>RegularExpression Id. </summary> //public const int RangeGoopToken = 32; ///// <summary>Lexical state. </summary> //public const int BoostToken = 0; ///// <summary>Lexical state. </summary> //public const int RangeToken = 1; ///// <summary>Lexical state. </summary> //public const int DefaultToken = 2; /// <summary>Literal token values. </summary> public static string[] TokenImage = new string[] { "<EOF>", "<_NUM_CHAR>", "<_ESCAPED_CHAR>", "<_TERM_START_CHAR>", "<_TERM_CHAR>", "<_WHITESPACE>", "<_QUOTED_CHAR>", "<token of kind 7>", "<AND>", "<OR>", "<NOT>", "\"+\"", "\"-\"", "<BAREOPER>", "\"(\"", "\")\"", "\":\"", "\"*\"", "\"^\"", "<QUOTED>", "<TERM>", "<FUZZY_SLOP>", "<PREFIXTERM>", "<WILDTERM>", "<REGEXPTERM>", "\"[\"", "\"{\"", "<NUMBER>", "\"TO\"", "\"]\"", "<RANGEIN_QUOTED>", "<RANGEIN_GOOP>", "\"TO\"", "\"}\"", "<RANGE_QUOTED>", "<RANGE_GOOP>" }; } }
using System; using System.IO; using System.Collections.Generic; using System.Text; using csmatio.common; using csmatio.types; #if !NET20 && !NET40 && !NET45 #error .NET-Version undefiniert #endif #if NET20 using zlib = ComponentAce.Compression.Libs.ZLib; #endif #if NET40 || NET45 using System.IO.Compression; #endif namespace csmatio.io { /// <summary> /// MAT-file reader. Reads MAT-file into <c>MLArray</c> objects. /// </summary> /// <example> /// <code> /// // read in the file /// MatFileReader mfr = new MatFileReader( "mat_file.mat" ); /// /// // Get array of a name "my_array" from file /// MLArray mlArrayRetrived = mfr.GetMLArray( "my_array" ); /// /// // or get the collection of all arrays that were stored in the file /// Hashtable content = mfr.Content; /// </code> /// </example> /// <author>David Zier (<a href="mailto:david.zier@gmail.com">david.zier@gmail.com</a>)</author> public class MatFileReader { /// <summary> /// MAT-file header /// </summary> private MatFileHeader _matFileHeader; /// <summary> /// Contianer for read <c>MLArray</c>s /// </summary> private Dictionary<string, MLArray> _data; // /// <summary> // /// Tells how bytes are organized in the buffer // /// </summary> // private ByteOrder _byteData; /// <summary> /// Array name filter /// </summary> private MatFileFilter _filter; /// <summary> /// Creates instance of <c>MatFileReader</c> and reads MAT-file with then name /// <c>fileName</c>. /// </summary> /// <remarks> /// This method reads MAT-file without filtering. /// </remarks> /// <param name="fileName">The name of the MAT-file to open</param> public MatFileReader(string fileName) : this(fileName, new MatFileFilter()) { } /// <summary> /// Creates instance of <c>MatFileReader</c> and reads MAT-file with then name /// <c>fileName</c>. /// </summary> /// <remarks> /// Results are filtered by <c>MatFileFilter</c>. Arrays that do not meet /// filter match condition will not be available in results. /// </remarks> /// <param name="fileName">The name of the MAT-file to open</param> /// <param name="filter"><c>MatFileFilter</c></param> public MatFileReader(string fileName, MatFileFilter filter) { _filter = filter; _data = new Dictionary<string, MLArray>(); // Try to open up the file as read-only FileStream dataIn; try { dataIn = new FileStream(fileName, FileMode.Open, FileAccess.Read); } catch (FileNotFoundException) { throw new MatlabIOException("Could not open the file '" + fileName + "' for reading!"); } // try and read in the file until completed try { ReadHeader(dataIn); for (; ; ) { ReadData(dataIn); } } catch (EndOfStreamException) { // Catch to break out of the for loop } catch (IOException e) { throw new MatlabIOException("Error in reading MAT-file '" + fileName + "':\n" + e.ToString()); } finally { dataIn.Close(); } } /// <summary> /// Gets MAT-file header. /// </summary> public MatFileHeader MatFileHeader { get { return _matFileHeader; } } /// <summary> /// Returns list of <c>MLArray</c> objects that were inside the MAT-file /// </summary> public List<MLArray> Data { get { return new List<MLArray>(_data.Values); } } /// <summary> /// Returns the value to which the read file maps the specific array name. /// </summary> /// <remarks> /// Returns <c>null</c> if the file contains no content for this name. /// </remarks> /// <param name="name">Array name</param> /// <returns>The <c>MLArray</c> to which this file maps the specific name, /// or null if the file contains no content for this name</returns> public MLArray GetMLArray(string name) { return _data.ContainsKey(name) ? (MLArray)_data[name] : null; } /// <summary> /// Returns a map of <c>MLArray</c> objects that were inside MAT-file. /// </summary> /// <remarks>MLArrays are keyed with the MLArrays' name.</remarks> public Dictionary<string, MLArray> Content { get { return _data; } } /// <summary> /// Decompresses (inflates) bytes from input stream. /// </summary> /// <remarks> /// Stream marker is being set at +<code>numOfBytes</code> position of the stream. /// </remarks> /// <param name="buf">Input byte buffer stream.</param> /// <param name="numOfBytes">The number of bytes to be read.</param> /// <returns>new <c>ByteBuffer</c> with the inflated block of data.</returns> /// <exception cref="IOException">When an error occurs while reading or inflating the buffer.</exception> private Stream Inflate(Stream buf, int numOfBytes) { if (buf.Length - buf.Position < numOfBytes) { throw new MatlabIOException("Compressed buffer length miscalculated!"); } #if false // test code! byte[] byteBuffer = new byte[numOfBytes]; long pos = buf.Position; int n = buf.Read(byteBuffer, 0, numOfBytes); buf.Position = pos; File.WriteAllBytes("DeflatedMatlabData.bin", byteBuffer); #endif try { #if NET20 MemoryStream inflatedStream = new MemoryStream(numOfBytes); // copy all the compressed bytes to a new stream. byte[] compressedBytes = new byte[numOfBytes]; int numBytesRead = buf.Read(compressedBytes, 0, numOfBytes); if (numBytesRead != numOfBytes) { throw new IOException("numBytesRead != numOfBytes"); } // now use zlib on the compressedBytes MemoryStream compressedStream = new MemoryStream(compressedBytes); zlib.ZInputStream zis = new zlib.ZInputStream(compressedStream); Helpers.CopyStream(zis, inflatedStream); zis.Close(); inflatedStream.Position = 0; return inflatedStream; #endif #if NET40 || NET45 // skip CRC (at end) and zip format (0x789C at begin) buf.Position += 2; numOfBytes -= 6; MemoryStream compressedStream = new MemoryStream(); int data; do { data = buf.ReadByte(); if (data != -1) { compressedStream.WriteByte((byte)(data & 0x000000FF)); } } while (data != -1 && compressedStream.Length < numOfBytes); // skip CRC buf.Position += 4; compressedStream.Position = 0; MemoryStream decompressedStream = new MemoryStream(); using (DeflateStream df = new DeflateStream(compressedStream, CompressionMode.Decompress)) { do { data = df.ReadByte(); if (data != -1) { decompressedStream.WriteByte((byte)(data & 0x000000FF)); } } while (data != -1); } decompressedStream.Position = 0; return decompressedStream; #endif } catch (IOException e) { throw new MatlabIOException("Could not decompress data: " + e); } } /// <summary> /// Reads data from the <c>BinaryReader</c> stream. Searches for either /// <c>miCOMPRESSED</c> data or <c>miMATRIX</c> data. /// </summary> /// <remarks> /// Compressed data is inflated and the product is recursively passed back /// to this same method. /// </remarks> /// <param name="buf">The input <c>BinaryReader</c> stream.</param> private void ReadData(Stream buf) { // read data ISMatTag tag = new ISMatTag(buf); switch (tag.Type) { case MatDataTypes.miCOMPRESSED: // inflate and recur { Stream uncompressed = Inflate(buf, tag.Size); ReadData(uncompressed); uncompressed.Close(); } break; case MatDataTypes.miMATRIX: // read in the matrix int pos = (int)buf.Position; int red, toread; MLArray element = ReadMatrix(buf, true); if (element != null) { _data.Add(element.Name, element); } else { red = (int)buf.Position - pos; toread = tag.Size - red; buf.Position = buf.Position + toread; } red = (int)buf.Position - pos; toread = tag.Size - red; if (toread != 0) { throw new MatlabIOException("Matrix was not read fully! " + toread + " remaining in the buffer."); } break; default: throw new MatlabIOException("Incorrect data tag: " + tag); } } /// <summary> /// Reads <c>miMATRIX</c> from the input stream. /// </summary> /// <remarks> /// If reading was not finished (which is normal for filtered results) /// returns <c>null</c>. /// </remarks> /// <param name="buf">The <c>BinaryReader</c> input stream.</param> /// <param name="isRoot">When <c>true</c> informs that if this is a top level /// matrix.</param> /// <returns><c>MLArray</c> or <c>null</c> if matrix does not match <c>filter</c></returns> private MLArray ReadMatrix(Stream buf, bool isRoot) { // result MLArray mlArray = null; ISMatTag tag; // read flags int[] flags = ReadFlags(buf); int attributes = (flags.Length != 0) ? flags[0] : 0; int nzmax = (flags.Length != 0) ? flags[1] : 0; int type = attributes & 0xff; // read Array dimension int[] dims = ReadDimension(buf); // read Array name string name = ReadName(buf); // If this array is filtered out return immediately if (isRoot && !_filter.Matches(name)) { return null; } // read data switch (type) { case MLArray.mxSTRUCT_CLASS: MLStructure mlStruct = new MLStructure(name, dims, type, attributes); BinaryReader br = new BinaryReader(buf); // field name length - this subelement always uses the compressed data element format tag = new ISMatTag(br.BaseStream); int maxlen = br.ReadInt32(); // Read fields data as Int8 tag = new ISMatTag(br.BaseStream); // calculate number of fields int numOfFields = tag.Size / maxlen; // padding after field names int padding = (tag.Size % 8) != 0 ? 8 - tag.Size % 8 : 0; string[] fieldNames = new string[numOfFields]; for (int i = 0; i < numOfFields; i++) { byte[] names = new byte[maxlen]; br.Read(names, 0, names.Length); fieldNames[i] = ZeroEndByteArrayToString(names); } br.ReadBytes(padding); // read fields for (int index = 0; index < mlStruct.M * mlStruct.N; index++) { for (int i = 0; i < numOfFields; i++) { // read matrix recursively tag = new ISMatTag(br.BaseStream); if (tag.Size > 0) { MLArray fieldValue = ReadMatrix(br.BaseStream, false); mlStruct[fieldNames[i], index] = fieldValue; } else { mlStruct[fieldNames[i], index] = new MLEmptyArray(); } } } mlArray = mlStruct; //br.Close(); break; case MLArray.mxCELL_CLASS: MLCell cell = new MLCell(name, dims, type, attributes); for (int i = 0; i < cell.M * cell.N; i++) { tag = new ISMatTag(buf); if (tag.Size > 0) { MLArray cellmatrix = ReadMatrix(buf, false); cell[i] = cellmatrix; } else { cell[i] = new MLEmptyArray(); } } mlArray = cell; break; case MLArray.mxDOUBLE_CLASS: mlArray = new MLDouble(name, dims, type, attributes); //read real tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<double>)mlArray).RealByteBuffer, (IByteStorageSupport)mlArray); // read complex if (mlArray.IsComplex) { tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<double>)mlArray).ImaginaryByteBuffer, (IByteStorageSupport)mlArray); } break; case MLArray.mxSINGLE_CLASS: mlArray = new MLSingle(name, dims, type, attributes); //read real tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<float>)mlArray).RealByteBuffer, (IByteStorageSupport)mlArray); // read complex if (mlArray.IsComplex) { tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<float>)mlArray).ImaginaryByteBuffer, (IByteStorageSupport)mlArray); } break; case MLArray.mxUINT8_CLASS: mlArray = new MLUInt8(name, dims, type, attributes); //read real tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<byte>)mlArray).RealByteBuffer, (IByteStorageSupport)mlArray); // read complex if (mlArray.IsComplex) { tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<byte>)mlArray).ImaginaryByteBuffer, (IByteStorageSupport)mlArray); } break; case MLArray.mxINT8_CLASS: mlArray = new MLInt8(name, dims, type, attributes); //read real tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<sbyte>)mlArray).RealByteBuffer, (IByteStorageSupport)mlArray); // read complex if (mlArray.IsComplex) { tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<sbyte>)mlArray).ImaginaryByteBuffer, (IByteStorageSupport)mlArray); } break; case MLArray.mxUINT16_CLASS: mlArray = new MLUInt16(name, dims, type, attributes); //read real tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<ushort>)mlArray).RealByteBuffer, (IByteStorageSupport)mlArray); // read complex if (mlArray.IsComplex) { tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<ushort>)mlArray).ImaginaryByteBuffer, (IByteStorageSupport)mlArray); } break; case MLArray.mxINT16_CLASS: mlArray = new MLInt16(name, dims, type, attributes); //read real tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<short>)mlArray).RealByteBuffer, (IByteStorageSupport)mlArray); // read complex if (mlArray.IsComplex) { tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<short>)mlArray).ImaginaryByteBuffer, (IByteStorageSupport)mlArray); } break; case MLArray.mxUINT32_CLASS: mlArray = new MLUInt32(name, dims, type, attributes); //read real tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<uint>)mlArray).RealByteBuffer, (IByteStorageSupport)mlArray); // read complex if (mlArray.IsComplex) { tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<uint>)mlArray).ImaginaryByteBuffer, (IByteStorageSupport)mlArray); } break; case MLArray.mxINT32_CLASS: mlArray = new MLInt32(name, dims, type, attributes); //read real tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<int>)mlArray).RealByteBuffer, (IByteStorageSupport)mlArray); // read complex if (mlArray.IsComplex) { tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<int>)mlArray).ImaginaryByteBuffer, (IByteStorageSupport)mlArray); } break; case MLArray.mxUINT64_CLASS: mlArray = new MLUInt64(name, dims, type, attributes); //read real tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<ulong>)mlArray).RealByteBuffer, (IByteStorageSupport)mlArray); // read complex if (mlArray.IsComplex) { tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<ulong>)mlArray).ImaginaryByteBuffer, (IByteStorageSupport)mlArray); } break; case MLArray.mxINT64_CLASS: mlArray = new MLInt64(name, dims, type, attributes); //read real tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<long>)mlArray).RealByteBuffer, (IByteStorageSupport)mlArray); // read complex if (mlArray.IsComplex) { tag = new ISMatTag(buf); tag.ReadToByteBuffer(((MLNumericArray<long>)mlArray).ImaginaryByteBuffer, (IByteStorageSupport)mlArray); } break; case MLArray.mxCHAR_CLASS: MLChar mlchar = new MLChar(name, dims, type, attributes); //read real tag = new ISMatTag(buf); char[] ac = tag.ReadToCharArray(); for (int i = 0; i < ac.Length; i++) { mlchar.SetChar(ac[i], i); } mlArray = mlchar; break; case MLArray.mxSPARSE_CLASS: MLSparse sparse = new MLSparse(name, dims, attributes, nzmax); // read ir (row indices) tag = new ISMatTag(buf); int[] ir = tag.ReadToIntArray(); // read jc (column indices) tag = new ISMatTag(buf); int[] jc = tag.ReadToIntArray(); // read pr (real part) tag = new ISMatTag(buf); double[] ad1 = tag.ReadToDoubleArray(); int n = 0; for (int i = 0; i < ir.Length; i++) { if (i < sparse.N) { n = jc[i]; } sparse.SetReal(ad1[i], ir[i], n); } //read pi (imaginary part) if (sparse.IsComplex) { tag = new ISMatTag(buf); double[] ad2 = tag.ReadToDoubleArray(); int n1 = 0; for (int i = 0; i < ir.Length; i++) { if (i < sparse.N) { n1 = jc[i]; } sparse.SetImaginary(ad2[i], ir[i], n1); } } mlArray = sparse; break; default: throw new MatlabIOException("Incorrect Matlab array class: " + MLArray.TypeToString(type)); } return mlArray; } /// <summary> /// Converts a byte array to <c>string</c>. It assumes that the string ends with \0 value. /// </summary> /// <param name="bytes">Byte array containing the string.</param> /// <returns>String retrieved from byte array</returns> private string ZeroEndByteArrayToString(byte[] bytes) { StringBuilder sb = new StringBuilder(); foreach (byte b in bytes) { if (b == 0) break; sb.Append((char)b); } return sb.ToString(); } /// <summary> /// Reads Matrix flags. /// </summary> /// <param name="buf"><c>BinaryReader</c> input stream</param> /// <returns>Flags int array</returns> private int[] ReadFlags(Stream buf) { ISMatTag tag = new ISMatTag(buf); int[] flags = tag.ReadToIntArray(); return flags; } /// <summary> /// Reads Matrix dimensions. /// </summary> /// <param name="buf"><c>BinaryReader</c> input stream</param> /// <returns>Dimensions int array</returns> private int[] ReadDimension(Stream buf) { ISMatTag tag = new ISMatTag(buf); int[] dims = tag.ReadToIntArray(); return dims; } /// <summary> /// Reads Matrix name. /// </summary> /// <param name="buf"><c>BinaryReader</c> input stream</param> /// <returns><c>string</c></returns> private string ReadName(Stream buf) { string s; ISMatTag tag = new ISMatTag(buf); char[] ac = tag.ReadToCharArray(); s = new string(ac); return s; } /// <summary> /// Reads MAT-file header. /// </summary> /// <param name="buf"><c>BinaryReader</c> input stream</param> private void ReadHeader(Stream buf) { string description; int version; BinaryReader br = new BinaryReader(buf); byte[] endianIndicator = new byte[2]; //descriptive text 116 bytes byte[] descriptionBuffer = new byte[116]; br.Read(descriptionBuffer, 0, descriptionBuffer.Length); description = ZeroEndByteArrayToString(descriptionBuffer); if (!description.StartsWith("MATLAB 5.0 MAT-file")) { throw new MatlabIOException("This is not a valid MATLAB 5.0 MAT-file."); } // subsyst data offset 8 bytes br.ReadBytes(8); byte[] bversion = new byte[2]; //version 2 bytes br.Read(bversion, 0, bversion.Length); //endian indicator 2 bytes br.Read(endianIndicator, 0, endianIndicator.Length); // Program reading the MAT-file must perform byte swapping to interpret the data // in the MAT-file correctly if ((char)endianIndicator[0] == 'I' && (char)endianIndicator[1] == 'M') { // We have a Little Endian MAT-file version = bversion[1] & 0xff | bversion[0] << 8; } else { // right now, this version of CSMatIO does not support Big Endian throw new MatlabIOException("This version of CSMatIO does not support Big Endian."); } _matFileHeader = new MatFileHeader(description, version, endianIndicator); } /// <summary> /// TAG operator. Facilitates reading operations. /// </summary> /// <remarks> /// <i>Note: Reading from buffer and/or stream modifies it's position.</i> /// </remarks> /// <author>David Zier (<a href="mailto:david.zier@gmail.com">david.zier@gmail.com</a>)</author> private class ISMatTag : MatTag { /// <summary> /// A <c>ByteBuffer</c> object for this tag /// </summary> public BinaryReader Buf; private int padding; /// <summary> /// Create an ISMatTag from a <c>ByteBuffer</c>. /// </summary> /// <param name="buf"><c>ByteBuffer</c></param> public ISMatTag(Stream buf) : base(0, 0) { Buf = new BinaryReader(buf); int tmp = Buf.ReadInt32(); bool compressed; // data not packed in the tag if (tmp >> 16 == 0) { _type = tmp; _size = Buf.ReadInt32(); compressed = false; } else // data _packed_ in the tag (compressed) { _size = tmp >> 16; // 2 more significant bytes _type = tmp & 0xffff; // 2 less significant bytes compressed = true; } padding = GetPadding(_size, compressed); } ///// <summary> ///// Gets the size of the <c>ISMatTag</c> ///// </summary> //public int Size //{ // get { return (int)Buf.BaseStream.Length; } //} /// <summary> /// Read MAT-file tag to a byte buffer. /// </summary> /// <param name="buff"><c>ByteBuffer</c></param> /// <param name="storage"><c>ByteStorageSupport</c></param> public void ReadToByteBuffer( ByteBuffer buff, IByteStorageSupport storage ) { MatFileInputStream mfis = new MatFileInputStream(Buf, _type); int elements = _size / SizeOf(); mfis.ReadToByteBuffer(buff, elements, storage); //skip padding if (padding > 0) Buf.ReadBytes(padding); } /// <summary> /// Read MAT-file tag to a <c>byte</c> array /// </summary> /// <returns><c>byte[]</c></returns> public byte[] ReadToByteArray() { // allocate memory for array elements int elements = _size / SizeOf(); byte[] ab = new byte[elements]; MatFileInputStream mfis = new MatFileInputStream(Buf, _type); for (int i = 0; i < elements; i++) ab[i] = mfis.ReadByte(); // skip padding if (padding > 0) Buf.ReadBytes(padding); return ab; } /// <summary> /// Read MAT-file tag to a <c>double</c> array /// </summary> /// <returns><c>double[]</c></returns> public double[] ReadToDoubleArray() { // allocate memory for array elements int elements = _size / SizeOf(); double[] ad = new double[elements]; MatFileInputStream mfis = new MatFileInputStream(Buf, _type); for (int i = 0; i < elements; i++) ad[i] = mfis.ReadDouble(); // skip padding if (padding > 0) Buf.ReadBytes(padding); return ad; } /// <summary> /// Read MAT-file tag to a <c>int</c> array /// </summary> /// <returns><c>int[]</c></returns> public int[] ReadToIntArray() { // allocate memory for array elements int elements = _size / SizeOf(); int[] ai = new int[elements]; MatFileInputStream mfis = new MatFileInputStream(Buf, _type); for (int i = 0; i < elements; i++) ai[i] = mfis.ReadInt(); // skip padding if (padding > 0) Buf.ReadBytes(padding); return ai; } /// <summary> /// Read MAT-file tag to a <c>char</c> array /// </summary> /// <returns><c>int[]</c></returns> public char[] ReadToCharArray() { // allocate memory for array elements int elements = _size / SizeOf(); char[] ac = new char[elements]; MatFileInputStream mfis = new MatFileInputStream(Buf, _type); for (int i = 0; i < elements; i++) ac[i] = mfis.ReadChar(); // skip padding if (padding > 0) Buf.ReadBytes(padding); return ac; } } } }
// 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 CompareNotGreaterThanOrEqualDouble() { var test = new SimpleBinaryOpTest__CompareNotGreaterThanOrEqualDouble(); 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 SimpleBinaryOpTest__CompareNotGreaterThanOrEqualDouble { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Double); private const int Op2ElementCount = VectorSize / sizeof(Double); private const int RetElementCount = VectorSize / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private SimpleBinaryOpTest__DataTable<Double, Double, Double> _dataTable; static SimpleBinaryOpTest__CompareNotGreaterThanOrEqualDouble() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__CompareNotGreaterThanOrEqualDouble() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Double, Double, Double>(_data1, _data2, new Double[RetElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.CompareNotGreaterThanOrEqual( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.CompareNotGreaterThanOrEqual( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.CompareNotGreaterThanOrEqual( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareNotGreaterThanOrEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareNotGreaterThanOrEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareNotGreaterThanOrEqual), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.CompareNotGreaterThanOrEqual( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var result = Sse2.CompareNotGreaterThanOrEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareNotGreaterThanOrEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse2.CompareNotGreaterThanOrEqual(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__CompareNotGreaterThanOrEqualDouble(); var result = Sse2.CompareNotGreaterThanOrEqual(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.CompareNotGreaterThanOrEqual(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Double> left, Vector128<Double> right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { if (BitConverter.DoubleToInt64Bits(result[0]) != (!(left[0] >= right[0]) ? -1 : 0)) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(result[i]) != (!(left[i] >= right[i]) ? -1 : 0)) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.CompareNotGreaterThanOrEqual)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// // Copyright (c) 2004-2016 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. // using System; namespace NLog.Layouts { using System.ComponentModel; using NLog.Config; using NLog.Internal; /// <summary> /// Abstract interface that layouts must implement. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces", Justification = "Few people will see this conflict.")] [NLogConfigurationItem] public abstract class Layout : ISupportsInitialize, IRenderable { /// <summary> /// Is this layout initialized? See <see cref="Initialize(NLog.Config.LoggingConfiguration)"/> /// </summary> private bool isInitialized; /// <summary> /// Does the layout contains threadAgnostic layout renders? If contains non-threadAgnostic-layoutrendender, then this layout is also not threadAgnostic. /// See <see cref="IsThreadAgnostic"/> and <see cref="Initialize"/>. /// </summary> private bool threadAgnostic; /// <summary> /// Gets a value indicating whether this layout is thread-agnostic (can be rendered on any thread). /// </summary> /// <remarks> /// Layout is thread-agnostic if it has been marked with [ThreadAgnostic] attribute and all its children are /// like that as well. /// Thread-agnostic layouts only use contents of <see cref="LogEventInfo"/> for its output. /// </remarks> internal bool IsThreadAgnostic { get { return this.threadAgnostic; } } /// <summary> /// Gets the logging configuration this target is part of. /// </summary> protected LoggingConfiguration LoggingConfiguration { get; private set; } /// <summary> /// Converts a given text to a <see cref="Layout" />. /// </summary> /// <param name="text">Text to be converted.</param> /// <returns><see cref="SimpleLayout"/> object represented by the text.</returns> public static implicit operator Layout([Localizable(false)] string text) { return FromString(text); } /// <summary> /// Implicitly converts the specified string to a <see cref="SimpleLayout"/>. /// </summary> /// <param name="layoutText">The layout string.</param> /// <returns>Instance of <see cref="SimpleLayout"/>.</returns> public static Layout FromString(string layoutText) { return FromString(layoutText, ConfigurationItemFactory.Default); } /// <summary> /// Implicitly converts the specified string to a <see cref="SimpleLayout"/>. /// </summary> /// <param name="layoutText">The layout string.</param> /// <param name="configurationItemFactory">The NLog factories to use when resolving layout renderers.</param> /// <returns>Instance of <see cref="SimpleLayout"/>.</returns> public static Layout FromString(string layoutText, ConfigurationItemFactory configurationItemFactory) { return new SimpleLayout(layoutText, configurationItemFactory); } /// <summary> /// Precalculates the layout for the specified log event and stores the result /// in per-log event cache. /// /// Only if the layout doesn't have [ThreadAgnostic] and doens't contain layouts with [ThreadAgnostic]. /// </summary> /// <param name="logEvent">The log event.</param> /// <remarks> /// Calling this method enables you to store the log event in a buffer /// and/or potentially evaluate it in another thread even though the /// layout may contain thread-dependent renderer. /// </remarks> public virtual void Precalculate(LogEventInfo logEvent) { if (!this.threadAgnostic) { this.Render(logEvent); } } /// <summary> /// Renders the event info in layout. /// </summary> /// <param name="logEvent">The event info.</param> /// <returns>String representing log event.</returns> public string Render(LogEventInfo logEvent) { if (!this.isInitialized) { this.isInitialized = true; this.InitializeLayout(); } return this.GetFormattedMessage(logEvent); } /// <summary> /// Initializes this instance. /// </summary> /// <param name="configuration">The configuration.</param> void ISupportsInitialize.Initialize(LoggingConfiguration configuration) { this.Initialize(configuration); } /// <summary> /// Closes this instance. /// </summary> void ISupportsInitialize.Close() { this.Close(); } /// <summary> /// Initializes this instance. /// </summary> /// <param name="configuration">The configuration.</param> internal void Initialize(LoggingConfiguration configuration) { if (!this.isInitialized) { this.LoggingConfiguration = configuration; this.isInitialized = true; // determine whether the layout is thread-agnostic // layout is thread agnostic if it is thread-agnostic and // all its nested objects are thread-agnostic. this.threadAgnostic = true; foreach (object item in ObjectGraphScanner.FindReachableObjects<object>(this)) { if (!item.GetType().IsDefined(typeof(ThreadAgnosticAttribute), true)) { this.threadAgnostic = false; break; } } this.InitializeLayout(); } } /// <summary> /// Closes this instance. /// </summary> internal void Close() { if (this.isInitialized) { this.LoggingConfiguration = null; this.isInitialized = false; this.CloseLayout(); } } /// <summary> /// Initializes the layout. /// </summary> protected virtual void InitializeLayout() { } /// <summary> /// Closes the layout. /// </summary> protected virtual void CloseLayout() { } /// <summary> /// Renders the layout for the specified logging event by invoking layout renderers. /// </summary> /// <param name="logEvent">The logging event.</param> /// <returns>The rendered layout.</returns> protected abstract string GetFormattedMessage(LogEventInfo logEvent); /// <summary> /// Register a custom Layout. /// </summary> /// <remarks>Short-cut for registing to default <see cref="ConfigurationItemFactory"/></remarks> /// <typeparam name="T"> Type of the Layout.</typeparam> /// <param name="name"> Name of the Layout.</param> public static void Register<T>(string name) where T : Layout { var layoutRendererType = typeof(T); Register(name, layoutRendererType); } /// <summary> /// Register a custom Layout. /// </summary> /// <remarks>Short-cut for registing to default <see cref="ConfigurationItemFactory"/></remarks> /// <param name="layoutType"> Type of the Layout.</param> /// <param name="name"> Name of the Layout.</param> public static void Register(string name, Type layoutType) { ConfigurationItemFactory.Default.Layouts .RegisterDefinition(name, layoutType); } } }
using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Plivo.Client; namespace Plivo.Resource.Endpoint { /// <summary> /// Endpoint interface. /// </summary> public class EndpointInterface : ResourceInterface { /// <summary> /// Initializes a new instance of the <see cref="T:plivo.Resource.Endpoint.EndpointInterface"/> class. /// </summary> /// <param name="client">Client.</param> public EndpointInterface(HttpClient client) : base(client) { Uri = "Account/" + Client.GetAuthId() + "/Endpoint/"; } #region Create /// <summary> /// Create Endpoint with the specified username, password, alias and appId. /// </summary> /// <returns>The create.</returns> /// <param name="username">Username.</param> /// <param name="password">Password.</param> /// <param name="alias">Alias.</param> /// <param name="appId">App identifier.</param> public EndpointCreateResponse Create( string username, string password, string alias, string appId = null) { var mandatoryParams = new List<string> { "" }; bool isVoiceRequest = true; var data = CreateData( mandatoryParams, new { username, password, alias, appId, isVoiceRequest }); return ExecuteWithExceptionUnwrap(() => { var result = Task.Run(async () => await Client.Update<EndpointCreateResponse>(Uri, data).ConfigureAwait(false)).Result; result.Object.StatusCode = result.StatusCode; return result.Object; }); } /// <summary> /// Asynchronous create Endpoint with the specified username, password, alias and appId. /// </summary> /// <returns>The create.</returns> /// <param name="username">Username.</param> /// <param name="password">Password.</param> /// <param name="alias">Alias.</param> /// <param name="appId">App identifier.</param> public async Task<EndpointCreateResponse> CreateAsync( string username, string password, string alias, string appId = null) { var mandatoryParams = new List<string> { "" }; bool isVoiceRequest = true; var data = CreateData( mandatoryParams, new { username, password, alias, appId, isVoiceRequest }); var result = await Client.Update<EndpointCreateResponse>(Uri, data); result.Object.StatusCode = result.StatusCode; return result.Object; } #endregion #region Get /// <summary> /// Get Endpoint with the specified endpointId. /// </summary> /// <returns>The get.</returns> /// <param name="endpointId">App identifier.</param> public Endpoint Get(string endpointId) { return ExecuteWithExceptionUnwrap(() => { var endpoint = Task.Run(async () => await GetResource<Endpoint>(endpointId, new Dictionary<string, object> () { {"is_voice_request", true} }).ConfigureAwait(false)).Result; endpoint.Interface = this; return endpoint; }); } /// <summary> /// Asynchronous get Endpoint with the specified endpointId. /// </summary> /// <returns>The get.</returns> /// <param name="endpointId">App identifier.</param> public async Task<Endpoint> GetAsync(string endpointId) { var endpoint = await GetResource<Endpoint>(endpointId, new Dictionary<string, object> () { {"is_voice_request", true} }); endpoint.Interface = this; return endpoint; } #endregion #region List /// <summary> /// List Endpoint with the specified subaccount, limit and offset. /// </summary> /// <returns>The list.</returns> /// <param name="subaccount">Subaccount.</param> /// <param name="limit">Limit.</param> /// <param name="offset">Offset.</param> public ListResponse<Endpoint> List( string subaccount = null, uint? limit = null, uint? offset = null) { var mandatoryParams = new List<string> { "" }; bool isVoiceRequest = true; var data = CreateData( mandatoryParams, new { subaccount, limit, offset, isVoiceRequest}); return ExecuteWithExceptionUnwrap(() => { var resources = Task.Run(async () => await ListResources<ListResponse<Endpoint>>(data).ConfigureAwait(false)).Result; resources.Objects.ForEach( (obj) => obj.Interface = this ); return resources; }); } /// <summary> /// List Endpoint with the specified subaccount, limit and offset. /// </summary> /// <returns>The list.</returns> /// <param name="subaccount">Subaccount.</param> /// <param name="limit">Limit.</param> /// <param name="offset">Offset.</param> public async Task<ListResponse<Endpoint>> ListAsync( string subaccount = null, uint? limit = null, uint? offset = null) { var mandatoryParams = new List<string> { "" }; bool isVoiceRequest = true; var data = CreateData( mandatoryParams, new { subaccount, limit, offset, isVoiceRequest }); var resources = await ListResources<ListResponse<Endpoint>>(data); resources.Objects.ForEach( (obj) => obj.Interface = this ); return resources; } #endregion #region Delete /// <summary> /// Delete Endpoint with the specified endpointId. /// </summary> /// <returns>The delete.</returns> /// <param name="endpointId">Endpoint identifier.</param> public DeleteResponse<Endpoint> Delete(string endpointId) { return ExecuteWithExceptionUnwrap(() => { return Task.Run(async () => await DeleteResource<DeleteResponse<Endpoint>>(endpointId, new Dictionary<string, object> () { {"is_voice_request", true} }).ConfigureAwait(false)).Result; }); } /// <summary> /// Asynchronously delete Endpoint with the specified endpointId. /// </summary> /// <returns>The delete.</returns> /// <param name="endpointId">Endpoint identifier.</param> public async Task<DeleteResponse<Endpoint>> DeleteAsync(string endpointId) { return await DeleteResource<DeleteResponse<Endpoint>>(endpointId, new Dictionary<string, object> () { {"is_voice_request", true} }); } #endregion #region Update /// <summary> /// Update Endpoint with the specified endpointId, password, alias and appId. /// </summary> /// <returns>The update.</returns> /// <param name="endpointId">Endpoint identifier.</param> /// <param name="password">Password.</param> /// <param name="alias">Alias.</param> /// <param name="appId">App identifier.</param> public UpdateResponse<Endpoint> Update( string endpointId, string password = null, string alias = null, string appId = null) { var mandatoryParams = new List<string> { "" }; bool isVoiceRequest = true; var data = CreateData( mandatoryParams, new { password, alias, appId, isVoiceRequest }); return ExecuteWithExceptionUnwrap(() => { var result = Task.Run(async () => await Client.Update<UpdateResponse<Endpoint>>(Uri + endpointId + "/", data).ConfigureAwait(false)).Result; result.Object.StatusCode = result.StatusCode; return result.Object; }); } /// <summary> /// Asynchronously update Endpoint with the specified endpointId, password, alias and appId. /// </summary> /// <returns>The update.</returns> /// <param name="endpointId">Endpoint identifier.</param> /// <param name="password">Password.</param> /// <param name="alias">Alias.</param> /// <param name="appId">App identifier.</param> public async Task<UpdateResponse<Endpoint>> UpdateAsync( string endpointId, string password = null, string alias = null, string appId = null) { var mandatoryParams = new List<string> { "" }; bool isVoiceRequest = true; var data = CreateData( mandatoryParams, new { password, alias, appId, isVoiceRequest }); var result = await Client.Update<UpdateResponse<Endpoint>>(Uri + endpointId + "/", data); result.Object.StatusCode = result.StatusCode; return result.Object; } #endregion } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.XWPF.UserModel { using System; using NPOI.OpenXmlFormats.Wordprocessing; using System.Collections.Generic; using System.Text; using System.Xml; /** * XWPFTableCell class. * * @author Gregg Morris (gregg dot morris at gmail dot com) - added XWPFVertAlign enum, * setColor(), * setVerticalAlignment() */ public class XWPFTableCell : IBody { private CT_Tc ctTc; protected List<XWPFParagraph> paragraphs = null; protected List<XWPFTable> tables = null; protected List<IBodyElement> bodyElements = null; protected IBody part; private XWPFTableRow tableRow = null; // Create a map from this XWPF-level enum to the STVerticalJc.Enum values public enum XWPFVertAlign { TOP, CENTER, BOTH, BOTTOM }; private static Dictionary<XWPFVertAlign, ST_VerticalJc> alignMap; // Create a map from the STVerticalJc.Enum values to the XWPF-level enums private static Dictionary<ST_VerticalJc, XWPFVertAlign> stVertAlignTypeMap; static XWPFTableCell() { // populate enum maps alignMap = new Dictionary<XWPFVertAlign, ST_VerticalJc>(); alignMap.Add(XWPFVertAlign.TOP, ST_VerticalJc.top); alignMap.Add(XWPFVertAlign.CENTER, ST_VerticalJc.center); alignMap.Add(XWPFVertAlign.BOTH, ST_VerticalJc.both); alignMap.Add(XWPFVertAlign.BOTTOM, ST_VerticalJc.bottom); stVertAlignTypeMap = new Dictionary<ST_VerticalJc, XWPFVertAlign>(); stVertAlignTypeMap.Add(ST_VerticalJc.top, XWPFVertAlign.TOP); stVertAlignTypeMap.Add(ST_VerticalJc.center, XWPFVertAlign.CENTER); stVertAlignTypeMap.Add(ST_VerticalJc.both, XWPFVertAlign.BOTH); stVertAlignTypeMap.Add(ST_VerticalJc.bottom, XWPFVertAlign.BOTTOM); } /** * If a table cell does not include at least one block-level element, then this document shall be considered corrupt */ public XWPFTableCell(CT_Tc cell, XWPFTableRow tableRow, IBody part) { this.ctTc = cell; this.part = part; this.tableRow = tableRow; // NB: If a table cell does not include at least one block-level element, then this document shall be considered corrupt. if(cell.GetPList().Count<1) cell.AddNewP(); bodyElements = new List<IBodyElement>(); paragraphs = new List<XWPFParagraph>(); tables = new List<XWPFTable>(); foreach (object o in ctTc.Items) { if (o is CT_P) { XWPFParagraph p = new XWPFParagraph((CT_P)o, this); paragraphs.Add(p); bodyElements.Add(p); } if (o is CT_Tbl) { XWPFTable t = new XWPFTable((CT_Tbl)o, this); tables.Add(t); bodyElements.Add(t); } } /* XmlCursor cursor = ctTc.NewCursor(); cursor.SelectPath("./*"); while (cursor.ToNextSelection()) { XmlObject o = cursor.Object; if (o is CTP) { XWPFParagraph p = new XWPFParagraph((CTP)o, this); paragraphs.Add(p); bodyElements.Add(p); } if (o is CTTbl) { XWPFTable t = new XWPFTable((CTTbl)o, this); tables.Add(t); bodyElements.Add(t); } } cursor.Dispose();*/ } public CT_Tc GetCTTc() { return ctTc; } /** * returns an Iterator with paragraphs and tables * @see NPOI.XWPF.UserModel.IBody#getBodyElements() */ public IList<IBodyElement> BodyElements { get { return bodyElements.AsReadOnly(); } } public void SetParagraph(XWPFParagraph p) { if (ctTc.SizeOfPArray() == 0) { ctTc.AddNewP(); } ctTc.SetPArray(0, p.GetCTP()); } /** * returns a list of paragraphs */ public IList<XWPFParagraph> Paragraphs { get { return paragraphs; } } /** * Add a Paragraph to this Table Cell * @return The paragraph which was Added */ public XWPFParagraph AddParagraph() { XWPFParagraph p = new XWPFParagraph(ctTc.AddNewP(), this); AddParagraph(p); return p; } /** * add a Paragraph to this TableCell * @param p the paragaph which has to be Added */ public void AddParagraph(XWPFParagraph p) { paragraphs.Add(p); } /** * Removes a paragraph of this tablecell * @param pos */ public void RemoveParagraph(int pos) { paragraphs.RemoveAt(pos); ctTc.RemoveP(pos); } /** * if there is a corresponding {@link XWPFParagraph} of the parameter ctTable in the paragraphList of this table * the method will return this paragraph * if there is no corresponding {@link XWPFParagraph} the method will return null * @param p is instance of CTP and is searching for an XWPFParagraph * @return null if there is no XWPFParagraph with an corresponding CTPparagraph in the paragraphList of this table * XWPFParagraph with the correspondig CTP p */ public XWPFParagraph GetParagraph(CT_P p) { foreach (XWPFParagraph paragraph in paragraphs) { if(p.Equals(paragraph.GetCTP())){ return paragraph; } } return null; } public void SetBorderBottom(XWPFTable.XWPFBorderType type, int size, int space, String rgbColor) { CT_TcPr ctTcPr = null; if (!GetCTTc().IsSetTcPr()) { ctTcPr = GetCTTc().AddNewTcPr(); } CT_TcBorders borders = ctTcPr.AddNewTcBorders(); borders.bottom = new CT_Border(); CT_Border b = borders.bottom; b.val = XWPFTable.xwpfBorderTypeMap[type]; b.sz = (ulong)size; b.space = (ulong)space; b.color = (rgbColor); } public void SetText(String text) { CT_P ctP = (ctTc.SizeOfPArray() == 0) ? ctTc.AddNewP() : ctTc.GetPArray(0); XWPFParagraph par = new XWPFParagraph(ctP, this); par.CreateRun().SetText(text); } public XWPFTableRow GetTableRow() { return tableRow; } /** * Set cell color. This sets some associated values; for finer control * you may want to access these elements individually. * @param rgbStr - the desired cell color, in the hex form "RRGGBB". */ public void SetColor(String rgbStr) { CT_TcPr tcpr = ctTc.IsSetTcPr() ? ctTc.tcPr : ctTc.AddNewTcPr(); CT_Shd ctshd = tcpr.IsSetShd() ? tcpr.shd : tcpr.AddNewShd(); ctshd.color = ("auto"); ctshd.val = (ST_Shd.clear); ctshd.fill = (rgbStr); } /** * Get cell color. Note that this method only returns the "fill" value. * @return RGB string of cell color */ public String GetColor() { String color = null; CT_TcPr tcpr = ctTc.tcPr; if (tcpr != null) { CT_Shd ctshd = tcpr.shd; if (ctshd != null) { color = ctshd.fill; } } return color; } /** * Set the vertical alignment of the cell. * @param vAlign - the desired alignment enum value */ public void SetVerticalAlignment(XWPFVertAlign vAlign) { CT_TcPr tcpr = ctTc.IsSetTcPr() ? ctTc.tcPr : ctTc.AddNewTcPr(); CT_VerticalJc va = tcpr.AddNewVAlign(); va.val = (alignMap[(vAlign)]); } /** * Get the vertical alignment of the cell. * @return the cell alignment enum value */ public XWPFVertAlign GetVerticalAlignment() { XWPFVertAlign vAlign = XWPFVertAlign.TOP; CT_TcPr tcpr = ctTc.tcPr; if (ctTc != null) { CT_VerticalJc va = tcpr.vAlign; vAlign = stVertAlignTypeMap[(va.val)]; } return vAlign; } /** * add a new paragraph at position of the cursor * @param cursor * @return the inserted paragraph */ public XWPFParagraph InsertNewParagraph(/*XmlCursor*/ XmlDocument cursor) { /*if(!isCursorInTableCell(cursor)) return null; String uri = CTP.type.Name.NamespaceURI; String localPart = "p"; cursor.BeginElement(localPart,uri); cursor.ToParent(); CTP p = (CTP)cursor.Object; XWPFParagraph newP = new XWPFParagraph(p, this); XmlObject o = null; while(!(o is CTP)&&(cursor.ToPrevSibling())){ o = cursor.Object; } if((!(o is CTP)) || (CTP)o == p){ paragraphs.Add(0, newP); } else{ int pos = paragraphs.IndexOf(getParagraph((CTP)o))+1; paragraphs.Add(pos,newP); } int i=0; cursor.ToCursor(p.NewCursor()); while(cursor.ToPrevSibling()){ o =cursor.Object; if(o is CTP || o is CTTbl) i++; } bodyElements.Add(i, newP); cursor.ToCursor(p.NewCursor()); cursor.ToEndToken(); return newP;*/ throw new NotImplementedException(); } public XWPFTable InsertNewTbl(/*XmlCursor*/ XmlDocument cursor) { /*if(isCursorInTableCell(cursor)){ String uri = CTTbl.type.Name.NamespaceURI; String localPart = "tbl"; cursor.BeginElement(localPart,uri); cursor.ToParent(); CTTbl t = (CTTbl)cursor.Object; XWPFTable newT = new XWPFTable(t, this); cursor.RemoveXmlContents(); XmlObject o = null; while(!(o is CTTbl)&&(cursor.ToPrevSibling())){ o = cursor.Object; } if(!(o is CTTbl)){ tables.Add(0, newT); } else{ int pos = tables.IndexOf(getTable((CTTbl)o))+1; tables.Add(pos,newT); } int i=0; cursor = t.NewCursor(); while(cursor.ToPrevSibling()){ o =cursor.Object; if(o is CTP || o is CTTbl) i++; } bodyElements.Add(i, newT); cursor = t.NewCursor(); cursor.ToEndToken(); return newT; } return null;*/ throw new NotImplementedException(); } /** * verifies that cursor is on the right position */ private bool IsCursorInTableCell(/*XmlCursor*/XmlDocument cursor) { /*XmlCursor verify = cursor.NewCursor(); verify.ToParent(); if(verify.Object == this.ctTc){ return true; } return false;*/ throw new NotImplementedException(); } /** * @see NPOI.XWPF.UserModel.IBody#getParagraphArray(int) */ public XWPFParagraph GetParagraphArray(int pos) { if (pos > 0 && pos < paragraphs.Count) { return paragraphs[(pos)]; } return null; } /** * Get the to which the TableCell belongs * * @see NPOI.XWPF.UserModel.IBody#getPart() */ public POIXMLDocumentPart GetPart() { return tableRow.GetTable().GetPart(); } /** * @see NPOI.XWPF.UserModel.IBody#getPartType() */ public BodyType PartType { get { return BodyType.TABLECELL; } } /** * Get a table by its CTTbl-Object * @see NPOI.XWPF.UserModel.IBody#getTable(org.Openxmlformats.schemas.wordProcessingml.x2006.main.CTTbl) */ public XWPFTable GetTable(CT_Tbl ctTable) { for(int i=0; i<tables.Count; i++){ if(this.Tables[(i)].GetCTTbl() == ctTable) return Tables[(i)]; } return null; } /** * @see NPOI.XWPF.UserModel.IBody#getTableArray(int) */ public XWPFTable GetTableArray(int pos) { if (pos >=0 && pos < tables.Count) { return tables[pos]; } return null; } /** * @see NPOI.XWPF.UserModel.IBody#getTables() */ public IList<XWPFTable> Tables { get { return tables.AsReadOnly(); } } /** * inserts an existing XWPFTable to the arrays bodyElements and tables * @see NPOI.XWPF.UserModel.IBody#insertTable(int, NPOI.XWPF.UserModel.XWPFTable) */ public void InsertTable(int pos, XWPFTable table) { bodyElements.Insert(pos, table); int i; for (i = 0; i < ctTc.GetTblList().Count; i++) { CT_Tbl tbl = ctTc.GetTblArray(i); if(tbl == table.GetCTTbl()){ break; } } tables.Insert(i, table); } public String GetText() { StringBuilder text = new StringBuilder(); foreach (XWPFParagraph p in paragraphs) { text.Append(p.Text); } return text.ToString(); } /** * Get the TableCell which belongs to the TableCell */ public XWPFTableCell GetTableCell(CT_Tc cell) { /*XmlCursor cursor = cell.NewCursor(); cursor.ToParent(); XmlObject o = cursor.Object; if(!(o is CTRow)){ return null; } CTRow row = (CTRow)o; cursor.ToParent(); o = cursor.Object; cursor.Dispose(); if(! (o is CTTbl)){ return null; } CTTbl tbl = (CTTbl) o; XWPFTable table = GetTable(tbl); if(table == null){ return null; } XWPFTableRow tableRow = table.GetRow(row); if(tableRow == null){ return null; } return tableRow.GetTableCell(cell);*/ throw new NotImplementedException(); } public XWPFDocument GetXWPFDocument() { return part.GetXWPFDocument(); } }// end class }
// 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.Collections.Generic; using System.Diagnostics; using System.Data; using System.Data.SqlTypes; namespace Microsoft.SqlServer.Server { // DESIGN NOTES // // The following classes are a tight inheritance heirarchy, and are not designed for // being inherited outside of this file. Instances are guaranteed to be immutable, and // outside classes rely on this fact. // // The various levels may not all be used outside of this file, but for clarity of purpose // they are all usefull distinctions to make. // // In general, moving lower in the type heirarchy exposes less portable values. Thus, // the root metadata can be readily shared across different (MSSQL) servers and clients, // while QueryMetaData has attributes tied to a specific query, running against specific // data storage on a specific server. // // The SmiMetaData heirarchy does not do data validation on retail builds! It will assert // that the values passed to it have been validated externally, however. // // SmiMetaData // // Root of the heirarchy. // Represents the minimal amount of metadata required to represent any Sql Server datum // without any references to any particular server or schema (thus, no server-specific multi-part names). // It could be used to communicate solely between two disconnected clients, for instance. // // NOTE: It currently does not contain sufficient information to describe typed XML, since we // don't have a good server-independent mechanism for such. // // This class is also used as implementation for the public SqlMetaData class. internal class SmiMetaData { private SqlDbType _databaseType; // Main enum that determines what is valid for other attributes. private long _maxLength; // Varies for variable-length types, others are fixed value per type private byte _precision; // Varies for SqlDbType.Decimal, others are fixed value per type private byte _scale; // Varies for SqlDbType.Decimal, others are fixed value per type private long _localeId; // Valid only for character types, others are 0 private SqlCompareOptions _compareOptions; // Valid only for character types, others are SqlCompareOptions.Default private bool _isMultiValued; // Multiple instances per value? (I.e. tables, arrays) private IList<SmiExtendedMetaData> _fieldMetaData; // Metadata of fields for structured types private SmiMetaDataPropertyCollection _extendedProperties; // Extended properties, Key columns, sort order, etc. // DevNote: For now, since the list of extended property types is small, we can handle them in a simple list. // In the future, we may need to create a more performant storage & lookup mechanism, such as a hash table // of lists indexed by type of property or an array of lists with a well-known index for each type. // Limits for attributes (SmiMetaData will assert that these limits as applicable in constructor) internal const long UnlimitedMaxLengthIndicator = -1; // unlimited (except by implementation) max-length. internal const long MaxUnicodeCharacters = 4000; // Maximum for limited type internal const long MaxANSICharacters = 8000; // Maximum for limited type internal const long MaxBinaryLength = 8000; // Maximum for limited type internal const int MinPrecision = 1; // SqlDecimal defines max precision internal const int MinScale = 0; // SqlDecimal defines max scale internal const int MaxTimeScale = 7; // Max scale for time, datetime2, and datetimeoffset internal static readonly DateTime MaxSmallDateTime = new DateTime(2079, 06, 06, 23, 59, 29, 998); internal static readonly DateTime MinSmallDateTime = new DateTime(1899, 12, 31, 23, 59, 29, 999); internal static readonly SqlMoney MaxSmallMoney = new SqlMoney(((Decimal)Int32.MaxValue) / 10000); internal static readonly SqlMoney MinSmallMoney = new SqlMoney(((Decimal)Int32.MinValue) / 10000); internal const SqlCompareOptions DefaultStringCompareOptions = SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth; internal const long MaxNameLength = 128; // maximum length in the server is 128. private static readonly IList<SmiExtendedMetaData> s_emptyFieldList = new SmiExtendedMetaData[0]; // Precision to max length lookup table private static byte[] s_maxLenFromPrecision = new byte[] {5,5,5,5,5,5,5,5,5,9,9,9,9,9, 9,9,9,9,9,13,13,13,13,13,13,13,13,13,17,17,17,17,17,17,17,17,17,17}; // Scale offset to max length lookup table private static byte[] s_maxVarTimeLenOffsetFromScale = new byte[] { 2, 2, 2, 1, 1, 0, 0, 0 }; // Defaults // SmiMetaData(SqlDbType, MaxLen, Prec, Scale, CompareOptions) internal static readonly SmiMetaData DefaultBigInt = new SmiMetaData(SqlDbType.BigInt, 8, 19, 0, SqlCompareOptions.None); // SqlDbType.BigInt internal static readonly SmiMetaData DefaultBinary = new SmiMetaData(SqlDbType.Binary, 1, 0, 0, SqlCompareOptions.None); // SqlDbType.Binary internal static readonly SmiMetaData DefaultBit = new SmiMetaData(SqlDbType.Bit, 1, 1, 0, SqlCompareOptions.None); // SqlDbType.Bit internal static readonly SmiMetaData DefaultChar_NoCollation = new SmiMetaData(SqlDbType.Char, 1, 0, 0, DefaultStringCompareOptions);// SqlDbType.Char internal static readonly SmiMetaData DefaultDateTime = new SmiMetaData(SqlDbType.DateTime, 8, 23, 3, SqlCompareOptions.None); // SqlDbType.DateTime internal static readonly SmiMetaData DefaultDecimal = new SmiMetaData(SqlDbType.Decimal, 9, 18, 0, SqlCompareOptions.None); // SqlDbType.Decimal internal static readonly SmiMetaData DefaultFloat = new SmiMetaData(SqlDbType.Float, 8, 53, 0, SqlCompareOptions.None); // SqlDbType.Float internal static readonly SmiMetaData DefaultImage = new SmiMetaData(SqlDbType.Image, UnlimitedMaxLengthIndicator, 0, 0, SqlCompareOptions.None); // SqlDbType.Image internal static readonly SmiMetaData DefaultInt = new SmiMetaData(SqlDbType.Int, 4, 10, 0, SqlCompareOptions.None); // SqlDbType.Int internal static readonly SmiMetaData DefaultMoney = new SmiMetaData(SqlDbType.Money, 8, 19, 4, SqlCompareOptions.None); // SqlDbType.Money internal static readonly SmiMetaData DefaultNChar_NoCollation = new SmiMetaData(SqlDbType.NChar, 1, 0, 0, DefaultStringCompareOptions);// SqlDbType.NChar internal static readonly SmiMetaData DefaultNText_NoCollation = new SmiMetaData(SqlDbType.NText, UnlimitedMaxLengthIndicator, 0, 0, DefaultStringCompareOptions);// SqlDbType.NText internal static readonly SmiMetaData DefaultNVarChar_NoCollation = new SmiMetaData(SqlDbType.NVarChar, MaxUnicodeCharacters, 0, 0, DefaultStringCompareOptions);// SqlDbType.NVarChar internal static readonly SmiMetaData DefaultReal = new SmiMetaData(SqlDbType.Real, 4, 24, 0, SqlCompareOptions.None); // SqlDbType.Real internal static readonly SmiMetaData DefaultUniqueIdentifier = new SmiMetaData(SqlDbType.UniqueIdentifier, 16, 0, 0, SqlCompareOptions.None); // SqlDbType.UniqueIdentifier internal static readonly SmiMetaData DefaultSmallDateTime = new SmiMetaData(SqlDbType.SmallDateTime, 4, 16, 0, SqlCompareOptions.None); // SqlDbType.SmallDateTime internal static readonly SmiMetaData DefaultSmallInt = new SmiMetaData(SqlDbType.SmallInt, 2, 5, 0, SqlCompareOptions.None); // SqlDbType.SmallInt internal static readonly SmiMetaData DefaultSmallMoney = new SmiMetaData(SqlDbType.SmallMoney, 4, 10, 4, SqlCompareOptions.None); // SqlDbType.SmallMoney internal static readonly SmiMetaData DefaultText_NoCollation = new SmiMetaData(SqlDbType.Text, UnlimitedMaxLengthIndicator, 0, 0, DefaultStringCompareOptions);// SqlDbType.Text internal static readonly SmiMetaData DefaultTimestamp = new SmiMetaData(SqlDbType.Timestamp, 8, 0, 0, SqlCompareOptions.None); // SqlDbType.Timestamp internal static readonly SmiMetaData DefaultTinyInt = new SmiMetaData(SqlDbType.TinyInt, 1, 3, 0, SqlCompareOptions.None); // SqlDbType.TinyInt internal static readonly SmiMetaData DefaultVarBinary = new SmiMetaData(SqlDbType.VarBinary, MaxBinaryLength, 0, 0, SqlCompareOptions.None); // SqlDbType.VarBinary internal static readonly SmiMetaData DefaultVarChar_NoCollation = new SmiMetaData(SqlDbType.VarChar, MaxANSICharacters, 0, 0, DefaultStringCompareOptions);// SqlDbType.VarChar internal static readonly SmiMetaData DefaultVariant = new SmiMetaData(SqlDbType.Variant, 8016, 0, 0, SqlCompareOptions.None); // SqlDbType.Variant internal static readonly SmiMetaData DefaultXml = new SmiMetaData(SqlDbType.Xml, UnlimitedMaxLengthIndicator, 0, 0, DefaultStringCompareOptions);// SqlDbType.Xml internal static readonly SmiMetaData DefaultStructured = new SmiMetaData(SqlDbType.Structured, 0, 0, 0, SqlCompareOptions.None); // SqlDbType.Structured internal static readonly SmiMetaData DefaultDate = new SmiMetaData(SqlDbType.Date, 3, 10, 0, SqlCompareOptions.None); // SqlDbType.Date internal static readonly SmiMetaData DefaultTime = new SmiMetaData(SqlDbType.Time, 5, 0, 7, SqlCompareOptions.None); // SqlDbType.Time internal static readonly SmiMetaData DefaultDateTime2 = new SmiMetaData(SqlDbType.DateTime2, 8, 0, 7, SqlCompareOptions.None); // SqlDbType.DateTime2 internal static readonly SmiMetaData DefaultDateTimeOffset = new SmiMetaData(SqlDbType.DateTimeOffset, 10, 0, 7, SqlCompareOptions.None); // SqlDbType.DateTimeOffset // No default for generic UDT internal static SmiMetaData DefaultNVarChar { get { return new SmiMetaData( DefaultNVarChar_NoCollation.SqlDbType, DefaultNVarChar_NoCollation.MaxLength, DefaultNVarChar_NoCollation.Precision, DefaultNVarChar_NoCollation.Scale, Locale.GetCurrentCultureLcid(), SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType | SqlCompareOptions.IgnoreWidth ); } } // SMI V100 (aka V3) constructor. Superceded in V200. internal SmiMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions ) : this(dbType, maxLength, precision, scale, localeId, compareOptions, false, null, null) { } // SMI V200 ctor. internal SmiMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, bool isMultiValued, IList<SmiExtendedMetaData> fieldTypes, SmiMetaDataPropertyCollection extendedProperties) : this(dbType, maxLength, precision, scale, localeId, compareOptions, null, isMultiValued, fieldTypes, extendedProperties) { } // SMI V220 ctor. internal SmiMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, string udtAssemblyQualifiedName, bool isMultiValued, IList<SmiExtendedMetaData> fieldTypes, SmiMetaDataPropertyCollection extendedProperties) { Debug.Assert(IsSupportedDbType(dbType), "Invalid SqlDbType: " + dbType); SetDefaultsForType(dbType); switch (dbType) { case SqlDbType.BigInt: case SqlDbType.Bit: case SqlDbType.DateTime: case SqlDbType.Float: case SqlDbType.Image: case SqlDbType.Int: case SqlDbType.Money: case SqlDbType.Real: case SqlDbType.SmallDateTime: case SqlDbType.SmallInt: case SqlDbType.SmallMoney: case SqlDbType.Timestamp: case SqlDbType.TinyInt: case SqlDbType.UniqueIdentifier: case SqlDbType.Variant: case SqlDbType.Xml: case SqlDbType.Date: break; case SqlDbType.Binary: case SqlDbType.VarBinary: _maxLength = maxLength; break; case SqlDbType.Char: case SqlDbType.NChar: case SqlDbType.NVarChar: case SqlDbType.VarChar: // locale and compare options are not validated until they get to the server _maxLength = maxLength; _localeId = localeId; _compareOptions = compareOptions; break; case SqlDbType.NText: case SqlDbType.Text: _localeId = localeId; _compareOptions = compareOptions; break; case SqlDbType.Decimal: Debug.Assert(MinPrecision <= precision && SqlDecimal.MaxPrecision >= precision, "Invalid precision: " + precision); Debug.Assert(MinScale <= scale && SqlDecimal.MaxScale >= scale, "Invalid scale: " + scale); Debug.Assert(scale <= precision, "Precision: " + precision + " greater than scale: " + scale); _precision = precision; _scale = scale; _maxLength = s_maxLenFromPrecision[precision - 1]; break; case SqlDbType.Udt: throw System.Data.Common.ADP.DbTypeNotSupported(SqlDbType.Udt.ToString()); case SqlDbType.Structured: if (null != fieldTypes) { _fieldMetaData = new System.Collections.ObjectModel.ReadOnlyCollection<SmiExtendedMetaData>(fieldTypes); } _isMultiValued = isMultiValued; _maxLength = _fieldMetaData.Count; break; case SqlDbType.Time: Debug.Assert(MinScale <= scale && scale <= MaxTimeScale, "Invalid time scale: " + scale); _scale = scale; _maxLength = 5 - s_maxVarTimeLenOffsetFromScale[scale]; break; case SqlDbType.DateTime2: Debug.Assert(MinScale <= scale && scale <= MaxTimeScale, "Invalid time scale: " + scale); _scale = scale; _maxLength = 8 - s_maxVarTimeLenOffsetFromScale[scale]; break; case SqlDbType.DateTimeOffset: Debug.Assert(MinScale <= scale && scale <= MaxTimeScale, "Invalid time scale: " + scale); _scale = scale; _maxLength = 10 - s_maxVarTimeLenOffsetFromScale[scale]; break; default: Debug.Assert(false, "How in the world did we get here? :" + dbType); break; } if (null != extendedProperties) { extendedProperties.SetReadOnly(); _extendedProperties = extendedProperties; } // properties and fields must meet the following conditions at this point: // 1) not null // 2) read only // 3) same number of columns in each list (0 count acceptable for properties that are "unused") Debug.Assert(null != _extendedProperties && _extendedProperties.IsReadOnly, "SmiMetaData.ctor: _extendedProperties is " + (null != _extendedProperties ? "writeable" : "null")); Debug.Assert(null != _fieldMetaData && _fieldMetaData.IsReadOnly, "SmiMetaData.ctor: _fieldMetaData is " + (null != _fieldMetaData ? "writeable" : "null")); #if DEBUG ((SmiDefaultFieldsProperty)_extendedProperties[SmiPropertySelector.DefaultFields]).CheckCount(_fieldMetaData.Count); ((SmiUniqueKeyProperty)_extendedProperties[SmiPropertySelector.UniqueKey]).CheckCount(_fieldMetaData.Count); #endif } // Sql-style compare options for character types. internal SqlCompareOptions CompareOptions { get { return _compareOptions; } } // LCID for type. 0 for non-character types. internal long LocaleId { get { return _localeId; } } // Units of length depend on type. // NVarChar, NChar, NText: # of unicode characters // Everything else: # of bytes internal long MaxLength { get { return _maxLength; } } internal byte Precision { get { return _precision; } } internal byte Scale { get { return _scale; } } internal SqlDbType SqlDbType { get { return _databaseType; } } internal bool IsMultiValued { get { return _isMultiValued; } } // Returns read-only list of field metadata internal IList<SmiExtendedMetaData> FieldMetaData { get { return _fieldMetaData; } } // Returns read-only list of extended properties internal SmiMetaDataPropertyCollection ExtendedProperties { get { return _extendedProperties; } } internal static bool IsSupportedDbType(SqlDbType dbType) { // Hole in SqlDbTypes between Xml and Udt for non-WinFS scenarios. return (SqlDbType.BigInt <= dbType && SqlDbType.Xml >= dbType) || (SqlDbType.Udt <= dbType && SqlDbType.DateTimeOffset >= dbType); } // Only correct access point for defaults per SqlDbType. internal static SmiMetaData GetDefaultForType(SqlDbType dbType) { Debug.Assert(IsSupportedDbType(dbType), "Unsupported SqlDbtype: " + dbType); Debug.Assert(dbType != SqlDbType.Udt, "UDT not supported"); return s_defaultValues[(int)dbType]; } // Private constructor used only to initialize default instance array elements. // DO NOT EXPOSE OUTSIDE THIS CLASS! private SmiMetaData( SqlDbType sqlDbType, long maxLength, byte precision, byte scale, SqlCompareOptions compareOptions) { _databaseType = sqlDbType; _maxLength = maxLength; _precision = precision; _scale = scale; _compareOptions = compareOptions; // defaults are the same for all types for the following attributes. _localeId = 0; _isMultiValued = false; _fieldMetaData = s_emptyFieldList; _extendedProperties = SmiMetaDataPropertyCollection.EmptyInstance; } // static array of default-valued metadata ordered by corresponding SqlDbType. // NOTE: INDEXED BY SqlDbType ENUM! MUST UPDATE THIS ARRAY WHEN UPDATING SqlDbType! // ONLY ACCESS THIS GLOBAL FROM GetDefaultForType! private static SmiMetaData[] s_defaultValues = { DefaultBigInt, // SqlDbType.BigInt DefaultBinary, // SqlDbType.Binary DefaultBit, // SqlDbType.Bit DefaultChar_NoCollation, // SqlDbType.Char DefaultDateTime, // SqlDbType.DateTime DefaultDecimal, // SqlDbType.Decimal DefaultFloat, // SqlDbType.Float DefaultImage, // SqlDbType.Image DefaultInt, // SqlDbType.Int DefaultMoney, // SqlDbType.Money DefaultNChar_NoCollation, // SqlDbType.NChar DefaultNText_NoCollation, // SqlDbType.NText DefaultNVarChar_NoCollation, // SqlDbType.NVarChar DefaultReal, // SqlDbType.Real DefaultUniqueIdentifier, // SqlDbType.UniqueIdentifier DefaultSmallDateTime, // SqlDbType.SmallDateTime DefaultSmallInt, // SqlDbType.SmallInt DefaultSmallMoney, // SqlDbType.SmallMoney DefaultText_NoCollation, // SqlDbType.Text DefaultTimestamp, // SqlDbType.Timestamp DefaultTinyInt, // SqlDbType.TinyInt DefaultVarBinary, // SqlDbType.VarBinary DefaultVarChar_NoCollation, // SqlDbType.VarChar DefaultVariant, // SqlDbType.Variant DefaultNVarChar_NoCollation, // Placeholder for value 24 DefaultXml, // SqlDbType.Xml DefaultNVarChar_NoCollation, // Placeholder for value 26 DefaultNVarChar_NoCollation, // Placeholder for value 27 DefaultNVarChar_NoCollation, // Placeholder for value 28 null, DefaultStructured, // Generic structured type DefaultDate, // SqlDbType.Date DefaultTime, // SqlDbType.Time DefaultDateTime2, // SqlDbType.DateTime2 DefaultDateTimeOffset, // SqlDbType.DateTimeOffset }; // Internal setter to be used by constructors only! Modifies state! private void SetDefaultsForType(SqlDbType dbType) { SmiMetaData smdDflt = GetDefaultForType(dbType); _databaseType = dbType; _maxLength = smdDflt.MaxLength; _precision = smdDflt.Precision; _scale = smdDflt.Scale; _localeId = smdDflt.LocaleId; _compareOptions = smdDflt.CompareOptions; _isMultiValued = smdDflt._isMultiValued; _fieldMetaData = smdDflt._fieldMetaData; // This is ok due to immutability _extendedProperties = smdDflt._extendedProperties; // This is ok due to immutability } } // SmiExtendedMetaData // // Adds server-specific type extension information to base metadata, but still portable across a specific server. // internal class SmiExtendedMetaData : SmiMetaData { private string _name; // context-dependant identifier, ie. parameter name for parameters, column name for columns, etc. // three-part name for typed xml schema and for udt names private string _typeSpecificNamePart1; private string _typeSpecificNamePart2; private string _typeSpecificNamePart3; internal SmiExtendedMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3) : this( dbType, maxLength, precision, scale, localeId, compareOptions, false, null, null, name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3) { } // SMI V200 ctor. internal SmiExtendedMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, bool isMultiValued, IList<SmiExtendedMetaData> fieldMetaData, SmiMetaDataPropertyCollection extendedProperties, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3) : this(dbType, maxLength, precision, scale, localeId, compareOptions, null, isMultiValued, fieldMetaData, extendedProperties, name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3) { } // SMI V220 ctor. internal SmiExtendedMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, string udtAssemblyQualifiedName, bool isMultiValued, IList<SmiExtendedMetaData> fieldMetaData, SmiMetaDataPropertyCollection extendedProperties, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3) : base(dbType, maxLength, precision, scale, localeId, compareOptions, udtAssemblyQualifiedName, isMultiValued, fieldMetaData, extendedProperties) { Debug.Assert(null == name || MaxNameLength >= name.Length, "Name is too long"); _name = name; _typeSpecificNamePart1 = typeSpecificNamePart1; _typeSpecificNamePart2 = typeSpecificNamePart2; _typeSpecificNamePart3 = typeSpecificNamePart3; } internal string Name { get { return _name; } } internal string TypeSpecificNamePart1 { get { return _typeSpecificNamePart1; } } internal string TypeSpecificNamePart2 { get { return _typeSpecificNamePart2; } } internal string TypeSpecificNamePart3 { get { return _typeSpecificNamePart3; } } } // SmiParameterMetaData // // MetaData class to send parameter definitions to server. // Sealed because we don't need to derive from it yet. internal sealed class SmiParameterMetaData : SmiExtendedMetaData { private ParameterDirection _direction; // SMI V200 ctor. internal SmiParameterMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, bool isMultiValued, IList<SmiExtendedMetaData> fieldMetaData, SmiMetaDataPropertyCollection extendedProperties, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3, ParameterDirection direction) : this(dbType, maxLength, precision, scale, localeId, compareOptions, null, isMultiValued, fieldMetaData, extendedProperties, name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3, direction) { } // SMI V220 ctor. internal SmiParameterMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, string udtAssemblyQualifiedName, bool isMultiValued, IList<SmiExtendedMetaData> fieldMetaData, SmiMetaDataPropertyCollection extendedProperties, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3, ParameterDirection direction) : base(dbType, maxLength, precision, scale, localeId, compareOptions, udtAssemblyQualifiedName, isMultiValued, fieldMetaData, extendedProperties, name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3) { Debug.Assert(ParameterDirection.Input == direction || ParameterDirection.Output == direction || ParameterDirection.InputOutput == direction || ParameterDirection.ReturnValue == direction, "Invalid direction: " + direction); _direction = direction; } internal ParameterDirection Direction { get { return _direction; } } } // SmiStorageMetaData // // This class represents the addition of storage-level attributes to the heirarchy (i.e. attributes from // underlying table, source variables, or whatever). // // Most values use Null (either IsNullable == true or CLR null) to indicate "Not specified" state. Selection // of which values allow "not specified" determined by backward compatibility. // // Maps approximately to TDS' COLMETADATA token with TABNAME and part of COLINFO thrown in. internal class SmiStorageMetaData : SmiExtendedMetaData { private SqlBoolean _isKey; // Is this one of a set of key columns that uniquely identify an underlying table? // SMI V220 ctor. internal SmiStorageMetaData( SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, bool isMultiValued, IList<SmiExtendedMetaData> fieldMetaData, SmiMetaDataPropertyCollection extendedProperties, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3, SqlBoolean isKey ) : base(dbType, maxLength, precision, scale, localeId, compareOptions, isMultiValued, fieldMetaData, extendedProperties, name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3) { _isKey = isKey; } internal SqlBoolean IsKey { get { return _isKey; } } } // SmiQueryMetaData // // Adds Query-specific attributes. // Sealed since we don't need to extend it for now. // Maps to full COLMETADATA + COLINFO + TABNAME tokens on TDS. internal class SmiQueryMetaData : SmiStorageMetaData { // SMI V220 ctor. internal SmiQueryMetaData(SqlDbType dbType, long maxLength, byte precision, byte scale, long localeId, SqlCompareOptions compareOptions, bool isMultiValued, IList<SmiExtendedMetaData> fieldMetaData, SmiMetaDataPropertyCollection extendedProperties, string name, string typeSpecificNamePart1, string typeSpecificNamePart2, string typeSpecificNamePart3, SqlBoolean isKey ) : base(dbType, maxLength, precision, scale, localeId, compareOptions, isMultiValued, fieldMetaData, extendedProperties, name, typeSpecificNamePart1, typeSpecificNamePart2, typeSpecificNamePart3, isKey ) { } } }
#if MONSTER_TEST_RUNTIME || UNITY_EDITOR using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Xml.Serialization; #if UNITY_EDITOR using UnityEditor; #endif // UNITY_EDITOR namespace Igor { [System.Serializable] #if UNITY_EDITOR [InitializeOnLoad] #endif // UNITY_EDITOR public class MonsterTest : LinkedEntity<MonsterTest> { public bool bAllowRunningInEditor = true; public bool bStartGameInEditor = true; public bool bForceLoadToFirstSceneInEditor = false; public static void RegisterType() { TypeUtils.RegisterType("MonsterTest", CreateNewMonsterTest, CreateMonsterTestSerializer); } public static object CreateNewMonsterTest() { return new MonsterTest(); } public static XmlSerializer CreateMonsterTestSerializer() { return new XmlSerializer(typeof(MonsterTest)); } public static MonsterTest LoadMonsterTest(string Filename) { MonsterTest LoadedInstance = new MonsterTest(); XMLSerializable.SerializeFromXML<MonsterTest>(GetFullPathFromFilename(Filename), ref LoadedInstance, false); return LoadedInstance; } public static string GetFullPathFromFilename(string Filename) { return MonsterTestCore.MonsterLocalDirectoryRoot + "/Config/Tests/" + Filename + ".xml"; } #if UNITY_EDITOR public virtual void EditorSaveMonsterTest() { MonsterTest ThisInst = this; XMLSerializable.SerializeFromXML<MonsterTest>(GetFullPathFromFilename(GetFilename()), ref ThisInst, true); } public override LinkedEntity<MonsterTest> EditorDuplicate(LinkedEntity<MonsterTest> DerivedDuplicateInto = null) { MonsterTest DuplicateInto = (MonsterTest)DerivedDuplicateInto; if(DuplicateInto == null) { DuplicateInto = new MonsterTest(); } return base.EditorDuplicate(DuplicateInto); } public override EntityID GenerateEntityIDForEvent() { EntityID NewID = new EntityID(); NewID.ChapterFilename = Filename; return NewID; } #endif // UNITY_EDITOR public MonsterTestManager TestStates = null; public class MonsterTestLink : EntityLink<MonsterTest> { public override string GetLinkTypeName() { return "MonsterTestLink"; } public override string GetLinkListName() { return "MonsterTestLinks"; } }; public override string GetEntityName() { return "MonsterTest"; } public override string GetLinkTypeName() { return "MonsterTestLink"; } public override string GetLinkListName() { return "LinkedMonsterTests"; } public virtual string GetTestStateListFilename() { return MonsterTestCore.MonsterLocalDirectoryRoot + "/Config/Tests/TestStateList" + GetFilename() + ".xml"; } public override MonsterTest GetLinkedEntityForFilename(string Filename) { // return MonsterTestManager.GetInstance().GetEntityByFileName(Filename); return null; } public override LinkedEntityManager<MonsterTest> GetEntityManager() { return null;//ChapterManager.GetInstance(); } public virtual void LoadTestStates() { TestStates = MonsterTestManager.SwapActiveMonsterTestManager(this); } public virtual IGraphEvent GetStartingEvent() { if(InputEvents.Count > 0) { return GetEventAndTriggerLink(InputEvents[0]); } return null; } public virtual void TestSucceeded() { MonsterDebug.Log("Test succeeded!"); } public virtual void TestFailed() { MonsterDebug.Log("Test failed!"); } public virtual IGraphEvent GetNextTest(EntityLink<MonsterTestBase> NextLink) { foreach(EntityLink<MonsterTest> CurrentLink in OutputEvents) { if(CurrentLink.Name == NextLink.Name) { if(CurrentLink.Name == "Test Succeeded") { TestSucceeded(); } else if(CurrentLink.Name == "Test Failed") { TestFailed(); } if(CurrentLink.LinkedEntities.Count > 0 && CurrentLink.LinkedEntities[0].GetOwner() != null) { return CurrentLink.LinkedEntities[0].GetOwner().GetStartingEvent(); } } } return null; } public override void CreateStaticNodesIfNotPresent() { base.CreateStaticNodesIfNotPresent(); if(InputEvents.Count == 0) { EntityLink<MonsterTest> InputLink = new EntityLink<MonsterTest>(); InputLink.SetOwner(this); InputLink.Name = "Test Started"; InputEvents.Add(InputLink); InputLink = new EntityLink<MonsterTest>(); InputLink.SetOwner(this); InputLink.Name = "Test Failed To Start"; InputEvents.Add(InputLink); } } public override IGraphEvent GetEventAndTriggerLink(EntityLink<MonsterTest> InputLink) { // MonsterTestManager.GetActiveInstance().CurrentNode = this; base.GetEventAndTriggerLink(InputLink); if(TestStates == null) { LoadTestStates(); } /* if(GameManager.GetInstance() != null) { GameManager.GetInstance().ChapterChanged(); }*/ return TestStates.GetEventForStart(InputLink); } public override void SerializeXML() { base.SerializeXML(); SerializeBool("bAllowRunningInEditor", ref bAllowRunningInEditor); SerializeBool("bStartGameInEditor", ref bStartGameInEditor); SerializeBool("bForceLoadToFirstSceneInEditor", ref bForceLoadToFirstSceneInEditor); } } } #endif // MONSTER_TEST_RUNTIME || UNITY_EDITOR
// // CompositeCell.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using System.Linq; using AppKit; using CoreGraphics; using Foundation; using ObjCRuntime; using Xwt.Backends; namespace Xwt.Mac { class CompositeCell : NSView, ICopiableObject, ICellDataSource, INSCopying { ICellSource source; NSObject val; List<ICellRenderer> cells = new List<ICellRenderer> (); ITablePosition tablePosition; ApplicationContext context; public List<ICellRenderer> Cells { get { return cells; } } public CompositeCell (ApplicationContext context, ICellSource source) { if (source == null) throw new ArgumentNullException (nameof (source)); this.context = context; this.source = source; } public CompositeCell (NativeHandle p) : base (p) { } CompositeCell () { } public ApplicationContext Context { get { return context; } } #region ICellDataSource implementation object ICellDataSource.GetValue (IDataField field) { return source.GetValue (tablePosition.Position, field.Index); } #endregion public void SetValue (IDataField field, object value) { source.SetValue (tablePosition.Position, field.Index, value); } public void SetCurrentEventRow () { source.SetCurrentEventRow (tablePosition.Position); } bool recalculatingHeight = false; public void InvalidateRowHeight () { if (tablePosition != null && !recalculatingHeight) { recalculatingHeight = true; source.InvalidateRowHeight (tablePosition.Position); recalculatingHeight = false; } } public double GetRequiredHeightForWidth (double width) { Fill (false); double height = 0; foreach (var c in GetCells (new CGSize (width, -1))) height = Math.Max (height, c.Frame.Height); return height; } public override NSObject Copy () { var ob = (ICopiableObject)base.Copy (); ob.CopyFrom (this); return (NSObject)ob; } NSObject INSCopying.Copy (NSZone zone) { var ob = (ICopiableObject)new CompositeCell (); ob.CopyFrom (this); return (NSObject)ob; } void ICopiableObject.CopyFrom (object other) { var ob = (CompositeCell)other; if (ob.source == null) throw new ArgumentException ("Cannot copy from a CompositeCell with a null `source`"); Identifier = ob.Identifier; context = ob.context; source = ob.source; cells = new List<ICellRenderer> (); foreach (var c in ob.cells) { var copy = (ICellRenderer)Activator.CreateInstance (c.GetType ()); copy.CopyFrom (c); AddCell (copy); } if (tablePosition != null) Fill (false); } public virtual NSObject ObjectValue { [Export ("objectValue")] get { return val; } [Export ("setObjectValue:")] set { val = value; if (val is ITablePosition) { tablePosition = (ITablePosition)val; Fill (); } else if (val is NSNumber) { tablePosition = new TableRow () { Row = ((NSNumber)val).Int32Value }; Fill (); } else tablePosition = null; } } internal ITablePosition TablePosition { get { return tablePosition; } } public void AddCell (ICellRenderer cell) { cell.CellContainer = this; cells.Add (cell); AddSubview ((NSView)cell); } public void ClearCells () { foreach (NSView cell in cells) { cell.RemoveFromSuperview (); } cells.Clear (); } public override CGRect Frame { get { return base.Frame; } set { var oldSize = base.Frame.Size; base.Frame = value; if (oldSize != value.Size && tablePosition != null) { Fill(false); double height = 0; foreach (var c in GetCells (value.Size)) { c.Cell.Frame = c.Frame; c.Cell.NeedsDisplay = true; height = Math.Max (height, c.Frame.Height); } if (Math.Abs(value.Height - height) > double.Epsilon) InvalidateRowHeight (); } } } public void Fill (bool reallocateCells = true) { foreach (var c in cells) { c.Backend.Load (c); c.Fill (); } if (!reallocateCells || Frame.IsEmpty) return; foreach (var c in GetCells (Frame.Size)) { c.Cell.Frame = c.Frame; c.Cell.NeedsDisplay = true; } } public NSView GetCellViewForBackend (ICellViewBackend backend) { return cells.FirstOrDefault (c => c.Backend == backend) as NSView; } CGSize CalcSize () { nfloat w = 0; nfloat h = 0; foreach (var cell in cells) { if (!cell.Backend.Frontend.Visible) continue; var c = (NSView)cell; var s = c.FittingSize; w += s.Width; if (s.Height > h) h = s.Height; } return new CGSize (w, h); } public override CGSize FittingSize { get { return CalcSize (); } } static readonly Selector selSetBackgroundStyle = new Selector ("setBackgroundStyle:"); NSBackgroundStyle backgroundStyle; public virtual NSBackgroundStyle BackgroundStyle { [Export ("backgroundStyle")] get { return backgroundStyle; } [Export ("setBackgroundStyle:")] set { backgroundStyle = value; foreach (NSView cell in cells) if (cell.RespondsToSelector (selSetBackgroundStyle)) { if (IntPtr.Size == 8) Messaging.void_objc_msgSend_Int64 (cell.Handle, selSetBackgroundStyle.Handle, (long)value); else Messaging.void_objc_msgSend_int (cell.Handle, selSetBackgroundStyle.Handle, (int)value); } else cell.NeedsDisplay = true; } } List <CellPos> GetCells (CGSize cellSize) { int nexpands = 0; double requiredSize = 0; double availableSize = cellSize.Width; var cellFrames = new List<CellPos> (cells.Count); // Get the natural size of each child foreach (var cell in cells) { if (!cell.Backend.Frontend.Visible) continue; var cellPos = new CellPos { Cell = (NSView)cell, Frame = CGRect.Empty }; cellFrames.Add (cellPos); var size = cellPos.Cell.FittingSize; cellPos.Frame.Width = size.Width; requiredSize += size.Width; if (cell.Backend.Frontend.Expands) nexpands++; } double remaining = availableSize - requiredSize; if (remaining > 0) { var expandRemaining = new SizeSplitter (remaining, nexpands); foreach (var cellFrame in cellFrames) { if (((ICellRenderer)cellFrame.Cell).Backend.Frontend.Expands) cellFrame.Frame.Width += (nfloat)expandRemaining.NextSizePart (); } } double x = 0; foreach (var cellFrame in cellFrames) { var width = cellFrame.Frame.Width; var canvas = cellFrame.Cell as ICanvasCellRenderer; var height = (canvas != null) ? canvas.GetRequiredSize (SizeConstraint.WithSize (width)).Height : cellFrame.Cell.FittingSize.Height; // y-align only if the cell has a valid height, otherwise we're just recalculating the required size var y = cellSize.Height > 0 ? (cellSize.Height - height) / 2 : 0; cellFrame.Frame = new CGRect (x, y, width, height); x += width; } return cellFrames; } class CellPos { public NSView Cell; public CGRect Frame; } class SizeSplitter { int rem; int part; public SizeSplitter (double total, int numParts) { if (numParts > 0) { part = ((int)total) / numParts; rem = ((int)total) % numParts; } } public double NextSizePart () { if (rem > 0) { rem--; return part + 1; } else return part; } } bool isDisposed; public bool IsDisposed { get { try { // Cocoa may dispose the native view in NSView based table mode // in this case Handle and SuperHandle will become Zero. return isDisposed || Handle == IntPtr.Zero || SuperHandle == IntPtr.Zero; } catch { return true; } } } protected override void Dispose(bool disposing) { isDisposed = true; base.Dispose(disposing); } } }
using Microsoft.Extensions.Logging; using System.Linq; using NBitcoin; using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Text; using NBXplorer.DerivationStrategy; using NBXplorer.Models; using System.Threading.Tasks; using System.Threading; using NBitcoin.Altcoins; using NBitcoin.RPC; using NBXplorer.Logging; using NBXplorer.Configuration; using Newtonsoft.Json.Linq; using static NBXplorer.TrackedTransaction; using Microsoft.Extensions.Hosting; using Microsoft.JSInterop; using System.Buffers; using DBTrie; using DBTrie.Storage.Cache; using System.Diagnostics; namespace NBXplorer { public class GenerateAddressQuery { public GenerateAddressQuery() { } public GenerateAddressQuery(int? minAddresses, int? maxAddresses) { MinAddresses = minAddresses; MaxAddresses = maxAddresses; } public int? MinAddresses { get; set; } public int? MaxAddresses { get; set; } } public class RepositoryProvider : IHostedService { DBTrie.DBTrieEngine _Engine; Dictionary<string, Repository> _Repositories = new Dictionary<string, Repository>(); private readonly KeyPathTemplates keyPathTemplates; ExplorerConfiguration _Configuration; private readonly NBXplorerNetworkProvider networks; public RepositoryProvider(NBXplorerNetworkProvider networks, KeyPathTemplates keyPathTemplates, ExplorerConfiguration configuration) { this.keyPathTemplates = keyPathTemplates; _Configuration = configuration; this.networks = networks; } private ChainConfiguration GetChainSetting(NBXplorerNetwork net) { return _Configuration.ChainConfigurations.FirstOrDefault(c => c.CryptoCode == net.CryptoCode); } public Repository GetRepository(string cryptoCode) { _Repositories.TryGetValue(cryptoCode, out Repository repository); return repository; } public Repository GetRepository(NBXplorerNetwork network) { return GetRepository(network.CryptoCode); } TaskCompletionSource<bool> _StartCompletion = new TaskCompletionSource<bool>(); public Task StartCompletion => _StartCompletion.Task; public async Task StartAsync(CancellationToken cancellationToken) { try { var directory = Path.Combine(_Configuration.DataDir, "db"); if (!Directory.Exists(directory)) Directory.CreateDirectory(directory); _Engine = await OpenEngine(directory, cancellationToken); if (_Configuration.DBCache > 0) { int pageSize = 8192; _Engine.ConfigurePagePool(new PagePool(pageSize, (_Configuration.DBCache * 1000 * 1000) / pageSize)); } foreach (var net in networks.GetAll()) { var settings = GetChainSetting(net); if (settings != null) { var repo = net.NBitcoinNetwork.NetworkSet == Liquid.Instance ? new LiquidRepository(_Engine, net, keyPathTemplates, settings.RPC) : new Repository(_Engine, net, keyPathTemplates, settings.RPC); repo.MaxPoolSize = _Configuration.MaxGapSize; repo.MinPoolSize = _Configuration.MinGapSize; repo.MinUtxoValue = settings.MinUtxoValue; _Repositories.Add(net.CryptoCode, repo); } } foreach (var repo in _Repositories.Select(kv => kv.Value)) { if (GetChainSetting(repo.Network) is ChainConfiguration chainConf && chainConf.Rescan && (chainConf.RescanIfTimeBefore is null || chainConf.RescanIfTimeBefore.Value >= DateTimeOffset.UtcNow)) { Logs.Configuration.LogInformation($"{repo.Network.CryptoCode}: Rescanning the chain..."); await repo.SetIndexProgress(null); } } Logs.Explorer.LogInformation("Defragmenting transaction tables..."); int saved = 0; var defragFile = Path.Combine(Path.Combine(_Configuration.DataDir), "defrag-lock"); if (!File.Exists(defragFile)) { File.Create(defragFile).Close(); foreach (var repo in _Repositories.Select(kv => kv.Value)) { if (GetChainSetting(repo.Network) is ChainConfiguration chainConf) { saved += await repo.DefragmentTables(cancellationToken); } if (File.Exists(defragFile)) File.Delete(defragFile); } Logs.Explorer.LogInformation($"Defragmentation succeed, {PrettyKB(saved)} saved"); } else { Logs.Explorer.LogWarning($"Defragmentation skipped, it seems to have crashed your NBXplorer before. (file {defragFile} already exists)"); } Logs.Explorer.LogInformation("Applying migration if needed, do not close NBXplorer..."); int migrated = 0; foreach (var repo in _Repositories.Select(kv => kv.Value)) { if (GetChainSetting(repo.Network) is ChainConfiguration chainConf) { migrated += await repo.MigrateSavedTransactions(cancellationToken); if (await repo.MigrateOutPoints(_Configuration.DataDir, cancellationToken)) { Logs.Explorer.LogInformation($"Created OutPoint table for {repo.Network.CryptoCode}..."); } } } if (migrated != 0) Logs.Explorer.LogInformation($"Migrated {migrated} tables..."); if (_Configuration.TrimEvents > 0) { Logs.Explorer.LogInformation("Trimming the event table if needed..."); int trimmed = 0; foreach (var repo in _Repositories.Select(kv => kv.Value)) { if (GetChainSetting(repo.Network) is ChainConfiguration chainConf) { trimmed += await repo.TrimmingEvents(_Configuration.TrimEvents, cancellationToken); } } if (trimmed != 0) Logs.Explorer.LogInformation($"Trimmed {trimmed} events in total..."); } _StartCompletion.TrySetResult(true); } catch { _StartCompletion.TrySetCanceled(); throw; } } private string PrettyKB(int bytes) { if (bytes < 1024) return $"{bytes} bytes"; if (bytes / 1024 < 1024) return $"{Math.Round((double)bytes / 1024.0, 2):0.00} kB"; return $"{Math.Round((double)bytes / 1024.0 / 1024.0, 2):0.00} MB"; } private async ValueTask<DBTrieEngine> OpenEngine(string directory, CancellationToken cancellationToken) { int tried = 0; retry: try { return await DBTrie.DBTrieEngine.OpenFromFolder(directory); } catch when (tried < 10) { tried++; await Task.Delay(500, cancellationToken); goto retry; } catch { throw; } } public async Task StopAsync(CancellationToken cancellationToken) { if (_Engine is null) return; await _Engine.DisposeAsync(); } } public class Repository { public async Task Ping() { using var tx = await engine.OpenTransaction(); } public async Task CancelReservation(DerivationStrategyBase strategy, KeyPath[] keyPaths) { if (keyPaths.Length == 0) return; using var tx = await engine.OpenTransaction(); bool needCommit = false; var featuresPerKeyPaths = keyPathTemplates.GetSupportedDerivationFeatures() .Select(f => (Feature: f, KeyPathTemplate: keyPathTemplates.GetKeyPathTemplate(f))) .ToDictionary(o => o.KeyPathTemplate, o => o.Feature); var groups = keyPaths.Where(k => k.Indexes.Length > 0).GroupBy(k => keyPathTemplates.GetKeyPathTemplate(k)); foreach (var group in groups) { if (featuresPerKeyPaths.TryGetValue(group.Key, out DerivationFeature feature)) { var reserved = GetReservedKeysIndex(tx, strategy, feature); var available = GetAvailableKeysIndex(tx, strategy, feature); int availableAdded = 0; foreach (var keyPath in group) { var key = (int)keyPath.Indexes.Last(); using var data = await reserved.SelectBytes(key); if (data == null) continue; await reserved.RemoveKey(data.Key); await available.Insert(data.Key, await data.ReadValue()); availableAdded++; needCommit = true; } UpdateAvailableCountCache(strategy, feature, availableAdded); } } if (needCommit) await tx.Commit(); } class Index { public DBTrie.Table table; public Index(DBTrie.Transaction tx, string tableName, string primaryKey) { PrimaryKey = primaryKey; this.table = tx.GetTable(tableName); } public string PrimaryKey { get; set; } public ValueTask<DBTrie.IRow> SelectBytes(int index) { return table.Get($"{PrimaryKey}-{index:D10}"); } public async ValueTask<bool> RemoveKey(string key) { return await table.Delete($"{PrimaryKey}-{key}"); } public async ValueTask RemoveKey(ReadOnlyMemory<byte> key) { await table.Delete(key); } public async ValueTask Insert(int index, ReadOnlyMemory<byte> value) { await table.Insert($"{index:D10}", value); } public async ValueTask Insert(ReadOnlyMemory<byte> key, ReadOnlyMemory<byte> value) { await (table).Insert(key, value); } // Old tables had a bug with startWith, which // was without effect if PrimaryKey for all row had same length. // To keep backcompatiblility we need to workdaround that // New tables don't have this bug. public bool OldTable { get; set; } = true; public async IAsyncEnumerable<DBTrie.IRow> SelectForwardSkip(int n, string startWith = null, EnumerationOrder order = EnumerationOrder.Ordered) { if (OldTable) { if (startWith == null) startWith = PrimaryKey; else startWith = $"{PrimaryKey}-{startWith}"; } else { startWith ??= string.Empty; startWith = $"{PrimaryKey}-{startWith}"; } int skipped = 0; await foreach (var row in table.Enumerate(startWith, order)) { if (skipped < n) { row.Dispose(); skipped++; } else yield return row; } } public async IAsyncEnumerable<DBTrie.IRow> SelectFrom(long key, int? limit) { var remaining = limit is int l ? l : int.MaxValue; if (remaining is 0) yield break; await foreach (var row in EnumerateFromKey(table, $"{PrimaryKey}-{key:D20}")) { yield return row; remaining--; if (remaining is 0) yield break; } } private async IAsyncEnumerable<IRow> EnumerateFromKey(Table table, string key) { var thisKey = Encoding.UTF8.GetBytes(key).AsMemory(); bool returns = false; await foreach (var row in table.Enumerate()) { if (returns) { yield return row; } else { var comparison = thisKey.Span.SequenceCompareTo(row.Key.Span); if (comparison <= 0) { returns = true; } if (comparison < 0) { yield return row; } else { row.Dispose(); } } } } public async Task<int> Count() { int count = 0; await foreach (var item in table.Enumerate(PrimaryKey)) { using (item) { count++; } } return count; } public async ValueTask Insert(int key, byte[] value) { await Insert($"{key:D10}", value); } public async ValueTask Insert(long key, byte[] value) { await Insert($"{key:D20}", value); } public async ValueTask Insert(string key, byte[] value, bool replace = true) { await table.Insert($"{PrimaryKey}-{key}", value, replace); } public async Task<int?> SelectInt(int index) { using var row = await SelectBytes(index); if (row == null) return null; var v = await row.ReadValue(); uint value = System.Buffers.Binary.BinaryPrimitives.ReadUInt32BigEndian(v.Span); value = value & ~0x8000_0000U; return (int)value; } public async Task<long?> SelectLong(int index) { using var row = await SelectBytes(index); if (row == null) return null; var v = await row.ReadValue(); ulong value = System.Buffers.Binary.BinaryPrimitives.ReadUInt64BigEndian(v.Span); value = value & ~0x8000_0000_0000_0000UL; return (long)value; } public async ValueTask Insert(int key, int value) { var bytes = NBitcoin.Utils.ToBytes((uint)value, false); await Insert(key, bytes); } public async ValueTask Insert(int key, long value) { var bytes = NBitcoin.Utils.ToBytes((ulong)value, false); await Insert(key, bytes); } } Index GetAvailableKeysIndex(DBTrie.Transaction tx, DerivationStrategyBase trackedSource, DerivationFeature feature) { return new Index(tx, $"{_Suffix}AvailableKeys", $"{trackedSource.GetHash()}-{feature}"); } Index GetScriptsIndex(DBTrie.Transaction tx, Script scriptPubKey) { return new Index(tx, $"{_Suffix}Scripts", $"{scriptPubKey.Hash}"); } Index GetOutPointsIndex(DBTrie.Transaction tx, OutPoint outPoint) { return new Index(tx, $"{_Suffix}OutPoints", $"{outPoint}") { OldTable = false }; } Index GetHighestPathIndex(DBTrie.Transaction tx, DerivationStrategyBase strategy, DerivationFeature feature) { return new Index(tx, $"{_Suffix}HighestPath", $"{strategy.GetHash()}-{feature}"); } Index GetReservedKeysIndex(DBTrie.Transaction tx, DerivationStrategyBase strategy, DerivationFeature feature) { return new Index(tx, $"{_Suffix}ReservedKeys", $"{strategy.GetHash()}-{feature}"); } Index GetTransactionsIndex(DBTrie.Transaction tx, TrackedSource trackedSource) { return new Index(tx, $"{_Suffix}Transactions", $"{trackedSource.GetHash()}"); } Index GetMetadataIndex(DBTrie.Transaction tx, TrackedSource trackedSource) { return new Index(tx, $"{_Suffix}Metadata", $"{trackedSource.GetHash()}"); } Index GetEventsIndex(DBTrie.Transaction tx) { return new Index(tx, $"{_Suffix}Events", string.Empty); } protected NBXplorerNetwork _Network; private readonly KeyPathTemplates keyPathTemplates; private readonly RPCClient rpc; public NBXplorerNetwork Network { get { return _Network; } } DBTrie.DBTrieEngine engine; internal Repository(DBTrie.DBTrieEngine engine, NBXplorerNetwork network, KeyPathTemplates keyPathTemplates, RPCClient rpc) { if (network == null) throw new ArgumentNullException(nameof(network)); _Network = network; this.keyPathTemplates = keyPathTemplates; this.rpc = rpc; Serializer = new Serializer(_Network); _Network = network; this.engine = engine; _Suffix = network.CryptoCode == "BTC" ? "" : network.CryptoCode; } public string _Suffix; public async Task<BlockLocator> GetIndexProgress() { using var tx = await engine.OpenTransaction(); using var existingRow = await tx.GetTable($"{_Suffix}IndexProgress").Get(""); if (existingRow == null) return null; BlockLocator locator = new BlockLocator(); locator.FromBytes(DBTrie.PublicExtensions.GetUnderlyingArraySegment(await existingRow.ReadValue()).Array); return locator; } public async Task SetIndexProgress(BlockLocator locator) { using var tx = await engine.OpenTransaction(); if (locator == null) await tx.GetTable($"{_Suffix}IndexProgress").Delete(string.Empty); else await tx.GetTable($"{_Suffix}IndexProgress").Insert(string.Empty, locator.ToBytes()); await tx.Commit(); } public async Task<KeyPathInformation> GetUnused(DerivationStrategyBase strategy, DerivationFeature derivationFeature, int n, bool reserve) { KeyPathInformation keyInfo = null; using (var tx = await engine.OpenTransaction()) { var availableTable = GetAvailableKeysIndex(tx, strategy, derivationFeature); var reservedTable = GetReservedKeysIndex(tx, strategy, derivationFeature); var rows = availableTable.SelectForwardSkip(n); await using var enumerator = rows.GetAsyncEnumerator(); if (!await enumerator.MoveNextAsync()) { await enumerator.DisposeAsync(); return null; } using var row = enumerator.Current; await enumerator.DisposeAsync(); keyInfo = ToObject<KeyPathInformation>(await row.ReadValue()).AddAddress(Network.NBitcoinNetwork); if (reserve) { await availableTable.RemoveKey(row.Key); UpdateAvailableCountCache(strategy, derivationFeature, -1); await reservedTable.Insert(row.Key, await row.ReadValue()); await tx.Commit(); } } if (keyInfo != null) { await ImportAddressToRPC(keyInfo.TrackedSource, keyInfo.Address, keyInfo.KeyPath); } return keyInfo; } Dictionary<(DerivationStrategyBase, DerivationFeature), int> _AvailableCache = new Dictionary<(DerivationStrategyBase, DerivationFeature), int>(); // Count() iterates on all the row, so if the table is big we need to cache this. // However, because this may introduce other bugs, we only do this for big pools. bool NeedCaching(int count) => count > 1000; bool TryGetAvailableCountFromCache(DerivationStrategyBase strategyBase, DerivationFeature derivationFeature, out int count) { lock (_AvailableCache) { return _AvailableCache.TryGetValue((strategyBase, derivationFeature), out count); } } void CleanAvailableCountToCache(DerivationStrategyBase derivationStrategy, DerivationFeature key) { lock (_AvailableCache) { _AvailableCache.Remove((derivationStrategy, key)); } } void SetAvailableCountToCache(DerivationStrategyBase strategy, DerivationFeature derivationFeature, int count) { if (!NeedCaching(count)) return; lock (_AvailableCache) { _AvailableCache.AddOrReplace((strategy, derivationFeature), count); } } void UpdateAvailableCountCache(DerivationStrategyBase strategy, DerivationFeature derivationFeature, int inc) { if (strategy is null) return; lock (_AvailableCache) { if (_AvailableCache.TryGetValue((strategy, derivationFeature), out var v)) { v += inc; _AvailableCache[(strategy, derivationFeature)] = v; } } } async Task<int> GetAddressToGenerateCount(DBTrie.Transaction tx, DerivationStrategyBase strategy, DerivationFeature derivationFeature) { if (!TryGetAvailableCountFromCache(strategy, derivationFeature, out var currentlyAvailable)) { var availableTable = GetAvailableKeysIndex(tx, strategy, derivationFeature); // Count() iterates on all the row, so if the table is big we need to cache this. // However, because this may introduce other bugs, we only do this for big pools. currentlyAvailable = await availableTable.Count(); SetAvailableCountToCache(strategy, derivationFeature, currentlyAvailable); } if (currentlyAvailable >= MinPoolSize) return 0; return Math.Max(0, MaxPoolSize - currentlyAvailable); } private async ValueTask RefillAvailable(DBTrie.Transaction tx, DerivationStrategyBase strategy, DerivationFeature derivationFeature, int toGenerate) { if (toGenerate <= 0) return; var availableTable = GetAvailableKeysIndex(tx, strategy, derivationFeature); var highestTable = GetHighestPathIndex(tx, strategy, derivationFeature); int highestGenerated = (await highestTable.SelectInt(0)) ?? -1; var feature = strategy.GetLineFor(keyPathTemplates.GetKeyPathTemplate(derivationFeature)); KeyPathInformation[] keyPathInformations = new KeyPathInformation[toGenerate]; Parallel.For(0, toGenerate, i => { var index = highestGenerated + i + 1; var derivation = feature.Derive((uint)index); var info = new KeyPathInformation(derivation, new DerivationSchemeTrackedSource(strategy), derivationFeature, keyPathTemplates.GetKeyPathTemplate(derivationFeature).GetKeyPath(index, false), Network); keyPathInformations[i] = info; }); int availableAdded = 0; for (int i = 0; i < toGenerate; i++) { var index = highestGenerated + i + 1; var info = keyPathInformations[i]; var bytes = ToBytes(info); await GetScriptsIndex(tx, info.ScriptPubKey).Insert($"{strategy.GetHash()}-{derivationFeature}", bytes); await availableTable.Insert(index, bytes); availableAdded++; } UpdateAvailableCountCache(strategy, derivationFeature, availableAdded); await highestTable.Insert(0, highestGenerated + toGenerate); await tx.Commit(); } public async Task<long> SaveEvent(NewEventBase evt) { // Fetch the lastEventId on row 0 // Increment it, // Insert event using var tx = await engine.OpenTransaction(); var idx = GetEventsIndex(tx); var lastEventIndexMaybe = await idx.SelectLong(0); var lastEventIndex = lastEventIndexMaybe.HasValue ? lastEventIndexMaybe.Value + 1 : 1; await idx.Insert(0, lastEventIndex); await idx.Insert(lastEventIndex, this.ToBytes(evt.ToJObject(Serializer.Settings))); await tx.Commit(); lastKnownEventIndex = lastEventIndex; return lastEventIndex; } long lastKnownEventIndex = -1; public async Task<IList<NewEventBase>> GetLatestEvents(int limit = 10) { using var tx = await engine.OpenTransaction(); if (limit < 1) return new List<NewEventBase>(); // Find the last event id var idx = GetEventsIndex(tx); var lastEventIndexMaybe = await idx.SelectLong(0); var lastEventIndex = lastEventIndexMaybe.HasValue ? lastEventIndexMaybe.Value : lastKnownEventIndex; // If less than 1, no events exist if (lastEventIndex < 1) return new List<NewEventBase>(); // Find where we want to start selecting // smallest value ex. limit = 1, lastEventIndex = 1 // 1 - 1 = 0 So we will never select index 0 (Which stores last index) var startId = lastEventIndex - limit; // Event must exist since lastEventIndex >= 1, set minimum to 0. var lastEventId = startId < 0 ? 0 : startId; // SelectFrom returns the first event after lastEventId // to lastEventId = 0 means it will select starting from the first event var query = idx.SelectFrom(lastEventId, limit); IList<NewEventBase> evts = new List<NewEventBase>(); await foreach (var value in query) { using (value) { var id = ExtractLong(value.Key); var evt = NewEventBase.ParseEvent(ToObject<JObject>(await value.ReadValue()), Serializer.Settings); evt.EventId = id; evts.Add(evt); } } return evts; } private long ExtractLong(ReadOnlyMemory<byte> key) { var span = Encoding.UTF8.GetString(key.Span).AsSpan(); var sep = span.LastIndexOf('-'); span = span.Slice(sep + 1); return long.Parse(span); } public async Task<IList<NewEventBase>> GetEvents(long lastEventId, int? limit = null) { if (lastEventId < 1 && limit.HasValue && limit.Value != int.MaxValue) limit = limit.Value + 1; // The row with key 0 holds the lastEventId using var tx = await engine.OpenTransaction(); if (lastKnownEventIndex != -1 && lastKnownEventIndex == lastEventId) return new List<NewEventBase>(); var idx = GetEventsIndex(tx); var query = idx.SelectFrom(lastEventId, limit); IList<NewEventBase> evts = new List<NewEventBase>(); await foreach (var value in query) { using (value) { var id = ExtractLong(value.Key); if (id == 0) // Last Index continue; var evt = NewEventBase.ParseEvent(ToObject<JObject>(await value.ReadValue()), Serializer.Settings); evt.EventId = id; evts.Add(evt); } } return evts; } public async Task SaveKeyInformations(KeyPathInformation[] keyPathInformations) { using var tx = await engine.OpenTransaction(); foreach (var info in keyPathInformations) { var bytes = ToBytes(info); await GetScriptsIndex(tx, info.ScriptPubKey).Insert($"{info.DerivationStrategy.GetHash()}-{info.Feature}", bytes); } await tx.Commit(); } public async Task<Dictionary<OutPoint, TxOut>> GetOutPointToTxOut(IList<OutPoint> outPoints) { var result = new Dictionary<OutPoint, TxOut>(); if (outPoints.Count == 0) return result; foreach (var batch in outPoints.Batch(BatchSize)) { using var tx = await engine.OpenTransaction(); foreach (var outPoint in batch) { var table = GetOutPointsIndex(tx, outPoint); await foreach (var row in table.SelectForwardSkip(0)) { using (row) { var bytes = await row.ReadValue(); var txout = Network.NBitcoinNetwork.Consensus.ConsensusFactory.CreateTxOut(); txout.ReadWrite(bytes.ToArray(), Network.NBitcoinNetwork); result[outPoint] = txout; } } } } return result; } public async Task Track(IDestination address) { using var tx = await engine.OpenTransaction(); var info = new KeyPathInformation() { ScriptPubKey = address.ScriptPubKey, TrackedSource = (TrackedSource)address, Address = (address as BitcoinAddress) ?? address.ScriptPubKey.GetDestinationAddress(Network.NBitcoinNetwork) }; var bytes = ToBytes(info); await GetScriptsIndex(tx, address.ScriptPubKey).Insert(address.ScriptPubKey.Hash.ToString(), bytes); await tx.Commit(); } public Task<int> GenerateAddresses(DerivationStrategyBase strategy, DerivationFeature derivationFeature, int maxAddresses) { return GenerateAddresses(strategy, derivationFeature, new GenerateAddressQuery(null, maxAddresses)); } public async Task<int> GenerateAddresses(DerivationStrategyBase strategy, DerivationFeature derivationFeature, GenerateAddressQuery query = null) { query = query ?? new GenerateAddressQuery(); using var tx = await engine.OpenTransaction(); var toGenerate = await GetAddressToGenerateCount(tx, strategy, derivationFeature); if (query.MaxAddresses is int max) toGenerate = Math.Min(max, toGenerate); if (query.MinAddresses is int min) toGenerate = Math.Max(min, toGenerate); await RefillAvailable(tx, strategy, derivationFeature, toGenerate); return toGenerate; } class TimeStampedTransaction : IBitcoinSerializable { public TimeStampedTransaction() { } public TimeStampedTransaction(Network network, ReadOnlyMemory<byte> hex) { var segment = DBTrie.PublicExtensions.GetUnderlyingArraySegment(hex); var stream = new BitcoinStream(segment.Array, segment.Offset, segment.Count); stream.ConsensusFactory = network.Consensus.ConsensusFactory; this.ReadWrite(stream); } public TimeStampedTransaction(NBitcoin.Transaction tx, ulong timestamp) { _TimeStamp = timestamp; _Transaction = tx; } NBitcoin.Transaction _Transaction; public NBitcoin.Transaction Transaction { get { return _Transaction; } set { _Transaction = value; } } ulong _TimeStamp = 0; public ulong TimeStamp { get { return _TimeStamp; } set { _TimeStamp = value; } } public void ReadWrite(BitcoinStream stream) { stream.ReadWrite(ref _Transaction); // So we don't crash on transactions indexed on old versions if (stream.Serializing || stream.Inner.Position != stream.Inner.Length) stream.ReadWrite(ref _TimeStamp); } } public int BatchSize { get; set; } = 100; public async Task<List<SavedTransaction>> SaveTransactions(DateTimeOffset now, NBitcoin.Transaction[] transactions, uint256 blockHash) { var result = new List<SavedTransaction>(); transactions = transactions.Distinct().ToArray(); if (transactions.Length == 0) return result; foreach (var batch in transactions.Batch(BatchSize)) { using var tx = await engine.OpenTransaction(); var date = NBitcoin.Utils.DateTimeToUnixTime(now); foreach (var btx in batch) { var timestamped = new TimeStampedTransaction(btx, date); var value = timestamped.ToBytes(); var key = GetSavedTransactionKey(btx.GetHash(), blockHash); await GetSavedTransactionTable(tx).Insert(key, value); result.Add(ToSavedTransaction(Network.NBitcoinNetwork, key, value)); } await tx.Commit(); } return result; } public class SavedTransaction { public NBitcoin.Transaction Transaction { get; set; } public uint256 BlockHash { get; set; } public DateTimeOffset Timestamp { get; set; } } public async Task<SavedTransaction[]> GetSavedTransactions(uint256 txid) { List<SavedTransaction> saved = new List<SavedTransaction>(); using var tx = await engine.OpenTransaction(); var table = GetSavedTransactionTable(tx); await foreach (var row in table.Enumerate(GetSavedTransactionKey(txid, null))) { using (row) { SavedTransaction t = ToSavedTransaction(Network.NBitcoinNetwork, row.Key, await row.ReadValue()); saved.Add(t); } } return saved.ToArray(); } private static SavedTransaction ToSavedTransaction(Network network, ReadOnlyMemory<byte> key, ReadOnlyMemory<byte> value) { SavedTransaction t = new SavedTransaction(); if (key.Length > 32) { t.BlockHash = new uint256(key.Span.Slice(32)); } var timeStamped = new TimeStampedTransaction(network, value); t.Transaction = timeStamped.Transaction; t.Timestamp = NBitcoin.Utils.UnixTimeToDateTime(timeStamped.TimeStamp); t.Transaction.PrecomputeHash(true, false); return t; } public async Task<MultiValueDictionary<Script, KeyPathInformation>> GetKeyInformations(IList<Script> scripts) { MultiValueDictionary<Script, KeyPathInformation> result = new MultiValueDictionary<Script, KeyPathInformation>(); if (scripts.Count == 0) return result; foreach (var batch in scripts.Batch(BatchSize)) { using var tx = await engine.OpenTransaction(); foreach (var script in batch) { var table = GetScriptsIndex(tx, script); var keyInfos = new List<KeyPathInformation>(); await foreach (var row in table.SelectForwardSkip(0)) { using (row) { var keyInfo = ToObject<KeyPathInformation>(await row.ReadValue()) .AddAddress(Network.NBitcoinNetwork); // Because xpub are mutable (several xpub map to same script) // an attacker could generate lot's of xpub mapping to the same script // and this would blow up here. This we take only 5 results max. keyInfos.Add(keyInfo); if (keyInfos.Count == 5) break; } } result.AddRange(script, keyInfos); } } return result; } public Serializer Serializer { get; private set; } private T ToObject<T>(ReadOnlyMemory<byte> value) { var result = Serializer.ToObject<T>(Unzip(value)); // For back compat, some old serialized KeyPathInformation do not have TrackedSource property set if (result is KeyPathInformation keyPathInfo) { if (keyPathInfo.TrackedSource == null && keyPathInfo.DerivationStrategy != null) { keyPathInfo.TrackedSource = new DerivationSchemeTrackedSource(keyPathInfo.DerivationStrategy); } } return result; } private byte[] ToBytes<T>(T obj) { return Zip(Serializer.ToString<T>(obj)); } private byte[] Zip(string unzipped) { MemoryStream ms = new MemoryStream(); using (GZipStream gzip = new GZipStream(ms, CompressionMode.Compress)) { StreamWriter writer = new StreamWriter(gzip, Encoding.UTF8); writer.Write(unzipped); writer.Flush(); } return ms.ToArray(); } private string Unzip(ReadOnlyMemory<byte> bytes) { var segment = DBTrie.PublicExtensions.GetUnderlyingArraySegment(bytes); MemoryStream ms = new MemoryStream(segment.Array, segment.Offset, segment.Count); using (GZipStream gzip = new GZipStream(ms, CompressionMode.Decompress)) { StreamReader reader = new StreamReader(gzip, Encoding.UTF8); var unzipped = reader.ReadToEnd(); return unzipped; } } public int MinPoolSize { get; set; } = 20; public int MaxPoolSize { get; set; } = 30; public Money MinUtxoValue { get; set; } = Money.Satoshis(1); public async Task<TrackedTransaction[]> GetTransactions(TrackedSource trackedSource, uint256 txId = null, CancellationToken cancellation = default) { Dictionary<uint256, long> firstSeenList = new Dictionary<uint256, long>(); HashSet<ITrackedTransactionSerializable> needRemove = new HashSet<ITrackedTransactionSerializable>(); HashSet<ITrackedTransactionSerializable> needUpdate = new HashSet<ITrackedTransactionSerializable>(); var transactions = new List<ITrackedTransactionSerializable>(); using (var tx = await engine.OpenTransaction(cancellation)) { var table = GetTransactionsIndex(tx, trackedSource); await foreach (var row in table.SelectForwardSkip(0, txId?.ToString(), EnumerationOrder.Unordered)) { using (row) { cancellation.ThrowIfCancellationRequested(); var seg = DBTrie.PublicExtensions.GetUnderlyingArraySegment(await row.ReadValue()); MemoryStream ms = new MemoryStream(seg.Array, seg.Offset, seg.Count); BitcoinStream bs = new BitcoinStream(ms, false); bs.ConsensusFactory = Network.NBitcoinNetwork.Consensus.ConsensusFactory; var data = CreateBitcoinSerializableTrackedTransaction(TrackedTransactionKey.Parse(row.Key.Span)); data.ReadWrite(bs); transactions.Add(data); long firstSeen; if (firstSeenList.TryGetValue(data.Key.TxId, out firstSeen)) { if (firstSeen > data.FirstSeenTickCount) firstSeenList[data.Key.TxId] = firstSeen; } else { firstSeenList.Add(data.Key.TxId, data.FirstSeenTickCount); } } } } ITrackedTransactionSerializable previousConfirmed = null; foreach (var tx in transactions) { if (tx.Key.BlockHash != null) { if (!tx.Key.IsPruned) { previousConfirmed = tx; } else if (previousConfirmed != null && tx.Key.TxId == previousConfirmed.Key.TxId && tx.Key.BlockHash == previousConfirmed.Key.BlockHash) { needRemove.Add(tx); foreach (var kv in tx.KnownKeyPathMapping) { // The pruned transaction has more info about owned utxo than the unpruned, we need to update the unpruned if (previousConfirmed.KnownKeyPathMapping.TryAdd(kv.Key, kv.Value)) needUpdate.Add(previousConfirmed); } } else { previousConfirmed = null; } } if (tx.FirstSeenTickCount != firstSeenList[tx.Key.TxId]) { needUpdate.Add(tx); tx.FirstSeenTickCount = firstSeenList[tx.Key.TxId]; } } if (needUpdate.Count != 0 || needRemove.Count != 0) { #pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed Cleanup(trackedSource, needRemove, needUpdate); #pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed } var tracked = new TrackedTransaction[transactions.Count - needRemove.Count]; int i = 0; foreach (var tx in transactions.Where(tt => !needRemove.Contains(tt))) tracked[i++] = ToTrackedTransaction(tx, trackedSource); Debug.Assert(tracked.Length == i); return tracked; } private async Task Cleanup(TrackedSource trackedSource, HashSet<ITrackedTransactionSerializable> needRemove, HashSet<ITrackedTransactionSerializable> needUpdate) { using (var tx = await engine.OpenTransaction()) { var table = GetTransactionsIndex(tx, trackedSource); foreach (var data in needUpdate.Where(t => !needRemove.Contains(t))) { await table.Insert(data.Key.ToString(), data.ToBytes()); } foreach (var data in needRemove) { await table.RemoveKey(data.Key.ToString()); } await tx.Commit(); } } TrackedTransaction ToTrackedTransaction(ITrackedTransactionSerializable tx, TrackedSource trackedSource) { var trackedTransaction = CreateTrackedTransaction(trackedSource, tx); trackedTransaction.Inserted = tx.TickCount == 0 ? NBitcoin.Utils.UnixTimeToDateTime(0) : new DateTimeOffset((long)tx.TickCount, TimeSpan.Zero); trackedTransaction.FirstSeen = tx.FirstSeenTickCount == 0 ? NBitcoin.Utils.UnixTimeToDateTime(0) : new DateTimeOffset((long)tx.FirstSeenTickCount, TimeSpan.Zero); return trackedTransaction; } public async Task SaveMetadata<TMetadata>(TrackedSource source, string key, TMetadata value) where TMetadata : class { using var tx = await engine.OpenTransaction(); var table = GetMetadataIndex(tx, source); if (value != null) { await table.Insert(key, Zip(Serializer.ToString(value))); _NoMetadataCache.Remove((source, key)); } else { await table.RemoveKey(key); _NoMetadataCache.Add((source, key)); } await tx.Commit(); } FixedSizeCache<(TrackedSource, String), string> _NoMetadataCache = new FixedSizeCache<(TrackedSource, String), string>(100, (kv) => $"{kv.Item1}:{kv.Item2}"); public async Task<TMetadata> GetMetadata<TMetadata>(TrackedSource source, string key) where TMetadata : class { if (_NoMetadataCache.Contains((source, key))) return default; using var tx = await engine.OpenTransaction(); var table = GetMetadataIndex(tx, source); await foreach (var row in table.SelectForwardSkip(0, key)) { using (row) { return Serializer.ToObject<TMetadata>(Unzip(await row.ReadValue())); } } _NoMetadataCache.Add((source, key)); return null; } public async Task SaveMatches(TrackedTransaction[] transactions) { if (transactions.Length == 0) return; var groups = transactions.GroupBy(i => i.TrackedSource); using var tx = await engine.OpenTransaction(); retry: bool aggressiveCommit = false; try { foreach (var group in groups) { var table = GetTransactionsIndex(tx, group.Key); foreach (var value in group) { if (group.Key is DerivationSchemeTrackedSource s) { foreach (var kv in value.KnownKeyPathMapping) { var derivation = s.DerivationStrategy.GetDerivation(kv.Value); var info = new KeyPathInformation(derivation, s, keyPathTemplates.GetDerivationFeature(kv.Value), kv.Value, _Network); var availableIndex = GetAvailableKeysIndex(tx, s.DerivationStrategy, info.Feature); var reservedIndex = GetReservedKeysIndex(tx, s.DerivationStrategy, info.Feature); var index = info.GetIndex(); var bytes = await availableIndex.SelectBytes(index); if (bytes != null) { await availableIndex.RemoveKey(bytes.Key); UpdateAvailableCountCache(info.DerivationStrategy, info.Feature, -1); } bytes = await reservedIndex.SelectBytes(index); if (bytes != null) { bytes.Dispose(); await reservedIndex.RemoveKey(bytes.Key); } } } var ms = new MemoryStream(); BitcoinStream bs = new BitcoinStream(ms, true); bs.ConsensusFactory = Network.NBitcoinNetwork.Consensus.ConsensusFactory; var data = value.CreateBitcoinSerializable(); bs.ReadWrite(data); await table.Insert(data.Key.ToString(), ms.ToArrayEfficient(), false); foreach (var coin in CreateTrackedTransaction(group.Key, data).ReceivedCoins) { var bytes = coin.TxOut.ToBytes(); await GetOutPointsIndex(tx, coin.Outpoint).Insert(0, bytes); } } if (aggressiveCommit) { await tx.Commit(); } } } catch (NoMorePageAvailableException) when (!aggressiveCommit) { aggressiveCommit = true; tx.Rollback(); goto retry; } await tx.Commit(); } internal async Task Prune(TrackedSource trackedSource, IEnumerable<TrackedTransaction> prunable) { if (prunable == null) return; if (prunable is IList<TrackedTransaction> pl && pl.Count == 0) return; if (prunable is TrackedTransaction[] pa && pa.Length == 0) return; using var tx = await engine.OpenTransaction(); var table = GetTransactionsIndex(tx, trackedSource); int deleted = 0; foreach (var tracked in prunable) { await table.RemoveKey(tracked.Key.ToString()); deleted++; if (deleted % BatchSize == 0) await tx.Commit(); } await tx.Commit(); } internal async Task UpdateAddressPool(DerivationSchemeTrackedSource trackedSource, Dictionary<DerivationFeature, int?> highestKeyIndexFound) { using var tx = await engine.OpenTransaction(); foreach (var kv in highestKeyIndexFound) { if (kv.Value == null) continue; var index = GetAvailableKeysIndex(tx, trackedSource.DerivationStrategy, kv.Key); CleanAvailableCountToCache(trackedSource.DerivationStrategy, kv.Key); bool needRefill = await CleanUsed(kv.Value.Value, index); index = GetReservedKeysIndex(tx, trackedSource.DerivationStrategy, kv.Key); needRefill |= await CleanUsed(kv.Value.Value, index); if (needRefill) { var hIndex = GetHighestPathIndex(tx, trackedSource.DerivationStrategy, kv.Key); int highestGenerated = (await hIndex.SelectInt(0)) ?? -1; if (highestGenerated < kv.Value.Value) await hIndex.Insert(0, kv.Value.Value); var toGenerate = await GetAddressToGenerateCount(tx, trackedSource.DerivationStrategy, kv.Key); await RefillAvailable(tx, trackedSource.DerivationStrategy, kv.Key, toGenerate); } } await tx.Commit(); } private async Task<bool> CleanUsed(int highestIndex, Index index) { bool needRefill = false; List<string> toRemove = new List<string>(); foreach (var row in await index.SelectForwardSkip(0).ToArrayAsync()) { using (row) { var keyInfo = ToObject<KeyPathInformation>(await row.ReadValue()); if (keyInfo.GetIndex() <= highestIndex) { await index.RemoveKey(row.Key); needRefill = true; } } } return needRefill; } FixedSizeCache<uint256, uint256> noMatchCache = new FixedSizeCache<uint256, uint256>(5000, k => k); public Task<TrackedTransaction[]> GetMatches(NBitcoin.Transaction tx, uint256 blockId, DateTimeOffset now, bool useCache) { return GetMatches(new[] { tx }, blockId, now, useCache); } public async Task<TrackedTransaction[]> GetMatches(IList<NBitcoin.Transaction> txs, uint256 blockId, DateTimeOffset now, bool useCache) { foreach (var tx in txs) tx.PrecomputeHash(false, true); var outputCount = txs.Select(tx => tx.Outputs.Count).Sum(); var inputCount = txs.Select(tx => tx.Inputs.Count).Sum(); var outpointCount = inputCount + outputCount; var scripts = new List<Script>(outpointCount); var transactionsPerOutpoint = new MultiValueDictionary<OutPoint, NBitcoin.Transaction>(inputCount); var transactionsPerScript = new MultiValueDictionary<Script, NBitcoin.Transaction>(outpointCount); var matches = new Dictionary<string, TrackedTransaction>(); var noMatchTransactions = new HashSet<uint256>(txs.Count); var transactions = new Dictionary<uint256, NBitcoin.Transaction>(txs.Count); var outpoints = new List<OutPoint>(inputCount); foreach (var tx in txs) { if (!transactions.TryAdd(tx.GetHash(), tx)) continue; if (blockId != null && useCache && noMatchCache.Contains(tx.GetHash())) { continue; } noMatchTransactions.Add(tx.GetHash()); if (!tx.IsCoinBase) { foreach (var input in tx.Inputs) { transactionsPerOutpoint.Add(input.PrevOut, tx); if (transactions.TryGetValue(input.PrevOut.Hash, out var prevtx)) { // Maybe this tx is spending another tx in the same block, in which case, it will not be fetched by GetOutPointToTxOut, // so we need to add it here. var txout = prevtx.Outputs[input.PrevOut.N]; scripts.Add(txout.ScriptPubKey); transactionsPerScript.Add(txout.ScriptPubKey, tx); } else { // Else, let's try to fetch it later. outpoints.Add(input.PrevOut); } } } foreach (var output in tx.Outputs) { if (MinUtxoValue != null && output.Value < MinUtxoValue) continue; scripts.Add(output.ScriptPubKey); transactionsPerScript.Add(output.ScriptPubKey, tx); } } foreach (var kv in await GetOutPointToTxOut(outpoints)) { if (kv.Value is null) continue; scripts.Add(kv.Value.ScriptPubKey); foreach (var tx in transactionsPerOutpoint[kv.Key]) { transactionsPerScript.Add(kv.Value.ScriptPubKey, tx); } } if (scripts.Count == 0) return Array.Empty<TrackedTransaction>(); var keyPathInformationsByTrackedTransaction = new MultiValueDictionary<TrackedTransaction, KeyPathInformation>(); var keyInformations = await GetKeyInformations(scripts); foreach (var keyInfoByScripts in keyInformations) { foreach (var tx in transactionsPerScript[keyInfoByScripts.Key]) { if (keyInfoByScripts.Value.Count != 0) noMatchTransactions.Remove(tx.GetHash()); foreach (var keyInfo in keyInfoByScripts.Value) { var matchesGroupingKey = $"{keyInfo.DerivationStrategy?.ToString() ?? keyInfo.ScriptPubKey.ToHex()}-[{tx.GetHash()}]"; if (!matches.TryGetValue(matchesGroupingKey, out TrackedTransaction match)) { match = CreateTrackedTransaction(keyInfo.TrackedSource, new TrackedTransactionKey(tx.GetHash(), blockId, false), tx, new Dictionary<Script, KeyPath>()); match.FirstSeen = now; match.Inserted = now; matches.Add(matchesGroupingKey, match); } if (keyInfo.KeyPath != null) match.KnownKeyPathMapping.TryAdd(keyInfo.ScriptPubKey, keyInfo.KeyPath); keyPathInformationsByTrackedTransaction.Add(match, keyInfo); } } } foreach (var m in matches.Values) { m.KnownKeyPathMappingUpdated(); await AfterMatch(m, keyPathInformationsByTrackedTransaction[m]); } foreach (var tx in txs) { if (blockId == null && noMatchTransactions.Contains(tx.GetHash())) { noMatchCache.Add(tx.GetHash()); } } return matches.Values.Count == 0 ? Array.Empty<TrackedTransaction>() : matches.Values.ToArray(); } public virtual TrackedTransaction CreateTrackedTransaction(TrackedSource trackedSource, TrackedTransactionKey transactionKey, NBitcoin.Transaction tx, Dictionary<Script, KeyPath> knownScriptMapping) { return new TrackedTransaction(transactionKey, trackedSource, tx, knownScriptMapping); } public virtual TrackedTransaction CreateTrackedTransaction(TrackedSource trackedSource, TrackedTransactionKey transactionKey, IEnumerable<Coin> coins, Dictionary<Script, KeyPath> knownScriptMapping) { return new TrackedTransaction(transactionKey, trackedSource, coins, knownScriptMapping); } public virtual TrackedTransaction CreateTrackedTransaction(TrackedSource trackedSource, ITrackedTransactionSerializable tx) { return tx.Key.IsPruned ? CreateTrackedTransaction(trackedSource, tx.Key, tx.GetCoins(), tx.KnownKeyPathMapping) : CreateTrackedTransaction(trackedSource, tx.Key, tx.Transaction, tx.KnownKeyPathMapping); } protected virtual ITrackedTransactionSerializable CreateBitcoinSerializableTrackedTransaction(TrackedTransactionKey trackedTransactionKey) { return new TrackedTransaction.TransactionMatchData(trackedTransactionKey); } protected virtual async Task AfterMatch(TrackedTransaction tx, IReadOnlyCollection<KeyPathInformation> keyInfos) { var shouldImportRPC = (await GetMetadata<string>(tx.TrackedSource, WellknownMetadataKeys.ImportAddressToRPC)).AsBoolean(); if (!shouldImportRPC) return; var accountKey = await GetMetadata<BitcoinExtKey>(tx.TrackedSource, WellknownMetadataKeys.AccountHDKey); foreach (var keyInfo in keyInfos) { await ImportAddressToRPC(accountKey, keyInfo.Address, keyInfo.KeyPath); } } private async Task ImportAddressToRPC(TrackedSource trackedSource, BitcoinAddress address, KeyPath keyPath) { var shouldImportRPC = (await GetMetadata<string>(trackedSource, WellknownMetadataKeys.ImportAddressToRPC)).AsBoolean(); if (!shouldImportRPC) return; var accountKey = await GetMetadata<BitcoinExtKey>(trackedSource, WellknownMetadataKeys.AccountHDKey); await ImportAddressToRPC(accountKey, address, keyPath); } private async Task ImportAddressToRPC(BitcoinExtKey accountKey, BitcoinAddress address, KeyPath keyPath) { if (accountKey != null) { await rpc.ImportPrivKeyAsync(accountKey.Derive(keyPath).PrivateKey.GetWif(Network.NBitcoinNetwork), null, false); } else { try { await rpc.ImportAddressAsync(address, null, false); } catch (RPCException) // Probably the private key has already been imported { } } } public async ValueTask<int> DefragmentTables(CancellationToken cancellationToken = default) { using var tx = await engine.OpenTransaction(cancellationToken); var table = tx.GetTable($"{_Suffix}Transactions"); return await Defragment(tx, table, cancellationToken); } public async ValueTask<int> TrimmingEvents(int maxEvents, CancellationToken cancellationToken = default) { using var tx = await engine.OpenTransaction(); var idx = GetEventsIndex(tx); // The first row is not a real event var eventCount = await idx.table.GetRecordCount() - 1; int deletedEvents = 0; while (eventCount > maxEvents) { var removing = (int)Math.Min(5000, eventCount - maxEvents); Logs.Explorer.LogInformation($"{Network.CryptoCode}: There is currently {eventCount} in the event table, removing a batch of {removing} of the oldest one."); var rows = await idx.SelectFrom(0, removing).ToArrayAsync(); foreach (var row in rows) { // Low evictable page, we should commit if (idx.table.PagePool.FreePageCount == 0 && (idx.table.PagePool.EvictablePageCount < idx.table.PagePool.MaxPageCount / 10)) await tx.Commit(); await idx.table.Delete(row.Key); deletedEvents++; row.Dispose(); } await tx.Commit(); eventCount = await idx.table.GetRecordCount() - 1; } try { await Defragment(tx, idx.table, cancellationToken); } catch (IndexOutOfRangeException) { Logs.Explorer.LogWarning($"{Network.CryptoCode}: The event table seems corrupted, deleting it..."); await idx.table.Delete(); } return deletedEvents; } private async ValueTask<int> Defragment(DBTrie.Transaction tx, Table table, CancellationToken cancellationToken) { int saved = 0; try { saved = await table.Defragment(cancellationToken); } catch when (!cancellationToken.IsCancellationRequested) { Logs.Explorer.LogWarning($"{Network.CryptoCode}: Careful, you are probably running low on storage space, so we attempt defragmentation directly on the table, please do not close NBXplorer during the defragmentation."); saved = await table.UnsafeDefragment(cancellationToken); } await tx.Commit(); table.ClearCache(); return saved; } public async ValueTask<int> MigrateSavedTransactions(CancellationToken cancellationToken = default) { using var tx = await engine.OpenTransaction(cancellationToken); var savedTransactions = GetSavedTransactionTable(tx); var legacyTableName = $"{_Suffix}tx-"; var legacyTables = await tx.Schema.GetTables(legacyTableName).ToArrayAsync(); if (legacyTables.Length == 0) return 0; int deleted = 0; var lastLogTime = DateTimeOffset.UtcNow; foreach (var tableName in legacyTables) { cancellationToken.ThrowIfCancellationRequested(); var legacyTable = tx.GetTable(tableName); await foreach (var row in legacyTable.Enumerate()) { using (row) { var txId = tableName.Substring(legacyTableName.Length); var blockId = Encoding.UTF8.GetString(row.Key.Span); await savedTransactions.Insert(GetSavedTransactionKey(new uint256(txId), blockId == "0" ? null : new uint256(blockId)), await row.ReadValue()); } } await tx.Commit(); await legacyTable.Delete(); deleted++; if (DateTimeOffset.UtcNow - lastLogTime > TimeSpan.FromMinutes(1.0)) { Logs.Explorer.LogInformation($"{Network.CryptoCode}: Still migrating tables {legacyTables.Length - deleted} remaining..."); lastLogTime = DateTimeOffset.UtcNow; } } return legacyTables.Length; } public async ValueTask<bool> MigrateOutPoints(string directory, CancellationToken cancellationToken = default) { using var tx = await engine.OpenTransaction(cancellationToken); var tableNameList = await tx.Schema.GetTables($"{_Suffix}OutPoints").ToArrayAsync(); string markerFilePath = Path.Combine(directory, "outpoint-migration.lock"); if (tableNameList.Length == 0) { Logs.Explorer.LogInformation($"{Network.CryptoCode}: No OutPoint Table found..."); Logs.Explorer.LogInformation($"{Network.CryptoCode}: Starting the Outpoint Migration..."); } else if (File.Exists(markerFilePath)) { Logs.Explorer.LogInformation($"{Network.CryptoCode}: OutPoint migration was interupted last time..."); Logs.Explorer.LogInformation($"{Network.CryptoCode}: Restarting the Outpoint Migration..."); } else { return false; } File.Create(markerFilePath).Close(); bool fixOldData = false; retry: try { int txnCount = 0; await foreach (var row in tx.GetTable($"{_Suffix}Transactions").Enumerate()) { txnCount++; using (row) { cancellationToken.ThrowIfCancellationRequested(); var seg = DBTrie.PublicExtensions.GetUnderlyingArraySegment(await row.ReadValue()); MemoryStream ms = new MemoryStream(seg.Array, seg.Offset, seg.Count); BitcoinStream bs = new BitcoinStream(ms, false); bs.ConsensusFactory = Network.NBitcoinNetwork.Consensus.ConsensusFactory; var data = CreateBitcoinSerializableTrackedTransaction(TrackedTransactionKey.Parse(row.Key.Span)); data.ReadWrite(bs); foreach (var coin in data.GetCoins()) { var bytes = coin.TxOut.ToBytes(); await GetOutPointsIndex(tx, coin.Outpoint).Insert(0, bytes); } } if (txnCount % BatchSize == 0) await tx.Commit(); } await tx.Commit(); } catch (FormatException) when (!fixOldData) { Logs.Explorer.LogWarning("Error while fetching outdated data from Transaction table... fixing the situation"); var invalidTxRows = tx.GetTable($"{_Suffix}InvalidTransactionsRows"); var transactions = tx.GetTable($"{_Suffix}Transactions"); fixOldData = true; int txnCount = 0; await foreach (var row in transactions.Enumerate()) { using (row) { try { TrackedTransactionKey.Parse(row.Key.Span); continue; } catch (FormatException) { txnCount++; } cancellationToken.ThrowIfCancellationRequested(); await invalidTxRows.Insert(row.Key, await row.ReadValue(), false); } if (txnCount % BatchSize == 0) await tx.Commit(); } await foreach (var row in invalidTxRows.Enumerate()) { using (row) { txnCount++; await transactions.Delete(row.Key); if (txnCount % BatchSize == 0) await tx.Commit(); } } await tx.Commit(); goto retry; } File.Delete(markerFilePath); return true; } private ReadOnlyMemory<byte> GetSavedTransactionKey(uint256 txId, uint256 blockId) { var key = new byte[blockId is null ? 32 : 64]; txId.ToBytes(key); if (blockId is uint256) { blockId.ToBytes(key.AsSpan().Slice(32)); } return key.AsMemory(); } private Table GetSavedTransactionTable(DBTrie.Transaction tx) { return tx.GetTable($"{_Suffix}Txs"); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. #region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a // References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll #endregion using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.CallStack; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Metadata; using Microsoft.VisualStudio.Debugger.Symbols; using Roslyn.Utilities; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; using TypeCode = Microsoft.VisualStudio.Debugger.Metadata.TypeCode; namespace Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation { public class DkmClrValue : DkmDataContainer { internal DkmClrValue( object value, object hostObjectValue, DkmClrType type, string alias, DkmEvaluationResultFlags evalFlags, DkmClrValueFlags valueFlags, DkmEvaluationResultCategory category = default(DkmEvaluationResultCategory), DkmEvaluationResultAccessType access = default(DkmEvaluationResultAccessType), ulong nativeComPointer = 0) { Debug.Assert((type == null) || !type.GetLmrType().IsTypeVariables() || (valueFlags == DkmClrValueFlags.Synthetic)); Debug.Assert((alias == null) || evalFlags.Includes(DkmEvaluationResultFlags.HasObjectId)); // The "real" DkmClrValue will always have a value of zero for null pointers. Debug.Assert((type == null) || !type.GetLmrType().IsPointer || (value != null)); this.RawValue = value; this.HostObjectValue = hostObjectValue; this.Type = type; this.Alias = alias; this.EvalFlags = evalFlags; this.ValueFlags = valueFlags; this.Category = category; this.Access = access; this.NativeComPointer = nativeComPointer; } public readonly DkmEvaluationResultFlags EvalFlags; public readonly DkmClrValueFlags ValueFlags; public readonly DkmClrType Type; public readonly DkmStackWalkFrame StackFrame; public readonly DkmEvaluationResultCategory Category; public readonly DkmEvaluationResultAccessType Access; public readonly DkmEvaluationResultStorageType StorageType; public readonly DkmEvaluationResultTypeModifierFlags TypeModifierFlags; public readonly DkmDataAddress Address; public readonly object HostObjectValue; public readonly string Alias; public readonly ulong NativeComPointer; internal readonly object RawValue; public void Close() { } public DkmClrValue Dereference(DkmInspectionContext inspectionContext) { if (inspectionContext == null) { throw new ArgumentNullException(nameof(inspectionContext)); } if (RawValue == null) { throw new InvalidOperationException("Cannot dereference invalid value"); } var elementType = this.Type.GetLmrType().GetElementType(); var evalFlags = DkmEvaluationResultFlags.None; var valueFlags = DkmClrValueFlags.None; object value; try { var intPtr = Environment.Is64BitProcess ? new IntPtr((long)RawValue) : new IntPtr((int)RawValue); value = Dereference(intPtr, elementType); } catch (Exception e) { value = e; evalFlags |= DkmEvaluationResultFlags.ExceptionThrown; } var valueType = new DkmClrType(this.Type.RuntimeInstance, (value == null || elementType.IsPointer) ? elementType : (TypeImpl)value.GetType()); return new DkmClrValue( value, value, valueType, alias: null, evalFlags: evalFlags, valueFlags: valueFlags, category: DkmEvaluationResultCategory.Other, access: DkmEvaluationResultAccessType.None); } public bool IsNull { get { if (this.IsError()) { // Should not be checking value for Error. (Throw rather than // assert since the property may be called during debugging.) throw new InvalidOperationException(); } var lmrType = Type.GetLmrType(); return ((RawValue == null) && !lmrType.IsValueType) || (lmrType.IsPointer && (Convert.ToInt64(RawValue) == 0)); } } internal static object GetHostObjectValue(Type lmrType, object rawValue) { // NOTE: This is just a "for testing purposes" approximation of what the real DkmClrValue.HostObjectValue // will return. We will need to update this implementation to match the real behavior we add // specialized support for additional types. var typeCode = Metadata.Type.GetTypeCode(lmrType); return (lmrType.IsPointer || lmrType.IsEnum || typeCode != TypeCode.DateTime || typeCode != TypeCode.Object) ? rawValue : null; } public string GetValueString(DkmInspectionContext inspectionContext, ReadOnlyCollection<string> formatSpecifiers) { if (inspectionContext == null) { throw new ArgumentNullException(nameof(inspectionContext)); } return inspectionContext.InspectionSession.InvokeFormatter(this, MethodId.GetValueString, f => f.GetValueString(this, inspectionContext, formatSpecifiers)); } public bool HasUnderlyingString(DkmInspectionContext inspectionContext) { if (inspectionContext == null) { throw new ArgumentNullException(nameof(inspectionContext)); } return inspectionContext.InspectionSession.InvokeFormatter(this, MethodId.HasUnderlyingString, f => f.HasUnderlyingString(this, inspectionContext)); } public string GetUnderlyingString(DkmInspectionContext inspectionContext) { if (inspectionContext == null) { throw new ArgumentNullException(nameof(inspectionContext)); } return inspectionContext.InspectionSession.InvokeFormatter(this, MethodId.GetUnderlyingString, f => f.GetUnderlyingString(this, inspectionContext)); } public void GetResult( DkmWorkList WorkList, DkmClrType DeclaredType, DkmClrCustomTypeInfo CustomTypeInfo, DkmInspectionContext InspectionContext, ReadOnlyCollection<string> FormatSpecifiers, string ResultName, string ResultFullName, DkmCompletionRoutine<DkmEvaluationAsyncResult> CompletionRoutine) { InspectionContext.InspectionSession.InvokeResultProvider( this, MethodId.GetResult, r => { r.GetResult( this, WorkList, DeclaredType, CustomTypeInfo, InspectionContext, FormatSpecifiers, ResultName, ResultFullName, CompletionRoutine); return (object)null; }); } public string EvaluateToString(DkmInspectionContext inspectionContext) { if (inspectionContext == null) { throw new ArgumentNullException(nameof(inspectionContext)); } // This is a rough approximation of the real functionality. Basically, // if object.ToString is not overridden, we return null and it is the // caller's responsibility to compute a string. var type = this.Type.GetLmrType(); while (type != null) { if (type.IsObject() || type.IsValueType()) { return null; } // We should check the signature and virtual-ness, but this is // close enough for testing. if (type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).Any(m => m.Name == "ToString")) { break; } type = type.BaseType; } var rawValue = RawValue; Debug.Assert(rawValue != null || this.Type.GetLmrType().IsVoid(), "In our mock system, this should only happen for void."); return rawValue == null ? null : rawValue.ToString(); } /// <remarks> /// Very simple expression evaluation (may not support all syntax supported by Concord). /// </remarks> public void EvaluateDebuggerDisplayString(DkmWorkList workList, DkmInspectionContext inspectionContext, DkmClrType targetType, string formatString, DkmCompletionRoutine<DkmEvaluateDebuggerDisplayStringAsyncResult> completionRoutine) { Debug.Assert(!this.IsNull, "Not supported by VIL"); if (inspectionContext == null) { throw new ArgumentNullException(nameof(inspectionContext)); } var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; int openPos = -1; int length = formatString.Length; for (int i = 0; i < length; i++) { char ch = formatString[i]; if (ch == '{') { if (openPos >= 0) { throw new ArgumentException(string.Format("Nested braces in '{0}'", formatString)); } openPos = i; } else if (ch == '}') { if (openPos < 0) { throw new ArgumentException(string.Format("Unmatched closing brace in '{0}'", formatString)); } string name = formatString.Substring(openPos + 1, i - openPos - 1); openPos = -1; var formatSpecifiers = Formatter.NoFormatSpecifiers; int commaIndex = name.IndexOf(','); if (commaIndex >= 0) { var rawFormatSpecifiers = name.Substring(commaIndex + 1).Split(','); var trimmedFormatSpecifiers = ArrayBuilder<string>.GetInstance(rawFormatSpecifiers.Length); trimmedFormatSpecifiers.AddRange(rawFormatSpecifiers.Select(fs => fs.Trim())); formatSpecifiers = trimmedFormatSpecifiers.ToImmutableAndFree(); foreach (var formatSpecifier in formatSpecifiers) { if (formatSpecifier == "nq") { inspectionContext = new DkmInspectionContext(inspectionContext.InspectionSession, inspectionContext.EvaluationFlags | DkmEvaluationFlags.NoQuotes, inspectionContext.Radix, inspectionContext.RuntimeInstance); } // If we need to support additional format specifiers, add them here... } name = name.Substring(0, commaIndex); } var type = ((TypeImpl)this.Type.GetLmrType()).Type; const System.Reflection.BindingFlags bindingFlags = System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Static; DkmClrValue exprValue; var appDomain = this.Type.AppDomain; var field = type.GetField(name, bindingFlags); if (field != null) { var fieldValue = field.GetValue(RawValue); exprValue = new DkmClrValue( fieldValue, fieldValue, DkmClrType.Create(appDomain, (TypeImpl)((fieldValue == null) ? field.FieldType : fieldValue.GetType())), alias: null, evalFlags: GetEvaluationResultFlags(fieldValue), valueFlags: DkmClrValueFlags.None); } else { var property = type.GetProperty(name, bindingFlags); if (property != null) { var propertyValue = property.GetValue(RawValue); exprValue = new DkmClrValue( propertyValue, propertyValue, DkmClrType.Create(appDomain, (TypeImpl)((propertyValue == null) ? property.PropertyType : propertyValue.GetType())), alias: null, evalFlags: GetEvaluationResultFlags(propertyValue), valueFlags: DkmClrValueFlags.None); } else { var openParenIndex = name.IndexOf('('); if (openParenIndex >= 0) { name = name.Substring(0, openParenIndex); } var method = type.GetMethod(name, bindingFlags); // The real implementation requires parens on method invocations, so // we'll return error if there wasn't at least an open paren... if ((openParenIndex >= 0) && method != null) { var methodValue = method.Invoke(RawValue, new object[] { }); exprValue = new DkmClrValue( methodValue, methodValue, DkmClrType.Create(appDomain, (TypeImpl)((methodValue == null) ? method.ReturnType : methodValue.GetType())), alias: null, evalFlags: GetEvaluationResultFlags(methodValue), valueFlags: DkmClrValueFlags.None); } else { var stringValue = "Problem evaluating expression"; var stringType = DkmClrType.Create(appDomain, (TypeImpl)typeof(string)); exprValue = new DkmClrValue( stringValue, stringValue, stringType, alias: null, evalFlags: DkmEvaluationResultFlags.None, valueFlags: DkmClrValueFlags.Error); } } } builder.Append(exprValue.GetValueString(inspectionContext, formatSpecifiers)); // Re-enter the formatter. } else if (openPos < 0) { builder.Append(ch); } } if (openPos >= 0) { throw new ArgumentException(string.Format("Unmatched open brace in '{0}'", formatString)); } workList.AddWork(() => completionRoutine(new DkmEvaluateDebuggerDisplayStringAsyncResult(pooled.ToStringAndFree()))); } public DkmClrValue GetMemberValue(string MemberName, int MemberType, string ParentTypeName, DkmInspectionContext InspectionContext) { if (InspectionContext == null) { throw new ArgumentNullException(nameof(InspectionContext)); } if (this.IsError()) { throw new InvalidOperationException(); } var runtime = this.Type.RuntimeInstance; var getMemberValue = runtime.GetMemberValue; if (getMemberValue != null) { var memberValue = getMemberValue(this, MemberName); if (memberValue != null) { return memberValue; } } var declaringType = this.Type.GetLmrType(); if (ParentTypeName != null) { declaringType = GetAncestorType(declaringType, ParentTypeName); Debug.Assert(declaringType != null); } // Special cases for nullables if (declaringType.IsNullable()) { if (MemberName == InternalWellKnownMemberNames.NullableHasValue) { // In our mock implementation, RawValue is null for null nullables, // so we have to compute HasValue some other way. var boolValue = RawValue != null; var boolType = runtime.GetType((TypeImpl)typeof(bool)); return new DkmClrValue( boolValue, boolValue, type: boolType, alias: null, evalFlags: DkmEvaluationResultFlags.None, valueFlags: DkmClrValueFlags.None, category: DkmEvaluationResultCategory.Property, access: DkmEvaluationResultAccessType.Public); } else if (MemberName == InternalWellKnownMemberNames.NullableValue) { // In our mock implementation, RawValue is of type T rather than // Nullable<T> for nullables, so we'll just return that value // (no need to unwrap by getting "value" field). var valueType = runtime.GetType((TypeImpl)RawValue.GetType()); return new DkmClrValue( RawValue, RawValue, type: valueType, alias: null, evalFlags: DkmEvaluationResultFlags.None, valueFlags: DkmClrValueFlags.None, category: DkmEvaluationResultCategory.Property, access: DkmEvaluationResultAccessType.Public); } } Type declaredType; object value; var evalFlags = DkmEvaluationResultFlags.None; var category = DkmEvaluationResultCategory.Other; var access = DkmEvaluationResultAccessType.None; const BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; switch ((MemberTypes)MemberType) { case MemberTypes.Field: var field = declaringType.GetField(MemberName, bindingFlags); declaredType = field.FieldType; category = DkmEvaluationResultCategory.Data; access = GetFieldAccess(field); if (field.Attributes.HasFlag(System.Reflection.FieldAttributes.Literal) || field.Attributes.HasFlag(System.Reflection.FieldAttributes.InitOnly)) { evalFlags |= DkmEvaluationResultFlags.ReadOnly; } try { value = field.GetValue(RawValue); } catch (System.Reflection.TargetInvocationException e) { var exception = e.InnerException; return new DkmClrValue( exception, exception, type: runtime.GetType((TypeImpl)exception.GetType()), alias: null, evalFlags: evalFlags | DkmEvaluationResultFlags.ExceptionThrown, valueFlags: DkmClrValueFlags.None, category: category, access: access); } break; case MemberTypes.Property: var property = declaringType.GetProperty(MemberName, bindingFlags); declaredType = property.PropertyType; category = DkmEvaluationResultCategory.Property; access = GetPropertyAccess(property); if (property.GetSetMethod(nonPublic: true) == null) { evalFlags |= DkmEvaluationResultFlags.ReadOnly; } try { value = property.GetValue(RawValue, bindingFlags, null, null, null); } catch (System.Reflection.TargetInvocationException e) { var exception = e.InnerException; return new DkmClrValue( exception, exception, type: runtime.GetType((TypeImpl)exception.GetType()), alias: null, evalFlags: evalFlags | DkmEvaluationResultFlags.ExceptionThrown, valueFlags: DkmClrValueFlags.None, category: category, access: access); } break; default: throw ExceptionUtilities.UnexpectedValue((MemberTypes)MemberType); } Type type; if (value is System.Reflection.Pointer) { value = UnboxPointer(value); type = declaredType; } else if (value == null || declaredType.IsNullable()) { type = declaredType; } else { type = (TypeImpl)value.GetType(); } return new DkmClrValue( value, value, type: runtime.GetType(type), alias: null, evalFlags: evalFlags, valueFlags: DkmClrValueFlags.None, category: category, access: access); } internal static unsafe object UnboxPointer(object value) { unsafe { if (Environment.Is64BitProcess) { return (long)System.Reflection.Pointer.Unbox(value); } else { return (int)System.Reflection.Pointer.Unbox(value); } } } public DkmClrValue GetArrayElement(int[] indices, DkmInspectionContext inspectionContext) { if (inspectionContext == null) { throw new ArgumentNullException(nameof(inspectionContext)); } var array = (System.Array)RawValue; var element = array.GetValue(indices); var type = DkmClrType.Create(this.Type.AppDomain, (TypeImpl)((element == null) ? array.GetType().GetElementType() : element.GetType())); return new DkmClrValue( element, element, type: type, alias: null, evalFlags: DkmEvaluationResultFlags.None, valueFlags: DkmClrValueFlags.None); } public ReadOnlyCollection<int> ArrayDimensions { get { var array = (Array)RawValue; if (array == null) { return null; } int rank = array.Rank; var builder = ArrayBuilder<int>.GetInstance(rank); for (int i = 0; i < rank; i++) { builder.Add(array.GetUpperBound(i) - array.GetLowerBound(i) + 1); } return builder.ToImmutableAndFree(); } } public ReadOnlyCollection<int> ArrayLowerBounds { get { var array = (Array)RawValue; if (array == null) { return null; } int rank = array.Rank; var builder = ArrayBuilder<int>.GetInstance(rank); for (int i = 0; i < rank; i++) { builder.Add(array.GetLowerBound(i)); } return builder.ToImmutableAndFree(); } } public DkmClrValue InstantiateProxyType(DkmInspectionContext inspectionContext, DkmClrType proxyType) { if (inspectionContext == null) { throw new ArgumentNullException(nameof(inspectionContext)); } var lmrType = proxyType.GetLmrType(); Debug.Assert(!lmrType.IsGenericTypeDefinition); const BindingFlags bindingFlags = BindingFlags.CreateInstance | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; var constructor = lmrType.GetConstructors(bindingFlags).Single(); var value = constructor.Invoke(bindingFlags, null, new[] { RawValue }, null); return new DkmClrValue( value, value, type: proxyType, alias: null, evalFlags: DkmEvaluationResultFlags.None, valueFlags: DkmClrValueFlags.None); } private static readonly ReadOnlyCollection<DkmClrType> s_noArguments = ArrayBuilder<DkmClrType>.GetInstance(0).ToImmutableAndFree(); public DkmClrValue InstantiateDynamicViewProxy(DkmInspectionContext inspectionContext) { if (inspectionContext == null) { throw new ArgumentNullException(nameof(inspectionContext)); } var module = new DkmClrModuleInstance( this.Type.AppDomain.RuntimeInstance, typeof(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException).Assembly, new DkmModule("Microsoft.CSharp.dll")); var proxyType = module.ResolveTypeName( "Microsoft.CSharp.RuntimeBinder.DynamicMetaObjectProviderDebugView", s_noArguments); return this.InstantiateProxyType(inspectionContext, proxyType); } public DkmClrValue InstantiateResultsViewProxy(DkmInspectionContext inspectionContext, DkmClrType enumerableType) { if (EvalFlags.Includes(DkmEvaluationResultFlags.ExceptionThrown)) { throw new InvalidOperationException(); } if (inspectionContext == null) { throw new ArgumentNullException(nameof(inspectionContext)); } var appDomain = enumerableType.AppDomain; var module = GetModule(appDomain, "System.Core.dll"); if (module == null) { return null; } var typeArgs = enumerableType.GenericArguments; Debug.Assert(typeArgs.Count <= 1); var proxyTypeName = (typeArgs.Count == 0) ? "System.Linq.SystemCore_EnumerableDebugView" : "System.Linq.SystemCore_EnumerableDebugView`1"; DkmClrType proxyType; try { proxyType = module.ResolveTypeName(proxyTypeName, typeArgs); } catch (ArgumentException) { // ResolveTypeName throws ArgumentException if type is not found. return null; } return this.InstantiateProxyType(inspectionContext, proxyType); } private static DkmClrModuleInstance GetModule(DkmClrAppDomain appDomain, string moduleName) { var modules = appDomain.GetClrModuleInstances(); foreach (var module in modules) { if (string.Equals(module.Name, moduleName, StringComparison.OrdinalIgnoreCase)) { return module; } } return null; } private static Type GetAncestorType(Type type, string ancestorTypeName) { if (type.FullName == ancestorTypeName) { return type; } // Search interfaces. foreach (var @interface in type.GetInterfaces()) { var ancestorType = GetAncestorType(@interface, ancestorTypeName); if (ancestorType != null) { return ancestorType; } } // Search base type. var baseType = type.BaseType; if (baseType != null) { return GetAncestorType(baseType, ancestorTypeName); } return null; } private static DkmEvaluationResultFlags GetEvaluationResultFlags(object value) { if (true.Equals(value)) { return DkmEvaluationResultFlags.BooleanTrue; } else if (value is bool) { return DkmEvaluationResultFlags.Boolean; } else { return DkmEvaluationResultFlags.None; } } private unsafe static object Dereference(IntPtr ptr, Type elementType) { // Only handling a subset of types currently. switch (Metadata.Type.GetTypeCode(elementType)) { case TypeCode.Int32: return *(int*)ptr; case TypeCode.Object: if (ptr == IntPtr.Zero) { throw new InvalidOperationException("Dereferencing null"); } var destinationType = elementType.IsPointer ? (Environment.Is64BitProcess ? typeof(long) : typeof(int)) : ((TypeImpl)elementType).Type; return Marshal.PtrToStructure(ptr, destinationType); default: throw new InvalidOperationException(); } } private static DkmEvaluationResultAccessType GetFieldAccess(Microsoft.VisualStudio.Debugger.Metadata.FieldInfo field) { if (field.IsPrivate) { return DkmEvaluationResultAccessType.Private; } else if (field.IsFamily) { return DkmEvaluationResultAccessType.Protected; } else if (field.IsAssembly) { return DkmEvaluationResultAccessType.Internal; } else { return DkmEvaluationResultAccessType.Public; } } private static DkmEvaluationResultAccessType GetPropertyAccess(Microsoft.VisualStudio.Debugger.Metadata.PropertyInfo property) { return GetMethodAccess(property.GetGetMethod(nonPublic: true)); } private static DkmEvaluationResultAccessType GetMethodAccess(Microsoft.VisualStudio.Debugger.Metadata.MethodBase method) { if (method.IsPrivate) { return DkmEvaluationResultAccessType.Private; } else if (method.IsFamily) { return DkmEvaluationResultAccessType.Protected; } else if (method.IsAssembly) { return DkmEvaluationResultAccessType.Internal; } else { return DkmEvaluationResultAccessType.Public; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. //----------------------------------------------------------------------- // <copyright file="BuildPropertyGroup_Tests.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <summary>Tests for all Public BuildPropertyGroup objects</summary> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using NUnit.Framework; using Microsoft.Build.BuildEngine; using Microsoft.Build.Framework; using Microsoft.Build.UnitTests; namespace Microsoft.Build.UnitTests.OM.OrcasCompatibility { /// <summary> /// Tests for BuildPropertyGroup /// </summary> [TestFixture] public class BuildPropertyGroup_Tests { #region Helper Fields /// <summary> /// Basic project content start /// </summary> private string basicProjectContentsBefore = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <PropertyGroup> <p1>true</p1> <p2>4</p2> </PropertyGroup> <PropertyGroup> <p3>v</p3> </PropertyGroup> </Project> "; /// <summary> /// Basic project content with only one property group /// </summary> private string basicProjectContentsWithOnePropertyGroup = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <PropertyGroup> <n>v</n> </PropertyGroup> </Project> "; #endregion #region Constructor Tests /// <summary> /// Tests BuildPropertyGroup Contructor with no parameters /// </summary> [Test] public void ConstructWithNothing() { BuildPropertyGroup group = new BuildPropertyGroup(); Assertion.AssertEquals(0, group.Count); Assertion.AssertEquals(false, group.IsImported); } /// <summary> /// Tests BuildPropertyGroup Contructor with a simple project /// </summary> [Test] public void ConstructWithSimpleProject() { Project p = Build.UnitTests.ObjectModelHelpers.CreateInMemoryProject(basicProjectContentsWithOnePropertyGroup); BuildPropertyGroup group = new BuildPropertyGroup(p); Assertion.AssertEquals(0, group.Count); Assertion.AssertEquals(false, group.IsImported); } /// <summary> /// Tests BuildPropertyGroup Contructor with a project that contains specific property groups and items /// </summary> [Test] public void ConstructWithProject() { Project p = Build.UnitTests.ObjectModelHelpers.CreateInMemoryProject(basicProjectContentsBefore); List<string> properties = GetListOfBuildProperties(p); Assertion.AssertEquals("p1", properties[0]); Assertion.AssertEquals("p2", properties[1]); Assertion.AssertEquals("p3", properties[2]); } #endregion #region Count Tests /// <summary> /// Tests BuildPropertyGroup Count with only one property set /// </summary> [Test] public void CountOne() { BuildPropertyGroup group = new BuildPropertyGroup(); group.SetProperty("n", "v"); Assertion.AssertEquals(1, group.Count); Assertion.AssertEquals("v", group["n"].Value); } /// <summary> /// Tests BuildPropertyGroup Count with no properties set /// </summary> [Test] public void CountZero() { BuildPropertyGroup group = new BuildPropertyGroup(); Assertion.AssertEquals(0, group.Count); } /// <summary> /// Tests BuildPropertyGroup Count after clearing it. /// </summary> [Test] public void CountAfterClear() { BuildPropertyGroup group = new BuildPropertyGroup(); group.SetProperty("n", "v"); group.Clear(); Assertion.AssertEquals(0, group.Count); } /// <summary> /// Tests BuildPropertyGroup Count after removing 1 of the properties /// </summary> [Test] public void CountAfterRemovingSomeProperties() { BuildPropertyGroup group = new BuildPropertyGroup(); group.SetProperty("n1", "v1"); group.SetProperty("n2", "v2"); group.RemoveProperty("n1"); Assertion.AssertEquals(1, group.Count); } /// <summary> /// Tests BuildPropertyGroup Count after removing 1 of the properties /// </summary> [Test] public void CountAfterRemovingAllProperties() { BuildPropertyGroup group = new BuildPropertyGroup(); group.SetProperty("n1", "v1"); group.SetProperty("n2", "v2"); group.SetProperty("n3", "v3"); group.RemoveProperty("n1"); group.RemoveProperty("n2"); group.RemoveProperty("n3"); Assertion.AssertEquals(0, group.Count); } #endregion #region Clone Tests /// <summary> /// Tests BuildPropertyGroup Clone Deep /// </summary> [Test] public void CloneDeep() { BuildPropertyGroup group = new BuildPropertyGroup(); group.SetProperty("n1", "v1"); group.SetProperty("n2", "v2"); BuildPropertyGroup clone = group.Clone(true); Assertion.AssertEquals(2, clone.Count); Assertion.AssertEquals(clone["n1"].Value, group["n1"].Value); Assertion.AssertEquals(clone["n2"].Value, group["n2"].Value); group.SetProperty("n1", "new"); Assertion.AssertEquals("new", group["n1"].Value); Assertion.AssertEquals("v1", clone["n1"].Value); } /// <summary> /// Tests BuildPropertyGroup Clone Deep with Clear /// </summary> [Test] public void CloneDeepClear() { BuildPropertyGroup group = new BuildPropertyGroup(); group.SetProperty("n1", "v1"); group.SetProperty("n2", "v2"); BuildPropertyGroup clone = group.Clone(true); clone.Clear(); Assertion.AssertEquals(0, clone.Count); Assertion.AssertEquals(2, group.Count); } /// <summary> /// Tests BuildPropertyGroup Clone Shallow /// </summary> [Test] public void CloneShallow() { BuildPropertyGroup group = new BuildPropertyGroup(); group.SetProperty("n1", "v1"); group.SetProperty("n2", "v2"); BuildPropertyGroup clone = group.Clone(false); group["n1"].Value = "new"; Assertion.AssertEquals(2, clone.Count); Assertion.AssertEquals(2, group.Count); Assertion.AssertEquals("new", group["n1"].Value); Assertion.AssertEquals("new", clone["n1"].Value); Assertion.AssertEquals(clone["n2"].Value, group["n2"].Value); } /// <summary> /// Tests BuildPropertyGroup Clone Shallow with Set Property /// </summary> [Test] public void CloneShallowSetProperty() { BuildPropertyGroup group = new BuildPropertyGroup(); group.SetProperty("n1", "v1"); group.SetProperty("n2", "v2"); BuildPropertyGroup clone = group.Clone(false); group.SetProperty("n1", "new"); Assertion.AssertEquals(2, clone.Count); Assertion.AssertEquals(2, group.Count); Assertion.AssertEquals("new", group["n1"].Value); Assertion.AssertEquals("v1", clone["n1"].Value); Assertion.AssertEquals(clone["n2"].Value, group["n2"].Value); } /// <summary> /// Tests BuildPropertyGroup Clone Shallow when you attempt a shallow clone of an XMLProject /// </summary> [Test] [ExpectedException(typeof(InvalidOperationException))] public void CloneShallowWithXMLProject() { Project p = Build.UnitTests.ObjectModelHelpers.CreateInMemoryProject(basicProjectContentsWithOnePropertyGroup); foreach (BuildPropertyGroup group in p.PropertyGroups) { BuildPropertyGroup clone = group.Clone(false); } } #endregion #region SetProperty Tests /// <summary> /// Tests BuildPropertyGroup SetProperty Value to an empty string /// </summary> [Test] public void SetPropertyEmptyValue() { BuildPropertyGroup group = new BuildPropertyGroup(); group.SetProperty("n", String.Empty); Assertion.AssertEquals(1, group.Count); Assertion.AssertEquals(String.Empty, group["n"].Value); } /// <summary> /// Tests BuildPropertyGroup SetProperty Value to null /// </summary> [Test] [ExpectedException(typeof(ArgumentNullException))] public void SetPropertyNullValue() { BuildPropertyGroup group = new BuildPropertyGroup(); group.SetProperty("n", null); } /// <summary> /// Tests BuildPropertyGroup SetProperty Name to an empty string /// </summary> [Test] [ExpectedException(typeof(ArgumentException))] public void SetPropertyEmptyName() { BuildPropertyGroup group = new BuildPropertyGroup(); group.SetProperty(String.Empty, "v"); } /// <summary> /// Tests BuildPropertyGroup SetProperty Name to null /// </summary> [Test] [ExpectedException(typeof(ArgumentNullException))] public void SetPropertyNullName() { BuildPropertyGroup group = new BuildPropertyGroup(); group.SetProperty(null, "v"); } /// <summary> /// Tests BuildPropertyGroup SetProperty setting Name and Value to a simple value /// </summary> [Test] public void SetPropertySimpleNameValue() { BuildPropertyGroup group = new BuildPropertyGroup(); group.SetProperty("n", "v"); Assertion.AssertEquals("v", group["n"].Value); } /// <summary> /// Tests BuildPropertyGroup SetProperty with Treat Property Value as Literal set to true/false /// </summary> [Test] public void SetPropertyTreatPropertyValueAsLiteral() { BuildPropertyGroup group = new BuildPropertyGroup(); group.SetProperty("n1", @"%*?@$();\", true); group.SetProperty("n2", @"%*?@$();\", false); Assertion.AssertEquals(@"%25%2a%3f%40%24%28%29%3b\", group["n1"].Value); Assertion.AssertEquals(@"%*?@$();\", group["n2"].Value); } /// <summary> /// Tests BuildPropertyGroup SetProperty with Treat Property Value as Literal set to false /// </summary> [Test] public void SetPropertyTreatPropertyValueAsLiteralFalse() { BuildPropertyGroup group = new BuildPropertyGroup(); group.SetProperty("n", "v", false); Assertion.AssertEquals("v", group["n"].Value); } /// <summary> /// Tests BuildPropertyGroup SetProperty with a project p /// </summary> [Test] public void SetPropertyWithProject() { Project p = Build.UnitTests.ObjectModelHelpers.CreateInMemoryProject(basicProjectContentsBefore); List<string> properties = GetListOfBuildProperties(p); properties[0] = "v"; Assertion.AssertEquals("v", properties[0]); Assertion.AssertEquals("p2", properties[1]); Assertion.AssertEquals("p3", properties[2]); } /// <summary> /// Tests BuildPropertyGroup SetProperty Value with special characters /// </summary> [Test] public void SetPropertyValueWithSpecialCharacters() { BuildPropertyGroup group = new BuildPropertyGroup(); group.SetProperty("n1", "%24"); group.SetProperty("n2", "%40"); group.SetProperty("n3", "%3b"); group.SetProperty("n4", "%5c"); group.SetProperty("n5", "%25"); Assertion.AssertEquals("$", group["n1"].FinalValue); Assertion.AssertEquals("@", group["n2"].FinalValue); Assertion.AssertEquals(";", group["n3"].FinalValue); Assertion.AssertEquals(@"\", group["n4"].FinalValue); Assertion.AssertEquals("%", group["n5"].FinalValue); } /// <summary> /// Tests BuildPropertyGroup SetProperty Name with special characters /// </summary> [Test] [ExpectedException(typeof(ArgumentException))] public void SetPropertyNameWithSpecialCharacters() { BuildPropertyGroup group = new BuildPropertyGroup(); group.SetProperty("%24", "v"); } #endregion #region RemoveProperty Tests /// <summary> /// Tests BuildPropertyGroup RemoveProperty by removing 1 of many by name /// </summary> [Test] public void RemovePropertyByNameOneOfSeveral() { BuildPropertyGroup group = new BuildPropertyGroup(); group.SetProperty("n1", "v1"); group.SetProperty("n2", "v2"); group.SetProperty("n3", "v3"); group.RemoveProperty("n1"); Assertion.AssertEquals(2, group.Count); Assertion.AssertNull(group["n1"]); Assertion.AssertEquals("v2", group["n2"].Value); Assertion.AssertEquals("v3", group["n3"].Value); } /// <summary> /// Tests BuildPropertyGroup RemoveProperty by removing all of many by name /// </summary> [Test] public void RemovePropertyByNameAllOfSeveral() { BuildPropertyGroup group = new BuildPropertyGroup(); group.SetProperty("n1", "v1"); group.SetProperty("n2", "v2"); group.SetProperty("n3", "v3"); group.RemoveProperty("n1"); group.RemoveProperty("n2"); group.RemoveProperty("n3"); Assertion.AssertEquals(0, group.Count); Assertion.AssertNull(group["n1"]); Assertion.AssertNull(group["n2"]); Assertion.AssertNull(group["n3"]); } /// <summary> /// Tests BuildPropertyGroup RemoveProperty by attempting to remove a property that doesn't actually exist /// </summary> [Test] public void RemovePropertyByNameOfANonExistingProperty() { BuildPropertyGroup group = new BuildPropertyGroup(); group.SetProperty("n", "v"); group.RemoveProperty("not"); Assertion.AssertEquals(1, group.Count); } /// <summary> /// Tests BuildPropertyGroup RemoveProperty by attempting to remove a property name that is null /// </summary> [Test] [ExpectedException(typeof(ArgumentNullException))] public void RemovePropertyByNameWhenNameIsNull() { BuildPropertyGroup group = new BuildPropertyGroup(); string name = null; group.RemoveProperty(name); } /// <summary> /// Tests BuildPropertyGroup RemoveProperty by attempting to remove a property name that is an empty string /// </summary> [Test] public void RemovePropertyByNameThatIsAnEmptyString() { BuildPropertyGroup group = new BuildPropertyGroup(); group.SetProperty("n", "v"); group.RemoveProperty(String.Empty); Assertion.AssertEquals(1, group.Count); } /// <summary> /// Tests BuildPropertyGroup RemoveProperty by removing 1 of several properties by BuildProperty /// </summary> [Test] public void RemovePropertyByBuildPropertyOneOfSeveral() { BuildPropertyGroup group = new BuildPropertyGroup(); group.SetProperty("n1", "v1"); group.SetProperty("n2", "v2"); group.SetProperty("n3", "v3"); BuildProperty property = GetSpecificBuildPropertyOutOfBuildPropertyGroup(group, "n2"); group.RemoveProperty(property); Assertion.AssertEquals(2, group.Count); Assertion.AssertEquals("v1", group["n1"].Value); Assertion.AssertNull(group["n2"]); Assertion.AssertEquals("v3", group["n3"].Value); } /// <summary> /// Tests BuildPropertyGroup RemoveProperty by all of several properties by BuildProperty /// </summary> [Test] public void RemovePropertyByBuildPropertyAllOfSeveral() { BuildPropertyGroup group = new BuildPropertyGroup(); group.SetProperty("n1", "v1"); group.SetProperty("n2", "v2"); group.SetProperty("n3", "v3"); BuildProperty[] property = new BuildProperty[] { GetSpecificBuildPropertyOutOfBuildPropertyGroup(group, "n1"), GetSpecificBuildPropertyOutOfBuildPropertyGroup(group, "n2"), GetSpecificBuildPropertyOutOfBuildPropertyGroup(group, "n3") }; group.RemoveProperty(property[0]); group.RemoveProperty(property[1]); group.RemoveProperty(property[2]); Assertion.AssertEquals(0, group.Count); Assertion.AssertNull(group["n1"]); Assertion.AssertNull(group["n2"]); Assertion.AssertNull(group["n3"]); } /// <summary> /// Tests BuildPropertyGroup RemoveProperty of a null property /// </summary> [Test] [ExpectedException(typeof(ArgumentNullException))] public void RemovePropertyByBuildPropertyWithNullProperty() { BuildPropertyGroup group = new BuildPropertyGroup(); BuildProperty property = null; group.RemoveProperty(property); } #endregion #region AddNewProperty Tests /// <summary> /// Tests BuildPropertyGroup AddNewProperty with setting Name to null /// </summary> [Test] [ExpectedException(typeof(ArgumentNullException))] public void AddNewPropertyNameToNull() { Project p = Build.UnitTests.ObjectModelHelpers.CreateInMemoryProject(basicProjectContentsBefore); AddNewPropertyToEachPropertyGroup(p, null, "v"); } /// <summary> /// Tests BuildPropertyGroup AddNewProperty with setting Name to an empty string /// </summary> [Test] [ExpectedException(typeof(ArgumentException))] public void AddNewPropertyNameToEmptyString() { Project p = Build.UnitTests.ObjectModelHelpers.CreateInMemoryProject(basicProjectContentsBefore); AddNewPropertyToEachPropertyGroup(p, string.Empty, "v"); } /// <summary> /// Tests BuildPropertyGroup AddNewProperty with setting Value to null /// </summary> [Test] [ExpectedException(typeof(ArgumentNullException))] public void AddNewPropertyValueToNull() { Project p = Build.UnitTests.ObjectModelHelpers.CreateInMemoryProject(basicProjectContentsBefore); AddNewPropertyToEachPropertyGroup(p, "n", null); } /// <summary> /// Tests BuildPropertyGroup AddNewProperty with setting Value to an empty string /// </summary> [Test] public void AddNewPropertyValueToEmptyString() { Project p = Build.UnitTests.ObjectModelHelpers.CreateInMemoryProject(basicProjectContentsBefore); AddNewPropertyToEachPropertyGroup(p, "n", String.Empty); string projectContentsAfter = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <PropertyGroup> <p1>true</p1> <p2>4</p2> <n></n> </PropertyGroup> <PropertyGroup> <p3>v</p3> <n></n> </PropertyGroup> </Project> "; Build.UnitTests.ObjectModelHelpers.CompareProjectContents(p, projectContentsAfter); } /// <summary> /// Tests BuildPropertyGroup AddNewProperty with simple Name and Value /// </summary> [Test] public void AddNewPropertySimpleNameValue() { Project p = Build.UnitTests.ObjectModelHelpers.CreateInMemoryProject(basicProjectContentsBefore); AddNewPropertyToEachPropertyGroup(p, "n", "v"); string projectContentsAfter = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <PropertyGroup> <p1>true</p1> <p2>4</p2> <n>v</n> </PropertyGroup> <PropertyGroup> <p3>v</p3> <n>v</n> </PropertyGroup> </Project> "; Build.UnitTests.ObjectModelHelpers.CompareProjectContents(p, projectContentsAfter); } /// <summary> /// Tests BuildPropertyGroup AddNewProperty several sets /// </summary> [Test] public void AddNewPropertySeveralNameValuePairs() { Project p = Build.UnitTests.ObjectModelHelpers.CreateInMemoryProject(basicProjectContentsBefore); AddNewPropertyToEachPropertyGroup(p, "n1", "v1"); AddNewPropertyToEachPropertyGroup(p, "n2", "v2"); AddNewPropertyToEachPropertyGroup(p, "n3", "v3"); AddNewPropertyToEachPropertyGroup(p, "n4", "v4"); string projectContentsAfter = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <PropertyGroup> <p1>true</p1> <p2>4</p2> <n1>v1</n1> <n2>v2</n2> <n3>v3</n3> <n4>v4</n4> </PropertyGroup> <PropertyGroup> <p3>v</p3> <n1>v1</n1> <n2>v2</n2> <n3>v3</n3> <n4>v4</n4> </PropertyGroup> </Project> "; Build.UnitTests.ObjectModelHelpers.CompareProjectContents(p, projectContentsAfter); } /// <summary> /// Tests BuildPropertyGroup AddNewProperty with simple Name and Value as well as setting Treat Property Value as Literal to true /// </summary> [Test] public void AddNewPropertySimpleNameValueWithTreatPropertyValueAsLiteralTrue() { Project p = Build.UnitTests.ObjectModelHelpers.CreateInMemoryProject(basicProjectContentsBefore); AddNewPropertyToEachPropertyGroupWithPropertyValueAsLiteral(p, "n", @"%*?@$();\", true); string projectContentsAfter = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <PropertyGroup> <p1>true</p1> <p2>4</p2> <n>%25%2a%3f%40%24%28%29%3b\</n> </PropertyGroup> <PropertyGroup> <p3>v</p3> <n>%25%2a%3f%40%24%28%29%3b\</n> </PropertyGroup> </Project> "; Build.UnitTests.ObjectModelHelpers.CompareProjectContents(p, projectContentsAfter); } /// <summary> /// Tests BuildPropertyGroup AddNewProperty with simple Name and Value as well as setting Treat Property Value as Literal to false /// </summary> [Test] public void AddNewPropertySimpleNameValueWithTreatPropertyValueAsLiteralFalse() { Project p = Build.UnitTests.ObjectModelHelpers.CreateInMemoryProject(basicProjectContentsBefore); AddNewPropertyToEachPropertyGroupWithPropertyValueAsLiteral(p, "n", @"%*?@$();\", false); string projectContentsAfter = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <PropertyGroup> <p1>true</p1> <p2>4</p2> <n>%*?@$();\</n> </PropertyGroup> <PropertyGroup> <p3>v</p3> <n>%*?@$();\</n> </PropertyGroup> </Project> "; Build.UnitTests.ObjectModelHelpers.CompareProjectContents(p, projectContentsAfter); } /// <summary> /// Tests BuildPropertyGroup AddNewProperty with special characters for the Name /// </summary> [Test] [ExpectedException(typeof(ArgumentException))] public void AddNewPropertyWithSpecialCharactersInName() { Project p = Build.UnitTests.ObjectModelHelpers.CreateInMemoryProject(basicProjectContentsWithOnePropertyGroup); AddNewPropertyToEachPropertyGroup(p, "%25", "v1"); } /// <summary> /// Tests BuildPropertyGroup AddNewProperty with special characters for the Value /// </summary> [Test] public void AddNewPropertyWithSpecialCharactersInValue() { Project p = Build.UnitTests.ObjectModelHelpers.CreateInMemoryProject(basicProjectContentsWithOnePropertyGroup); AddNewPropertyToEachPropertyGroup(p, "n1", "%24%40%3b%5c%25"); Dictionary<string, string> properties = GetDictionaryOfPropertiesInProject(p); Assertion.AssertEquals("%24%40%3b%5c%25", properties["n1"].ToString()); } /// <summary> /// Tests BuildPropertyGroup AddNewProperty with an in memory build property group /// </summary> [Test] [ExpectedException(typeof(InvalidOperationException))] public void AddNewPropertyToInMemoryGroup() { BuildPropertyGroup group = new BuildPropertyGroup(); group.SetProperty("n1", "v1"); group.AddNewProperty("n3", "v3"); } #endregion #region Condition tests /// <summary> /// Tests BuildPropertyGroup Condition Get /// </summary> [Test] public void ConditionGetWhenSetItXML() { string projectContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <PropertyGroup Condition="" '$(Foo)' == 'Bar' ""> <n1>v1</n1> <n2>v2</n2> <n3 Condition='true'>v3</n3> </PropertyGroup> <PropertyGroup Condition="" '$(A)' == 'B' ""> <n4>v4</n4> </PropertyGroup> <PropertyGroup Condition=""'$(C)' == 'D'""> </PropertyGroup> <PropertyGroup Condition=""""> <n5>v5</n5> </PropertyGroup> </Project> "; Project p = Build.UnitTests.ObjectModelHelpers.CreateInMemoryProject(projectContents); List<string> conditions = GetListOfBuildPropertyGroupConditions(p); Assertion.AssertEquals(" '$(Foo)' == 'Bar' ", conditions[0].ToString()); Assertion.AssertEquals(" '$(A)' == 'B' ", conditions[1].ToString()); Assertion.AssertEquals("'$(C)' == 'D'", conditions[2].ToString()); Assertion.AssertEquals(String.Empty, conditions[3].ToString()); } /// <summary> /// Tests BuildPropertyGroup Condition Set for a simple set /// </summary> [Test] public void ConditionSetSimple() { Project p = ObjectModelHelpers.CreateInMemoryProject(basicProjectContentsWithOnePropertyGroup); SetPropertyGroupConditionOnEachPropertyGroup(p, "'$(C)' == 'D'"); List<string> conditions = GetListOfBuildPropertyGroupConditions(p); Assertion.AssertEquals("'$(C)' == 'D'", conditions[0].ToString()); } /// <summary> /// Tests BuildPropertyGroup Condition Set to multiple PropertyGroups /// </summary> [Test] public void ConditionSetToMultipleGroups() { Project p = Build.UnitTests.ObjectModelHelpers.CreateInMemoryProject(basicProjectContentsBefore); SetPropertyGroupConditionOnEachPropertyGroup(p, "'$(C)' == 'D'"); List<string> conditions = GetListOfBuildPropertyGroupConditions(p); Assertion.AssertEquals("'$(C)' == 'D'", conditions[0].ToString()); Assertion.AssertEquals("'$(C)' == 'D'", conditions[1].ToString()); } /// <summary> /// Tests BuildPropertyGroup Condition Set after setting the condition (setting two times in a row) /// </summary> [Test] public void ConditionSetAfterSetting() { Project p = Build.UnitTests.ObjectModelHelpers.CreateInMemoryProject(basicProjectContentsWithOnePropertyGroup); SetPropertyGroupConditionOnEachPropertyGroup(p, "'$(C)' == 'D'"); SetPropertyGroupConditionOnEachPropertyGroup(p, " '$(Foo)' == 'Bar' "); List<string> conditions = GetListOfBuildPropertyGroupConditions(p); Assertion.AssertEquals(" '$(Foo)' == 'Bar' ", conditions[0].ToString()); } /// <summary> /// Tests BuildPropertyGroup Condition Set with an escape character like lessthan /// </summary> [Test] public void ConditionSetWithEscapeCharacter() { Project p = Build.UnitTests.ObjectModelHelpers.CreateInMemoryProject(basicProjectContentsWithOnePropertyGroup); SetPropertyGroupConditionOnEachPropertyGroup(p, "'&lt;' == 'D'"); List<string> conditions = GetListOfBuildPropertyGroupConditions(p); Assertion.AssertEquals("'&lt;' == 'D'", conditions[0].ToString()); } /// <summary> /// Tests BuildPropertyGroup Condition Set with Special Characters (; $ @ \ $ %) /// </summary> [Test] public void ConditionSetWithSpecialCharacters() { Project p = Build.UnitTests.ObjectModelHelpers.CreateInMemoryProject(basicProjectContentsWithOnePropertyGroup); SetPropertyGroupConditionOnEachPropertyGroup(p, "'%24A' == 'D'"); List<string> conditions = GetListOfBuildPropertyGroupConditions(p); Assertion.AssertEquals("'%24A' == 'D'", conditions[0].ToString()); } #endregion #region IsImported Tests /// <summary> /// Tests BuildPropertyGroup IsImported when all BuildPropertyGroups are defined within main project /// </summary> [Test] public void IsImportedAllFromMainProject() { string projectContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <PropertyGroup> <n1>v1</n1> <n2>v2</n2> <n3 Condition='true'>v3</n3> </PropertyGroup> <PropertyGroup> <n4>v4</n4> </PropertyGroup> </Project> "; Project p = Build.UnitTests.ObjectModelHelpers.CreateInMemoryProject(projectContents); foreach (BuildPropertyGroup group in p.PropertyGroups) { Assertion.AssertEquals(false, group.IsImported); } } /// <summary> /// Tests BuildPropertyGroup IsImported when all BuildPropertyGroups are defined within an import /// </summary> [Test] public void IsImportedAllFromImportProject() { string projectContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <Import Project='$(MSBuildToolsPath)\Microsoft.CSharp.targets' /> </Project> "; Project p = Build.UnitTests.ObjectModelHelpers.CreateInMemoryProject(projectContents); foreach (BuildPropertyGroup group in p.PropertyGroups) { Assertion.AssertEquals(true, group.IsImported); } } /// <summary> /// Tests BuildPropertyGroup IsImported when BuildPropertyGroups are defined within main project and an import /// </summary> [Test] public void IsImportedFromMainProjectAndImported() { string projectContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <PropertyGroup> <n1>v1</n1> <n2>v2</n2> <n3 Condition='true'>v3</n3> </PropertyGroup> <PropertyGroup> <n4>v4</n4> </PropertyGroup> <Import Project='$(MSBuildToolsPath)\Microsoft.CSharp.targets' /> </Project> "; Project p = Build.UnitTests.ObjectModelHelpers.CreateInMemoryProject(projectContents); Assertion.AssertEquals(false, IsPropertyImported(p, "n1")); Assertion.AssertEquals(false, IsPropertyImported(p, "n2")); Assertion.AssertEquals(false, IsPropertyImported(p, "n3")); Assertion.AssertEquals(false, IsPropertyImported(p, "n4")); Assertion.AssertEquals(true, IsPropertyImported(p, "OutDir")); Assertion.AssertEquals(true, IsPropertyImported(p, "ProjectExt")); Assertion.AssertEquals(true, IsPropertyImported(p, "DefaultLanguageSourceExtension")); } /// <summary> /// Tests BuildPropertyGroup IsImported when BuildPropertyGroups are Virtual Property groups /// </summary> [Test] public void IsImportedWithVirtualPropertyGroups() { BuildPropertyGroup group = new BuildPropertyGroup(); group.SetProperty("n1", "v1"); foreach (BuildProperty property in group) { Assertion.AssertEquals(false, property.IsImported); } } #endregion #region SetImportedPropertyGroupCondition tests /// <summary> /// Tests BuildPropertyGroup SetImportedPropertyGroupCondition setting to true /// </summary> [Test] public void SetImportedPropertyGroupConditionTrue() { string projectContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <Import Project='$(MSBuildToolsPath)\Microsoft.CSharp.targets' /> </Project> "; Project p = Build.UnitTests.ObjectModelHelpers.CreateInMemoryProject(projectContents); foreach (BuildPropertyGroup group in p.PropertyGroups) { group.SetImportedPropertyGroupCondition("true"); Assertion.AssertEquals("true", group.Condition); } } /// <summary> /// Tests BuildPropertyGroup SetImportedPropertyGroupCondition setting to false /// </summary> [Test] public void SetImportedPropertyGroupConditionFalse() { string projectContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <Import Project='$(MSBuildToolsPath)\Microsoft.CSharp.targets' /> </Project> "; Project p = Build.UnitTests.ObjectModelHelpers.CreateInMemoryProject(projectContents); foreach (BuildPropertyGroup group in p.PropertyGroups) { group.SetImportedPropertyGroupCondition("false"); Assertion.AssertEquals("false", group.Condition); } } /// <summary> /// Tests BuildPropertyGroup SetImportedPropertyGroupCondition setting general /// </summary> [Test] public void SetImportedPropertyGroupCondition() { string projectContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <Import Project='$(MSBuildToolsPath)\Microsoft.CSharp.targets' /> </Project> "; Project p = Build.UnitTests.ObjectModelHelpers.CreateInMemoryProject(projectContents); foreach (BuildPropertyGroup group in p.PropertyGroups) { group.SetImportedPropertyGroupCondition("'$(C)' == 'D'"); Assertion.AssertEquals("'$(C)' == 'D'", group.Condition); } } /// <summary> /// Tests BuildPropertyGroup SetImportedPropertyGroupCondition setting to empty string /// </summary> [Test] public void SetImportedPropertyGroupConditionToEmtpySTring() { string projectContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <Import Project='$(MSBuildToolsPath)\Microsoft.CSharp.targets' /> </Project> "; Project p = Build.UnitTests.ObjectModelHelpers.CreateInMemoryProject(projectContents); foreach (BuildPropertyGroup group in p.PropertyGroups) { group.SetImportedPropertyGroupCondition(String.Empty); Assertion.AssertEquals(String.Empty, group.Condition); } } /// <summary> /// Tests BuildPropertyGroup SetImportedPropertyGroupCondition setting to null /// </summary> [Test] public void SetImportedPropertyGroupConditionToNull() { string projectContents = @" <Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <Import Project='$(MSBuildToolsPath)\Microsoft.CSharp.targets' /> </Project> "; Project p = Build.UnitTests.ObjectModelHelpers.CreateInMemoryProject(projectContents); foreach (BuildPropertyGroup group in p.PropertyGroups) { group.SetImportedPropertyGroupCondition(null); Assertion.AssertEquals(String.Empty, group.Condition); } } #endregion #region this[string propertyName] { get; set; } Tests /// <summary> /// Tests BuildPropertyGroup this[string propertyName] Get /// </summary> [Test] public void ThisGet() { BuildPropertyGroup group = new BuildPropertyGroup(); group.SetProperty("n1", "v1"); group.SetProperty("n2", "v2"); Assertion.AssertEquals("v1", group["n1"].FinalValue); Assertion.AssertEquals("v2", group["n2"].FinalValue); } /// <summary> /// Tests BuildPropertyGroup this[string propertyName] Set /// </summary> [Test] public void ThisSet() { BuildPropertyGroup group = new BuildPropertyGroup(); group.SetProperty("n1", "v"); group.SetProperty("n2", group["n1"].FinalValue); group["n1"].Value = "value"; Assertion.AssertEquals("value", group["n1"].FinalValue); } #endregion #region BuildPropertyGroup Helpers /// <summary> /// Tells you if your specified BuildProperty name within your Project is imported or not /// </summary> /// <param name="p">Project</param> /// <param name="propertyNameWanted">BuildProperty name</param> /// <returns>true if specified BuildProject name is in a BuildPropertyGroup that is imported, false if not</returns> private static bool IsPropertyImported(Project p, string propertyNameWanted) { foreach (BuildPropertyGroup group in p.PropertyGroups) { foreach (BuildProperty property in group) { if (String.Equals(property.Name, propertyNameWanted, StringComparison.OrdinalIgnoreCase)) { return group.IsImported; } } } return false; } /// <summary> /// Gets a Dictionary List of properties in your project (Key = property.Name, Value = propery.Value) /// </summary> /// <param name="p">Project</param> /// <returns>A Dictionary List of properties in your project (Key = property.Name, Value = propery.Value)</returns> private static Dictionary<string, string> GetDictionaryOfPropertiesInProject(Project p) { Dictionary<string, string> properties = new Dictionary<string, string>(); foreach (BuildPropertyGroup group in p.PropertyGroups) { foreach (BuildProperty prop in group) { properties.Add(prop.Name, prop.Value); } } return properties; } /// <summary> /// Gets a List of all BuildProperties within your Project /// </summary> /// <param name="p">Project</param> /// <returns>A List of strings of all Build Properties</returns> private static List<string> GetListOfBuildProperties(Project p) { List<string> properties = new List<string>(); foreach (BuildPropertyGroup group in p.PropertyGroups) { foreach (BuildProperty property in group) { properties.Add(property.Name); } } return properties; } /// <summary> /// Gets a List of all BuildPropertyGroup conditions in your Project /// </summary> /// <param name="p">Project</param> /// <returns>A List of strings of all Build Property Group conditions</returns> private static List<string> GetListOfBuildPropertyGroupConditions(Project p) { List<string> conditions = new List<string>(); foreach (BuildPropertyGroup group in p.PropertyGroups) { conditions.Add(group.Condition); } return conditions; } /// <summary> /// Helper method to set a PropertyGroup condition on all PropertyGroups within a Project /// </summary> /// <param name="p">Project</param> /// <param name="condition">The condition you want to set, example "'$(C)' == 'D'"</param> private static void SetPropertyGroupConditionOnEachPropertyGroup(Project p, string condition) { foreach (BuildPropertyGroup group in p.PropertyGroups) { group.Condition = condition; } } /// <summary> /// Helper method to add new property to BuildPropertyGroups within your project /// </summary> /// <param name="p">Project</param> /// <param name="name">String of the property name</param> /// <param name="value">String of the property value</param> private static void AddNewPropertyToEachPropertyGroup(Project p, string name, string value) { foreach (BuildPropertyGroup group in p.PropertyGroups) { group.AddNewProperty(name, value); } } /// <summary> /// Helper method to add new property to BuildPropertyGroups within your project where you can set Property Value as Literal or not /// </summary> /// <param name="p">Project</param> /// <param name="name">String of the property name</param> /// <param name="value">String of the property value</param> /// <param name="treatPropertyValueAsLiteral">true or false</param> private static void AddNewPropertyToEachPropertyGroupWithPropertyValueAsLiteral(Project p, string name, string value, bool treatPropertyValueAsLiteral) { foreach (BuildPropertyGroup group in p.PropertyGroups) { group.AddNewProperty(name, value, treatPropertyValueAsLiteral); } } /// <summary> /// Gets a specific BuildProperty out of your BuildPropertyGroup /// </summary> /// <param name="group">Your BuildPropertyGroup</param> /// <param name="propertyNameWanted">The BuildProperty name that you want</param> /// <returns>The BuildProperty of the BuildProperty name you requested</returns> private static BuildProperty GetSpecificBuildPropertyOutOfBuildPropertyGroup(BuildPropertyGroup group, string propertyNameWanted) { foreach (BuildProperty property in group) { if (String.Equals(property.Name, propertyNameWanted, StringComparison.OrdinalIgnoreCase)) { return property; } } return null; } #endregion } }
using System; using System.Collections.Generic; using System.Web.Routing; using Nop.Core.Domain.Orders; using Nop.Core.Domain.Payments; using Nop.Core.Plugins; using Nop.Plugin.Payments.PurchaseOrder.Controllers; using Nop.Services.Configuration; using Nop.Services.Localization; using Nop.Services.Orders; using Nop.Services.Payments; namespace Nop.Plugin.Payments.PurchaseOrder { /// <summary> /// PurchaseOrder payment processor /// </summary> public class PurchaseOrderPaymentProcessor : BasePlugin, IPaymentMethod { #region Fields private readonly PurchaseOrderPaymentSettings _purchaseOrderPaymentSettings; private readonly ISettingService _settingService; private readonly IOrderTotalCalculationService _orderTotalCalculationService; #endregion #region Ctor public PurchaseOrderPaymentProcessor(PurchaseOrderPaymentSettings purchaseOrderPaymentSettings, ISettingService settingService, IOrderTotalCalculationService orderTotalCalculationService) { this._purchaseOrderPaymentSettings = purchaseOrderPaymentSettings; this._settingService = settingService; this._orderTotalCalculationService = orderTotalCalculationService; } #endregion #region Methods /// <summary> /// Process a payment /// </summary> /// <param name="processPaymentRequest">Payment info required for an order processing</param> /// <returns>Process payment result</returns> public ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest) { var result = new ProcessPaymentResult(); result.NewPaymentStatus = PaymentStatus.Pending; return result; } /// <summary> /// Post process payment (used by payment gateways that require redirecting to a third-party URL) /// </summary> /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param> public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest) { //nothing } /// <summary> /// Gets additional handling fee /// </summary> /// <param name="cart">Shoping cart</param> /// <returns>Additional handling fee</returns> public decimal GetAdditionalHandlingFee(IList<ShoppingCartItem> cart) { var result = this.CalculateAdditionalFee(_orderTotalCalculationService, cart, _purchaseOrderPaymentSettings.AdditionalFee, _purchaseOrderPaymentSettings.AdditionalFeePercentage); return result; } /// <summary> /// Captures payment /// </summary> /// <param name="capturePaymentRequest">Capture payment request</param> /// <returns>Capture payment result</returns> public CapturePaymentResult Capture(CapturePaymentRequest capturePaymentRequest) { var result = new CapturePaymentResult(); result.AddError("Capture method not supported"); return result; } /// <summary> /// Refunds a payment /// </summary> /// <param name="refundPaymentRequest">Request</param> /// <returns>Result</returns> public RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest) { var result = new RefundPaymentResult(); result.AddError("Refund method not supported"); return result; } /// <summary> /// Voids a payment /// </summary> /// <param name="voidPaymentRequest">Request</param> /// <returns>Result</returns> public VoidPaymentResult Void(VoidPaymentRequest voidPaymentRequest) { var result = new VoidPaymentResult(); result.AddError("Void method not supported"); return result; } /// <summary> /// Process recurring payment /// </summary> /// <param name="processPaymentRequest">Payment info required for an order processing</param> /// <returns>Process payment result</returns> public ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest) { var result = new ProcessPaymentResult(); result.AddError("Recurring payment not supported"); return result; } /// <summary> /// Cancels a recurring payment /// </summary> /// <param name="cancelPaymentRequest">Request</param> /// <returns>Result</returns> public CancelRecurringPaymentResult CancelRecurringPayment(CancelRecurringPaymentRequest cancelPaymentRequest) { var result = new CancelRecurringPaymentResult(); result.AddError("Recurring payment not supported"); return result; } /// <summary> /// Gets a value indicating whether customers can complete a payment after order is placed but not completed (for redirection payment methods) /// </summary> /// <param name="order">Order</param> /// <returns>Result</returns> public bool CanRePostProcessPayment(Order order) { if (order == null) throw new ArgumentNullException("order"); //it's not a redirection payment method. So we always return false return false; } /// <summary> /// Gets a route for provider configuration /// </summary> /// <param name="actionName">Action name</param> /// <param name="controllerName">Controller name</param> /// <param name="routeValues">Route values</param> public void GetConfigurationRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues) { actionName = "Configure"; controllerName = "PaymentPurchaseOrder"; routeValues = new RouteValueDictionary() { { "Namespaces", "Nop.Plugin.Payments.PurchaseOrder.Controllers" }, { "area", null } }; } /// <summary> /// Gets a route for payment info /// </summary> /// <param name="actionName">Action name</param> /// <param name="controllerName">Controller name</param> /// <param name="routeValues">Route values</param> public void GetPaymentInfoRoute(out string actionName, out string controllerName, out RouteValueDictionary routeValues) { actionName = "PaymentInfo"; controllerName = "PaymentPurchaseOrder"; routeValues = new RouteValueDictionary() { { "Namespaces", "Nop.Plugin.Payments.PurchaseOrder.Controllers" }, { "area", null } }; } public Type GetControllerType() { return typeof(PaymentPurchaseOrderController); } /// <summary> /// Install plugin /// </summary> public override void Install() { //settings var settings = new PurchaseOrderPaymentSettings() { AdditionalFee = 0, }; _settingService.SaveSetting(settings); //locales this.AddOrUpdatePluginLocaleResource("Plugins.Payment.PurchaseOrder.PurchaseOrderNumber", "PO Number"); this.AddOrUpdatePluginLocaleResource("Plugins.Payment.PurchaseOrder.AdditionalFee", "Additional fee"); this.AddOrUpdatePluginLocaleResource("Plugins.Payment.PurchaseOrder.AdditionalFee.Hint", "The additional fee."); this.AddOrUpdatePluginLocaleResource("Plugins.Payment.PurchaseOrder.AdditionalFeePercentage", "Additional fee. Use percentage"); this.AddOrUpdatePluginLocaleResource("Plugins.Payment.PurchaseOrder.AdditionalFeePercentage.Hint", "Determines whether to apply a percentage additional fee to the order total. If not enabled, a fixed value is used."); base.Install(); } public override void Uninstall() { //settings _settingService.DeleteSetting<PurchaseOrderPaymentSettings>(); //locales this.DeletePluginLocaleResource("Plugins.Payment.PurchaseOrder.PurchaseOrderNumber"); this.DeletePluginLocaleResource("Plugins.Payment.PurchaseOrder.AdditionalFee"); this.DeletePluginLocaleResource("Plugins.Payment.PurchaseOrder.AdditionalFee.Hint"); this.DeletePluginLocaleResource("Plugins.Payment.PurchaseOrder.AdditionalFeePercentage"); this.DeletePluginLocaleResource("Plugins.Payment.PurchaseOrder.AdditionalFeePercentage.Hint"); base.Uninstall(); } #endregion #region Properies /// <summary> /// Gets a value indicating whether capture is supported /// </summary> public bool SupportCapture { get { return false; } } /// <summary> /// Gets a value indicating whether partial refund is supported /// </summary> public bool SupportPartiallyRefund { get { return false; } } /// <summary> /// Gets a value indicating whether refund is supported /// </summary> public bool SupportRefund { get { return false; } } /// <summary> /// Gets a value indicating whether void is supported /// </summary> public bool SupportVoid { get { return false; } } /// <summary> /// Gets a recurring payment type of payment method /// </summary> public RecurringPaymentType RecurringPaymentType { get { return RecurringPaymentType.NotSupported; } } /// <summary> /// Gets a payment method type /// </summary> public PaymentMethodType PaymentMethodType { get { return PaymentMethodType.Standard; } } /// <summary> /// Gets a value indicating whether we should display a payment information page for this plugin /// </summary> public bool SkipPaymentInfo { get { return false; } } #endregion } }
// // vorbis-sharp.cs - Tremolo (libvorbisidec) binding // // Author: // Atsushi Enomoto http://d.hatena.ne.jp/atsushieno // // 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.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Text; using C_INT = System.Int32; #if BUILD_64 using C_LONG = System.Int64; #else using C_LONG = System.Int32; #endif using C_SIZE_T = System.Int32; using C_VOIDPTR = System.IntPtr; using C_CHARPTR = System.IntPtr; using C_UCHARPTR = System.IntPtr; using C_FILEPTR = System.IntPtr; // FILE * using VorbisInfoPtr = System.IntPtr; using VorbisCommentPtr = System.IntPtr; using VorbisDspStatePtr = System.IntPtr; using VorbisBlockPtr = System.IntPtr; using OggPacketPtr = System.IntPtr; using OggVorbisFilePtr = System.IntPtr; // LAMESPEC: this definition is wrong, but it seems some devices (such as HTC Desire) doesn't // work fine if I correctly define this. using OV_LONG = System.Int32; namespace UnmanagedOgg { public class VorbisException : Exception { public VorbisException () : base ("Vorbis exception") { } public VorbisException (string message) : base (message) { } public VorbisException (string message, Exception innerException) : base (message, innerException) { } public VorbisException (int errorCode) : base (String.Format ("Vorbis exception error code {0}", errorCode) ) { } } public struct OggVorbisInfo { readonly VorbisInfo info; internal OggVorbisInfo (VorbisInfo info) { this.info = info; } public OggVorbisInfo (IntPtr ptr) { info = (VorbisInfo) Marshal.PtrToStructure (ptr, typeof (VorbisInfo) ); } public C_INT Version { get { return info.Version; } } public C_INT Channels { get { return info.Channels; } } public C_LONG Rate { get { return info.Rate; } } public C_LONG BitrateUpper { get { return info.BitrateUpper; } } public C_LONG BitrateNominal { get { return info.BitrateNominal; } } public C_LONG BitrateLower { get { return info.BitrateLower; } } public C_LONG BitrateWindow { get { return info.BitrateWindow; } } // is it unsafe to expose? public C_VOIDPTR CodecSetup { get { return info.CodecSetup; } } } public class OggVorbisComment { readonly VorbisComment c; readonly Encoding text_encoding; internal OggVorbisComment (VorbisComment c, Encoding textEncoding) { this.c = c; text_encoding = textEncoding; } public OggVorbisComment (IntPtr ptr, Encoding textEncoding) { c = (VorbisComment) Marshal.PtrToStructure (ptr, typeof (VorbisComment) ); text_encoding = textEncoding; } public string [] Comments { get { var ret = new string [c.CommentCount]; for (int i = 0; i < ret.Length; i++) unsafe { var cptr = (char**) c.UserComments; var ptr = * (cptr + i); var lptr = (int*) (c.CommentLengths) + i; byte [] buf = new byte [*lptr]; Marshal.Copy ( (IntPtr) ptr, buf, 0, buf.Length); ret [i] = text_encoding.GetString (buf); } return ret; } } // Unlike comments I cannot simply use text_encoding here (due to MarshalAs limitation) ... public string Vendor { get { return c.Vendor; } } } public class OggStreamBuffer : IDisposable { public OggStreamBuffer (string path) : this (path, Encoding.Default) { } public OggStreamBuffer (string path, Encoding textEncoding) { text_encoding = textEncoding; OvMarshal.ov_open (OvMarshal.fopen (path, "r") , ref vorbis_file, IntPtr.Zero, 0); handle_ovf = GCHandle.Alloc (vorbis_file, GCHandleType.Pinned); callbacks = vorbis_file.Callbacks; } public OggStreamBuffer (Stream stream) : this (stream, Encoding.Default) { } public OggStreamBuffer (Stream stream, Encoding textEncoding) { this.stream = stream; text_encoding = textEncoding; read = new OvReadFunc (Read); seek = new OvSeekFunc (Seek); close = new OvCloseFunc (Close); tell = new OvTellFunc (Tell); callbacks = new OvCallbacks (read, seek, close, tell); OvMarshal.ov_open_callbacks (new IntPtr (1) , ref vorbis_file, IntPtr.Zero, 0, callbacks); handle_ovf = GCHandle.Alloc (vorbis_file, GCHandleType.Pinned); } Stream stream; // those delegates have to be kept. Preserving inside OvCallbacks doesn't help (mono bug?) OvReadFunc read; OvSeekFunc seek; OvCloseFunc close; OvTellFunc tell; GCHandle handle_ovf; Encoding text_encoding; OvCallbacks callbacks; OggVorbisFile vorbis_file; C_LONG? bitrate_instant, streams; bool? seekable; int current_bit_stream; byte [] buffer; IntPtr vfp { get { return handle_ovf.AddrOfPinnedObject (); } } internal OggVorbisFile VorbisFile { get { return vorbis_file; } } public int CurrentBitStream { get { return current_bit_stream; } } public int BitrateInstant { get { if (bitrate_instant == null) bitrate_instant = OvMarshal.ov_bitrate_instant (vfp); return (int) bitrate_instant; } } public int Streams { get { if (streams == null) streams = OvMarshal.ov_streams (vfp); return (int) streams; } } public bool Seekable { get { if (seekable == null) seekable = OvMarshal.ov_seekable (vfp) != 0; return (bool) seekable; } } public void Dispose () { OvMarshal.ov_clear (vfp); if (handle_ovf.IsAllocated) handle_ovf.Free (); } public int GetBitrate (int i) { C_LONG ret = OvMarshal.ov_bitrate (vfp, i); return (int) ret; } public int GetSerialNumber (int i) { C_LONG ret = OvMarshal.ov_serialnumber (vfp, i); return (int) ret; } public OggVorbisInfo GetInfo (int i) { IntPtr ret = OvMarshal.ov_info (vfp, i); return new OggVorbisInfo (ret); } public OggVorbisComment GetComment (int link) { IntPtr ret = OvMarshal.ov_comment (vfp, link); return new OggVorbisComment (ret, text_encoding); } public long GetTotalRaw (int i) { long ret = OvMarshal.ov_raw_total (vfp, i); return ret; } public long GetTotalPcm (int i) { long ret = OvMarshal.ov_pcm_total (vfp, i); return ret; } public long GetTotalTime (int i) { long ret = OvMarshal.ov_time_total (vfp, i); return ret; } public int SeekRaw (long pos) { int ret = OvMarshal.ov_raw_seek (vfp, pos); return ret; } public int SeekPcm (long pos) { int ret = OvMarshal.ov_pcm_seek (vfp, pos); return ret; } public int SeekTime (long pos) { int ret = OvMarshal.ov_time_seek (vfp, pos); return ret; } public long TellRaw () { long ret = OvMarshal.ov_raw_tell (vfp); return ret; } public long TellPcm () { long ret = OvMarshal.ov_pcm_tell (vfp); return ret; } public long TellTime () { long ret = OvMarshal.ov_time_tell (vfp); return ret; } public long Read (short [] buffer, C_INT index, C_INT length) { return Read (buffer, index, length, ref current_bit_stream); } public long Read (short [] buffer, C_INT index, C_INT length, ref int bitStream) { long ret = 0; unsafe { fixed (short* bufptr = buffer) ret = OvMarshal.ov_read (vfp, (IntPtr) (bufptr + index) , length / 2, ref bitStream); } return ret / 2; } public long Read (byte [] buffer, C_INT index, C_INT length) { return Read (buffer, index, length, ref current_bit_stream); } public long Read (byte [] buffer, C_INT index, C_INT length, ref int bitStream) { long ret = 0; unsafe { fixed (byte* bufptr = buffer) ret = OvMarshal.ov_read (vfp, (IntPtr) (bufptr + index) , length, ref bitStream); } return ret; } C_SIZE_T Read (C_VOIDPTR ptr, C_SIZE_T size, C_SIZE_T nmemb, C_VOIDPTR datasource) { if (buffer == null || buffer.Length < size * nmemb) buffer = new byte [size * nmemb]; var actual = (C_SIZE_T) stream.Read (buffer, 0, buffer.Length); if (actual < 0) return 0;//throw new VorbisException (String.Format ("Stream of type {0} returned a negative number: {1}", stream.GetType () , (int) actual) ); Marshal.Copy (buffer, 0, ptr, actual); return actual; } C_INT Seek (C_VOIDPTR datasource, long offset, C_INT whence) { if (!stream.CanSeek) return -1; var ret = stream.Seek (offset, (SeekOrigin) whence); return (C_INT) ret; } C_INT Close (C_VOIDPTR datasource) { stream.Close (); return 0; } C_LONG Tell (C_VOIDPTR datasource) { return (C_LONG) stream.Position; } } #region ogg.h [StructLayout (LayoutKind.Sequential)] internal struct OggPackBuffer { public C_LONG EndByte; public C_INT EndBit; public C_UCHARPTR Buffer; public C_UCHARPTR Ptr; public C_LONG Storage; } [StructLayout (LayoutKind.Sequential)] internal struct OggSyncState { public C_UCHARPTR Data; public C_INT Storage; public C_INT Fill; public C_INT Returned; public C_INT Unsynced; public C_INT HeaderBytes; public C_INT BodyBytes; } [StructLayout (LayoutKind.Sequential, Size = 282)] internal struct OggStreamStateHeader { } [StructLayout (LayoutKind.Sequential, CharSet = CharSet.Ansi)] internal struct OggStreamState { public C_UCHARPTR BodyData; public C_LONG BodyStorage; public C_LONG BodyFill; public C_LONG BodyReturned; public IntPtr LacingValues; // int* public IntPtr GranuleValues; // ogg_int64_t * public C_LONG LacingStorage; public C_LONG LacingFill; public C_LONG LacingPacket; public C_LONG LacingReturned; // [MarshalAs (UnmanagedType.ByValTStr, SizeConst = 282)] //public string Header; public OggStreamStateHeader Header; public C_INT HeaderFill; public C_INT E_O_S; public C_INT B_O_S; public C_LONG SerialNumber; public C_LONG PageNumber; public long PacketNumber; public long GranulePosition; } #endregion #region ivorbiscodec.h [StructLayout (LayoutKind.Sequential)] internal struct VorbisInfo { public C_INT Version; public C_INT Channels; public C_LONG Rate; public C_LONG BitrateUpper; public C_LONG BitrateNominal; public C_LONG BitrateLower; public C_LONG BitrateWindow; public C_VOIDPTR CodecSetup; } [StructLayout (LayoutKind.Sequential)] internal struct VorbisDspState { public int AnalysisP; public IntPtr VorbisInfo; // vorbis_info * public IntPtr Pcm; // ogg_int32_t ** public IntPtr PcmRet; // ogg_int32_t ** public C_INT PcmStorage; public C_INT PcmCurrent; public C_INT PcmReturned; public C_INT PreExtrapolate; public C_INT EofFlag; public C_LONG LW; public C_LONG W; public C_LONG NW; public C_LONG CenterW; public long GranulePosision; public long Sequence; public C_VOIDPTR BackendState; } [StructLayout (LayoutKind.Sequential)] internal struct VorbisBlock { public IntPtr Pcm; // ogg_int32_t ** public OggPackBuffer OPB; public C_LONG LW; public C_LONG W; public C_LONG NW; public C_INT PcmEnd; public C_INT Mode; public C_INT EofFlag; public long GranulePosision; public long Sequence; public IntPtr DspState; // vorbis_dsp_state * , read-only public C_VOIDPTR LocalStore; public C_LONG LocalTop; public C_LONG LocalAlloc; public C_LONG TotalUse; public IntPtr Reap; // struct alloc_chain * } [StructLayout (LayoutKind.Sequential)] internal struct AllocChain { public C_VOIDPTR Ptr; public IntPtr Next; // struct alloc_chain * } [StructLayout (LayoutKind.Sequential)] public struct VorbisComment { public readonly IntPtr UserComments; // char ** public readonly IntPtr CommentLengths; // int * public readonly C_INT CommentCount; [MarshalAs (UnmanagedType.LPStr)] public readonly string Vendor; } #endregion #region ivorbisfile.h internal delegate C_SIZE_T OvReadFunc (C_VOIDPTR ptr, C_SIZE_T size, C_SIZE_T nmemb, C_VOIDPTR datasource); internal delegate C_INT OvSeekFunc (C_VOIDPTR datasource, long offset, C_INT whence); internal delegate C_INT OvCloseFunc (C_VOIDPTR datasource); internal delegate C_LONG OvTellFunc (C_VOIDPTR datasource); [StructLayout (LayoutKind.Sequential)] internal struct OvCallbacks { #if true public OvCallbacks (OvReadFunc read, OvSeekFunc seek, OvCloseFunc close, OvTellFunc tell) { ReadFunc = Marshal.GetFunctionPointerForDelegate (read); SeekFunc = Marshal.GetFunctionPointerForDelegate (seek); CloseFunc = Marshal.GetFunctionPointerForDelegate (close); TellFunc = Marshal.GetFunctionPointerForDelegate (tell); } public IntPtr ReadFunc; public IntPtr SeekFunc; public IntPtr CloseFunc; public IntPtr TellFunc; #else public OvCallbacks (OvReadFunc read, OvSeekFunc seek, OvCloseFunc close, OvTellFunc tell) { ReadFunc = read; SeekFunc = seek; CloseFunc = close; TellFunc = tell; } public OvReadFunc ReadFunc; public OvSeekFunc SeekFunc; public OvCloseFunc CloseFunc; public OvTellFunc TellFunc; #endif } [StructLayout (LayoutKind.Sequential)] internal struct OggVorbisFile { public C_VOIDPTR DataSource; public C_INT Seekable; public long Offset; public long End; public OggSyncState OY; public C_INT Links; public IntPtr Offsets; // ogg_int64_t * public IntPtr DataOffsets; // ogg_int64_t * public IntPtr SerialNumbers; // ogg_uint32_t * public IntPtr PcmLengths; // ogg_int64_t * public VorbisInfoPtr VorbisInfo; public VorbisCommentPtr VorbisComment; public long PcmOffset; public C_INT ReadyState; public uint CurrentSerialNumber; public C_INT CurrentLink; public long BitTrack; public long SampTrack; public OggStreamState StreamState; public VorbisDspState DspState; // central working state public VorbisBlock Block; // local working space public OvCallbacks Callbacks; } #endregion internal static class OvMarshal { #if FULL const string FileLibrary = "vorbisfile"; const string TremoloLibrary = "vorbis"; #else const string FileLibrary = "vorbisidec"; const string TremoloLibrary = "vorbisidec"; #endif #region ivorbiscodec.h [DllImport (TremoloLibrary)] static internal extern void vorbis_info_init (ref VorbisInfo vi); // vorbis_info *, to output allocated pointer [DllImport (TremoloLibrary)] static internal extern void vorbis_info_clear (ref VorbisInfo vi); // vorbis_info *, to dealloc [DllImport (TremoloLibrary)] static internal extern C_INT vorbis_info_blocksize (VorbisInfoPtr vi, int zo); [DllImport (TremoloLibrary)] static internal extern void vorbis_comment_init (VorbisCommentPtr vc); [DllImport (TremoloLibrary)] static internal extern void vorbis_comment_add (VorbisCommentPtr vc, C_CHARPTR comment); [DllImport (TremoloLibrary)] static internal extern void vorbis_comment_add_tag (VorbisCommentPtr vc, C_CHARPTR tag, C_CHARPTR contents); [DllImport (TremoloLibrary)] static internal extern C_CHARPTR vorbis_comment_query (VorbisCommentPtr vc, C_CHARPTR tag, int count); [DllImport (TremoloLibrary)] static internal extern C_INT vorbis_comment_query_count (VorbisCommentPtr vc, C_CHARPTR tag); [DllImport (TremoloLibrary)] static internal extern void vorbis_comment_clear (VorbisCommentPtr vc); [DllImport (TremoloLibrary)] static internal extern C_INT vorbis_block_init (VorbisDspStatePtr v, VorbisBlockPtr vb); [DllImport (TremoloLibrary)] static internal extern C_INT vorbis_block_clear (VorbisBlockPtr vb); [DllImport (TremoloLibrary)] static internal extern void vorbis_dsp_clear (VorbisDspStatePtr v); [DllImport (TremoloLibrary)] static internal extern C_INT vorbis_synthesis_idheader (OggPacketPtr op); [DllImport (TremoloLibrary)] static internal extern C_INT vorbis_synthesis_headerin (VorbisInfoPtr vi, VorbisCommentPtr vc, OggPacketPtr op); [DllImport (TremoloLibrary)] static internal extern C_INT vorbis_synthesis_init (VorbisDspStatePtr v, VorbisInfoPtr vi); [DllImport (TremoloLibrary)] static internal extern C_INT vorbis_synthesis_restart (VorbisDspStatePtr v); [DllImport (TremoloLibrary)] static internal extern C_INT vorbis_synthesis (VorbisBlockPtr vb, OggPacketPtr op); [DllImport (TremoloLibrary)] static internal extern C_INT vorbis_synthesis_trackonly (VorbisBlockPtr vb, OggPacketPtr op); [DllImport (TremoloLibrary)] static internal extern C_INT vorbis_synthesis_blockin (VorbisDspStatePtr v, VorbisBlockPtr vb); [DllImport (TremoloLibrary)] static internal extern C_INT vorbis_synthesis_pcmout (VorbisDspStatePtr v, IntPtr pcm); // ogg_int32_t *** [DllImport (TremoloLibrary)] static internal extern C_INT vorbis_synthesis_read (VorbisDspStatePtr v, int samples); [DllImport (TremoloLibrary)] static internal extern C_LONG vorbis_packet_blocksize (VorbisInfoPtr vi, OggPacketPtr op); #endregion #region ivorbisfile.h [DllImport (FileLibrary)] static internal extern C_INT ov_clear (OggVorbisFilePtr vf); [DllImport (FileLibrary)] static internal extern C_INT ov_open (C_FILEPTR f, [In, Out] ref OggVorbisFile vf, C_CHARPTR initial, C_LONG ibytes); [DllImport (FileLibrary)] static internal extern C_INT ov_open_callbacks (IntPtr datasource, [In, Out] ref OggVorbisFile vf, C_CHARPTR initial, C_LONG ibytes, OvCallbacks callbacks); [DllImport (FileLibrary)] static internal extern C_INT ov_test (C_FILEPTR f, [In, Out] ref OggVorbisFile vf, C_CHARPTR initial, C_LONG ibytes); [DllImport (FileLibrary)] static internal extern C_INT ov_test_callbacks (IntPtr datasource, [In, Out] ref OggVorbisFile vf, C_CHARPTR initial, C_LONG ibytes, OvCallbacks callbacks); [DllImport (FileLibrary)] static internal extern C_INT ov_test_open ( [In, Out] ref OggVorbisFile vf); [DllImport (FileLibrary)] static internal extern C_LONG ov_bitrate (OggVorbisFilePtr vf, C_INT i); [DllImport (FileLibrary)] static internal extern C_LONG ov_bitrate_instant (OggVorbisFilePtr vf); [DllImport (FileLibrary)] static internal extern C_LONG ov_streams (OggVorbisFilePtr vf); [DllImport (FileLibrary)] static internal extern C_LONG ov_seekable (OggVorbisFilePtr vf); [DllImport (FileLibrary)] static internal extern C_LONG ov_serialnumber (OggVorbisFilePtr vf, C_INT i); [DllImport (FileLibrary)] static internal extern long ov_raw_total (OggVorbisFilePtr vf, C_INT i); [DllImport (FileLibrary)] static internal extern long ov_pcm_total (OggVorbisFilePtr vf, C_INT i); [DllImport (FileLibrary)] static internal extern OV_LONG ov_time_total (OggVorbisFilePtr vf, C_INT i); [DllImport (FileLibrary)] static internal extern C_INT ov_raw_seek (OggVorbisFilePtr vf, long pos); [DllImport (FileLibrary)] static internal extern C_INT ov_pcm_seek (OggVorbisFilePtr vf, long pos); [DllImport (FileLibrary)] static internal extern C_INT ov_pcm_seek_page (OggVorbisFilePtr vf, long pos); [DllImport (FileLibrary)] static internal extern C_INT ov_time_seek (OggVorbisFilePtr vf, long pos); [DllImport (FileLibrary)] static internal extern C_INT ov_time_seek_page (OggVorbisFilePtr vf, long pos); [DllImport (FileLibrary)] static internal extern long ov_raw_tell (OggVorbisFilePtr vf); [DllImport (FileLibrary)] static internal extern long ov_pcm_tell (OggVorbisFilePtr vf); [DllImport (FileLibrary)] static internal extern long ov_time_tell (OggVorbisFilePtr vf); [DllImport (FileLibrary)] static internal extern VorbisInfoPtr ov_info (OggVorbisFilePtr vf, C_INT link); [DllImport (FileLibrary)] static internal extern VorbisCommentPtr ov_comment (OggVorbisFilePtr vf, C_INT link); [DllImport (FileLibrary)] // FIXME: this mismatch occurs on Desire. static internal extern OV_LONG ov_read (OggVorbisFilePtr vf, IntPtr buffer, C_INT length, ref int bitstream); [DllImport ("libc")] static internal extern C_FILEPTR fopen (string path, string mode); #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.Buffers; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.Text { // ASCIIEncoding // // Note that ASCIIEncoding is optimized with no best fit and ? for fallback. // It doesn't come in other flavors. // // Note: ASCIIEncoding is the only encoding that doesn't do best fit (windows has best fit). // // Note: IsAlwaysNormalized remains false because 1/2 the code points are unassigned, so they'd // use fallbacks, and we cannot guarantee that fallbacks are normalized. public partial class ASCIIEncoding : Encoding { // This specialized sealed type has two benefits: // 1) it allows for devirtualization (see https://github.com/dotnet/coreclr/pull/9230), and // 2) it allows us to provide highly optimized implementations of certain routines because // we can make assumptions about the fallback mechanisms in use (in particular, always // replace with "?"). // // (We don't take advantage of #2 yet, but we can do so in the future because the implementation // of cloning below allows us to make assumptions about the behaviors of the sealed type.) internal sealed class ASCIIEncodingSealed : ASCIIEncoding { public override object Clone() { // The base implementation of Encoding.Clone calls object.MemberwiseClone and marks the new object mutable. // We don't want to do this because it violates the invariants we have set for the sealed type. // Instead, we'll create a new instance of the base ASCIIEncoding type and mark it mutable. return new ASCIIEncoding() { IsReadOnly = false }; } } // Used by Encoding.ASCII for lazy initialization // The initialization code will not be run until a static member of the class is referenced internal static readonly ASCIIEncodingSealed s_default = new ASCIIEncodingSealed(); public ASCIIEncoding() : base(Encoding.CodePageASCII) { } internal sealed override void SetDefaultFallbacks() { // For ASCIIEncoding we just use default replacement fallback this.encoderFallback = EncoderFallback.ReplacementFallback; this.decoderFallback = DecoderFallback.ReplacementFallback; } // WARNING: GetByteCount(string chars), GetBytes(string chars,...), and GetString(byte[] byteIndex...) // WARNING: have different variable names than EncodingNLS.cs, so this can't just be cut & pasted, // WARNING: or it'll break VB's way of calling these. // // The following methods are copied from EncodingNLS.cs. // Unfortunately EncodingNLS.cs is internal and we're public, so we have to re-implement them here. // These should be kept in sync for the following classes: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // Returns the number of bytes required to encode a range of characters in // a character array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount(char[] chars, int index, int count) { // Validate input parameters if (chars is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.chars, ExceptionResource.ArgumentNull_Array); } if ((index | count) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((index < 0) ? ExceptionArgument.index : ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (chars!.Length - index < count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.chars, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer); } fixed (char* pChars = chars) { return GetByteCountCommon(pChars + index, count); } } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount(string chars) { // Validate input parameters if (chars is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.chars); } fixed (char* pChars = chars) { return GetByteCountCommon(pChars, chars!.Length); } } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetByteCount(char* chars, int count) { // Validate Parameters if (chars == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.chars); } if (count < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } return GetByteCountCommon(chars, count); } public override unsafe int GetByteCount(ReadOnlySpan<char> chars) { // It's ok for us to pass null pointers down to the workhorse below. fixed (char* charsPtr = &MemoryMarshal.GetReference(chars)) { return GetByteCountCommon(charsPtr, chars.Length); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe int GetByteCountCommon(char* pChars, int charCount) { // Common helper method for all non-EncoderNLS entry points to GetByteCount. // A modification of this method should be copied in to each of the supported encodings: ASCII, UTF8, UTF16, UTF32. Debug.Assert(charCount >= 0, "Caller shouldn't specify negative length buffer."); Debug.Assert(pChars != null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); // First call into the fast path. int totalByteCount = GetByteCountFast(pChars, charCount, EncoderFallback, out int charsConsumed); if (charsConsumed != charCount) { // If there's still data remaining in the source buffer, go down the fallback path. // We need to check for integer overflow since the fallback could change the required // output count in unexpected ways. totalByteCount += GetByteCountWithFallback(pChars, charCount, charsConsumed); if (totalByteCount < 0) { ThrowConversionOverflow(); } } return totalByteCount; } [MethodImpl(MethodImplOptions.AggressiveInlining)] // called directly by GetByteCountCommon private protected sealed override unsafe int GetByteCountFast(char* pChars, int charsLength, EncoderFallback? fallback, out int charsConsumed) { // First: Can we short-circuit the entire calculation? // If an EncoderReplacementFallback is in use, all non-ASCII chars // (including surrogate halves) are replaced with the default string. // If the default string consists of a single ASCII value, then we // know there's a 1:1 char->byte transcoding in all cases. int byteCount = charsLength; if (!(fallback is EncoderReplacementFallback replacementFallback && replacementFallback.MaxCharCount == 1 && replacementFallback.DefaultString[0] <= 0x7F)) { // Unrecognized fallback mechanism - count chars manually. byteCount = (int)ASCIIUtility.GetIndexOfFirstNonAsciiChar(pChars, (uint)charsLength); } charsConsumed = byteCount; return byteCount; } // Parent method is safe. // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding public override unsafe int GetBytes(string chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { // Validate Parameters if (chars is null || bytes is null) { ThrowHelper.ThrowArgumentNullException( argument: (chars is null) ? ExceptionArgument.chars : ExceptionArgument.bytes, resource: ExceptionResource.ArgumentNull_Array); } if ((charIndex | charCount) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException( argument: (charIndex < 0) ? ExceptionArgument.charIndex : ExceptionArgument.charCount, resource: ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (chars!.Length - charIndex < charCount) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.chars, ExceptionResource.ArgumentOutOfRange_IndexCount); } if ((uint)byteIndex > bytes!.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.byteIndex, ExceptionResource.ArgumentOutOfRange_Index); } fixed (char* pChars = chars) fixed (byte* pBytes = bytes) { return GetBytesCommon(pChars + charIndex, charCount, pBytes + byteIndex, bytes.Length - byteIndex); } } // Encodes a range of characters in a character array into a range of bytes // in a byte array. An exception occurs if the byte array is not large // enough to hold the complete encoding of the characters. The // GetByteCount method can be used to determine the exact number of // bytes that will be produced for a given range of characters. // Alternatively, the GetMaxByteCount method can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { // Validate parameters if (chars is null || bytes is null) { ThrowHelper.ThrowArgumentNullException( argument: (chars is null) ? ExceptionArgument.chars : ExceptionArgument.bytes, resource: ExceptionResource.ArgumentNull_Array); } if ((charIndex | charCount) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException( argument: (charIndex < 0) ? ExceptionArgument.charIndex : ExceptionArgument.charCount, resource: ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (chars!.Length - charIndex < charCount) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.chars, ExceptionResource.ArgumentOutOfRange_IndexCount); } if ((uint)byteIndex > bytes!.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.byteIndex, ExceptionResource.ArgumentOutOfRange_Index); } fixed (char* pChars = chars) fixed (byte* pBytes = bytes) { return GetBytesCommon(pChars + charIndex, charCount, pBytes + byteIndex, bytes.Length - byteIndex); } } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { // Validate Parameters if (chars == null || bytes == null) { ThrowHelper.ThrowArgumentNullException( argument: (chars is null) ? ExceptionArgument.chars : ExceptionArgument.bytes, resource: ExceptionResource.ArgumentNull_Array); } if ((charCount | byteCount) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException( argument: (charCount < 0) ? ExceptionArgument.charCount : ExceptionArgument.byteCount, resource: ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } return GetBytesCommon(chars, charCount, bytes, byteCount); } public override unsafe int GetBytes(ReadOnlySpan<char> chars, Span<byte> bytes) { // It's ok for us to operate on null / empty spans. fixed (char* charsPtr = &MemoryMarshal.GetReference(chars)) fixed (byte* bytesPtr = &MemoryMarshal.GetReference(bytes)) { return GetBytesCommon(charsPtr, chars.Length, bytesPtr, bytes.Length); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe int GetBytesCommon(char* pChars, int charCount, byte* pBytes, int byteCount) { // Common helper method for all non-EncoderNLS entry points to GetBytes. // A modification of this method should be copied in to each of the supported encodings: ASCII, UTF8, UTF16, UTF32. Debug.Assert(charCount >= 0, "Caller shouldn't specify negative length buffer."); Debug.Assert(pChars != null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); Debug.Assert(byteCount >= 0, "Caller shouldn't specify negative length buffer."); Debug.Assert(pBytes != null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); // First call into the fast path. int bytesWritten = GetBytesFast(pChars, charCount, pBytes, byteCount, out int charsConsumed); if (charsConsumed == charCount) { // All elements converted - return immediately. return bytesWritten; } else { // Simple narrowing conversion couldn't operate on entire buffer - invoke fallback. return GetBytesWithFallback(pChars, charCount, pBytes, byteCount, charsConsumed, bytesWritten); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] // called directly by GetBytesCommon private protected sealed override unsafe int GetBytesFast(char* pChars, int charsLength, byte* pBytes, int bytesLength, out int charsConsumed) { int bytesWritten = (int)ASCIIUtility.NarrowUtf16ToAscii(pChars, pBytes, (uint)Math.Min(charsLength, bytesLength)); charsConsumed = bytesWritten; return bytesWritten; } private protected sealed override unsafe int GetBytesWithFallback(ReadOnlySpan<char> chars, int originalCharsLength, Span<byte> bytes, int originalBytesLength, EncoderNLS? encoder) { // We special-case EncoderReplacementFallback if it's telling us to write a single ASCII char, // since we believe this to be relatively common and we can handle it more efficiently than // the base implementation. if (((encoder is null) ? this.EncoderFallback : encoder.Fallback) is EncoderReplacementFallback replacementFallback && replacementFallback.MaxCharCount == 1 && replacementFallback.DefaultString[0] <= 0x7F) { byte replacementByte = (byte)replacementFallback.DefaultString[0]; int numElementsToConvert = Math.Min(chars.Length, bytes.Length); int idx = 0; fixed (char* pChars = &MemoryMarshal.GetReference(chars)) fixed (byte* pBytes = &MemoryMarshal.GetReference(bytes)) { // In a loop, replace the non-convertible data, then bulk-convert as much as we can. while (idx < numElementsToConvert) { pBytes[idx++] = replacementByte; if (idx < numElementsToConvert) { idx += (int)ASCIIUtility.NarrowUtf16ToAscii(&pChars[idx], &pBytes[idx], (uint)(numElementsToConvert - idx)); } Debug.Assert(idx <= numElementsToConvert, "Somehow went beyond bounds of source or destination buffer?"); } } // Slice off how much we consumed / wrote. chars = chars.Slice(numElementsToConvert); bytes = bytes.Slice(numElementsToConvert); } // If we couldn't go through our fast fallback mechanism, or if we still have leftover // data because we couldn't consume everything in the loop above, we need to go down the // slow fallback path. if (chars.IsEmpty) { return originalBytesLength - bytes.Length; // total number of bytes written } else { return base.GetBytesWithFallback(chars, originalCharsLength, bytes, originalBytesLength, encoder); } } // Returns the number of characters produced by decoding a range of bytes // in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetCharCount(byte[] bytes, int index, int count) { // Validate Parameters if (bytes is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.bytes, ExceptionResource.ArgumentNull_Array); } if ((index | count) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException((index < 0) ? ExceptionArgument.index : ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (bytes!.Length - index < count) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer); } fixed (byte* pBytes = bytes) { return GetCharCountCommon(pBytes + index, count); } } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetCharCount(byte* bytes, int count) { // Validate Parameters if (bytes == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.bytes, ExceptionResource.ArgumentNull_Array); } if (count < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } return GetCharCountCommon(bytes, count); } public override unsafe int GetCharCount(ReadOnlySpan<byte> bytes) { // It's ok for us to pass null pointers down to the workhorse routine. fixed (byte* bytesPtr = &MemoryMarshal.GetReference(bytes)) { return GetCharCountCommon(bytesPtr, bytes.Length); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe int GetCharCountCommon(byte* pBytes, int byteCount) { // Common helper method for all non-DecoderNLS entry points to GetCharCount. // A modification of this method should be copied in to each of the supported encodings: ASCII, UTF8, UTF16, UTF32. Debug.Assert(byteCount >= 0, "Caller shouldn't specify negative length buffer."); Debug.Assert(pBytes != null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); // First call into the fast path. int totalCharCount = GetCharCountFast(pBytes, byteCount, DecoderFallback, out int bytesConsumed); if (bytesConsumed != byteCount) { // If there's still data remaining in the source buffer, go down the fallback path. // We need to check for integer overflow since the fallback could change the required // output count in unexpected ways. totalCharCount += GetCharCountWithFallback(pBytes, byteCount, bytesConsumed); if (totalCharCount < 0) { ThrowConversionOverflow(); } } return totalCharCount; } [MethodImpl(MethodImplOptions.AggressiveInlining)] // called directly by GetCharCountCommon private protected sealed override unsafe int GetCharCountFast(byte* pBytes, int bytesLength, DecoderFallback? fallback, out int bytesConsumed) { // First: Can we short-circuit the entire calculation? // If a DecoderReplacementFallback is in use, all non-ASCII bytes are replaced with // the default string. If the default string consists of a single BMP value, then we // know there's a 1:1 byte->char transcoding in all cases. int charCount = bytesLength; if (!(fallback is DecoderReplacementFallback replacementFallback) || replacementFallback.MaxCharCount != 1) { // Unrecognized fallback mechanism - count bytes manually. charCount = (int)ASCIIUtility.GetIndexOfFirstNonAsciiByte(pBytes, (uint)bytesLength); } bytesConsumed = charCount; return charCount; } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // Validate Parameters if (bytes is null || chars is null) { ThrowHelper.ThrowArgumentNullException( argument: (bytes is null) ? ExceptionArgument.bytes : ExceptionArgument.chars, resource: ExceptionResource.ArgumentNull_Array); } if ((byteIndex | byteCount) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException( argument: (byteIndex < 0) ? ExceptionArgument.byteIndex : ExceptionArgument.byteCount, resource: ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (bytes!.Length - byteIndex < byteCount) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer); } if ((uint)charIndex > (uint)chars!.Length) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.charIndex, ExceptionResource.ArgumentOutOfRange_Index); } fixed (byte* pBytes = bytes) fixed (char* pChars = chars) { return GetCharsCommon(pBytes + byteIndex, byteCount, pChars + charIndex, chars.Length - charIndex); } } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { // Validate Parameters if (bytes is null || chars is null) { ThrowHelper.ThrowArgumentNullException( argument: (bytes is null) ? ExceptionArgument.bytes : ExceptionArgument.chars, resource: ExceptionResource.ArgumentNull_Array); } if ((byteCount | charCount) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException( argument: (byteCount < 0) ? ExceptionArgument.byteCount : ExceptionArgument.charCount, resource: ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } return GetCharsCommon(bytes, byteCount, chars, charCount); } public override unsafe int GetChars(ReadOnlySpan<byte> bytes, Span<char> chars) { // It's ok for us to pass null pointers down to the workhorse below. fixed (byte* bytesPtr = &MemoryMarshal.GetReference(bytes)) fixed (char* charsPtr = &MemoryMarshal.GetReference(chars)) { return GetCharsCommon(bytesPtr, bytes.Length, charsPtr, chars.Length); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private unsafe int GetCharsCommon(byte* pBytes, int byteCount, char* pChars, int charCount) { // Common helper method for all non-DecoderNLS entry points to GetChars. // A modification of this method should be copied in to each of the supported encodings: ASCII, UTF8, UTF16, UTF32. Debug.Assert(byteCount >= 0, "Caller shouldn't specify negative length buffer."); Debug.Assert(pBytes != null || byteCount == 0, "Input pointer shouldn't be null if non-zero length specified."); Debug.Assert(charCount >= 0, "Caller shouldn't specify negative length buffer."); Debug.Assert(pChars != null || charCount == 0, "Input pointer shouldn't be null if non-zero length specified."); // First call into the fast path. int charsWritten = GetCharsFast(pBytes, byteCount, pChars, charCount, out int bytesConsumed); if (bytesConsumed == byteCount) { // All elements converted - return immediately. return charsWritten; } else { // Simple narrowing conversion couldn't operate on entire buffer - invoke fallback. return GetCharsWithFallback(pBytes, byteCount, pChars, charCount, bytesConsumed, charsWritten); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] // called directly by GetCharsCommon private protected sealed override unsafe int GetCharsFast(byte* pBytes, int bytesLength, char* pChars, int charsLength, out int bytesConsumed) { int charsWritten = (int)ASCIIUtility.WidenAsciiToUtf16(pBytes, pChars, (uint)Math.Min(bytesLength, charsLength)); bytesConsumed = charsWritten; return charsWritten; } private protected sealed override unsafe int GetCharsWithFallback(ReadOnlySpan<byte> bytes, int originalBytesLength, Span<char> chars, int originalCharsLength, DecoderNLS? decoder) { // We special-case DecoderReplacementFallback if it's telling us to write a single BMP char, // since we believe this to be relatively common and we can handle it more efficiently than // the base implementation. if ((decoder is null ? DecoderFallback : decoder.Fallback) is DecoderReplacementFallback replacementFallback && replacementFallback.MaxCharCount == 1) { char replacementChar = replacementFallback.DefaultString[0]; int numElementsToConvert = Math.Min(bytes.Length, chars.Length); int idx = 0; fixed (byte* pBytes = &MemoryMarshal.GetReference(bytes)) fixed (char* pChars = &MemoryMarshal.GetReference(chars)) { // In a loop, replace the non-convertible data, then bulk-convert as much as we can. while (idx < numElementsToConvert) { pChars[idx++] = replacementChar; if (idx < numElementsToConvert) { idx += (int)ASCIIUtility.WidenAsciiToUtf16(&pBytes[idx], &pChars[idx], (uint)(numElementsToConvert - idx)); } Debug.Assert(idx <= numElementsToConvert, "Somehow went beyond bounds of source or destination buffer?"); } } // Slice off how much we consumed / wrote. bytes = bytes.Slice(numElementsToConvert); chars = chars.Slice(numElementsToConvert); } // If we couldn't go through our fast fallback mechanism, or if we still have leftover // data because we couldn't consume everything in the loop above, we need to go down the // slow fallback path. if (bytes.IsEmpty) { return originalCharsLength - chars.Length; // total number of chars written } else { return base.GetCharsWithFallback(bytes, originalBytesLength, chars, originalCharsLength, decoder); } } // Returns a string containing the decoded representation of a range of // bytes in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe string GetString(byte[] bytes, int byteIndex, int byteCount) { // Validate Parameters if (bytes is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.bytes, ExceptionResource.ArgumentNull_Array); } if ((byteIndex | byteCount) < 0) { ThrowHelper.ThrowArgumentOutOfRangeException( argument: (byteIndex < 0) ? ExceptionArgument.byteIndex : ExceptionArgument.byteCount, resource: ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (bytes!.Length - byteIndex < byteCount) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.bytes, ExceptionResource.ArgumentOutOfRange_IndexCountBuffer); } // Avoid problems with empty input buffer if (byteCount == 0) return string.Empty; fixed (byte* pBytes = bytes) { return string.CreateStringFromEncoding(pBytes + byteIndex, byteCount, this); } } // // End of standard methods copied from EncodingNLS.cs // // // Beginning of methods used by shared fallback logic. // internal sealed override bool TryGetByteCount(Rune value, out int byteCount) { if (value.IsAscii) { byteCount = 1; return true; } else { byteCount = default; return false; } } internal sealed override OperationStatus EncodeRune(Rune value, Span<byte> bytes, out int bytesWritten) { if (value.IsAscii) { if (!bytes.IsEmpty) { bytes[0] = (byte)value.Value; bytesWritten = 1; return OperationStatus.Done; } else { bytesWritten = 0; return OperationStatus.DestinationTooSmall; } } else { bytesWritten = 0; return OperationStatus.InvalidData; } } internal sealed override OperationStatus DecodeFirstRune(ReadOnlySpan<byte> bytes, out Rune value, out int bytesConsumed) { if (!bytes.IsEmpty) { byte b = bytes[0]; if (b <= 0x7F) { // ASCII byte value = new Rune(b); bytesConsumed = 1; return OperationStatus.Done; } else { // Non-ASCII byte value = Rune.ReplacementChar; bytesConsumed = 1; return OperationStatus.InvalidData; } } else { // No data to decode value = Rune.ReplacementChar; bytesConsumed = 0; return OperationStatus.NeedMoreData; } } // // End of methods used by shared fallback logic. // public override int GetMaxByteCount(int charCount) { if (charCount < 0) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); // Characters would be # of characters + 1 in case high surrogate is ? * max fallback long byteCount = (long)charCount + 1; if (EncoderFallback.MaxCharCount > 1) byteCount *= EncoderFallback.MaxCharCount; // 1 to 1 for most characters. Only surrogates with fallbacks have less. if (byteCount > 0x7fffffff) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GetByteCountOverflow); return (int)byteCount; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); // Just return length, SBCS stay the same length because they don't map to surrogate long charCount = (long)byteCount; // 1 to 1 for most characters. Only surrogates with fallbacks have less, unknown fallbacks could be longer. if (DecoderFallback.MaxCharCount > 1) charCount *= DecoderFallback.MaxCharCount; if (charCount > 0x7fffffff) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_GetCharCountOverflow); return (int)charCount; } // True if and only if the encoding only uses single byte code points. (Ie, ASCII, 1252, etc) public override bool IsSingleByte => true; public override Decoder GetDecoder() => new DecoderNLS(this); public override Encoder GetEncoder() => new EncoderNLS(this); } }
#region Copyright (c) 2003, newtelligence AG. All rights reserved. // Copyright (c) 2003, newtelligence AG. (http://www.newtelligence.com) // Original BlogX Source Code: Copyright (c) 2003, Chris Anderson (http://simplegeek.com) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted // provided that the following conditions are met: // // (1) Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // (2) Redistributions in binary form must reproduce the above copyright notice, this list of // conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // (3) Neither the name of the newtelligence AG 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. // ------------------------------------------------------------------------- // // Original BlogX source code (c) 2003 by Chris Anderson (http://simplegeek.com) // // newtelligence is a registered trademark of newtelligence Aktiengesellschaft. // // For portions of this software, the some additional copyright notices may apply // which can either be found in the license.txt file included in the source distribution // or following this notice. // ------- // Copyright 2003, Microsoft Coporation // // Original source code by Nikhil Kothari // // Integrated into DasBlog by Chris Anderson // // Provided as is, with no warrenty, etc. // License is granted to use, copy, modify, // with or without credit to me, just don't // blame me if it doesn't work. // ------- #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using newtelligence.DasBlog.Runtime.Html.Formatting; namespace newtelligence.DasBlog.Util.Html { /// <summary> /// </summary> /// TODO: Have the formatter take a TextBuffer and format that buffer and output a string /// TODO: Handle TD tags correctly public sealed class HtmlFormatter { private static IDictionary<string, TagInfo> tagTable; //private delegate bool CanContainTag(TagInfo info); private static TagInfo commentTag; private static TagInfo directiveTag; private static TagInfo otherServerSideScriptTag; private static TagInfo nestedXmlTag; private static TagInfo unknownXmlTag; private static TagInfo unknownHtmlTag; static HtmlFormatter() { commentTag = new TagInfo("", FormattingFlags.Comment | FormattingFlags.NoEndTag, WhiteSpaceType.CarryThrough, WhiteSpaceType.CarryThrough, ElementType.Any); directiveTag = new TagInfo("", FormattingFlags.NoEndTag, WhiteSpaceType.NotSignificant, WhiteSpaceType.NotSignificant, ElementType.Any); otherServerSideScriptTag = new TagInfo("", FormattingFlags.NoEndTag | FormattingFlags.Inline, ElementType.Any); unknownXmlTag = new TagInfo("", FormattingFlags.Xml, WhiteSpaceType.NotSignificant, WhiteSpaceType.NotSignificant, ElementType.Any); nestedXmlTag = new TagInfo("", FormattingFlags.AllowPartialTags, WhiteSpaceType.NotSignificant, WhiteSpaceType.NotSignificant, ElementType.Any); unknownHtmlTag = new TagInfo("", FormattingFlags.None, WhiteSpaceType.NotSignificant, WhiteSpaceType.NotSignificant, ElementType.Any); tagTable = new Dictionary<string, TagInfo>(StringComparer.OrdinalIgnoreCase); tagTable["a"] = new TagInfo("a", FormattingFlags.Inline, ElementType.Inline); tagTable["acronym"] = new TagInfo("acronym", FormattingFlags.Inline, ElementType.Inline); tagTable["address"] = new TagInfo("address", FormattingFlags.None, WhiteSpaceType.Significant, WhiteSpaceType.NotSignificant, ElementType.Block); tagTable["applet"] = new TagInfo("applet", FormattingFlags.Inline, WhiteSpaceType.CarryThrough, WhiteSpaceType.Significant, ElementType.Inline); tagTable["area"] = new TagInfo("area", FormattingFlags.NoEndTag); tagTable["b"] = new TagInfo("b", FormattingFlags.Inline, ElementType.Inline); tagTable["base"] = new TagInfo("base", FormattingFlags.NoEndTag); tagTable["basefont"] = new TagInfo("basefont", FormattingFlags.NoEndTag, ElementType.Block); tagTable["bdo"] = new TagInfo("bdo", FormattingFlags.Inline, ElementType.Inline); tagTable["bgsound"] = new TagInfo("bgsound", FormattingFlags.NoEndTag); tagTable["big"] = new TagInfo("big", FormattingFlags.Inline, ElementType.Inline); tagTable["blink"] = new TagInfo("blink", FormattingFlags.Inline); tagTable["blockquote"] = new TagInfo("blockquote", FormattingFlags.Inline, WhiteSpaceType.Significant, WhiteSpaceType.NotSignificant, ElementType.Block); tagTable["body"] = new TagInfo("body", FormattingFlags.None); tagTable["br"] = new TagInfo("br", FormattingFlags.NoEndTag, WhiteSpaceType.NotSignificant, WhiteSpaceType.NotSignificant, ElementType.Inline); //tagTable["br"] = new TagInfo("br", FormattingFlags.NoEndTag, WhiteSpaceType.Significant, WhiteSpaceType.Significant, ElementType.Inline); tagTable["button"] = new TagInfo("button", FormattingFlags.Inline, ElementType.Inline); tagTable["caption"] = new TagInfo("caption", FormattingFlags.None); tagTable["cite"] = new TagInfo("cite", FormattingFlags.Inline, ElementType.Inline); tagTable["center"] = new TagInfo("center", FormattingFlags.None, WhiteSpaceType.Significant, WhiteSpaceType.NotSignificant, ElementType.Block); tagTable["code"] = new TagInfo("code", FormattingFlags.Inline, ElementType.Inline); tagTable["col"] = new TagInfo("col", FormattingFlags.NoEndTag); tagTable["colgroup"] = new TagInfo("colgroup", FormattingFlags.None); tagTable["dd"] = new TagInfo("dd", FormattingFlags.None); tagTable["del"] = new TagInfo("del", FormattingFlags.None); tagTable["dfn"] = new TagInfo("dfn", FormattingFlags.Inline, ElementType.Inline); tagTable["dir"] = new TagInfo("dir", FormattingFlags.None, ElementType.Block); tagTable["div"] = new TagInfo("div", FormattingFlags.None, WhiteSpaceType.Significant, WhiteSpaceType.NotSignificant, ElementType.Block); tagTable["dl"] = new TagInfo("dl", FormattingFlags.None, WhiteSpaceType.NotSignificant, WhiteSpaceType.NotSignificant, ElementType.Block); tagTable["dt"] = new TagInfo("dt", FormattingFlags.Inline); tagTable["em"] = new TagInfo("em", FormattingFlags.Inline, ElementType.Inline); tagTable["embed"] = new TagInfo("embed", FormattingFlags.Inline, WhiteSpaceType.Significant, WhiteSpaceType.CarryThrough, ElementType.Inline); tagTable["fieldset"] = new TagInfo("fieldset", FormattingFlags.None, WhiteSpaceType.Significant, WhiteSpaceType.NotSignificant, ElementType.Block); tagTable["font"] = new TagInfo("font", FormattingFlags.Inline, ElementType.Inline); tagTable["form"] = new TagInfo("form", FormattingFlags.None, WhiteSpaceType.NotSignificant, WhiteSpaceType.NotSignificant, ElementType.Block); tagTable["frame"] = new TagInfo("frame", FormattingFlags.NoEndTag); tagTable["frameset"] = new TagInfo("frameset", FormattingFlags.None); tagTable["head"] = new TagInfo("head", FormattingFlags.None, WhiteSpaceType.NotSignificant, WhiteSpaceType.NotSignificant); tagTable["h1"] = new TagInfo("h1", FormattingFlags.None, WhiteSpaceType.Significant, WhiteSpaceType.NotSignificant, ElementType.Block); tagTable["h2"] = new TagInfo("h2", FormattingFlags.None, WhiteSpaceType.Significant, WhiteSpaceType.NotSignificant, ElementType.Block); tagTable["h3"] = new TagInfo("h3", FormattingFlags.None, WhiteSpaceType.Significant, WhiteSpaceType.NotSignificant, ElementType.Block); tagTable["h4"] = new TagInfo("h4", FormattingFlags.None, WhiteSpaceType.Significant, WhiteSpaceType.NotSignificant, ElementType.Block); tagTable["h5"] = new TagInfo("h5", FormattingFlags.None, WhiteSpaceType.Significant, WhiteSpaceType.NotSignificant, ElementType.Block); tagTable["h6"] = new TagInfo("h6", FormattingFlags.None, WhiteSpaceType.Significant, WhiteSpaceType.NotSignificant, ElementType.Block); // REVIEW: <hr> was changed to be an Block element b/c IE appears to allow it. tagTable["hr"] = new TagInfo("hr", FormattingFlags.NoEndTag, WhiteSpaceType.NotSignificant, WhiteSpaceType.NotSignificant, ElementType.Block); tagTable["html"] = new TagInfo("html", FormattingFlags.NoIndent, WhiteSpaceType.NotSignificant, WhiteSpaceType.NotSignificant); tagTable["i"] = new TagInfo("i", FormattingFlags.Inline, ElementType.Inline); tagTable["iframe"] = new TagInfo("iframe", FormattingFlags.None, WhiteSpaceType.CarryThrough, WhiteSpaceType.NotSignificant, ElementType.Inline); tagTable["img"] = new TagInfo("img", FormattingFlags.Inline | FormattingFlags.NoEndTag, WhiteSpaceType.Significant, WhiteSpaceType.Significant, ElementType.Inline); tagTable["input"] = new TagInfo("input", FormattingFlags.NoEndTag, WhiteSpaceType.Significant, WhiteSpaceType.Significant, ElementType.Inline); tagTable["ins"] = new TagInfo("ins", FormattingFlags.None); tagTable["isindex"] = new TagInfo("isindex", FormattingFlags.None, WhiteSpaceType.NotSignificant, WhiteSpaceType.CarryThrough, ElementType.Block); tagTable["kbd"] = new TagInfo("kbd", FormattingFlags.Inline, ElementType.Inline); tagTable["label"] = new TagInfo("label", FormattingFlags.Inline, ElementType.Inline); tagTable["legend"] = new TagInfo("legend", FormattingFlags.None); tagTable["li"] = new LITagInfo(); tagTable["link"] = new TagInfo("link", FormattingFlags.NoEndTag); tagTable["listing"] = new TagInfo("listing", FormattingFlags.None, WhiteSpaceType.CarryThrough, WhiteSpaceType.NotSignificant, ElementType.Block); tagTable["map"] = new TagInfo("map", FormattingFlags.Inline, ElementType.Inline); tagTable["marquee"] = new TagInfo("marquee", FormattingFlags.None, WhiteSpaceType.Significant, WhiteSpaceType.NotSignificant, ElementType.Block); tagTable["menu"] = new TagInfo("menu", FormattingFlags.None, WhiteSpaceType.Significant, WhiteSpaceType.NotSignificant, ElementType.Block); tagTable["meta"] = new TagInfo("meta", FormattingFlags.NoEndTag); tagTable["nobr"] = new TagInfo("nobr", FormattingFlags.Inline | FormattingFlags.NoEndTag, ElementType.Inline); tagTable["noembed"] = new TagInfo("noembed", FormattingFlags.None, ElementType.Block); tagTable["noframes"] = new TagInfo("noframes", FormattingFlags.None, ElementType.Block); tagTable["noscript"] = new TagInfo("noscript", FormattingFlags.None, ElementType.Block); tagTable["object"] = new TagInfo("object", FormattingFlags.None, ElementType.Inline); tagTable["ol"] = new OLTagInfo(); tagTable["option"] = new TagInfo("option", FormattingFlags.None, WhiteSpaceType.Significant, WhiteSpaceType.CarryThrough); tagTable["p"] = new PTagInfo(); tagTable["param"] = new TagInfo("param", FormattingFlags.NoEndTag); tagTable["pre"] = new TagInfo("pre", FormattingFlags.PreserveContent, WhiteSpaceType.CarryThrough, WhiteSpaceType.Significant, ElementType.Block); tagTable["q"] = new TagInfo("q", FormattingFlags.Inline, ElementType.Inline); tagTable["rt"] = new TagInfo("rt", FormattingFlags.None); tagTable["ruby"] = new TagInfo("ruby", FormattingFlags.None, ElementType.Inline); tagTable["s"] = new TagInfo("s", FormattingFlags.Inline, ElementType.Inline); tagTable["samp"] = new TagInfo("samp", FormattingFlags.None, ElementType.Inline); tagTable["script"] = new TagInfo("script", FormattingFlags.PreserveContent, WhiteSpaceType.CarryThrough, WhiteSpaceType.CarryThrough, ElementType.Inline); tagTable["select"] = new TagInfo("select", FormattingFlags.None, WhiteSpaceType.CarryThrough, WhiteSpaceType.Significant, ElementType.Block); tagTable["small"] = new TagInfo("small", FormattingFlags.Inline, ElementType.Inline); tagTable["span"] = new TagInfo("span", FormattingFlags.Inline, ElementType.Inline); tagTable["strike"] = new TagInfo("strike", FormattingFlags.Inline, ElementType.Inline); tagTable["strong"] = new TagInfo("strong", FormattingFlags.Inline, ElementType.Inline); tagTable["style"] = new TagInfo("style", FormattingFlags.PreserveContent, WhiteSpaceType.NotSignificant, WhiteSpaceType.NotSignificant, ElementType.Any); tagTable["sub"] = new TagInfo("sub", FormattingFlags.Inline, ElementType.Inline); tagTable["sup"] = new TagInfo("sup", FormattingFlags.Inline, ElementType.Inline); tagTable["table"] = new TagInfo("table", FormattingFlags.None, WhiteSpaceType.NotSignificant, WhiteSpaceType.NotSignificant, ElementType.Block); tagTable["tbody"] = new TagInfo("tbody", FormattingFlags.None); tagTable["td"] = new TDTagInfo(); tagTable["textarea"] = new TagInfo("textarea", FormattingFlags.Inline, WhiteSpaceType.CarryThrough, WhiteSpaceType.Significant, ElementType.Inline); tagTable["tfoot"] = new TagInfo("tfoot", FormattingFlags.None); tagTable["th"] = new TagInfo("th", FormattingFlags.None); tagTable["thead"] = new TagInfo("thead", FormattingFlags.None); tagTable["title"] = new TagInfo("title", FormattingFlags.Inline); tagTable["tr"] = new TRTagInfo(); tagTable["tt"] = new TagInfo("tt", FormattingFlags.Inline, ElementType.Inline); tagTable["u"] = new TagInfo("u", FormattingFlags.Inline, ElementType.Inline); tagTable["ul"] = new TagInfo("ul", FormattingFlags.None, WhiteSpaceType.NotSignificant, WhiteSpaceType.NotSignificant, ElementType.Block); tagTable["xml"] = new TagInfo("xml", FormattingFlags.Xml, WhiteSpaceType.Significant, WhiteSpaceType.NotSignificant, ElementType.Block); tagTable["xmp"] = new TagInfo("xmp", FormattingFlags.PreserveContent, WhiteSpaceType.CarryThrough, WhiteSpaceType.NotSignificant, ElementType.Block); tagTable["var"] = new TagInfo("var", FormattingFlags.Inline, ElementType.Inline); tagTable["wbr"] = new TagInfo("wbr", FormattingFlags.Inline | FormattingFlags.NoEndTag, ElementType.Inline); } public void Format(string input, TextWriter output, HtmlFormatterOptions options) { // Determine if we are outputting xhtml bool makeXhtml = options.MakeXhtml; // Save the max line length int maxLineLength = options.MaxLineLength; // Make the indent string string indentString = new String(options.IndentChar, options.IndentSize); char[] chars = input.ToCharArray(); Stack<FormatInfo> tagStack = new Stack<FormatInfo>(); Stack<HtmlWriter> writerStack = new Stack<HtmlWriter>(); // The previous begin or end tag that was seen FormatInfo previousTag = null; // The current begin or end tag that was seen FormatInfo currentTag = null; // The text between previousTag and currentTag string text = String.Empty; // True if we've seen whitespace at the end of the last text outputted bool sawWhiteSpace = false; // True if the last tag seen was self-terminated with a '/>' bool sawSelfTerminatingTag = false; // True if we saw a tag that we decided not to render bool ignoredLastTag = false; // Put the initial writer on the stack HtmlWriter writer = new HtmlWriter(output, indentString, maxLineLength); writerStack.Push(writer); Token t = HtmlTokenizer.GetFirstToken(chars); Token lastToken = t; while (t != null) { writer = writerStack.Peek(); switch (t.Type) { case Token.AttrName: if (makeXhtml) { string attrName = String.Empty; if (!previousTag.tagInfo.IsXml) { // Need to lowercase the HTML attribute names for XHTML attrName = t.Text.ToLower(); } else { attrName = t.Text; } writer.Write(attrName); // If we are trying to be compliant XHTML, don't allow attribute minimization Token nextToken = HtmlTokenizer.GetNextToken(t); if (nextToken.Type != Token.EqualsChar) { writer.Write("=\"" + attrName + "\""); } } else { // Convert the case of the attribute if the tag isn't xml if (!previousTag.tagInfo.IsXml) { if (options.AttributeCasing == HtmlFormatterCase.UpperCase) { writer.Write(t.Text.ToUpper()); } else if (options.AttributeCasing == HtmlFormatterCase.LowerCase) { writer.Write(t.Text.ToLower()); } else { writer.Write(t.Text); } } else { writer.Write(t.Text); } } break; case Token.AttrVal: if (makeXhtml && (lastToken.Type != Token.DoubleQuote) && (lastToken.Type != Token.SingleQuote)) { // If the attribute value isn't quoted, double quote it, replacing the inner double quotes writer.Write('\"'); writer.Write(t.Text.Replace("\"", "&quot;")); writer.Write('\"'); } else { writer.Write(t.Text); } break; case Token.CloseBracket: if (makeXhtml) { if (ignoredLastTag) { // Don't render the close bracket if we ignored the last tag ignoredLastTag = false; } else { if (sawSelfTerminatingTag && (!previousTag.tagInfo.IsComment)) { // If we saw a self terminating tag, that doesn't have the forward slash, put it in (except for comments) writer.Write(" />"); } else { // If we are just closing a normal tag, just put in a normal close bracket writer.Write('>'); } } } else { // If there's no XHTML to be made, just put in a normal close bracket writer.Write('>'); } break; case Token.DoubleQuote: writer.Write('\"'); break; case Token.Empty: break; case Token.EqualsChar: writer.Write('='); break; case Token.Error: if (lastToken.Type == Token.OpenBracket) { // Since we aren't outputting open brackets right away, we might have to output one now writer.Write('<'); } writer.Write(t.Text); break; case Token.ForwardSlash: case Token.OpenBracket: // Just push these symbols on the stack for now... output them when we write the tag break; case Token.SelfTerminating: previousTag.isEndTag = true; if (!previousTag.tagInfo.NoEndTag) { // If the tag that is self-terminating is normally not a self-closed tag // then we've placed an entry on the stack for it. Since it's self terminating, we now need // to pop that item off of the tag stack tagStack.Pop(); // If it was a self-closed Xml tag, then we also need to clean up the writerStack if (previousTag.tagInfo.IsXml) { HtmlWriter oldWriter = writerStack.Pop(); writer = writerStack.Peek(); // Since a self-closed xml tag can't have any text content, we can just write out the formatted contents writer.Write(oldWriter.Content); } } if ((lastToken.Type == Token.Whitespace) && (lastToken.Text.Length > 0)) { writer.Write("/>"); } else { writer.Write(" />"); } break; case Token.SingleQuote: writer.Write('\''); break; case Token.XmlDirective: writer.WriteLineIfNotOnNewLine(); writer.Write('<'); writer.Write(t.Text); writer.Write('>'); writer.WriteLineIfNotOnNewLine(); ignoredLastTag = true; break; case Token.TagName: case Token.Comment: case Token.InlineServerScript: string tagName; // Reset the self terminating tag flag sawSelfTerminatingTag = false; // Create or get the proper tagInfo, depending on the type of token TagInfo info; if (t.Type == Token.Comment) { // Handle comment tags tagName = t.Text; info = new TagInfo(t.Text, commentTag); } else if (t.Type == Token.InlineServerScript) { // Handle server-side script tags string script = t.Text.Trim(); script = script.Substring(1); tagName = script; if (script.StartsWith("%@")) { // Directives are block tags info = new TagInfo(script, directiveTag); } else { // Other server side script tags aren't info = new TagInfo(script, otherServerSideScriptTag); } } else { // Otherwise, this is a normal tag, and try to get a TagInfo for it tagName = t.Text; if (!tagTable.TryGetValue(tagName, out info) || info == null) { // if we couldn't find one, create a copy of the unknownTag with a new tagname if (tagName.IndexOf(':') > -1) { // If it is a prefixed tag, it's probably unknown XML info = new TagInfo(tagName, unknownXmlTag); } else if (writer is XmlWriter) { info = new TagInfo(tagName, nestedXmlTag); } else { // If it is a not prefixed, it's probably an unknown HTML tag info = new TagInfo(tagName, unknownHtmlTag); } } else { // If it's not an unknown tag, converting to the desired case (and leave as is for PreserveCase) if ((options.ElementCasing == HtmlFormatterCase.LowerCase) || makeXhtml) { tagName = info.TagName; } else if (options.ElementCasing == HtmlFormatterCase.UpperCase) { tagName = info.TagName.ToUpper(); } } } if (previousTag == null) { // Special case for the first tag seen previousTag = new FormatInfo(info, false); // Since this is the first tag, set it's indent to 0 previousTag.indent = 0; // Push it on the stack tagStack.Push(previousTag); // And output the preceeding text writer.Write(text); if (info.IsXml) { // When we encounter an xml block, create a new writer to contain the inner content of the xml HtmlWriter newWriter = new XmlWriter(writer.Indent, info.TagName, indentString, maxLineLength); writerStack.Push(newWriter); writer = newWriter; } if (lastToken.Type == Token.ForwardSlash) { // If this is an end tag, output the proper prefix writer.Write("</"); } else { writer.Write('<'); } // Write the name writer.Write(tagName); // Indicate that we've written out the last text block text = String.Empty; } else { // Put the new tag in the next spot currentTag = new FormatInfo(info, (lastToken.Type == Token.ForwardSlash)); WhiteSpaceType whiteSpaceType; if (previousTag.isEndTag) { // If the previous tag is an end tag, we need to check the following whitespace whiteSpaceType = previousTag.tagInfo.FollowingWhiteSpaceType; } else { // otherwise check the initial inner whitespace whiteSpaceType = previousTag.tagInfo.InnerWhiteSpaceType; } // Flag that indicates if the previous tag (before the text) is an inline tag bool inline = previousTag.tagInfo.IsInline; bool emptyXml = false; bool firstOrLastUnknownXmlText = false; if (writer is XmlWriter) { // if we're in an xml block XmlWriter xmlWriter = (XmlWriter)writer; if (xmlWriter.IsUnknownXml) { // Special case for unknown XML tags // Determine if this is the first or last xml text in an unknown xml tag, so we know to preserve the text content here firstOrLastUnknownXmlText = (((previousTag.isBeginTag) && (previousTag.tagInfo.TagName.ToLower() == xmlWriter.TagName.ToLower())) || ((currentTag.isEndTag) && (currentTag.tagInfo.TagName.ToLower() == xmlWriter.TagName.ToLower()))) && (!FormattedTextWriter.IsWhiteSpace(text)); } if (previousTag.isBeginTag) { if (FormattedTextWriter.IsWhiteSpace(text)) { if ((xmlWriter.IsUnknownXml) && (currentTag.isEndTag) && (previousTag.tagInfo.TagName.ToLower() == currentTag.tagInfo.TagName.ToLower())) { // Special case for unknown XML tags: // If the previous tag is an open tag and the next tag is the corresponding close tag and the text is only whitespace, also // treat the tag as inline, so the begin and end tag appear on the same line inline = true; emptyXml = true; // Empty the text since we want the open and close tag to be touching text = ""; } } else { if (!xmlWriter.IsUnknownXml) { // If there is non-whitespace text and we're in a normal Xml block, then remember that there was text xmlWriter.ContainsText = true; } } } } // Flag that indicates if we want to preserve whitespace in the front of the text bool frontWhitespace = true; if ((previousTag.isBeginTag) && (previousTag.tagInfo.PreserveContent)) { // If the previous tag is a begin tag and we're preserving the content as-is, just write out the text writer.Write(text); } else { if (whiteSpaceType == WhiteSpaceType.NotSignificant) { // If the whitespace is not significant in this location if (!inline && !firstOrLastUnknownXmlText) { // If the previous tag is not an inline tag, write out a new line writer.WriteLineIfNotOnNewLine(); // Since we've written out a newline, we no longer need to preserve front whitespace frontWhitespace = false; } } else if (whiteSpaceType == WhiteSpaceType.Significant) { // If the whitespace in this location is significant if (FormattedTextWriter.HasFrontWhiteSpace(text)) { // If there is whitespace in the front, that means we can insert more whitespace without // changing rendering behavior if (!inline && !firstOrLastUnknownXmlText) { // Only insert a new line if the tag isn't inline writer.WriteLineIfNotOnNewLine(); frontWhitespace = false; } } } else if (whiteSpaceType == WhiteSpaceType.CarryThrough) { // If the whitespace in this location is carry through (meaning whitespace at the end of the previous // text block eats up any whitespace in this location if ((sawWhiteSpace) || (FormattedTextWriter.HasFrontWhiteSpace(text))) { // If the last text block ended in whitspace or if there is already whitespace in this location // we can add a new line if (!inline && !firstOrLastUnknownXmlText) { // Only add it if the previous tag isn't inline writer.WriteLineIfNotOnNewLine(); frontWhitespace = false; } } } if (previousTag.isBeginTag) { // If the previous tag is a begin tag if (!previousTag.tagInfo.NoIndent && !inline) { // Indent if desired writer.Indent++; } } // Special case for unknown XML tags: if (firstOrLastUnknownXmlText) { writer.Write(text); } else { writer.WriteLiteral(text, frontWhitespace); } } if (currentTag.isEndTag) { // If the currentTag is an end tag if (!currentTag.tagInfo.NoEndTag) { // Figure out where the corresponding begin tag is List<FormatInfo> popped = new List<FormatInfo>(); FormatInfo formatInfo = null; bool foundOpenTag = false; bool allowPartial = false; if ((currentTag.tagInfo.Flags & FormattingFlags.AllowPartialTags) != 0) { // Once we've exited a tag that allows partial tags, clear the flag allowPartial = true; } // Start popping off the tag stack if there are tags on the stack if (tagStack.Count > 0) { // Keep popping until we find the right tag, remember what we've popped off formatInfo = (FormatInfo)tagStack.Pop(); popped.Add(formatInfo); while ((tagStack.Count > 0) && (formatInfo.tagInfo.TagName.ToLower() != currentTag.tagInfo.TagName.ToLower())) { if ((formatInfo.tagInfo.Flags & FormattingFlags.AllowPartialTags) != 0) { // Special case for tags that allow partial tags inside of them. allowPartial = true; break; } formatInfo = (FormatInfo)tagStack.Pop(); popped.Add(formatInfo); } if (formatInfo.tagInfo.TagName.ToLower() != currentTag.tagInfo.TagName.ToLower()) { // If we didn't find the corresponding open tag, push everything back on for (int i = popped.Count - 1; i >= 0; i--) { tagStack.Push(popped[i]); } } else { foundOpenTag = true; for (int i = 0; i < popped.Count - 1; i++) { FormatInfo fInfo = (FormatInfo)popped[i]; if (fInfo.tagInfo.IsXml) { // If we have an xml tag that was unclosed, we need to clean up the xml stack if (writerStack.Count > 1) { HtmlWriter oldWriter = writerStack.Pop(); writer = writerStack.Peek(); // Write out the contents of the old writer writer.Write(oldWriter.Content); } } if (!fInfo.tagInfo.NoEndTag) { writer.WriteLineIfNotOnNewLine(); writer.Indent = fInfo.indent; if ((makeXhtml) && (!allowPartial)) { // If we're trying to be XHTML compliant, close unclosed child tags // Don't close if we are under a tag that allows partial tags writer.Write("</" + fInfo.tagInfo.TagName + ">"); } } } // Set the indent to the indent of the corresponding open tag writer.Indent = formatInfo.indent; } } if (foundOpenTag || allowPartial) { // Only write out the close tag if there was a corresponding open tag or we are under // a tag that allows partial tags if ((!emptyXml) && (!firstOrLastUnknownXmlText) && (!currentTag.tagInfo.IsInline) && (!currentTag.tagInfo.PreserveContent) && (FormattedTextWriter.IsWhiteSpace(text) || FormattedTextWriter.HasBackWhiteSpace(text) || (currentTag.tagInfo.FollowingWhiteSpaceType == WhiteSpaceType.NotSignificant) ) && (!(currentTag.tagInfo is TDTagInfo) || FormattedTextWriter.HasBackWhiteSpace(text) ) ) { // Insert a newline before the next tag, if allowed writer.WriteLineIfNotOnNewLine(); } // Write out the end tag prefix writer.Write("</"); // Finally, write out the tag name writer.Write(tagName); } else { ignoredLastTag = true; } if (currentTag.tagInfo.IsXml) { // If we have an xml tag that was unclosed, we need to clean up the xml stack if (writerStack.Count > 1) { HtmlWriter oldWriter = writerStack.Pop(); writer = writerStack.Peek(); // Write out the contents of the old writer writer.Write(oldWriter.Content); } } } else { ignoredLastTag = true; } } else { // If the currentTag is a begin tag bool done = false; // Close implicitClosure tags while (!done && (tagStack.Count > 0)) { // Peek at the top of the stack to see the last unclosed tag FormatInfo fInfo = (FormatInfo)tagStack.Peek(); // If the currentTag can't be a child of that tag, then we need to close that tag done = fInfo.tagInfo.CanContainTag(currentTag.tagInfo); if (!done) { // Pop it off and write a close tag for it // REVIEW: Will XML tags always be able to contained in any tag? If not we should be cleaning up the writerStack as well... tagStack.Pop(); writer.Indent = fInfo.indent; // If we're trying to be XHTML compliant, write in the end tags if (makeXhtml) { if (!fInfo.tagInfo.IsInline) { // Only insert a newline if we are allowed to writer.WriteLineIfNotOnNewLine(); } writer.Write("</" + fInfo.tagInfo.TagName + ">"); } } } // Remember the indent so we can properly indent the corresponding close tag for this open tag currentTag.indent = writer.Indent; if ((!firstOrLastUnknownXmlText) && (!currentTag.tagInfo.IsInline) && (!currentTag.tagInfo.PreserveContent) && ((FormattedTextWriter.IsWhiteSpace(text) || FormattedTextWriter.HasBackWhiteSpace(text)) || ((text.Length == 0) && (((previousTag.isBeginTag) && (previousTag.tagInfo.InnerWhiteSpaceType == WhiteSpaceType.NotSignificant)) || ((previousTag.isEndTag) && (previousTag.tagInfo.FollowingWhiteSpaceType == WhiteSpaceType.NotSignificant)) ) ) ) ) { // Insert a newline before the currentTag if we are allowed to writer.WriteLineIfNotOnNewLine(); } if (!currentTag.tagInfo.NoEndTag) { // Only push tags with close tags onto the stack tagStack.Push(currentTag); } else { // If this tag doesn't have a close tag, remember that it is self terminating sawSelfTerminatingTag = true; } if (currentTag.tagInfo.IsXml) { // When we encounter an xml block, create a new writer to contain the inner content of the xml HtmlWriter newWriter = new XmlWriter(writer.Indent, currentTag.tagInfo.TagName, indentString, maxLineLength); writerStack.Push(newWriter); writer = newWriter; } writer.Write('<'); // Finally, write out the tag name writer.Write(tagName); } // Remember if the text ended in whitespace sawWhiteSpace = FormattedTextWriter.HasBackWhiteSpace(text); // Clear out the text, since we have already outputted it text = String.Empty; previousTag = currentTag; } break; case Token.ServerScriptBlock: case Token.ClientScriptBlock: case Token.Style: case Token.TextToken: // Remember all these types of tokens as text so we can output them between the tags if (makeXhtml) { // UNDONE: Need to implement this in the tokenizer, etc... text += t.Text.Replace("&nbsp;", "&#160;"); } else { text += t.Text; } break; case Token.Whitespace: if (t.Text.Length > 0) { writer.Write(' '); } break; default: Debug.Fail("Invalid token type!"); break; } // Remember what the last token was lastToken = t; // Get the next token t = HtmlTokenizer.GetNextToken(t); } if (text.Length > 0) { // Write out the last text if there is any writer.Write(text); } while (writerStack.Count > 1) { // If we haven't cleared out the writer stack, do it HtmlWriter oldWriter = writerStack.Pop(); writer = writerStack.Peek(); writer.Write(oldWriter.Content); } // Flush the writer original writer.Flush(); } private sealed class FormatInfo { public readonly TagInfo tagInfo; public bool isEndTag; public int indent; public FormatInfo(TagInfo info, bool isEnd) { tagInfo = info; isEndTag = isEnd; } public bool isBeginTag { get { return !isEndTag; } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using NHibernate; using NHibernate.Criterion; using NHibernate.Impl; using NHibernate.Linq; using Orchard.ContentManagement.Records; using Orchard.Data; using NHibernate.Transform; using NHibernate.SqlCommand; using Orchard.Utility.Extensions; using Orchard.Caching; namespace Orchard.ContentManagement { public class DefaultContentQuery : IContentQuery { private readonly ITransactionManager _transactionManager; private ISession _session; private ICriteria _itemVersionCriteria; private VersionOptions _versionOptions; private ICacheManager _cacheManager; private ISignals _signals; private IRepository<ContentTypeRecord> _contentTypeRepository; public DefaultContentQuery( IContentManager contentManager, ITransactionManager transactionManager, ICacheManager cacheManager, ISignals signals, IRepository<ContentTypeRecord> contentTypeRepository) { _transactionManager = transactionManager; ContentManager = contentManager; _cacheManager = cacheManager; _signals = signals; _contentTypeRepository = contentTypeRepository; } public IContentManager ContentManager { get; private set; } ISession BindSession() { if (_session == null) _session = _transactionManager.GetSession(); return _session; } ICriteria BindCriteriaByPath(ICriteria criteria, string path) { return criteria.GetCriteriaByPath(path) ?? criteria.CreateCriteria(path); } //ICriteria BindTypeCriteria() { // // ([ContentItemVersionRecord] >join> [ContentItemRecord]) >join> [ContentType] // return BindCriteriaByPath(BindItemCriteria(), "ContentType"); //} ICriteria BindItemCriteria() { // [ContentItemVersionRecord] >join> [ContentItemRecord] return BindCriteriaByPath(BindItemVersionCriteria(), "ContentItemRecord"); } ICriteria BindItemVersionCriteria() { if (_itemVersionCriteria == null) { _itemVersionCriteria = BindSession().CreateCriteria<ContentItemVersionRecord>(); _itemVersionCriteria.SetCacheable(true); } return _itemVersionCriteria; } ICriteria BindPartCriteria<TRecord>() where TRecord : ContentPartRecord { if (typeof(TRecord).IsSubclassOf(typeof(ContentPartVersionRecord))) { return BindCriteriaByPath(BindItemVersionCriteria(), typeof(TRecord).Name); } return BindCriteriaByPath(BindItemCriteria(), typeof(TRecord).Name); } private int GetContentTypeRecordId(string contentType) { return _cacheManager.Get(contentType + "_Record", ctx => { ctx.Monitor(_signals.When(contentType + "_Record")); var contentTypeRecord = _contentTypeRepository.Get(x => x.Name == contentType); if (contentTypeRecord == null) { //TEMP: this is not safe... ContentItem types could be created concurrently? contentTypeRecord = new ContentTypeRecord { Name = contentType }; _contentTypeRepository.Create(contentTypeRecord); } return contentTypeRecord.Id; }); } private void ForType(params string[] contentTypeNames) { if (contentTypeNames != null && contentTypeNames.Length != 0) { var contentTypeIds = contentTypeNames.Select(GetContentTypeRecordId).ToArray(); // don't use the IN operator if not needed for performance reasons if (contentTypeNames.Length == 1) { BindItemCriteria().Add(Restrictions.Eq("ContentType.Id", contentTypeIds[0])); } else { BindItemCriteria().Add(Restrictions.InG("ContentType.Id", contentTypeIds)); } } } public void ForVersion(VersionOptions options) { _versionOptions = options; } private void ForContentItems(IEnumerable<int> ids) { if (ids == null) throw new ArgumentNullException("ids"); // Converting to array as otherwise an exception "Expression argument must be of type ICollection." is thrown. Where<ContentItemRecord>(record => ids.ToArray().Contains(record.Id), BindCriteriaByPath(BindItemCriteria(), typeof(ContentItemRecord).Name)); } private void Where<TRecord>() where TRecord : ContentPartRecord { // this simply demands an inner join BindPartCriteria<TRecord>(); } private void Where<TRecord>(Expression<Func<TRecord, bool>> predicate) where TRecord : ContentPartRecord { Where<TRecord>(predicate, BindPartCriteria<TRecord>()); } private void Where<TRecord>(Expression<Func<TRecord, bool>> predicate, ICriteria bindCriteria) { // build a linq to nhibernate expression var options = new QueryOptions(); var queryProvider = new NHibernateQueryProvider(BindSession(), options); var queryable = new Query<TRecord>(queryProvider, options).Where(predicate); // translate it into the nhibernate ICriteria implementation var criteria = (CriteriaImpl)queryProvider.TranslateExpression(queryable.Expression); // attach the criterion from the predicate to this query's criteria for the record var recordCriteria = bindCriteria; foreach (var expressionEntry in criteria.IterateExpressionEntries()) { recordCriteria.Add(expressionEntry.Criterion); } } private void OrderBy<TRecord, TKey>(Expression<Func<TRecord, TKey>> keySelector) where TRecord : ContentPartRecord { // build a linq to nhibernate expression var options = new QueryOptions(); var queryProvider = new NHibernateQueryProvider(BindSession(), options); var queryable = new Query<TRecord>(queryProvider, options).OrderBy(keySelector); // translate it into the nhibernate ordering var criteria = (CriteriaImpl)queryProvider.TranslateExpression(queryable.Expression); // attaching orderings to the query's criteria var recordCriteria = BindPartCriteria<TRecord>(); foreach (var ordering in criteria.IterateOrderings()) { recordCriteria.AddOrder(ordering.Order); } } private void OrderByDescending<TRecord, TKey>(Expression<Func<TRecord, TKey>> keySelector) where TRecord : ContentPartRecord { // build a linq to nhibernate expression var options = new QueryOptions(); var queryProvider = new NHibernateQueryProvider(BindSession(), options); var queryable = new Query<TRecord>(queryProvider, options).OrderByDescending(keySelector); // translate it into the nhibernate ICriteria implementation var criteria = (CriteriaImpl)queryProvider.TranslateExpression(queryable.Expression); // attaching orderings to the query's criteria var recordCriteria = BindPartCriteria<TRecord>(); foreach (var ordering in criteria.IterateOrderings()) { recordCriteria.AddOrder(ordering.Order); } } private IEnumerable<ContentItem> Slice(int skip, int count) { var criteria = BindItemVersionCriteria(); criteria.ApplyVersionOptionsRestrictions(_versionOptions); criteria.SetFetchMode("ContentItemRecord", FetchMode.Eager); criteria.SetFetchMode("ContentItemRecord.ContentType", FetchMode.Eager); // TODO: put 'removed false' filter in place if (skip != 0) { criteria = criteria.SetFirstResult(skip); } if (count != 0) { criteria = criteria.SetMaxResults(count); } return criteria .List<ContentItemVersionRecord>() .Select(x => ContentManager.Get(x.ContentItemRecord.Id, _versionOptions != null && _versionOptions.IsDraftRequired ? _versionOptions : VersionOptions.VersionRecord(x.Id))) .ToReadOnlyCollection(); } int Count() { var criteria = (ICriteria)BindItemVersionCriteria().Clone(); criteria.ClearOrders(); criteria.ApplyVersionOptionsRestrictions(_versionOptions); return criteria.SetProjection(Projections.RowCount()).UniqueResult<Int32>(); } void WithQueryHints(QueryHints hints) { if (hints == QueryHints.Empty) { return; } var contentItemVersionCriteria = BindItemVersionCriteria(); var contentItemCriteria = BindItemCriteria(); var contentItemMetadata = _session.SessionFactory.GetClassMetadata(typeof(ContentItemRecord)); var contentItemVersionMetadata = _session.SessionFactory.GetClassMetadata(typeof(ContentItemVersionRecord)); // break apart and group hints by their first segment var hintDictionary = hints.Records .Select(hint => new { Hint = hint, Segments = hint.Split('.') }) .GroupBy(item => item.Segments.FirstOrDefault()) .ToDictionary(grouping => grouping.Key, StringComparer.InvariantCultureIgnoreCase); // locate hints that match properties in the ContentItemVersionRecord foreach (var hit in contentItemVersionMetadata.PropertyNames.Where(hintDictionary.ContainsKey).SelectMany(key => hintDictionary[key])) { contentItemVersionCriteria.SetFetchMode(hit.Hint, FetchMode.Eager); hit.Segments.Take(hit.Segments.Count() - 1).Aggregate(contentItemVersionCriteria, ExtendCriteria); } // locate hints that match properties in the ContentItemRecord foreach (var hit in contentItemMetadata.PropertyNames.Where(hintDictionary.ContainsKey).SelectMany(key => hintDictionary[key])) { contentItemVersionCriteria.SetFetchMode("ContentItemRecord." + hit.Hint, FetchMode.Eager); hit.Segments.Take(hit.Segments.Count() - 1).Aggregate(contentItemCriteria, ExtendCriteria); } if (hintDictionary.SelectMany(x => x.Value).Any(x => x.Segments.Count() > 1)) contentItemVersionCriteria.SetResultTransformer(new DistinctRootEntityResultTransformer()); } void WithQueryHintsFor(string contentType) { var contentItem = ContentManager.New(contentType); var contentPartRecords = new List<string>(); foreach (var part in contentItem.Parts) { var partType = part.GetType().BaseType; if (partType.IsGenericType && partType.GetGenericTypeDefinition() == typeof(ContentPart<>)) { var recordType = partType.GetGenericArguments().Single(); contentPartRecords.Add(recordType.Name); } } WithQueryHints(new QueryHints().ExpandRecords(contentPartRecords)); } private static ICriteria ExtendCriteria(ICriteria criteria, string segment) { return criteria.GetCriteriaByPath(segment) ?? criteria.CreateCriteria(segment, JoinType.LeftOuterJoin); } IContentQuery<TPart> IContentQuery.ForPart<TPart>() { return new ContentQuery<TPart>(this); } class ContentQuery<T> : IContentQuery<T> where T : IContent { protected readonly DefaultContentQuery _query; public ContentQuery(DefaultContentQuery query) { _query = query; } public IContentManager ContentManager { get { return _query.ContentManager; } } IContentQuery<TPart> IContentQuery.ForPart<TPart>() { return new ContentQuery<TPart>(_query); } IContentQuery<T> IContentQuery<T>.ForType(params string[] contentTypes) { _query.ForType(contentTypes); return this; } IContentQuery<T> IContentQuery<T>.ForVersion(VersionOptions options) { _query.ForVersion(options); return this; } IContentQuery<T> IContentQuery<T>.ForContentItems(IEnumerable<int> ids) { _query.ForContentItems(ids); return this; } IEnumerable<T> IContentQuery<T>.List() { return _query.Slice(0, 0).AsPart<T>(); } IEnumerable<T> IContentQuery<T>.Slice(int skip, int count) { return _query.Slice(skip, count).AsPart<T>(); } int IContentQuery<T>.Count() { return _query.Count(); } IContentQuery<T, TRecord> IContentQuery<T>.Join<TRecord>() { _query.Where<TRecord>(); return new ContentQuery<T, TRecord>(_query); } IContentQuery<T, TRecord> IContentQuery<T>.Where<TRecord>(Expression<Func<TRecord, bool>> predicate) { _query.Where(predicate); return new ContentQuery<T, TRecord>(_query); } IContentQuery<T, TRecord> IContentQuery<T>.OrderBy<TRecord>(Expression<Func<TRecord, object>> keySelector) { _query.OrderBy(keySelector); return new ContentQuery<T, TRecord>(_query); } IContentQuery<T, TRecord> IContentQuery<T>.OrderByDescending<TRecord>(Expression<Func<TRecord, object>> keySelector) { _query.OrderByDescending(keySelector); return new ContentQuery<T, TRecord>(_query); } IContentQuery<T> IContentQuery<T>.WithQueryHints(QueryHints hints) { _query.WithQueryHints(hints); return this; } IContentQuery<T> IContentQuery<T>.WithQueryHintsFor(string contentType) { _query.WithQueryHintsFor(contentType); return this; } } class ContentQuery<T, TR> : ContentQuery<T>, IContentQuery<T, TR> where T : IContent where TR : ContentPartRecord { public ContentQuery(DefaultContentQuery query) : base(query) { } IContentQuery<T, TR> IContentQuery<T, TR>.ForVersion(VersionOptions options) { _query.ForVersion(options); return this; } IContentQuery<T, TR> IContentQuery<T, TR>.Where(Expression<Func<TR, bool>> predicate) { _query.Where(predicate); return this; } IContentQuery<T, TR> IContentQuery<T, TR>.OrderBy<TKey>(Expression<Func<TR, TKey>> keySelector) { _query.OrderBy(keySelector); return this; } IContentQuery<T, TR> IContentQuery<T, TR>.OrderByDescending<TKey>(Expression<Func<TR, TKey>> keySelector) { _query.OrderByDescending(keySelector); return this; } IContentQuery<T, TR> IContentQuery<T, TR>.WithQueryHints(QueryHints hints) { _query.WithQueryHints(hints); return this; } IContentQuery<T, TR> IContentQuery<T, TR>.WithQueryHintsFor(string contentType) { _query.WithQueryHintsFor(contentType); return this; } } } internal static class CriteriaExtensions { internal static void ApplyVersionOptionsRestrictions(this ICriteria criteria, VersionOptions versionOptions) { if (versionOptions == null) { criteria.Add(Restrictions.Eq("Published", true)); } else if (versionOptions.IsPublished) { criteria.Add(Restrictions.Eq("Published", true)); } else if (versionOptions.IsLatest) { criteria.Add(Restrictions.Eq("Latest", true)); } else if (versionOptions.IsDraft && !versionOptions.IsDraftRequired) { criteria.Add(Restrictions.And( Restrictions.Eq("Latest", true), Restrictions.Eq("Published", false))); } else if (versionOptions.IsDraft || versionOptions.IsDraftRequired) { criteria.Add(Restrictions.Eq("Latest", true)); } else if (versionOptions.IsAllVersions) { // no-op... all versions will be returned by default } else { throw new ApplicationException("Invalid VersionOptions for content query"); } } } }
namespace eidss.main.Login { public partial class ChangePasswordForm { //Inherits System.Windows.Forms.Form //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool disposing) { try { if (disposing && components != null) { components.Dispose(); } } finally { base.Dispose(disposing); } } //Required by the Windows Form Designer private System.ComponentModel.Container components = null; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. //<System.Diagnostics.DebuggerStepThrough()> _ private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ChangePasswordForm)); this.lbPassword2 = new System.Windows.Forms.Label(); this.txtNewPassword2 = new DevExpress.XtraEditors.TextEdit(); this.lbPassword1 = new System.Windows.Forms.Label(); this.txtNewPassword1 = new DevExpress.XtraEditors.TextEdit(); this.lbOrganization = new System.Windows.Forms.Label(); this.lbUserName = new System.Windows.Forms.Label(); this.txtOrganization = new DevExpress.XtraEditors.TextEdit(); this.txtUserName = new DevExpress.XtraEditors.TextEdit(); this.lbPassword = new System.Windows.Forms.Label(); this.txtPassword = new DevExpress.XtraEditors.TextEdit(); this.btnOk = new DevExpress.XtraEditors.SimpleButton(); this.btnCancel = new DevExpress.XtraEditors.SimpleButton(); this.lbCurrPassLng = new DevExpress.XtraEditors.LabelControl(); this.lbLoginLng = new DevExpress.XtraEditors.LabelControl(); this.lbConfNewPassLng = new DevExpress.XtraEditors.LabelControl(); this.lbNewPassLng = new DevExpress.XtraEditors.LabelControl(); ((System.ComponentModel.ISupportInitialize)(this.txtNewPassword2.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.txtNewPassword1.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.txtOrganization.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.txtUserName.Properties)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.txtPassword.Properties)).BeginInit(); this.SuspendLayout(); // // lbPassword2 // resources.ApplyResources(this.lbPassword2, "lbPassword2"); this.lbPassword2.Name = "lbPassword2"; // // txtNewPassword2 // resources.ApplyResources(this.txtNewPassword2, "txtNewPassword2"); this.txtNewPassword2.Name = "txtNewPassword2"; this.txtNewPassword2.Properties.PasswordChar = '*'; this.txtNewPassword2.Tag = "{M}"; this.txtNewPassword2.Enter += new System.EventHandler(this.Control_Enter); this.txtNewPassword2.Leave += new System.EventHandler(this.Control_Leave); // // lbPassword1 // resources.ApplyResources(this.lbPassword1, "lbPassword1"); this.lbPassword1.Name = "lbPassword1"; // // txtNewPassword1 // resources.ApplyResources(this.txtNewPassword1, "txtNewPassword1"); this.txtNewPassword1.Name = "txtNewPassword1"; this.txtNewPassword1.Properties.PasswordChar = '*'; this.txtNewPassword1.Tag = "{M}"; this.txtNewPassword1.Enter += new System.EventHandler(this.Control_Enter); this.txtNewPassword1.Leave += new System.EventHandler(this.Control_Leave); // // lbOrganization // resources.ApplyResources(this.lbOrganization, "lbOrganization"); this.lbOrganization.Name = "lbOrganization"; // // lbUserName // resources.ApplyResources(this.lbUserName, "lbUserName"); this.lbUserName.Name = "lbUserName"; // // txtOrganization // resources.ApplyResources(this.txtOrganization, "txtOrganization"); this.txtOrganization.Name = "txtOrganization"; this.txtOrganization.Tag = "{R}"; // // txtUserName // resources.ApplyResources(this.txtUserName, "txtUserName"); this.txtUserName.Name = "txtUserName"; this.txtUserName.Tag = "{M}"; this.txtUserName.Enter += new System.EventHandler(this.Control_Enter); this.txtUserName.Leave += new System.EventHandler(this.Control_Leave); // // lbPassword // resources.ApplyResources(this.lbPassword, "lbPassword"); this.lbPassword.Name = "lbPassword"; // // txtPassword // resources.ApplyResources(this.txtPassword, "txtPassword"); this.txtPassword.Name = "txtPassword"; this.txtPassword.Properties.PasswordChar = '*'; this.txtPassword.Tag = "{M}"; this.txtPassword.Enter += new System.EventHandler(this.Control_Enter); this.txtPassword.Leave += new System.EventHandler(this.Control_Leave); // // btnOk // resources.ApplyResources(this.btnOk, "btnOk"); this.btnOk.Name = "btnOk"; this.btnOk.Click += new System.EventHandler(this.btnOk_Click); // // btnCancel // this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; resources.ApplyResources(this.btnCancel, "btnCancel"); this.btnCancel.Name = "btnCancel"; // // lbCurrPassLng // this.lbCurrPassLng.Appearance.BackColor = ((System.Drawing.Color)(resources.GetObject("lbCurrPassLng.Appearance.BackColor"))); this.lbCurrPassLng.Appearance.ForeColor = ((System.Drawing.Color)(resources.GetObject("lbCurrPassLng.Appearance.ForeColor"))); this.lbCurrPassLng.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; resources.ApplyResources(this.lbCurrPassLng, "lbCurrPassLng"); this.lbCurrPassLng.Name = "lbCurrPassLng"; // // lbLoginLng // this.lbLoginLng.Appearance.BackColor = ((System.Drawing.Color)(resources.GetObject("lbLoginLng.Appearance.BackColor"))); this.lbLoginLng.Appearance.ForeColor = ((System.Drawing.Color)(resources.GetObject("lbLoginLng.Appearance.ForeColor"))); this.lbLoginLng.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; resources.ApplyResources(this.lbLoginLng, "lbLoginLng"); this.lbLoginLng.Name = "lbLoginLng"; // // lbConfNewPassLng // this.lbConfNewPassLng.Appearance.BackColor = ((System.Drawing.Color)(resources.GetObject("lbConfNewPassLng.Appearance.BackColor"))); this.lbConfNewPassLng.Appearance.ForeColor = ((System.Drawing.Color)(resources.GetObject("lbConfNewPassLng.Appearance.ForeColor"))); this.lbConfNewPassLng.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; resources.ApplyResources(this.lbConfNewPassLng, "lbConfNewPassLng"); this.lbConfNewPassLng.Name = "lbConfNewPassLng"; // // lbNewPassLng // this.lbNewPassLng.Appearance.BackColor = ((System.Drawing.Color)(resources.GetObject("lbNewPassLng.Appearance.BackColor"))); this.lbNewPassLng.Appearance.ForeColor = ((System.Drawing.Color)(resources.GetObject("lbNewPassLng.Appearance.ForeColor"))); this.lbNewPassLng.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center; resources.ApplyResources(this.lbNewPassLng, "lbNewPassLng"); this.lbNewPassLng.Name = "lbNewPassLng"; // // ChangePasswordForm // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.lbConfNewPassLng); this.Controls.Add(this.lbNewPassLng); this.Controls.Add(this.lbCurrPassLng); this.Controls.Add(this.lbLoginLng); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnOk); this.Controls.Add(this.lbPassword1); this.Controls.Add(this.lbOrganization); this.Controls.Add(this.lbUserName); this.Controls.Add(this.txtOrganization); this.Controls.Add(this.txtUserName); this.Controls.Add(this.txtPassword); this.Controls.Add(this.txtNewPassword1); this.Controls.Add(this.txtNewPassword2); this.Controls.Add(this.lbPassword2); this.Controls.Add(this.lbPassword); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.HelpTopicId = "Changing_Password"; this.MaximizeBox = false; this.Name = "ChangePasswordForm"; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; ((System.ComponentModel.ISupportInitialize)(this.txtNewPassword2.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.txtNewPassword1.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.txtOrganization.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.txtUserName.Properties)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.txtPassword.Properties)).EndInit(); this.ResumeLayout(false); } internal System.Windows.Forms.Label lbPassword2; internal DevExpress.XtraEditors.TextEdit txtNewPassword2; internal System.Windows.Forms.Label lbPassword1; internal DevExpress.XtraEditors.TextEdit txtNewPassword1; internal System.Windows.Forms.Label lbOrganization; internal System.Windows.Forms.Label lbUserName; protected internal DevExpress.XtraEditors.TextEdit txtOrganization; protected internal DevExpress.XtraEditors.TextEdit txtUserName; internal System.Windows.Forms.Label lbPassword; internal DevExpress.XtraEditors.TextEdit txtPassword; internal DevExpress.XtraEditors.SimpleButton btnOk; internal DevExpress.XtraEditors.SimpleButton btnCancel; internal DevExpress.XtraEditors.LabelControl lbCurrPassLng; internal DevExpress.XtraEditors.LabelControl lbLoginLng; internal DevExpress.XtraEditors.LabelControl lbConfNewPassLng; internal DevExpress.XtraEditors.LabelControl lbNewPassLng; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Diagnostics; using System.Collections; using System.Threading.Tasks; namespace System.Net { // LazyAsyncResult - Base class for all IAsyncResult classes that want to take advantage of // lazily-allocated event handles. internal class LazyAsyncResult : IAsyncResult { private const int HighBit = unchecked((int)0x80000000); private const int ForceAsyncCount = 50; // This is to avoid user mistakes when they queue another async op from a callback the completes sync. [ThreadStatic] private static ThreadContext s_threadContext; private static ThreadContext CurrentThreadContext { get { ThreadContext threadContext = s_threadContext; if (threadContext == null) { threadContext = new ThreadContext(); s_threadContext = threadContext; } return threadContext; } } private class ThreadContext { internal int _nestedIOCount; } #if DEBUG internal object _debugAsyncChain = null; // Optionally used to track chains of async calls. private bool _protectState; // Used by ContextAwareResult to prevent some calls. #endif private object _asyncObject; // Caller's async object. private object _asyncState; // Caller's state object. private AsyncCallback _asyncCallback; // Caller's callback method. private object _result; // Final IO result to be returned byt the End*() method. private int _errorCode; // Win32 error code for Win32 IO async calls (that want to throw). private int _intCompleted; // Sign bit indicates synchronous completion if set. // Remaining bits count the number of InvokeCallbak() calls. private bool _endCalled; // True if the user called the End*() method. private bool _userEvent; // True if the event has been (or is about to be) handed to the user private object _event; // Lazy allocated event to be returned in the IAsyncResult for the client to wait on. internal LazyAsyncResult(object myObject, object myState, AsyncCallback myCallBack) { _asyncObject = myObject; _asyncState = myState; _asyncCallback = myCallBack; _result = DBNull.Value; if (GlobalLog.IsEnabled) { GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::.ctor()"); } } // Allows creating a pre-completed result with less interlockeds. Beware! Constructor calls the callback. // If a derived class ever uses this and overloads Cleanup, this may need to change. internal LazyAsyncResult(object myObject, object myState, AsyncCallback myCallBack, object result) { if (result == DBNull.Value) { if (GlobalLog.IsEnabled) { GlobalLog.AssertFormat("LazyAsyncResult#{0}::.ctor()|Result can't be set to DBNull - it's a special internal value.", LoggingHash.HashString(this)); } Debug.Fail("LazyAsyncResult#" + LoggingHash.HashString(this) + "::.ctor()|Result can't be set to DBNull - it's a special internal value."); } _asyncObject = myObject; _asyncState = myState; _asyncCallback = myCallBack; _result = result; _intCompleted = 1; if (_asyncCallback != null) { if (GlobalLog.IsEnabled) { GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::Complete() invoking callback"); } _asyncCallback(this); } else if (GlobalLog.IsEnabled) { GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::Complete() no callback to invoke"); } if (GlobalLog.IsEnabled) { GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::.ctor() (pre-completed)"); } } // Interface method to return the original async object. internal object AsyncObject { get { return _asyncObject; } } // Interface method to return the caller's state object. public object AsyncState { get { return _asyncState; } } protected AsyncCallback AsyncCallback { get { return _asyncCallback; } set { _asyncCallback = value; } } // Interface property to return a WaitHandle that can be waited on for I/O completion. // // This property implements lazy event creation. // // If this is used, the event cannot be disposed because it is under the control of the // application. Internal should use InternalWaitForCompletion instead - never AsyncWaitHandle. public WaitHandle AsyncWaitHandle { get { if (GlobalLog.IsEnabled) { GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::get_AsyncWaitHandle()"); } #if DEBUG // Can't be called when state is protected. if (_protectState) { throw new InvalidOperationException("get_AsyncWaitHandle called in protected state"); } #endif ManualResetEvent asyncEvent; // Indicates that the user has seen the event; it can't be disposed. _userEvent = true; // The user has access to this object. Lock-in CompletedSynchronously. if (_intCompleted == 0) { Interlocked.CompareExchange(ref _intCompleted, HighBit, 0); } // Because InternalWaitForCompletion() tries to dispose this event, it's // possible for _event to become null immediately after being set, but only if // IsCompleted has become true. Therefore it's possible for this property // to give different (set) events to different callers when IsCompleted is true. asyncEvent = (ManualResetEvent)_event; while (asyncEvent == null) { LazilyCreateEvent(out asyncEvent); } if (GlobalLog.IsEnabled) { GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::get_AsyncWaitHandle() _event:" + LoggingHash.HashString(_event)); } return asyncEvent; } } // Returns true if this call created the event. // May return with a null handle. That means it thought it got one, but it was disposed in the mean time. private bool LazilyCreateEvent(out ManualResetEvent waitHandle) { waitHandle = new ManualResetEvent(false); try { if (Interlocked.CompareExchange(ref _event, waitHandle, null) == null) { if (InternalPeekCompleted) { waitHandle.Set(); } return true; } else { waitHandle.Dispose(); waitHandle = (ManualResetEvent)_event; // There's a chance here that _event became null. But the only way is if another thread completed // in InternalWaitForCompletion and disposed it. If we're in InternalWaitForCompletion, we now know // IsCompleted is set, so we can avoid the wait when waitHandle comes back null. AsyncWaitHandle // will try again in this case. return false; } } catch { // This should be very rare, but doing this will reduce the chance of deadlock. _event = null; if (waitHandle != null) { waitHandle.Dispose(); } throw; } } // This allows ContextAwareResult to not let anyone trigger the CompletedSynchronously tripwire while the context is being captured. [Conditional("DEBUG")] protected void DebugProtectState(bool protect) { #if DEBUG _protectState = protect; #endif } // Interface property, returning synchronous completion status. public bool CompletedSynchronously { get { if (GlobalLog.IsEnabled) { GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::get_CompletedSynchronously()"); } #if DEBUG // Can't be called when state is protected. if (_protectState) { throw new InvalidOperationException("get_CompletedSynchronously called in protected state"); } #endif // If this returns greater than zero, it means it was incremented by InvokeCallback before anyone ever saw it. int result = _intCompleted; if (result == 0) { result = Interlocked.CompareExchange(ref _intCompleted, HighBit, 0); } if (GlobalLog.IsEnabled) { GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::get_CompletedSynchronously() returns: " + ((result > 0) ? "true" : "false")); } return result > 0; } } // Interface property, returning completion status. public bool IsCompleted { get { if (GlobalLog.IsEnabled) { GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::get_IsCompleted()"); } #if DEBUG // Can't be called when state is protected. if (_protectState) { throw new InvalidOperationException("get_IsCompleted called in protected state"); } #endif // Verify low bits to see if it's been incremented. If it hasn't, set the high bit // to show that it's been looked at. int result = _intCompleted; if (result == 0) { result = Interlocked.CompareExchange(ref _intCompleted, HighBit, 0); } return (result & ~HighBit) != 0; } } // Use to see if something's completed without fixing CompletedSynchronously. internal bool InternalPeekCompleted { get { return (_intCompleted & ~HighBit) != 0; } } // Internal property for setting the IO result. internal object Result { get { return _result == DBNull.Value ? null : _result; } set { // Ideally this should never be called, since setting // the result object really makes sense when the IO completes. // // But if the result was set here (as a preemptive error or for some other reason), // then the "result" parameter passed to InvokeCallback() will be ignored. // It's an error to call after the result has been completed or with DBNull. if (value == DBNull.Value) { if (GlobalLog.IsEnabled) { GlobalLog.AssertFormat("LazyAsyncResult#{0}::set_Result()|Result can't be set to DBNull - it's a special internal value.", LoggingHash.HashString(this)); } Debug.Fail("LazyAsyncResult#" + LoggingHash.HashString(this) + "::set_Result()|Result can't be set to DBNull - it's a special internal value."); } if (InternalPeekCompleted) { if (GlobalLog.IsEnabled) { GlobalLog.AssertFormat("LazyAsyncResult#{0}::set_Result()|Called on completed result.", LoggingHash.HashString(this)); } Debug.Fail("LazyAsyncResult#" + LoggingHash.HashString(this) + "::set_Result()|Called on completed result."); } _result = value; } } internal bool EndCalled { get { return _endCalled; } set { _endCalled = value; } } // Internal property for setting the Win32 IO async error code. internal int ErrorCode { get { return _errorCode; } set { _errorCode = value; } } // A method for completing the IO with a result and invoking the user's callback. // Used by derived classes to pass context into an overridden Complete(). Useful // for determining the 'winning' thread in case several may simultaneously call // the equivalent of InvokeCallback(). protected void ProtectedInvokeCallback(object result, IntPtr userToken) { if (GlobalLog.IsEnabled) { GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::ProtectedInvokeCallback() result = " + (result is Exception ? ((Exception)result).Message : result == null ? "<null>" : result.ToString()) + ", userToken:" + userToken.ToString()); } // Critical to disallow DBNull here - it could result in a stuck spinlock in WaitForCompletion. if (result == DBNull.Value) { throw new ArgumentNullException("result"); } #if DEBUG // Always safe to ask for the state now. _protectState = false; #endif if ((_intCompleted & ~HighBit) == 0 && (Interlocked.Increment(ref _intCompleted) & ~HighBit) == 1) { // DBNull.Value is used to guarantee that the first caller wins, // even if the result was set to null. if (_result == DBNull.Value) { _result = result; } ManualResetEvent asyncEvent = (ManualResetEvent)_event; if (asyncEvent != null) { try { asyncEvent.Set(); } catch (ObjectDisposedException) { // Simply ignore this exception - There is apparently a rare race condition // where the event is disposed before the completion method is called. } } Complete(userToken); } } // Completes the IO with a result and invoking the user's callback. internal void InvokeCallback(object result) { ProtectedInvokeCallback(result, IntPtr.Zero); } // Completes the IO without a result and invoking the user's callback. internal void InvokeCallback() { ProtectedInvokeCallback(null, IntPtr.Zero); } // NOTE: THIS METHOD MUST NOT BE CALLED DIRECTLY. // // This method does the callback's job and is guaranteed to be called exactly once. // A derived overriding method must call the base class somewhere or the completion is lost. protected virtual void Complete(IntPtr userToken) { bool offloaded = false; ThreadContext threadContext = CurrentThreadContext; try { ++threadContext._nestedIOCount; if (_asyncCallback != null) { if (GlobalLog.IsEnabled) { GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::Complete() invoking callback"); } if (threadContext._nestedIOCount >= ForceAsyncCount) { if (GlobalLog.IsEnabled) { GlobalLog.Print("LazyAsyncResult::Complete *** OFFLOADED the user callback ***"); } Task.Factory.StartNew( s => WorkerThreadComplete(s), this, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); offloaded = true; } else { _asyncCallback(this); } } else if (GlobalLog.IsEnabled) { GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::Complete() no callback to invoke"); } } finally { --threadContext._nestedIOCount; // Never call this method unless interlocked _intCompleted check has succeeded (like in this case). if (!offloaded) { Cleanup(); } } } // Only called by the above method. private static void WorkerThreadComplete(object state) { Debug.Assert(state is LazyAsyncResult); LazyAsyncResult thisPtr = (LazyAsyncResult)state; try { thisPtr._asyncCallback(thisPtr); } finally { thisPtr.Cleanup(); } } // Custom instance cleanup method. // // Derived types override this method to release unmanaged resources associated with an IO request. protected virtual void Cleanup() { } internal object InternalWaitForCompletion() { return WaitForCompletion(true); } private object WaitForCompletion(bool snap) { ManualResetEvent waitHandle = null; bool createdByMe = false; bool complete = snap ? IsCompleted : InternalPeekCompleted; if (!complete) { // Not done yet, so wait: waitHandle = (ManualResetEvent)_event; if (waitHandle == null) { createdByMe = LazilyCreateEvent(out waitHandle); } } if (waitHandle != null) { try { if (GlobalLog.IsEnabled) { GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::InternalWaitForCompletion() Waiting for completion _event#" + LoggingHash.HashString(waitHandle)); } waitHandle.WaitOne(Timeout.Infinite); } catch (ObjectDisposedException) { // This can occur if this method is called from two different threads. // This possibility is the trade-off for not locking. } finally { // We also want to dispose the event although we can't unless we did wait on it here. if (createdByMe && !_userEvent) { // Does _userEvent need to be volatile (or _event set via Interlocked) in order // to avoid giving a user a disposed event? ManualResetEvent oldEvent = (ManualResetEvent)_event; _event = null; if (!_userEvent) { oldEvent.Dispose(); } } } } // A race condition exists because InvokeCallback sets _intCompleted before _result (so that _result // can benefit from the synchronization of _intCompleted). That means you can get here before _result got // set (although rarely - once every eight hours of stress). Handle that case with a spin-lock. SpinWait sw = new SpinWait(); while (_result == DBNull.Value) { sw.SpinOnce(); } if (GlobalLog.IsEnabled) { GlobalLog.Print("LazyAsyncResult#" + LoggingHash.HashString(this) + "::InternalWaitForCompletion() done: " + (_result is Exception ? ((Exception)_result).Message : _result == null ? "<null>" : _result.ToString())); } return _result; } // A general interface that is called to release unmanaged resources associated with the class. // It completes the result but doesn't do any of the notifications. internal void InternalCleanup() { if ((_intCompleted & ~HighBit) == 0 && (Interlocked.Increment(ref _intCompleted) & ~HighBit) == 1) { // Set no result so that just in case there are waiters, they don't hang in the spin lock. _result = null; Cleanup(); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Reflection; using TestConsoleLib; using TestConsoleLib.ObjectReporting; using VMTest.Utilities; namespace VMTest { internal class TypedVMInfo<T> : VMInfo where T : class, INotifyPropertyChanged { private object _lock = new object(); private readonly Output _output; private readonly Dictionary<string, VMInfo> _notifyingChildren = new Dictionary<string, VMInfo>(); private readonly Dictionary<string, VMInfo> _notifyingCollections = new Dictionary<string, VMInfo>(); private readonly Dictionary<string, VMInfo> _simpleCollections = new Dictionary<string, VMInfo>(); private DataErrorInfoMonitor _errorInfoMonitor; public TypedVMInfo(Output output, T vm, string name, VMMonitor container, VMInfo parent) : base(container, parent) { VM = vm; Name = name; _output = output; vm.PropertyChanged += OnPropertyChanged; _errorInfoMonitor = new DataErrorInfoMonitor(output, this, vm); SignUpForChildNotifications(); } private void SignUpForChildNotifications() { lock (_lock) { foreach (var prop in typeof (T).GetProperties()) { CallAttachChild(prop); CallAttachCollection(prop); } } } private void CallAttachChild(PropertyInfo prop) { if (!typeof (INotifyPropertyChanged).IsAssignableFrom(prop.PropertyType) || prop.GetIndexParameters().Any()) return; var method = GetType().GetMethod("Attach", BindingFlags.NonPublic | BindingFlags.Instance); Debug.Assert(method != null); Debug.Assert(method.IsGenericMethodDefinition); var typedMethod = method.MakeGenericMethod(prop.PropertyType); MethodInvoker.Invoke(typedMethod, this, prop); } private void CallAttachCollection(PropertyInfo prop) { MethodInfo method = null; var isCollection = typeof(ICollection).IsAssignableFrom(prop.PropertyType); var isNotifyingCollection = typeof (INotifyCollectionChanged).IsAssignableFrom(prop.PropertyType); if (isNotifyingCollection && isCollection) { method = GetType().GetMethod("AttachNotifyingCollection", BindingFlags.NonPublic | BindingFlags.Instance); Debug.Assert(method != null); Debug.Assert(method.IsGenericMethodDefinition); } else if (isCollection) { method = GetType().GetMethod("AttachSimpleCollection", BindingFlags.NonPublic | BindingFlags.Instance); Debug.Assert(method != null); Debug.Assert(method.IsGenericMethodDefinition); } if (method != null) { var typedMethod = method.MakeGenericMethod(prop.PropertyType); MethodInvoker.Invoke(typedMethod, this, prop); } } // ReSharper disable once UnusedMember.Global internal void Attach<TProp>(PropertyInfo prop) where TProp : class, INotifyPropertyChanged { lock (_lock) { var item = prop.GetValue(VM, null) as TProp; if (item != null) { VMInfo existing; if (_notifyingChildren.TryGetValue(prop.Name, out existing)) { existing.Detach(); } _notifyingChildren[prop.Name] = new TypedVMInfo<TProp>(_output, item, prop.Name, Container, this) { VMType = item.GetType() }; } } } // ReSharper disable once UnusedMember.Global internal void AttachNotifyingCollection<TProp>(PropertyInfo prop) where TProp : class, INotifyCollectionChanged, ICollection { lock (_lock) { var item = prop.GetValue(VM, null) as TProp; if (item != null) { VMInfo existing; if (_notifyingCollections.TryGetValue(prop.Name, out existing)) { existing.Detach(); } _notifyingCollections[prop.Name] = new TypedVMNotifyingCollectionInfo<TProp>(_output, item, prop.Name, Container, this) { VMType = item.GetType() }; } } } // ReSharper disable once UnusedMember.Global internal void AttachSimpleCollection<TProp>(PropertyInfo prop) where TProp : class, ICollection { lock (_lock) { var item = prop.GetValue(VM, null) as TProp; if (item != null) { VMInfo existing; if (_simpleCollections.TryGetValue(prop.Name, out existing)) { existing.Detach(); } _simpleCollections[prop.Name] = new TypedVMCollectionInfo<TProp>(_output, item, prop.Name, Container, this) { VMType = item.GetType() }; } } } public T VM { get; private set; } public override void ReportState(IInfoAccess infoAccess, ReportType reportType) { infoAccess.ReportState<T>(this, reportType); } public override void Detach() { lock (_lock) { foreach (var child in _notifyingChildren) { child.Value.Detach(); } _notifyingChildren.Clear(); VM.PropertyChanged -= OnPropertyChanged; } } public override object GetValue() { return VM; } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { lock (Container) { if (!ReferenceEquals(sender, VM)) return; var prop = FindPropertyOnVMType(e.PropertyName); if (prop == null) { _output.WrapLine("-->{0}.{1} Change event for unknown property.", FullName, e.PropertyName); return; } VMInfo child; if (_notifyingChildren.TryGetValue(e.PropertyName, out child)) { child.Detach(); _notifyingChildren.Remove(e.PropertyName); } if (_simpleCollections.TryGetValue(e.PropertyName, out child)) { child.Detach(); _simpleCollections.Remove(e.PropertyName); } if (_notifyingCollections.TryGetValue(e.PropertyName, out child)) { child.Detach(); _notifyingCollections.Remove(e.PropertyName); } CallAttachChild(prop); ReportValue(sender, e, prop); } } private PropertyInfo FindPropertyOnVMType(string propertyName) { var prop = VMType.GetProperty(propertyName); if (prop == null && propertyName.EndsWith("[]")) return FindPropertyOnVMType(propertyName.Substring(0, propertyName.Length - 2)); return prop; } private void ReportValue(object sender, PropertyChangedEventArgs e, PropertyInfo prop) { if (prop.GetIndexParameters().Any()) { _output.WrapLine("-->{0}.{1} changed", FullName, e.PropertyName); return; } _output.Wrap("-->{0}.{1} = ", FullName, e.PropertyName); var value = prop.GetValue(sender, null); if (value != null && Type.GetTypeCode(value.GetType()) == TypeCode.Object) { _output.WriteLine(); ReportObject(value); return; } _output.WrapLine("{0}", value); } private void ReportObject(object value) { var reporterFn = GetType() .GetMethod("ReportObjectWithType", BindingFlags.NonPublic | BindingFlags.Instance); var typedFn = reporterFn.MakeGenericMethod(value.GetType()); _output.WriteLine(); typedFn.Invoke(this, new [] {value}); _output.WriteLine(); } internal void ReportObjectWithType<TValue>(TValue value) { var reporter = new ObjectReporter<TValue>(); reporter.Report(value, _output); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Resources; using System.Runtime.ExceptionServices; using Xunit; using Xunit.NetCore.Extensions; namespace System.Tests { // No appdomain in UWP or CoreRT [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot | TargetFrameworkMonikers.NetFramework, "dotnet/corefx #18718")] public class AppDomainTests : RemoteExecutorTestBase { public AppDomainTests() { string sourceTestAssemblyPath = Path.Combine(Environment.CurrentDirectory, "AssemblyResolveTests.dll"); string destTestAssemblyPath = Path.Combine(Environment.CurrentDirectory, "AssemblyResolveTests", "AssemblyResolveTests.dll"); if (File.Exists(sourceTestAssemblyPath)) { Directory.CreateDirectory(Path.GetDirectoryName(destTestAssemblyPath)); File.Copy(sourceTestAssemblyPath, destTestAssemblyPath, true); File.Delete(sourceTestAssemblyPath); } sourceTestAssemblyPath = Path.Combine(Environment.CurrentDirectory, "TestAppOutsideOfTPA.exe"); destTestAssemblyPath = Path.Combine(Environment.CurrentDirectory, "TestAppOutsideOfTPA", "TestAppOutsideOfTPA.exe"); if (File.Exists(sourceTestAssemblyPath)) { Directory.CreateDirectory(Path.GetDirectoryName(destTestAssemblyPath)); File.Copy(sourceTestAssemblyPath, destTestAssemblyPath, true); File.Delete(sourceTestAssemblyPath); } } [Fact] public void CurrentDomain_Not_Null() { Assert.NotNull(AppDomain.CurrentDomain); } [Fact] public void CurrentDomain_Idempotent() { Assert.Equal(AppDomain.CurrentDomain, AppDomain.CurrentDomain); } [Fact] public void BaseDirectory_Same_As_AppContext() { Assert.Equal(AppDomain.CurrentDomain.BaseDirectory, AppContext.BaseDirectory); } [Fact] public void RelativeSearchPath_Is_Null() { Assert.Null(AppDomain.CurrentDomain.RelativeSearchPath); } [Fact] public void UnhandledException_Add_Remove() { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler); AppDomain.CurrentDomain.UnhandledException -= new UnhandledExceptionEventHandler(MyHandler); } [Fact] public void UnhandledException_NotCalled_When_Handled() { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(NotExpectedToBeCalledHandler); try { throw new Exception(); } catch { } AppDomain.CurrentDomain.UnhandledException -= new UnhandledExceptionEventHandler(NotExpectedToBeCalledHandler); } [ActiveIssue(12716)] [PlatformSpecific(~TestPlatforms.OSX)] // Unhandled exception on a separate process causes xunit to crash on osx [Fact] public void UnhandledException_Called() { System.IO.File.Delete("success.txt"); RemoteInvokeOptions options = new RemoteInvokeOptions(); options.CheckExitCode = false; RemoteInvoke(() => { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler); throw new Exception("****This Unhandled Exception is Expected****"); #pragma warning disable 0162 return SuccessExitCode; #pragma warning restore 0162 }, options).Dispose(); Assert.True(System.IO.File.Exists("success.txt")); } static void NotExpectedToBeCalledHandler(object sender, UnhandledExceptionEventArgs args) { Assert.True(false, "UnhandledException handler not expected to be called"); } static void MyHandler(object sender, UnhandledExceptionEventArgs args) { System.IO.File.Create("success.txt"); } [Fact] public void DynamicDirectory_Null() { Assert.Null(AppDomain.CurrentDomain.DynamicDirectory); } [Fact] public void FriendlyName() { string s = AppDomain.CurrentDomain.FriendlyName; Assert.NotNull(s); string expected = Assembly.GetEntryAssembly().GetName().Name; Assert.Equal(expected, s); } [Fact] public void Id() { Assert.Equal(1, AppDomain.CurrentDomain.Id); } [Fact] public void IsFullyTrusted() { Assert.True(AppDomain.CurrentDomain.IsFullyTrusted); } [Fact] public void IsHomogenous() { Assert.True(AppDomain.CurrentDomain.IsHomogenous); } [Fact] public void FirstChanceException_Add_Remove() { EventHandler<FirstChanceExceptionEventArgs> handler = (sender, e) => { }; AppDomain.CurrentDomain.FirstChanceException += handler; AppDomain.CurrentDomain.FirstChanceException -= handler; } [Fact] public void FirstChanceException_Called() { bool flag = false; EventHandler<FirstChanceExceptionEventArgs> handler = (sender, e) => { Exception ex = (Exception) e.Exception; if (ex is FirstChanceTestException) { flag = !flag; } }; AppDomain.CurrentDomain.FirstChanceException += handler; try { throw new FirstChanceTestException("testing"); } catch { } AppDomain.CurrentDomain.FirstChanceException -= handler; Assert.True(flag, "FirstChanceHandler not called"); } class FirstChanceTestException : Exception { public FirstChanceTestException(string message) : base(message) { } } [Fact] public void ProcessExit_Add_Remove() { EventHandler handler = (sender, e) => { }; AppDomain.CurrentDomain.ProcessExit += handler; AppDomain.CurrentDomain.ProcessExit -= handler; } [Fact] public void ProcessExit_Called() { string path = GetTestFilePath(); RemoteInvoke((pathToFile) => { EventHandler handler = (sender, e) => { File.Create(pathToFile); }; AppDomain.CurrentDomain.ProcessExit += handler; return SuccessExitCode; }, path).Dispose(); Assert.True(File.Exists(path)); } [Fact] public void ApplyPolicy() { AssertExtensions.Throws<ArgumentNullException>("assemblyName", () => { AppDomain.CurrentDomain.ApplyPolicy(null); }); Assert.Throws<ArgumentException>(() => { AppDomain.CurrentDomain.ApplyPolicy(""); }); Assert.Equal(AppDomain.CurrentDomain.ApplyPolicy(Assembly.GetEntryAssembly().FullName), Assembly.GetEntryAssembly().FullName); } [Fact] public void CreateDomain() { AssertExtensions.Throws<ArgumentNullException>("friendlyName", () => { AppDomain.CreateDomain(null); }); Assert.Throws<PlatformNotSupportedException>(() => { AppDomain.CreateDomain("test"); }); } [Fact] public void ExecuteAssemblyByName() { string name = "TestApp"; var assembly = Assembly.Load(name); Assert.Equal(5, AppDomain.CurrentDomain.ExecuteAssemblyByName(assembly.FullName)); Assert.Equal(10, AppDomain.CurrentDomain.ExecuteAssemblyByName(assembly.FullName, new string[2] {"2", "3"})); Assert.Throws<FormatException>(() => AppDomain.CurrentDomain.ExecuteAssemblyByName(assembly.FullName, new string[1] {"a"})); AssemblyName assemblyName = assembly.GetName(); assemblyName.CodeBase = null; Assert.Equal(105, AppDomain.CurrentDomain.ExecuteAssemblyByName(assemblyName, new string[3] {"50", "25", "25"})); } [Fact] public void ExecuteAssembly() { string name = Path.Combine(Environment.CurrentDirectory, "TestAppOutsideOfTPA", "TestAppOutsideOfTPA.exe"); AssertExtensions.Throws<ArgumentNullException>("assemblyFile", () => AppDomain.CurrentDomain.ExecuteAssembly(null)); Assert.Throws<FileNotFoundException>(() => AppDomain.CurrentDomain.ExecuteAssembly("NonExistentFile.exe")); Assert.Throws<PlatformNotSupportedException>(() => AppDomain.CurrentDomain.ExecuteAssembly(name, new string[2] {"2", "3"}, null, Configuration.Assemblies.AssemblyHashAlgorithm.SHA1)); Assert.Equal(5, AppDomain.CurrentDomain.ExecuteAssembly(name)); Assert.Equal(10, AppDomain.CurrentDomain.ExecuteAssembly(name, new string[2] { "2", "3" })); } [Fact] public void GetData_SetData() { AssertExtensions.Throws<ArgumentNullException>("name", () => { AppDomain.CurrentDomain.SetData(null, null); }); AppDomain.CurrentDomain.SetData("", null); Assert.Null(AppDomain.CurrentDomain.GetData("")); AppDomain.CurrentDomain.SetData("randomkey", 4); Assert.Equal(4, AppDomain.CurrentDomain.GetData("randomkey")); } [Fact] public void SetData_SameKeyMultipleTimes_ReplacesOldValue() { string key = Guid.NewGuid().ToString("N"); for (int i = 0; i < 3; i++) { AppDomain.CurrentDomain.SetData(key, i.ToString()); Assert.Equal(i.ToString(), AppDomain.CurrentDomain.GetData(key)); } AppDomain.CurrentDomain.SetData(key, null); } [Fact] public void IsCompatibilitySwitchSet() { Assert.Throws<ArgumentNullException>(() => { AppDomain.CurrentDomain.IsCompatibilitySwitchSet(null); }); Assert.Throws<ArgumentException>(() => { AppDomain.CurrentDomain.IsCompatibilitySwitchSet("");}); Assert.Null(AppDomain.CurrentDomain.IsCompatibilitySwitchSet("randomSwitch")); } [Fact] public void IsDefaultAppDomain() { Assert.True(AppDomain.CurrentDomain.IsDefaultAppDomain()); } [Fact] public void IsFinalizingForUnload() { Assert.False(AppDomain.CurrentDomain.IsFinalizingForUnload()); } [Fact] public void toString() { string actual = AppDomain.CurrentDomain.ToString(); string expected = "Name:" + AppDomain.CurrentDomain.FriendlyName + Environment.NewLine + "There are no context policies."; Assert.Equal(expected, actual); } [Fact] public void Unload() { AssertExtensions.Throws<ArgumentNullException>("domain", () => { AppDomain.Unload(null);}); Assert.Throws<CannotUnloadAppDomainException>(() => { AppDomain.Unload(AppDomain.CurrentDomain); }); } [Fact] public void Load() { AssemblyName assemblyName = typeof(AppDomainTests).Assembly.GetName(); assemblyName.CodeBase = null; Assert.NotNull(AppDomain.CurrentDomain.Load(assemblyName)); Assert.NotNull(AppDomain.CurrentDomain.Load(typeof(AppDomainTests).Assembly.FullName)); Assembly assembly = typeof(AppDomainTests).Assembly; byte[] aBytes = System.IO.File.ReadAllBytes(assembly.Location); Assert.NotNull(AppDomain.CurrentDomain.Load(aBytes)); } [Fact] public void ReflectionOnlyGetAssemblies() { Assert.Equal(Array.Empty<Assembly>(), AppDomain.CurrentDomain.ReflectionOnlyGetAssemblies()); } [Fact] public void MonitoringIsEnabled() { Assert.False(AppDomain.MonitoringIsEnabled); Assert.Throws<ArgumentException>(() => {AppDomain.MonitoringIsEnabled = false;}); Assert.Throws<PlatformNotSupportedException>(() => {AppDomain.MonitoringIsEnabled = true;}); } [Fact] public void MonitoringSurvivedMemorySize() { Assert.Throws<InvalidOperationException>(() => { var t = AppDomain.CurrentDomain.MonitoringSurvivedMemorySize; }); } [Fact] public void MonitoringSurvivedProcessMemorySize() { Assert.Throws<InvalidOperationException>(() => { var t = AppDomain.MonitoringSurvivedProcessMemorySize; }); } [Fact] public void MonitoringTotalAllocatedMemorySize() { Assert.Throws<InvalidOperationException>(() => { var t = AppDomain.CurrentDomain.MonitoringTotalAllocatedMemorySize; } ); } [Fact] public void MonitoringTotalProcessorTime() { Assert.Throws<InvalidOperationException>(() => { var t = AppDomain.CurrentDomain.MonitoringTotalProcessorTime; } ); } #pragma warning disable 618 [Fact] public void GetCurrentThreadId() { Assert.True(AppDomain.GetCurrentThreadId() == Environment.CurrentManagedThreadId); } [Fact] public void ShadowCopyFiles() { Assert.False(AppDomain.CurrentDomain.ShadowCopyFiles); } [Fact] public void AppendPrivatePath() { AppDomain.CurrentDomain.AppendPrivatePath("test"); } [Fact] public void ClearPrivatePath() { AppDomain.CurrentDomain.ClearPrivatePath(); } [Fact] public void ClearShadowCopyPath() { AppDomain.CurrentDomain.ClearShadowCopyPath(); } [Fact] public void SetCachePath() { AppDomain.CurrentDomain.SetCachePath("test"); } [Fact] public void SetShadowCopyFiles() { AppDomain.CurrentDomain.SetShadowCopyFiles(); } [Fact] public void SetShadowCopyPath() { AppDomain.CurrentDomain.SetShadowCopyPath("test"); } #pragma warning restore 618 [Fact] public void GetAssemblies() { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); Assert.NotNull(assemblies); Assert.True(assemblies.Length > 0, "There must be assemblies already loaded in the process"); AppDomain.CurrentDomain.Load(typeof(AppDomainTests).Assembly.GetName().FullName); Assembly[] assemblies1 = AppDomain.CurrentDomain.GetAssemblies(); // Another thread could have loaded an assembly hence not checking for equality Assert.True(assemblies1.Length >= assemblies.Length, "Assembly.Load of an already loaded assembly should not cause another load"); Assembly.LoadFile(typeof(AppDomain).Assembly.Location); Assembly[] assemblies2 = AppDomain.CurrentDomain.GetAssemblies(); Assert.True(assemblies2.Length > assemblies.Length, "Assembly.LoadFile should cause an increase in GetAssemblies list"); int ctr = 0; foreach (var a in assemblies2) { // Dynamic assemblies do not support Location property. if (!a.IsDynamic) { if (a.Location == typeof(AppDomain).Assembly.Location) ctr++; } } foreach (var a in assemblies) { if (!a.IsDynamic) { if (a.Location == typeof(AppDomain).Assembly.Location) ctr--; } } Assert.True(ctr > 0, "Assembly.LoadFile should cause file to be loaded again"); } [Fact] public void AssemblyLoad() { bool AssemblyLoadFlag = false; AssemblyLoadEventHandler handler = (sender, args) => { if (args.LoadedAssembly.FullName.Equals(typeof(AppDomainTests).Assembly.FullName)) { AssemblyLoadFlag = !AssemblyLoadFlag; } }; AppDomain.CurrentDomain.AssemblyLoad += handler; try { Assembly.LoadFile(typeof(AppDomainTests).Assembly.Location); } finally { AppDomain.CurrentDomain.AssemblyLoad -= handler; } Assert.True(AssemblyLoadFlag); } [Fact] public void AssemblyResolve() { RemoteInvoke(() => { ResolveEventHandler handler = (sender, e) => { return Assembly.LoadFile(Path.Combine(Environment.CurrentDirectory, "AssemblyResolveTests", "AssemblyResolveTests.dll")); }; AppDomain.CurrentDomain.AssemblyResolve += handler; Type t = Type.GetType("AssemblyResolveTests.Class1, AssemblyResolveTests", true); Assert.NotNull(t); return SuccessExitCode; }).Dispose(); } [Fact] public void AssemblyResolve_RequestingAssembly() { RemoteInvoke(() => { Assembly a = Assembly.LoadFile(Path.Combine(Environment.CurrentDirectory, "TestAppOutsideOfTPA", "TestAppOutsideOfTPA.exe")); ResolveEventHandler handler = (sender, e) => { Assert.Equal(e.RequestingAssembly, a); return Assembly.LoadFile(Path.Combine(Environment.CurrentDirectory, "AssemblyResolveTests", "AssemblyResolveTests.dll")); }; AppDomain.CurrentDomain.AssemblyResolve += handler; Type ptype = a.GetType("Program"); MethodInfo myMethodInfo = ptype.GetMethod("foo"); object ret = myMethodInfo.Invoke(null, null); Assert.NotNull(ret); return SuccessExitCode; }).Dispose(); } [Fact] public void TypeResolve() { Assert.Throws<TypeLoadException>(() => Type.GetType("Program", true)); ResolveEventHandler handler = (sender, args) => { return Assembly.Load("TestApp"); }; AppDomain.CurrentDomain.TypeResolve += handler; Type t; try { t = Type.GetType("Program", true); } finally { AppDomain.CurrentDomain.TypeResolve -= handler; } Assert.NotNull(t); } [Fact] public void ResourceResolve() { ResourceManager res = new ResourceManager(typeof(FxResources.TestApp.SR)); Assert.Throws<MissingManifestResourceException>(() => res.GetString("Message")); ResolveEventHandler handler = (sender, args) => { return Assembly.Load("TestApp"); }; AppDomain.CurrentDomain.ResourceResolve += handler; String s; try { s = res.GetString("Message"); } finally { AppDomain.CurrentDomain.ResourceResolve -= handler; } Assert.Equal(s, "Happy Halloween"); } [Fact] public void SetThreadPrincipal() { Assert.Throws<ArgumentNullException>(() => {AppDomain.CurrentDomain.SetThreadPrincipal(null);}); var identity = new System.Security.Principal.GenericIdentity("NewUser"); var principal = new System.Security.Principal.GenericPrincipal(identity, null); AppDomain.CurrentDomain.SetThreadPrincipal(principal); } } } namespace FxResources.TestApp { class SR { } }
using UnityEngine; using System.Collections; using System; namespace RootMotion.FinalIK { /// <summary> /// Analytic %IK solver based on the Law of Cosines. /// </summary> [System.Serializable] public class IKSolverTrigonometric: IKSolver { #region Main Interface /// <summary> /// The target Transform. /// </summary> public Transform target; /// <summary> /// The %IK rotation weight (rotation of the last bone). /// </summary> [Range(0f, 1f)] public float IKRotationWeight = 1f; /// <summary> /// The %IK rotation target. /// </summary> public Quaternion IKRotation; /// <summary> /// The bend plane normal. /// </summary> public Vector3 bendNormal = Vector3.right; /// <summary> /// The first bone (upper arm or thigh). /// </summary> public TrigonometricBone bone1 = new TrigonometricBone(); /// <summary> /// The second bone (forearm or calf). /// </summary> public TrigonometricBone bone2 = new TrigonometricBone(); /// <summary> /// The third bone (hand or foot). /// </summary> public TrigonometricBone bone3 = new TrigonometricBone(); /// <summary> /// Sets the bend goal position. /// </summary> /// <param name='goalPosition'> /// Goal position. /// </param> public void SetBendGoalPosition(Vector3 goalPosition, float weight) { if (!initiated) return; if (weight <= 0f) return; Vector3 normal = Vector3.Cross(goalPosition - bone1.transform.position, IKPosition - bone1.transform.position); if (normal != Vector3.zero) { if (weight >= 1f) { bendNormal = normal; return; } bendNormal = Vector3.Lerp(bendNormal, normal, weight); } } /// <summary> /// Sets the bend plane to match current bone rotations. /// </summary> public void SetBendPlaneToCurrent() { if (!initiated) return; Vector3 normal = Vector3.Cross(bone2.transform.position - bone1.transform.position, bone3.transform.position - bone2.transform.position); if (normal != Vector3.zero) bendNormal = normal; } /// <summary> /// Sets the %IK rotation. /// </summary> public void SetIKRotation(Quaternion rotation) { IKRotation = rotation; } /// <summary> /// Sets the %IK rotation weight. /// </summary> public void SetIKRotationWeight(float weight) { IKRotationWeight = Mathf.Clamp(weight, 0f, 1f); } /// <summary> /// Gets the %IK rotation. /// </summary> public Quaternion GetIKRotation() { return IKRotation; } /// <summary> /// Gets the %IK rotation weight. /// </summary> public float GetIKRotationWeight() { return IKRotationWeight; } public override IKSolver.Point[] GetPoints() { return new IKSolver.Point[3] { (IKSolver.Point)bone1, (IKSolver.Point)bone2, (IKSolver.Point)bone3 }; } public override IKSolver.Point GetPoint(Transform transform) { if (bone1.transform == transform) return (IKSolver.Point)bone1; if (bone2.transform == transform) return (IKSolver.Point)bone2; if (bone3.transform == transform) return (IKSolver.Point)bone3; return null; } public override void StoreDefaultLocalState() { bone1.StoreDefaultLocalState(); bone2.StoreDefaultLocalState(); bone3.StoreDefaultLocalState(); } public override void FixTransforms() { bone1.FixTransform(); bone2.FixTransform(); bone3.FixTransform(); } public override bool IsValid(bool log) { if (bone1.transform == null || bone2.transform == null || bone3.transform == null) { if (log) LogWarning("Bone transform is null in IKSolverTrigonometric. Can't initiate solver."); return false; } if (bone1.transform.position == bone2.transform.position) { if (log) LogWarning("first bone position is the same as second bone position. Can't initiate solver."); return false; } if (bone2.transform.position == bone3.transform.position) { if (log) LogWarning("second bone position is the same as third bone position. Can't initiate solver."); return false; } Transform duplicate = (Transform)Hierarchy.ContainsDuplicate(new Transform[3] { bone1.transform, bone2.transform, bone3.transform }); if (duplicate != null) { if (log) LogWarning(duplicate.name + " is represented multiple times in a single IK chain. Can't initiate solver."); return false; } return true; } /// <summary> /// Bone type used by IKSolverTrigonometric. /// </summary> [System.Serializable] public class TrigonometricBone: IKSolver.Bone { public float sqrMag; // Square magnitude to the next bone private Quaternion targetToLocalSpace; private Vector3 defaultLocalBendNormal; #region Public methods /* * Initiates the bone, precalculates values. * */ public void Initiate(Vector3 childPosition, Vector3 bendNormal) { // Get default target rotation that looks at child position with bendNormal as up Quaternion defaultTargetRotation = Quaternion.LookRotation(childPosition - transform.position, bendNormal); // Covert default target rotation to local space targetToLocalSpace = QuaTools.RotationToLocalSpace(transform.rotation, defaultTargetRotation); defaultLocalBendNormal = Quaternion.Inverse(transform.rotation) * bendNormal; } /* * Calculates the rotation of this bone to targetPosition. * */ public Quaternion GetRotation(Vector3 direction, Vector3 bendNormal) { return Quaternion.LookRotation(direction, bendNormal) * targetToLocalSpace; } /* * Gets the bend normal from current bone rotation. * */ public Vector3 GetBendNormalFromCurrentRotation() { return transform.rotation * defaultLocalBendNormal; } #endregion Public methods } /// <summary> /// Reinitiate the solver with new bone Transforms. /// </summary> /// <returns> /// Returns true if the new chain is valid. /// </returns> public bool SetChain(Transform bone1, Transform bone2, Transform bone3, Transform root) { this.bone1.transform = bone1; this.bone2.transform = bone2; this.bone3.transform = bone3; Initiate(root); return initiated; } #endregion Main Interface protected override void OnInitiate() { if (bendNormal == Vector3.zero) bendNormal = Vector3.right; OnInitiateVirtual(); IKPosition = bone3.transform.position; IKRotation = bone3.transform.rotation; // Initiating bones InitiateBones(); directHierarchy = IsDirectHierarchy(); } // Are the bones parented directly to each other? private bool IsDirectHierarchy() { if (bone3.transform.parent != bone2.transform) return false; if (bone2.transform.parent != bone1.transform) return false; return true; } // Set the defaults for the bones private void InitiateBones() { bone1.Initiate(bone2.transform.position, bendNormal); bone2.Initiate(bone3.transform.position, bendNormal); SetBendPlaneToCurrent(); } protected override void OnUpdate() { IKPositionWeight = Mathf.Clamp(IKPositionWeight, 0f, 1f); IKRotationWeight = Mathf.Clamp(IKRotationWeight, 0f, 1f); if (target != null) { IKPosition = target.position; IKRotation = target.rotation; } OnUpdateVirtual(); if (IKPositionWeight > 0) { // Reinitiating the bones when the hierarchy is not direct. This allows for skipping animated bones in the hierarchy. if (!directHierarchy) { bone1.Initiate(bone2.transform.position, bendNormal); bone2.Initiate(bone3.transform.position, bendNormal); } // Find out if bone lengths should be updated bone1.sqrMag = (bone2.transform.position - bone1.transform.position).sqrMagnitude; bone2.sqrMag = (bone3.transform.position - bone2.transform.position).sqrMagnitude; if (bendNormal == Vector3.zero && !Warning.logged) LogWarning("IKSolverTrigonometric Bend Normal is Vector3.zero."); weightIKPosition = Vector3.Lerp(bone3.transform.position, IKPosition, IKPositionWeight); // Interpolating bend normal Vector3 currentBendNormal = Vector3.Lerp(bone1.GetBendNormalFromCurrentRotation(), bendNormal, IKPositionWeight); // Calculating and interpolating bend direction Vector3 bendDirection = Vector3.Lerp(bone2.transform.position - bone1.transform.position, GetBendDirection(weightIKPosition, currentBendNormal), IKPositionWeight); if (bendDirection == Vector3.zero) bendDirection = bone2.transform.position - bone1.transform.position; // Rotating bone1 bone1.transform.rotation = bone1.GetRotation(bendDirection, currentBendNormal); // Rotating bone 2 bone2.transform.rotation = bone2.GetRotation(weightIKPosition - bone2.transform.position, bone2.GetBendNormalFromCurrentRotation()); } // Rotating bone3 if (IKRotationWeight > 0) { bone3.transform.rotation = Quaternion.Slerp(bone3.transform.rotation, IKRotation, IKRotationWeight); } OnPostSolveVirtual(); } protected Vector3 weightIKPosition; protected virtual void OnInitiateVirtual() {} protected virtual void OnUpdateVirtual() {} protected virtual void OnPostSolveVirtual() {} protected bool directHierarchy = true; /* * Calculates the bend direction based on the Law of Cosines. * */ protected Vector3 GetBendDirection(Vector3 IKPosition, Vector3 bendNormal) { Vector3 direction = IKPosition - bone1.transform.position; if (direction == Vector3.zero) return Vector3.zero; float directionSqrMag = direction.sqrMagnitude; float directionMagnitude = (float)Math.Sqrt(directionSqrMag); float x = (directionSqrMag + bone1.sqrMag - bone2.sqrMag) / 2f / directionMagnitude; float y = (float)Math.Sqrt(Mathf.Clamp(bone1.sqrMag - x * x, 0, Mathf.Infinity)); Vector3 yDirection = Vector3.Cross(direction, bendNormal); return Quaternion.LookRotation(direction, yDirection) * new Vector3(0f, y, x); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V9.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V9.Services { /// <summary>Settings for <see cref="ProductGroupViewServiceClient"/> instances.</summary> public sealed partial class ProductGroupViewServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="ProductGroupViewServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="ProductGroupViewServiceSettings"/>.</returns> public static ProductGroupViewServiceSettings GetDefault() => new ProductGroupViewServiceSettings(); /// <summary> /// Constructs a new <see cref="ProductGroupViewServiceSettings"/> object with default settings. /// </summary> public ProductGroupViewServiceSettings() { } private ProductGroupViewServiceSettings(ProductGroupViewServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetProductGroupViewSettings = existing.GetProductGroupViewSettings; OnCopy(existing); } partial void OnCopy(ProductGroupViewServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ProductGroupViewServiceClient.GetProductGroupView</c> and /// <c>ProductGroupViewServiceClient.GetProductGroupViewAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetProductGroupViewSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="ProductGroupViewServiceSettings"/> object.</returns> public ProductGroupViewServiceSettings Clone() => new ProductGroupViewServiceSettings(this); } /// <summary> /// Builder class for <see cref="ProductGroupViewServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class ProductGroupViewServiceClientBuilder : gaxgrpc::ClientBuilderBase<ProductGroupViewServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public ProductGroupViewServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public ProductGroupViewServiceClientBuilder() { UseJwtAccessWithScopes = ProductGroupViewServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref ProductGroupViewServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ProductGroupViewServiceClient> task); /// <summary>Builds the resulting client.</summary> public override ProductGroupViewServiceClient Build() { ProductGroupViewServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<ProductGroupViewServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<ProductGroupViewServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private ProductGroupViewServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return ProductGroupViewServiceClient.Create(callInvoker, Settings); } private async stt::Task<ProductGroupViewServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return ProductGroupViewServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => ProductGroupViewServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => ProductGroupViewServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => ProductGroupViewServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>ProductGroupViewService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage product group views. /// </remarks> public abstract partial class ProductGroupViewServiceClient { /// <summary> /// The default endpoint for the ProductGroupViewService service, which is a host of "googleads.googleapis.com" /// and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default ProductGroupViewService scopes.</summary> /// <remarks> /// The default ProductGroupViewService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="ProductGroupViewServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="ProductGroupViewServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="ProductGroupViewServiceClient"/>.</returns> public static stt::Task<ProductGroupViewServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new ProductGroupViewServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="ProductGroupViewServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="ProductGroupViewServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="ProductGroupViewServiceClient"/>.</returns> public static ProductGroupViewServiceClient Create() => new ProductGroupViewServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="ProductGroupViewServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="ProductGroupViewServiceSettings"/>.</param> /// <returns>The created <see cref="ProductGroupViewServiceClient"/>.</returns> internal static ProductGroupViewServiceClient Create(grpccore::CallInvoker callInvoker, ProductGroupViewServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } ProductGroupViewService.ProductGroupViewServiceClient grpcClient = new ProductGroupViewService.ProductGroupViewServiceClient(callInvoker); return new ProductGroupViewServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> 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 stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC ProductGroupViewService client</summary> public virtual ProductGroupViewService.ProductGroupViewServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested product group view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </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 gagvr::ProductGroupView GetProductGroupView(GetProductGroupViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested product group view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </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 stt::Task<gagvr::ProductGroupView> GetProductGroupViewAsync(GetProductGroupViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested product group view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ProductGroupView> GetProductGroupViewAsync(GetProductGroupViewRequest request, st::CancellationToken cancellationToken) => GetProductGroupViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested product group view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the product group view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::ProductGroupView GetProductGroupView(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetProductGroupView(new GetProductGroupViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested product group view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the product group view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ProductGroupView> GetProductGroupViewAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetProductGroupViewAsync(new GetProductGroupViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested product group view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the product group view to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ProductGroupView> GetProductGroupViewAsync(string resourceName, st::CancellationToken cancellationToken) => GetProductGroupViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested product group view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the product group view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::ProductGroupView GetProductGroupView(gagvr::ProductGroupViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetProductGroupView(new GetProductGroupViewRequest { ResourceNameAsProductGroupViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested product group view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the product group view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ProductGroupView> GetProductGroupViewAsync(gagvr::ProductGroupViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetProductGroupViewAsync(new GetProductGroupViewRequest { ResourceNameAsProductGroupViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested product group view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the product group view to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::ProductGroupView> GetProductGroupViewAsync(gagvr::ProductGroupViewName resourceName, st::CancellationToken cancellationToken) => GetProductGroupViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>ProductGroupViewService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage product group views. /// </remarks> public sealed partial class ProductGroupViewServiceClientImpl : ProductGroupViewServiceClient { private readonly gaxgrpc::ApiCall<GetProductGroupViewRequest, gagvr::ProductGroupView> _callGetProductGroupView; /// <summary> /// Constructs a client wrapper for the ProductGroupViewService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="ProductGroupViewServiceSettings"/> used within this client. /// </param> public ProductGroupViewServiceClientImpl(ProductGroupViewService.ProductGroupViewServiceClient grpcClient, ProductGroupViewServiceSettings settings) { GrpcClient = grpcClient; ProductGroupViewServiceSettings effectiveSettings = settings ?? ProductGroupViewServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetProductGroupView = clientHelper.BuildApiCall<GetProductGroupViewRequest, gagvr::ProductGroupView>(grpcClient.GetProductGroupViewAsync, grpcClient.GetProductGroupView, effectiveSettings.GetProductGroupViewSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetProductGroupView); Modify_GetProductGroupViewApiCall(ref _callGetProductGroupView); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetProductGroupViewApiCall(ref gaxgrpc::ApiCall<GetProductGroupViewRequest, gagvr::ProductGroupView> call); partial void OnConstruction(ProductGroupViewService.ProductGroupViewServiceClient grpcClient, ProductGroupViewServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC ProductGroupViewService client</summary> public override ProductGroupViewService.ProductGroupViewServiceClient GrpcClient { get; } partial void Modify_GetProductGroupViewRequest(ref GetProductGroupViewRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested product group view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </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 gagvr::ProductGroupView GetProductGroupView(GetProductGroupViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetProductGroupViewRequest(ref request, ref callSettings); return _callGetProductGroupView.Sync(request, callSettings); } /// <summary> /// Returns the requested product group view in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </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 stt::Task<gagvr::ProductGroupView> GetProductGroupViewAsync(GetProductGroupViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetProductGroupViewRequest(ref request, ref callSettings); return _callGetProductGroupView.Async(request, callSettings); } } }
// Copyright (c) The Mapsui authors. // The Mapsui authors licensed this file under the MIT license. // See the LICENSE file in the project root for full license information. // This file was originally created by Paul den Dulk (Geodan) as part of SharpMap #nullable enable using System; using System.Threading.Tasks; using Windows.Devices.Sensors; using Windows.Foundation; using Windows.System; #if __WINUI__ using System.Runtime.Versioning; using Mapsui.UI.WinUI.Extensions; using Microsoft.UI; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml.Input; using Microsoft.UI.Xaml.Media; using Microsoft.UI.Xaml.Shapes; using SkiaSharp.Views.Windows; using HorizontalAlignment = Microsoft.UI.Xaml.HorizontalAlignment; using VerticalAlignment = Microsoft.UI.Xaml.VerticalAlignment; #else using Mapsui.UI.Uwp.Extensions; using Windows.Graphics.Display; using Windows.UI; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Shapes; using SkiaSharp.Views.UWP; using HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment; using VerticalAlignment = Windows.UI.Xaml.VerticalAlignment; #endif #if __WINUI__ [assembly: SupportedOSPlatform("windows10.0.18362.0")] namespace Mapsui.UI.WinUI #else namespace Mapsui.UI.Uwp #endif { public partial class MapControl : Grid, IMapControl, IDisposable { private readonly Rectangle _selectRectangle = CreateSelectRectangle(); private readonly SKXamlCanvas _canvas = CreateRenderTarget(); private double _innerRotation; public MouseWheelAnimation MouseWheelAnimation { get; } = new MouseWheelAnimation { Duration = 0 }; public MapControl() { CommonInitialize(); Initialize(); } private void Initialize() { _invalidate = () => { // The commented out code crashes the app when MouseWheelAnimation.Duration > 0. Could be a bug in SKXamlCanvas //if (Dispatcher.HasThreadAccess) _canvas?.Invalidate(); //else RunOnUIThread(() => _canvas?.Invalidate()); RunOnUIThread(() => _canvas?.Invalidate()); }; Background = new SolidColorBrush(Colors.White); // DON'T REMOVE! Touch events do not work without a background Children.Add(_canvas); Children.Add(_selectRectangle); _canvas.PaintSurface += Canvas_PaintSurface; Loaded += MapControlLoaded; SizeChanged += MapControlSizeChanged; PointerWheelChanged += MapControl_PointerWheelChanged; ManipulationMode = ManipulationModes.Scale | ManipulationModes.TranslateX | ManipulationModes.TranslateY | ManipulationModes.Rotate; ManipulationStarted += OnManipulationStarted; ManipulationDelta += OnManipulationDelta; ManipulationCompleted += OnManipulationCompleted; ManipulationInertiaStarting += OnManipulationInertiaStarting; Tapped += OnSingleTapped; DoubleTapped += OnDoubleTapped; var orientationSensor = SimpleOrientationSensor.GetDefault(); if (orientationSensor != null) orientationSensor.OrientationChanged += (sender, args) => RunOnUIThread(() => Refresh()); } private void OnManipulationCompleted(object sender, ManipulationCompletedRoutedEventArgs e) { RefreshData(); Console.WriteLine(Guid.NewGuid()); } private void OnManipulationStarted(object sender, ManipulationStartedRoutedEventArgs e) { _innerRotation = _viewport.Rotation; } private void OnDoubleTapped(object sender, DoubleTappedRoutedEventArgs e) { var tapPosition = e.GetPosition(this).ToMapsui(); OnInfo(InvokeInfo(tapPosition, tapPosition, 2)); } private void OnSingleTapped(object sender, TappedRoutedEventArgs e) { var tabPosition = e.GetPosition(this).ToMapsui(); OnInfo(InvokeInfo(tabPosition, tabPosition, 1)); } private static Rectangle CreateSelectRectangle() { return new Rectangle { Fill = new SolidColorBrush(Colors.Red), Stroke = new SolidColorBrush(Colors.Black), StrokeThickness = 3, RadiusX = 0.5, RadiusY = 0.5, StrokeDashArray = new DoubleCollection { 3.0 }, Opacity = 0.3, VerticalAlignment = VerticalAlignment.Top, HorizontalAlignment = HorizontalAlignment.Left, Visibility = Visibility.Collapsed }; } private static SKXamlCanvas CreateRenderTarget() { return new SKXamlCanvas { VerticalAlignment = VerticalAlignment.Stretch, HorizontalAlignment = HorizontalAlignment.Stretch, Background = new SolidColorBrush(Colors.Transparent) }; } private void MapControl_PointerWheelChanged(object sender, PointerRoutedEventArgs e) { if (_map?.ZoomLock ?? true) return; if (!Viewport.HasSize) return; var currentPoint = e.GetCurrentPoint(this); #if __WINUI__ var mousePosition = new MPoint(currentPoint.Position.X, currentPoint.Position.Y); #else var mousePosition = new MPoint(currentPoint.RawPosition.X, currentPoint.RawPosition.Y); #endif var resolution = MouseWheelAnimation.GetResolution(currentPoint.Properties.MouseWheelDelta, _viewport, _map); // Limit target resolution before animation to avoid an animation that is stuck on the max resolution, which would cause a needless delay if (this.Map == null) return; resolution = Map.Limiter.LimitResolution(resolution, Viewport.Width, Viewport.Height, Map.Resolutions, Map.Extent); Navigator.ZoomTo(resolution, mousePosition, MouseWheelAnimation.Duration, MouseWheelAnimation.Easing); e.Handled = true; } private void MapControlLoaded(object sender, RoutedEventArgs e) { SetViewportSize(); } private void MapControlSizeChanged(object sender, SizeChangedEventArgs e) { Clip = new RectangleGeometry { Rect = new Rect(0, 0, ActualWidth, ActualHeight) }; SetViewportSize(); } private void RunOnUIThread(Action action) { #if __WINUI__ Task.Run(() => DispatcherQueue.TryEnqueue(Microsoft.UI.Dispatching.DispatcherQueuePriority.Normal, () => action())); #else Task.Run(() => Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => action())); #endif } private void Canvas_PaintSurface(object? sender, SKPaintSurfaceEventArgs e) { if (PixelDensity <= 0) return; var canvas = e.Surface.Canvas; canvas.Scale(PixelDensity, PixelDensity); CommonDrawControl(canvas); } private static void OnManipulationInertiaStarting(object sender, ManipulationInertiaStartingRoutedEventArgs e) { e.TranslationBehavior.DesiredDeceleration = 25 * 96.0 / (1000.0 * 1000.0); } private void OnManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e) { var center = e.Position.ToMapsui(); var radius = e.Delta.Scale; var rotation = e.Delta.Rotation; var previousCenter = e.Position.ToMapsui().Offset(-e.Delta.Translation.X, -e.Delta.Translation.Y); var previousRadius = 1f; var previousRotation = 0f; double rotationDelta = 0; if (!(Map?.RotationLock ?? false)) { _innerRotation += rotation - previousRotation; _innerRotation %= 360; if (_innerRotation > 180) _innerRotation -= 360; else if (_innerRotation < -180) _innerRotation += 360; if (Viewport.Rotation == 0 && Math.Abs(_innerRotation) >= Math.Abs(UnSnapRotationDegrees)) rotationDelta = _innerRotation; else if (Viewport.Rotation != 0) { if (Math.Abs(_innerRotation) <= Math.Abs(ReSnapRotationDegrees)) rotationDelta = -Viewport.Rotation; else rotationDelta = _innerRotation - Viewport.Rotation; } } _viewport.Transform(center, previousCenter, radius / previousRadius, rotationDelta); RefreshGraphics(); e.Handled = true; } public void OpenBrowser(string url) { Task.Run(() => Launcher.LaunchUriAsync(new Uri(url))); } private float ViewportWidth => (float)ActualWidth; private float ViewportHeight => (float)ActualHeight; private float GetPixelDensity() { #if __WINUI__ return (float)XamlRoot.RasterizationScale; #else return (float)DisplayInformation.GetForCurrentView().RawPixelsPerViewPixel; #endif } #if __ANDROID__ protected override void Dispose(bool disposing) #elif __IOS__ || __MACOS__ protected new virtual void Dispose(bool disposing) #else protected virtual void Dispose(bool disposing) #endif { if (disposing) { (_canvas as IDisposable)?.Dispose(); #if __IOS__ || __MACOS__ || __ANDROID__ || NETSTANDARD (_selectRectangle as IDisposable)?.Dispose(); #endif _map?.Dispose(); } CommonDispose(disposing); #if __ANDROID__ || __IOS__ || __MACOS__ base.Dispose(disposing); #endif } #if !(__ANDROID__ ) #if __IOS__ || __MACOS__ || NETSTANDARD public new void Dispose() #else public void Dispose() #endif { Dispose(true); GC.SuppressFinalize(this); } #endif } }
using Xunit; using Exercism.Tests; public class QuestLogicTests { [Fact] [Task(1)] public void Cannot_execute_fast_attack_if_knight_is_awake() { var knightIsAwake = true; Assert.False(QuestLogic.CanFastAttack(knightIsAwake)); } [Fact] [Task(1)] public void Can_execute_fast_attack_if_knight_is_sleeping() { var knightIsAwake = false; Assert.True(QuestLogic.CanFastAttack(knightIsAwake)); } [Fact] [Task(2)] public void Cannot_spy_if_everyone_is_sleeping() { var knightIsAwake = false; var archerIsAwake = false; var prisonerIsAwake = false; Assert.False(QuestLogic.CanSpy(knightIsAwake, archerIsAwake, prisonerIsAwake)); } [Fact] [Task(2)] public void Can_spy_if_everyone_but_knight_is_sleeping() { var knightIsAwake = true; var archerIsAwake = false; var prisonerIsAwake = false; Assert.True(QuestLogic.CanSpy(knightIsAwake, archerIsAwake, prisonerIsAwake)); } [Fact] [Task(2)] public void Can_spy_if_everyone_but_archer_is_sleeping() { var knightIsAwake = false; var archerIsAwake = true; var prisonerIsAwake = false; Assert.True(QuestLogic.CanSpy(knightIsAwake, archerIsAwake, prisonerIsAwake)); } [Fact] [Task(2)] public void Can_spy_if_everyone_but_prisoner_is_sleeping() { var knightIsAwake = false; var archerIsAwake = false; var prisonerIsAwake = true; Assert.True(QuestLogic.CanSpy(knightIsAwake, archerIsAwake, prisonerIsAwake)); } [Fact] [Task(2)] public void Can_spy_if_only_knight_is_sleeping() { var knightIsAwake = false; var archerIsAwake = true; var prisonerIsAwake = true; Assert.True(QuestLogic.CanSpy(knightIsAwake, archerIsAwake, prisonerIsAwake)); } [Fact] [Task(2)] public void Can_spy_if_only_archer_is_sleeping() { var knightIsAwake = true; var archerIsAwake = false; var prisonerIsAwake = true; Assert.True(QuestLogic.CanSpy(knightIsAwake, archerIsAwake, prisonerIsAwake)); } [Fact] [Task(2)] public void Can_spy_if_only_prisoner_is_sleeping() { var knightIsAwake = true; var archerIsAwake = true; var prisonerIsAwake = false; Assert.True(QuestLogic.CanSpy(knightIsAwake, archerIsAwake, prisonerIsAwake)); } [Fact] [Task(2)] public void Can_spy_if_everyone_is_awake() { var knightIsAwake = true; var archerIsAwake = true; var prisonerIsAwake = true; Assert.True(QuestLogic.CanSpy(knightIsAwake, archerIsAwake, prisonerIsAwake)); } [Fact] [Task(3)] public void Can_signal_prisoner_if_archer_is_sleeping_and_prisoner_is_awake() { var archerIsAwake = false; var prisonerIsAwake = true; Assert.True(QuestLogic.CanSignalPrisoner(archerIsAwake, prisonerIsAwake)); } [Fact] [Task(3)] public void Cannot_signal_prisoner_if_archer_is_awake_and_prisoner_is_sleeping() { var archerIsAwake = true; var prisonerIsAwake = false; Assert.False(QuestLogic.CanSignalPrisoner(archerIsAwake, prisonerIsAwake)); } [Fact] [Task(3)] public void Cannot_signal_prisoner_if_archer_and_prisoner_are_both_sleeping() { var archerIsAwake = false; var prisonerIsAwake = false; Assert.False(QuestLogic.CanSignalPrisoner(archerIsAwake, prisonerIsAwake)); } [Fact] [Task(3)] public void Cannot_signal_prisoner_if_archer_and_prisoner_are_both_awake() { var archerIsAwake = true; var prisonerIsAwake = true; Assert.False(QuestLogic.CanSignalPrisoner(archerIsAwake, prisonerIsAwake)); } [Fact] [Task(4)] public void Cannot_free_prisoner_if_everyone_is_awake_and_pet_dog_is_present() { var knightIsAwake = true; var archerIsAwake = true; var prisonerIsAwake = true; var petDogIsPresent = true; Assert.False(QuestLogic.CanFreePrisoner(knightIsAwake, archerIsAwake, prisonerIsAwake, petDogIsPresent)); } [Fact] [Task(4)] public void Cannot_free_prisoner_if_everyone_is_awake_and_pet_dog_is_absent() { var knightIsAwake = true; var archerIsAwake = true; var prisonerIsAwake = true; var petDogIsPresent = false; Assert.False(QuestLogic.CanFreePrisoner(knightIsAwake, archerIsAwake, prisonerIsAwake, petDogIsPresent)); } [Fact] [Task(4)] public void Can_free_prisoner_if_everyone_is_asleep_and_pet_dog_is_present() { var knightIsAwake = false; var archerIsAwake = false; var prisonerIsAwake = false; var petDogIsPresent = true; Assert.True(QuestLogic.CanFreePrisoner(knightIsAwake, archerIsAwake, prisonerIsAwake, petDogIsPresent)); } [Fact] [Task(4)] public void Cannot_free_prisoner_if_everyone_is_asleep_and_pet_dog_is_absent() { var knightIsAwake = false; var archerIsAwake = false; var prisonerIsAwake = false; var petDogIsPresent = false; Assert.False(QuestLogic.CanFreePrisoner(knightIsAwake, archerIsAwake, prisonerIsAwake, petDogIsPresent)); } [Fact] [Task(4)] public void Can_free_prisoner_if_only_prisoner_is_awake_and_pet_dog_is_present() { var knightIsAwake = false; var archerIsAwake = false; var prisonerIsAwake = true; var petDogIsPresent = true; Assert.True(QuestLogic.CanFreePrisoner(knightIsAwake, archerIsAwake, prisonerIsAwake, petDogIsPresent)); } [Fact] [Task(4)] public void Can_free_prisoner_if_only_prisoner_is_awake_and_pet_dog_is_absent() { var knightIsAwake = false; var archerIsAwake = false; var prisonerIsAwake = true; var petDogIsPresent = false; Assert.True(QuestLogic.CanFreePrisoner(knightIsAwake, archerIsAwake, prisonerIsAwake, petDogIsPresent)); } [Fact] [Task(4)] public void Cannot_free_prisoner_if_only_archer_is_awake_and_pet_dog_is_present() { var knightIsAwake = false; var archerIsAwake = true; var prisonerIsAwake = false; var petDogIsPresent = true; Assert.False(QuestLogic.CanFreePrisoner(knightIsAwake, archerIsAwake, prisonerIsAwake, petDogIsPresent)); } [Fact] [Task(4)] public void Cannot_free_prisoner_if_only_archer_is_awake_and_pet_dog_is_absent() { var knightIsAwake = false; var archerIsAwake = true; var prisonerIsAwake = false; var petDogIsPresent = false; Assert.False(QuestLogic.CanFreePrisoner(knightIsAwake, archerIsAwake, prisonerIsAwake, petDogIsPresent)); } [Fact] [Task(4)] public void Can_free_prisoner_if_only_knight_is_awake_and_pet_dog_is_present() { var knightIsAwake = true; var archerIsAwake = false; var prisonerIsAwake = false; var petDogIsPresent = true; Assert.True(QuestLogic.CanFreePrisoner(knightIsAwake, archerIsAwake, prisonerIsAwake, petDogIsPresent)); } [Fact] [Task(4)] public void Cannot_free_prisoner_if_only_knight_is_awake_and_pet_dog_is_absent() { var knightIsAwake = true; var archerIsAwake = false; var prisonerIsAwake = false; var petDogIsPresent = false; Assert.False(QuestLogic.CanFreePrisoner(knightIsAwake, archerIsAwake, prisonerIsAwake, petDogIsPresent)); } [Fact] [Task(4)] public void Cannot_free_prisoner_if_only_knight_is_asleep_and_pet_dog_is_present() { var knightIsAwake = false; var archerIsAwake = true; var prisonerIsAwake = true; var petDogIsPresent = true; Assert.False(QuestLogic.CanFreePrisoner(knightIsAwake, archerIsAwake, prisonerIsAwake, petDogIsPresent)); } [Fact] [Task(4)] public void Cannot_free_prisoner_if_only_knight_is_asleep_and_pet_dog_is_absent() { var knightIsAwake = false; var archerIsAwake = true; var prisonerIsAwake = true; var petDogIsPresent = false; Assert.False(QuestLogic.CanFreePrisoner(knightIsAwake, archerIsAwake, prisonerIsAwake, petDogIsPresent)); } [Fact] [Task(4)] public void Can_free_prisoner_if_only_archer_is_asleep_and_pet_dog_is_present() { var knightIsAwake = true; var archerIsAwake = false; var prisonerIsAwake = true; var petDogIsPresent = true; Assert.True(QuestLogic.CanFreePrisoner(knightIsAwake, archerIsAwake, prisonerIsAwake, petDogIsPresent)); } [Fact] [Task(4)] public void Cannot_free_prisoner_if_only_archer_is_asleep_and_pet_dog_is_absent() { var knightIsAwake = true; var archerIsAwake = false; var prisonerIsAwake = true; var petDogIsPresent = false; Assert.False(QuestLogic.CanFreePrisoner(knightIsAwake, archerIsAwake, prisonerIsAwake, petDogIsPresent)); } [Fact] [Task(4)] public void Cannot_free_prisoner_if_only_prisoner_is_asleep_and_pet_dog_is_present() { var knightIsAwake = true; var archerIsAwake = true; var prisonerIsAwake = false; var petDogIsPresent = true; Assert.False(QuestLogic.CanFreePrisoner(knightIsAwake, archerIsAwake, prisonerIsAwake, petDogIsPresent)); } [Fact] [Task(4)] public void Cannot_free_prisoner_if_only_prisoner_is_asleep_and_pet_dog_is_absent() { var knightIsAwake = true; var archerIsAwake = true; var prisonerIsAwake = false; var petDogIsPresent = false; Assert.False(QuestLogic.CanFreePrisoner(knightIsAwake, archerIsAwake, prisonerIsAwake, petDogIsPresent)); } }
using System; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.Versioning; using NuGet.Resources; namespace NuGet { public class PackageManager : IPackageManager { private ILogger _logger; public event EventHandler<PackageOperationEventArgs> PackageInstalling; public event EventHandler<PackageOperationEventArgs> PackageInstalled; public event EventHandler<PackageOperationEventArgs> PackageUninstalling; public event EventHandler<PackageOperationEventArgs> PackageUninstalled; public PackageManager(IPackageRepository sourceRepository, string path) : this(sourceRepository, new DefaultPackagePathResolver(path), new PhysicalFileSystem(path)) { } public PackageManager(IPackageRepository sourceRepository, IPackagePathResolver pathResolver, IFileSystem fileSystem) : this(sourceRepository, pathResolver, fileSystem, new LocalPackageRepository(pathResolver, fileSystem)) { } public PackageManager(IPackageRepository sourceRepository, IPackagePathResolver pathResolver, IFileSystem fileSystem, IPackageRepository localRepository) { if (sourceRepository == null) { throw new ArgumentNullException("sourceRepository"); } if (pathResolver == null) { throw new ArgumentNullException("pathResolver"); } if (fileSystem == null) { throw new ArgumentNullException("fileSystem"); } if (localRepository == null) { throw new ArgumentNullException("localRepository"); } SourceRepository = sourceRepository; PathResolver = pathResolver; FileSystem = fileSystem; LocalRepository = localRepository; } public IFileSystem FileSystem { get; set; } public IPackageRepository SourceRepository { get; private set; } public IPackageRepository LocalRepository { get; private set; } public IPackagePathResolver PathResolver { get; private set; } public ILogger Logger { get { return _logger ?? NullLogger.Instance; } set { _logger = value; } } public void InstallPackage(string packageId) { InstallPackage(packageId, version: null, ignoreDependencies: false, allowPrereleaseVersions: false); } public void InstallPackage(string packageId, SemanticVersion version) { InstallPackage(packageId, version, ignoreDependencies: false, allowPrereleaseVersions: false); } public virtual void InstallPackage(string packageId, SemanticVersion version, bool ignoreDependencies, bool allowPrereleaseVersions) { IPackage package = PackageHelper.ResolvePackage(SourceRepository, LocalRepository, packageId, version, allowPrereleaseVersions); InstallPackage(package, ignoreDependencies, allowPrereleaseVersions); } public virtual void InstallPackage(IPackage package, bool ignoreDependencies, bool allowPrereleaseVersions) { InstallPackage(package, targetFramework: null, ignoreDependencies: ignoreDependencies, allowPrereleaseVersions: allowPrereleaseVersions); } protected void InstallPackage(IPackage package, FrameworkName targetFramework, bool ignoreDependencies, bool allowPrereleaseVersions) { Execute(package, new InstallWalker(LocalRepository, SourceRepository, targetFramework, Logger, ignoreDependencies, allowPrereleaseVersions)); } private void Execute(IPackage package, IPackageOperationResolver resolver) { var operations = resolver.ResolveOperations(package); if (operations.Any()) { foreach (PackageOperation operation in operations) { Execute(operation); } } else if (LocalRepository.Exists(package)) { // If the package wasn't installed by our set of operations, notify the user. Logger.Log(MessageLevel.Info, NuGetResources.Log_PackageAlreadyInstalled, package.GetFullName()); } } protected void Execute(PackageOperation operation) { bool packageExists = LocalRepository.Exists(operation.Package); if (operation.Action == PackageAction.Install) { // If the package is already installed, then skip it if (packageExists) { Logger.Log(MessageLevel.Info, NuGetResources.Log_PackageAlreadyInstalled, operation.Package.GetFullName()); } else { ExecuteInstall(operation.Package); } } else { if (packageExists) { ExecuteUninstall(operation.Package); } } } protected void ExecuteInstall(IPackage package) { PackageOperationEventArgs args = CreateOperation(package); OnInstalling(args); if (args.Cancel) { return; } OnExpandFiles(args); LocalRepository.AddPackage(package); Logger.Log(MessageLevel.Info, NuGetResources.Log_PackageInstalledSuccessfully, package.GetFullName()); OnInstalled(args); } private void ExpandFiles(IPackage package) { var batchProcessor = FileSystem as IBatchProcessor<string>; try { var files = package.GetFiles().ToList(); if (batchProcessor != null) { // Notify the batch processor that the files are being added. This is to allow source controlled file systems // to manage previously uninstalled files. batchProcessor.BeginProcessing(files.Select(p => p.Path), PackageAction.Install); } string packageDirectory = PathResolver.GetPackageDirectory(package); // Add files FileSystem.AddFiles(files, packageDirectory); // If this is a Satellite Package, then copy the satellite files into the related runtime package folder too IPackage runtimePackage; if (PackageUtility.IsSatellitePackage(package, LocalRepository, targetFramework: null, runtimePackage: out runtimePackage)) { var satelliteFiles = package.GetSatelliteFiles(); var runtimePath = PathResolver.GetPackageDirectory(runtimePackage); FileSystem.AddFiles(satelliteFiles, runtimePath); } } finally { if (batchProcessor != null) { batchProcessor.EndProcessing(); } } } public void UninstallPackage(string packageId) { UninstallPackage(packageId, version: null, forceRemove: false, removeDependencies: false); } public void UninstallPackage(string packageId, SemanticVersion version) { UninstallPackage(packageId, version: version, forceRemove: false, removeDependencies: false); } public void UninstallPackage(string packageId, SemanticVersion version, bool forceRemove) { UninstallPackage(packageId, version: version, forceRemove: forceRemove, removeDependencies: false); } public virtual void UninstallPackage(string packageId, SemanticVersion version, bool forceRemove, bool removeDependencies) { if (String.IsNullOrEmpty(packageId)) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId"); } IPackage package = LocalRepository.FindPackage(packageId, version: version); if (package == null) { throw new InvalidOperationException(String.Format( CultureInfo.CurrentCulture, NuGetResources.UnknownPackage, packageId)); } UninstallPackage(package, forceRemove, removeDependencies); } public void UninstallPackage(IPackage package) { UninstallPackage(package, forceRemove: false, removeDependencies: false); } public void UninstallPackage(IPackage package, bool forceRemove) { UninstallPackage(package, forceRemove: forceRemove, removeDependencies: false); } public virtual void UninstallPackage(IPackage package, bool forceRemove, bool removeDependencies) { Execute(package, new UninstallWalker(LocalRepository, new DependentsWalker(LocalRepository, targetFramework: null), targetFramework: null, logger: Logger, removeDependencies: removeDependencies, forceRemove: forceRemove)); } protected virtual void ExecuteUninstall(IPackage package) { PackageOperationEventArgs args = CreateOperation(package); OnUninstalling(args); if (args.Cancel) { return; } OnRemoveFiles(args); LocalRepository.RemovePackage(package); Logger.Log(MessageLevel.Info, NuGetResources.Log_SuccessfullyUninstalledPackage, package.GetFullName()); OnUninstalled(args); } private void RemoveFiles(IPackage package) { string packageDirectory = PathResolver.GetPackageDirectory(package); // If this is a Satellite Package, then remove the files from the related runtime package folder too IPackage runtimePackage; if (PackageUtility.IsSatellitePackage(package, LocalRepository, targetFramework: null, runtimePackage: out runtimePackage)) { var satelliteFiles = package.GetSatelliteFiles(); var runtimePath = PathResolver.GetPackageDirectory(runtimePackage); FileSystem.DeleteFiles(satelliteFiles, runtimePath); } // Remove package files // IMPORTANT: This has to be done AFTER removing satellite files from runtime package, // because starting from 2.1, we read satellite files directly from package files, instead of .nupkg FileSystem.DeleteFiles(package.GetFiles(), packageDirectory); } protected virtual void OnInstalling(PackageOperationEventArgs e) { if (PackageInstalling != null) { PackageInstalling(this, e); } } protected virtual void OnExpandFiles(PackageOperationEventArgs e) { ExpandFiles(e.Package); } protected virtual void OnInstalled(PackageOperationEventArgs e) { if (PackageInstalled != null) { PackageInstalled(this, e); } } protected virtual void OnUninstalling(PackageOperationEventArgs e) { if (PackageUninstalling != null) { PackageUninstalling(this, e); } } protected virtual void OnRemoveFiles(PackageOperationEventArgs e) { RemoveFiles(e.Package); } protected virtual void OnUninstalled(PackageOperationEventArgs e) { if (PackageUninstalled != null) { PackageUninstalled(this, e); } } private PackageOperationEventArgs CreateOperation(IPackage package) { return new PackageOperationEventArgs(package, FileSystem, PathResolver.GetInstallPath(package)); } public void UpdatePackage(string packageId, bool updateDependencies, bool allowPrereleaseVersions) { UpdatePackage(packageId, version: null, updateDependencies: updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions); } public void UpdatePackage(string packageId, IVersionSpec versionSpec, bool updateDependencies, bool allowPrereleaseVersions) { UpdatePackage(packageId, () => SourceRepository.FindPackage(packageId, versionSpec, allowPrereleaseVersions, allowUnlisted: false), updateDependencies, allowPrereleaseVersions); } public void UpdatePackage(string packageId, SemanticVersion version, bool updateDependencies, bool allowPrereleaseVersions) { UpdatePackage(packageId, () => SourceRepository.FindPackage(packageId, version, allowPrereleaseVersions, allowUnlisted: false), updateDependencies, allowPrereleaseVersions); } internal void UpdatePackage(string packageId, Func<IPackage> resolvePackage, bool updateDependencies, bool allowPrereleaseVersions) { if (String.IsNullOrEmpty(packageId)) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId"); } IPackage oldPackage = LocalRepository.FindPackage(packageId); // Check to see if this package is installed if (oldPackage == null) { throw new InvalidOperationException( String.Format(CultureInfo.CurrentCulture, NuGetResources.UnknownPackage, packageId)); } Logger.Log(MessageLevel.Debug, NuGetResources.Debug_LookingForUpdates, packageId); IPackage newPackage = resolvePackage(); if (newPackage != null && oldPackage.Version != newPackage.Version) { UpdatePackage(newPackage, updateDependencies, allowPrereleaseVersions); } else { Logger.Log(MessageLevel.Info, NuGetResources.Log_NoUpdatesAvailable, packageId); } } public void UpdatePackage(IPackage newPackage, bool updateDependencies, bool allowPrereleaseVersions) { Execute(newPackage, new UpdateWalker(LocalRepository, SourceRepository, new DependentsWalker(LocalRepository, targetFramework: null), NullConstraintProvider.Instance, targetFramework: null, logger: Logger, updateDependencies: updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions)); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using NMock2; using NUnit.Framework; using OpenQA.Selenium.Environment; namespace OpenQA.Selenium.Support.UI { [TestFixture] public class SelectBrowserTests : DriverTestFixture { [TestFixtureSetUp] public void RunBeforeAnyTest() { EnvironmentManager.Instance.WebServer.Start(); } [TestFixtureTearDown] public void RunAfterAnyTests() { EnvironmentManager.Instance.CloseCurrentDriver(); EnvironmentManager.Instance.WebServer.Stop(); } [SetUp] public void Setup() { driver.Url = formsPage; } [Test] [ExpectedException(typeof(UnexpectedTagNameException))] public void ShouldThrowAnExceptionIfTheElementIsNotASelectElement() { IWebElement element = driver.FindElement(By.Name("checky")); SelectElement elementWrapper = new SelectElement(element); } [Test] public void ShouldIndicateThatASelectCanSupportMultipleOptions() { IWebElement element = driver.FindElement(By.Name("multi")); SelectElement elementWrapper = new SelectElement(element); Assert.IsTrue(elementWrapper.IsMultiple); } [Test] public void ShouldIndicateThatASelectCanSupportMultipleOptionsWithEmptyMultipleAttribute() { IWebElement element = driver.FindElement(By.Name("select_empty_multiple")); SelectElement elementWrapper = new SelectElement(element); Assert.IsTrue(elementWrapper.IsMultiple); } [Test] public void ShouldIndicateThatASelectCanSupportMultipleOptionsWithTrueMultipleAttribute() { IWebElement element = driver.FindElement(By.Name("multi_true")); SelectElement elementWrapper = new SelectElement(element); Assert.IsTrue(elementWrapper.IsMultiple); } [Test] public void ShouldNotIndicateThatANormalSelectSupportsMulitpleOptions() { IWebElement element = driver.FindElement(By.Name("selectomatic")); SelectElement elementWrapper = new SelectElement(element); Assert.IsFalse(elementWrapper.IsMultiple); } [Test] public void ShouldIndicateThatASelectCanSupportMultipleOptionsWithFalseMultipleAttribute() { IWebElement element = driver.FindElement(By.Name("multi_false")); SelectElement elementWrapper = new SelectElement(element); Assert.IsTrue(elementWrapper.IsMultiple); } [Test] public void ShouldReturnAllOptionsWhenAsked() { IWebElement element = driver.FindElement(By.Name("selectomatic")); SelectElement elementWrapper = new SelectElement(element); IList<IWebElement> returnedOptions = elementWrapper.Options; Assert.AreEqual(4, returnedOptions.Count); string one = returnedOptions[0].Text; Assert.AreEqual("One", one); string two = returnedOptions[1].Text; Assert.AreEqual("Two", two); string three = returnedOptions[2].Text; Assert.AreEqual("Four", three); string four = returnedOptions[3].Text; Assert.AreEqual("Still learning how to count, apparently", four); } [Test] public void ShouldReturnOptionWhichIsSelected() { IWebElement element = driver.FindElement(By.Name("selectomatic")); SelectElement elementWrapper = new SelectElement(element); IList<IWebElement> returnedOptions = elementWrapper.AllSelectedOptions; Assert.AreEqual(1, returnedOptions.Count); string one = returnedOptions[0].Text; Assert.AreEqual("One", one); } [Test] public void ShouldReturnOptionsWhichAreSelected() { IWebElement element = driver.FindElement(By.Name("multi")); SelectElement elementWrapper = new SelectElement(element); IList<IWebElement> returnedOptions = elementWrapper.AllSelectedOptions; Assert.AreEqual(2, returnedOptions.Count); string one = returnedOptions[0].Text; Assert.AreEqual("Eggs", one); string two = returnedOptions[1].Text; Assert.AreEqual("Sausages", two); } [Test] public void ShouldReturnFirstSelectedOption() { IWebElement element = driver.FindElement(By.Name("multi")); SelectElement elementWrapper = new SelectElement(element); IWebElement firstSelected = elementWrapper.AllSelectedOptions[0]; Assert.AreEqual("Eggs", firstSelected.Text); } // [Test] // [ExpectedException(typeof(NoSuchElementException))] // The .NET bindings do not have a "FirstSelectedOption" property, // and no one has asked for it to this point. Given that, this test // is not a valid test. public void ShouldThrowANoSuchElementExceptionIfNothingIsSelected() { IWebElement element = driver.FindElement(By.Name("select_empty_multiple")); SelectElement elementWrapper = new SelectElement(element); Assert.AreEqual(0, elementWrapper.AllSelectedOptions.Count); } [Test] public void ShouldAllowOptionsToBeSelectedByVisibleText() { IWebElement element = driver.FindElement(By.Name("select_empty_multiple")); SelectElement elementWrapper = new SelectElement(element); elementWrapper.SelectByText("select_2"); IWebElement firstSelected = elementWrapper.AllSelectedOptions[0]; Assert.AreEqual("select_2", firstSelected.Text); } [Test] [ExpectedException(typeof(NoSuchElementException))] public void ShouldNotAllowInvisibleOptionsToBeSelectedByVisibleText() { IWebElement element = driver.FindElement(By.Name("invisi_select")); SelectElement elementWrapper = new SelectElement(element); elementWrapper.SelectByText("Apples"); } [Test] [ExpectedException(typeof(NoSuchElementException))] public void ShouldThrowExceptionOnSelectByVisibleTextIfOptionDoesNotExist() { IWebElement element = driver.FindElement(By.Name("select_empty_multiple")); SelectElement elementWrapper = new SelectElement(element); elementWrapper.SelectByText("not there"); } [Test] public void ShouldAllowOptionsToBeSelectedByIndex() { IWebElement element = driver.FindElement(By.Name("select_empty_multiple")); SelectElement elementWrapper = new SelectElement(element); elementWrapper.SelectByIndex(1); IWebElement firstSelected = elementWrapper.AllSelectedOptions[0]; Assert.AreEqual("select_2", firstSelected.Text); } [Test] [ExpectedException(typeof(NoSuchElementException))] public void ShouldThrowExceptionOnSelectByIndexIfOptionDoesNotExist() { IWebElement element = driver.FindElement(By.Name("select_empty_multiple")); SelectElement elementWrapper = new SelectElement(element); elementWrapper.SelectByIndex(10); } [Test] public void ShouldAllowOptionsToBeSelectedByReturnedValue() { IWebElement element = driver.FindElement(By.Name("select_empty_multiple")); SelectElement elementWrapper = new SelectElement(element); elementWrapper.SelectByValue("select_2"); IWebElement firstSelected = elementWrapper.AllSelectedOptions[0]; Assert.AreEqual("select_2", firstSelected.Text); } [Test] [ExpectedException(typeof(NoSuchElementException))] public void ShouldThrowExceptionOnSelectByReturnedValueIfOptionDoesNotExist() { IWebElement element = driver.FindElement(By.Name("select_empty_multiple")); SelectElement elementWrapper = new SelectElement(element); elementWrapper.SelectByValue("not there"); } [Test] public void ShouldAllowUserToDeselectAllWhenSelectSupportsMultipleSelections() { IWebElement element = driver.FindElement(By.Name("multi")); SelectElement elementWrapper = new SelectElement(element); elementWrapper.DeselectAll(); IList<IWebElement> returnedOptions = elementWrapper.AllSelectedOptions; Assert.AreEqual(0, returnedOptions.Count); } [Test] [ExpectedException(typeof(InvalidOperationException))] public void ShouldNotAllowUserToDeselectAllWhenSelectDoesNotSupportMultipleSelections() { IWebElement element = driver.FindElement(By.Name("selectomatic")); SelectElement elementWrapper = new SelectElement(element); elementWrapper.DeselectAll(); } [Test] public void ShouldAllowUserToDeselectOptionsByVisibleText() { IWebElement element = driver.FindElement(By.Name("multi")); SelectElement elementWrapper = new SelectElement(element); elementWrapper.DeselectByText("Eggs"); IList<IWebElement> returnedOptions = elementWrapper.AllSelectedOptions; Assert.AreEqual(1, returnedOptions.Count); } [Test] [ExpectedException(typeof(NoSuchElementException))] public void ShouldNotAllowUserToDeselectOptionsByInvisibleText() { IWebElement element = driver.FindElement(By.Name("invisi_select")); SelectElement elementWrapper = new SelectElement(element); elementWrapper.DeselectByText("Apples"); } [Test] public void ShouldAllowOptionsToBeDeselectedByIndex() { IWebElement element = driver.FindElement(By.Name("multi")); SelectElement elementWrapper = new SelectElement(element); elementWrapper.DeselectByIndex(0); IList<IWebElement> returnedOptions = elementWrapper.AllSelectedOptions; Assert.AreEqual(1, returnedOptions.Count); } [Test] public void ShouldAllowOptionsToBeDeselectedByReturnedValue() { IWebElement element = driver.FindElement(By.Name("multi")); SelectElement elementWrapper = new SelectElement(element); elementWrapper.DeselectByValue("eggs"); IList<IWebElement> returnedOptions = elementWrapper.AllSelectedOptions; Assert.AreEqual(1, returnedOptions.Count); } } }
using System; using System.Collections.Generic; using CocosSharp; using System.Diagnostics; using System.Linq; using Shapes; using System.Threading.Tasks; using Patternizer; using Sampleapp.Shapes; namespace Sampleapp { public class MainLayer : CCLayerColor { private bool _drawDebug = true; private CCDrawNode _canvasNode; private CCDrawNode _shapeNode; private CCPoint _lastKnownPoint; private LineRecognizer _lineRecognizer; private ShapeNode _trackedShape; private CCDrawNode _recognizerCanvasNode; private List<Line> _buffer = new List<Line>(); private const float _clearTTLResetValue = 1f; private float _clearTTL = 0f; private PatternEvaluator _patternEvaluator; public MainLayer() : base(CCColor4B.AliceBlue) { _canvasNode = new CCDrawNode(); _recognizerCanvasNode = new CCDrawNode(); _lineRecognizer = new LineRecognizer(); _shapeNode = new CCDrawNode(); AddChild(_shapeNode); AddChild(_canvasNode); AddChild(_recognizerCanvasNode); if (_drawDebug) { _lineRecognizer.LineFound = (line) => _recognizerCanvasNode.DrawLine(line.P1.ToCCPoint(), line.P2.ToCCPoint(), 5, CCColor4B.Blue); } // Register patterns (concept) _patternEvaluator = new PatternEvaluator(); _patternEvaluator.Add("button").When(Pattern.WideRectangle); _patternEvaluator.Add("image").When(Pattern.Cross); _patternEvaluator.Add("text").When(p => p.Repetitive(ip => ip.MovesRight().MovesLeftAndDown()).MovesRight()); _patternEvaluator.Add("entry").When(p => p.MovesDown().MovesRight().MovesUp().Bounds(BoundsDescriptor.IsWide)); _patternEvaluator.Add("lineoftext").When(p => p.MovesRight()); _patternEvaluator.Add("delete").When(p => p.MovesRightAndUp()); } protected override void AddedToScene () { base.AddedToScene(); // Use the bounds to layout the positioning of our drawable assets CCRect bounds = VisibleBoundsWorldspace; var l = new CCEventListenerTouchAllAtOnce(); l.OnTouchesBegan += OnTouchesBegan; l.OnTouchesMoved += OnTouchesMoved; l.OnTouchesEnded += OnTouchesEnded; AddEventListener(l, this); } void OnTouchesBegan(List<CCTouch> touches, CCEvent touchEvent) { touches = FindUniqueTouches(touches); if (touches.Count == 1) { var touch = touches[0]; _lastKnownPoint = touch.Location; _trackedShape = null; _lineRecognizer.Clear(); } else if (touches.Count > 1) { EvaluateResizeOrMoveStart(touches); } } void EvaluateResizeOrMoveStart(List<CCTouch> touches) { touches = FindUniqueTouches (touches); var touch = touches [0]; _lastKnownPoint = touch.Location; if (_shapeNode.Children != null) { foreach (var obj in _shapeNode.Children) { if (obj is ShapeNode) { if (obj.BoundingBox.ContainsPoint (_lastKnownPoint)) { _trackedShape = obj as ShapeNode; } } } } } void OnTouchesMoved(List<CCTouch> touches, CCEvent touchEvent) { touches = FindUniqueTouches(touches); _clearTTL = _clearTTLResetValue; if (touches.Count == 1) { var touch = touches[0]; if (_trackedShape != null) { _trackedShape.Position += touch.Delta; } else { var location = touch.LocationOnScreen; _canvasNode.DrawLine(_lastKnownPoint, touch.Location, 5, CCColor4B.Red, CCLineCap.Round); if (_drawDebug) { _canvasNode.DrawSolidCircle(_lastKnownPoint, 5, CCColor4B.Green); } _lineRecognizer.RegisterPoint(_lastKnownPoint.X, _lastKnownPoint.Y); _lastKnownPoint = touch.Location; } } else if (touches.Count > 1 && _trackedShape != null) { var touch = touches[0]; _trackedShape.Position += touch.Delta; var t1 = touches[0]; var t2 = touches[1]; CCPoint p1; CCPoint p2; if (t1.Location.X < t2.Location.X) { p1.X = t1.Delta.X; p2.X = t2.Delta.X; } else { p1.X = t2.Delta.X; p2.X = t1.Delta.X; } if (t1.Location.Y < t2.Location.Y) { p1.Y = t1.Delta.Y; p2.Y = t2.Delta.Y; } else { p1.Y = t2.Delta.Y; p2.Y = t1.Delta.Y; } _trackedShape.SetNewPoints(_trackedShape.P1 + p1, _trackedShape.P2 + p2); } else { _lineRecognizer.Clear(); EvaluateResizeOrMoveStart(touches); } } private void OnTouchesEnded(List<CCTouch> touches, CCEvent touchEvent) { touches = FindUniqueTouches(touches); if (_trackedShape != null) { _trackedShape = null; return; } var lines = _lineRecognizer.End(); // Concept if (lines.Count == 0 && _shapeNode.ChildrenCount > 0) { // Most likely a touch, evaulate the touch on known child nodes foreach (var node in _shapeNode.Children.OfType<ShapeNode>()) { node.EvaulateTap(touches.First().Location); } } else if (lines.Count > 0) { EvaluateLines(lines); Debug.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(_lineRecognizer.AllPoints)); } } public override void Update (float dt) { _clearTTL -= dt; if (_clearTTL > 0 && _clearTTL < 0.3f) { IsColorModifiedByOpacity = true; IsOpacityCascaded = true; var diff = (_clearTTL / 0.3f) * 255; _recognizerCanvasNode.IsColorModifiedByOpacity = true; _recognizerCanvasNode.Opacity = (byte)(int)diff; } if (_clearTTL < 0) { _buffer.Clear(); _recognizerCanvasNode.Clear(); _canvasNode.Clear(); } base.Update(dt); } /// <summary> /// Evaluates the lines we have in the buffer /// </summary> /// <param name="lines">Lines</param> /// <remarks> /// We keep a buffer of lines. If a list of lines cannot be /// evaluated we wait for another second or so to allow for more lines. /// When that times out and no shape can be determined, then /// we clear the buffer. /// </remarks> private void EvaluateLines(List<Line> lines) { _clearTTL = _clearTTLResetValue; _buffer.AddRange(lines); var result = _patternEvaluator.Evaluate(_buffer); if (!result.IsValid) { return; } Debug.WriteLine("evaluation succeeded: " + result.Key); switch (result.Key) { case "button": var rectShape = new RectangleShape() { P1 = result.UpperLeft.ToCCPoint(), P2 = result.LowerRight.ToCCPoint() }; _shapeNode.AddChild(new ShapeNode(rectShape)); _recognizerCanvasNode.Clear(); break; case "image": var imageShape = new ImageShape() { P1 = result.UpperLeft.ToCCPoint(), P2 = result.LowerRight.ToCCPoint() }; _shapeNode.AddChild(new ShapeNode(imageShape)); _recognizerCanvasNode.Clear(); break; case "text": var textShape = new TextShape() { P1 = result.UpperLeft.ToCCPoint(), P2 = result.LowerRight.ToCCPoint() }; _shapeNode.AddChild(new ShapeNode(textShape)); _recognizerCanvasNode.Clear(); break; case "entry": var entryShape = new EntryShape() { P1 = result.UpperLeft.ToCCPoint(), P2 = result.LowerRight.ToCCPoint() }; _shapeNode.AddChild(new ShapeNode(entryShape)); _recognizerCanvasNode.Clear(); break; case "lineoftext": var lineoftext = new LineOfTextShape() { P1 = result.UpperLeft.ToCCPoint(), P2 = result.LowerRight.ToCCPoint() }; _shapeNode.AddChild(new ShapeNode(lineoftext)); _recognizerCanvasNode.Clear(); break; case "delete": var deleteShape = new DeleteShape() { P1 = result.UpperLeft.ToCCPoint(), P2 = result.LowerRight.ToCCPoint() }; var victims = IsShapeOverOtherShapes(deleteShape); foreach (var victim in victims) { _shapeNode.RemoveChild(victim); } _recognizerCanvasNode.Clear(); break; } _canvasNode.Clear(); _buffer.Clear(); } private ShapeNode IsShapeWithinOtherShape(Shape shape) { if (_shapeNode.ChildrenCount == 0) { return null; } foreach (var item in _shapeNode.Children.OfType<ShapeNode>()) { var bounds = shape.Bounds(); if (item.BoundingBox.MinX < bounds.MinX && item.BoundingBox.MaxX > bounds.MaxX && item.BoundingBox.MinY < bounds.MinY && item.BoundingBox.MaxY > bounds.MaxY) { return item; } } return null; } private List<ShapeNode> IsShapeOverOtherShapes(Shape shape) { var result = new List<ShapeNode>(); foreach (var item in _shapeNode.Children.OfType<ShapeNode>()) { var bounds = shape.Bounds(); if (bounds.IntersectsRect(item.BoundingBox)) result.Add(item); } return result; } private static List<CCTouch> FindUniqueTouches (List<CCTouch> touches) { var list = new List<CCTouch>(); foreach (var touch in touches) { if (!list.Any(e => e.Id == touch.Id)) { list.Add(touch); } } return list; } } }
// <copyright file="InMemoryFileSystem.cs" company="Fubar Development Junker"> // Copyright (c) Fubar Development Junker. All rights reserved. // </copyright> using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using FubarDev.FtpServer.BackgroundTransfer; using FubarDev.FtpServer.FileSystem.Error; namespace FubarDev.FtpServer.FileSystem.InMemory { /// <summary> /// The implementation of the in-memory file system. /// </summary> public class InMemoryFileSystem : IUnixFileSystem { /// <summary> /// Initializes a new instance of the <see cref="InMemoryFileSystem"/> class. /// </summary> /// <param name="fileSystemEntryComparer">The file system entry name comparer.</param> public InMemoryFileSystem(StringComparer fileSystemEntryComparer) { Root = new InMemoryDirectoryEntry( null, string.Empty, new Dictionary<string, IUnixFileSystemEntry>(fileSystemEntryComparer)); FileSystemEntryComparer = fileSystemEntryComparer; } /// <inheritdoc /> public bool SupportsAppend { get; } = true; /// <inheritdoc /> public bool SupportsNonEmptyDirectoryDelete { get; } = true; /// <inheritdoc /> public StringComparer FileSystemEntryComparer { get; } /// <inheritdoc /> public IUnixDirectoryEntry Root { get; } /// <inheritdoc /> public Task<IReadOnlyList<IUnixFileSystemEntry>> GetEntriesAsync( IUnixDirectoryEntry directoryEntry, CancellationToken cancellationToken) { var entry = (InMemoryDirectoryEntry)directoryEntry; lock (entry.ChildrenLock) { var children = entry.Children.Values.ToList(); return Task.FromResult<IReadOnlyList<IUnixFileSystemEntry>>(children); } } /// <inheritdoc /> public Task<IUnixFileSystemEntry?> GetEntryByNameAsync(IUnixDirectoryEntry directoryEntry, string name, CancellationToken cancellationToken) { var entry = (InMemoryDirectoryEntry)directoryEntry; lock (entry.ChildrenLock) { if (entry.Children.TryGetValue(name, out var childEntry)) { return Task.FromResult<IUnixFileSystemEntry?>(childEntry); } } return Task.FromResult<IUnixFileSystemEntry?>(null); } /// <inheritdoc /> public Task<IUnixFileSystemEntry> MoveAsync( IUnixDirectoryEntry parent, IUnixFileSystemEntry source, IUnixDirectoryEntry target, string fileName, CancellationToken cancellationToken) { var parentEntry = (InMemoryDirectoryEntry)parent; var sourceEntry = (InMemoryFileSystemEntry)source; var targetEntry = (InMemoryDirectoryEntry)target; lock (parentEntry.ChildrenLock) { if (!parentEntry.Children.Remove(source.Name)) { targetEntry.Children.Remove(fileName); throw new FileUnavailableException( $"The source file {source.Name} couldn't be found in directory {parentEntry.Name}"); } } var now = DateTimeOffset.Now; parentEntry.SetLastWriteTime(now); targetEntry.SetLastWriteTime(now); lock (targetEntry.ChildrenLock) { sourceEntry.Parent = targetEntry; sourceEntry.Name = fileName; targetEntry.Children.Add(fileName, source); } return Task.FromResult(source); } /// <inheritdoc /> public Task UnlinkAsync(IUnixFileSystemEntry entry, CancellationToken cancellationToken) { var fsEntry = (InMemoryFileSystemEntry)entry; var parent = fsEntry.Parent; if (parent != null) { lock (parent.ChildrenLock) { if (parent.Children.Remove(entry.Name)) { parent.SetLastWriteTime(DateTimeOffset.Now); fsEntry.Parent = null; } } } return Task.CompletedTask; } /// <inheritdoc /> public Task<IUnixDirectoryEntry> CreateDirectoryAsync( IUnixDirectoryEntry targetDirectory, string directoryName, CancellationToken cancellationToken) { var dirEntry = (InMemoryDirectoryEntry)targetDirectory; var childEntry = new InMemoryDirectoryEntry( dirEntry, directoryName, new Dictionary<string, IUnixFileSystemEntry>(FileSystemEntryComparer)); lock (dirEntry.ChildrenLock) { dirEntry.Children.Add(directoryName, childEntry); } var now = DateTimeOffset.Now; dirEntry.SetLastWriteTime(now) .SetCreateTime(now); return Task.FromResult<IUnixDirectoryEntry>(childEntry); } /// <inheritdoc /> public Task<Stream> OpenReadAsync(IUnixFileEntry fileEntry, long startPosition, CancellationToken cancellationToken) { var entry = (InMemoryFileEntry)fileEntry; var stream = new MemoryStream(entry.Data) { Position = startPosition, }; return Task.FromResult<Stream>(stream); } /// <inheritdoc /> public async Task<IBackgroundTransfer?> AppendAsync(IUnixFileEntry fileEntry, long? startPosition, Stream data, CancellationToken cancellationToken) { var entry = (InMemoryFileEntry)fileEntry; // Copy original data into memory stream var temp = new MemoryStream(); temp.Write(entry.Data, 0, entry.Data.Length); // Set new write position (if given) if (startPosition.HasValue) { temp.Position = startPosition.Value; } // Copy given data await data.CopyToAsync(temp, 81920, cancellationToken) .ConfigureAwait(false); // Update data entry.Data = temp.ToArray(); entry.SetLastWriteTime(DateTimeOffset.Now); return null; } /// <inheritdoc /> public async Task<IBackgroundTransfer?> CreateAsync( IUnixDirectoryEntry targetDirectory, string fileName, Stream data, CancellationToken cancellationToken) { var temp = new MemoryStream(); await data.CopyToAsync(temp, 81920, cancellationToken) .ConfigureAwait(false); var targetEntry = (InMemoryDirectoryEntry)targetDirectory; var entry = new InMemoryFileEntry(targetEntry, fileName, temp.ToArray()); lock (targetEntry.ChildrenLock) { targetEntry.Children.Add(fileName, entry); } var now = DateTimeOffset.Now; targetEntry.SetLastWriteTime(now); entry .SetLastWriteTime(now) .SetCreateTime(now); return null; } /// <inheritdoc /> public async Task<IBackgroundTransfer?> ReplaceAsync(IUnixFileEntry fileEntry, Stream data, CancellationToken cancellationToken) { var temp = new MemoryStream(); await data.CopyToAsync(temp, 81920, cancellationToken) .ConfigureAwait(false); var entry = (InMemoryFileEntry)fileEntry; entry.Data = temp.ToArray(); var now = DateTimeOffset.Now; entry.SetLastWriteTime(now); return null; } /// <inheritdoc /> public Task<IUnixFileSystemEntry> SetMacTimeAsync( IUnixFileSystemEntry entry, DateTimeOffset? modify, DateTimeOffset? access, DateTimeOffset? create, CancellationToken cancellationToken) { var fsEntry = (InMemoryFileSystemEntry)entry; if (modify != null) { fsEntry.SetLastWriteTime(modify.Value); } if (create != null) { fsEntry.SetCreateTime(create.Value); } return Task.FromResult(entry); } } }
using System; using AutoFixture.Idioms; using Xunit; namespace AutoFixture.IdiomsUnitTest { public class WhiteSpaceStringBehaviorExpectationTest { [Fact] public void SutIsBehaviorExpectation() { // Arrange var expectation = new WhiteSpaceStringBehaviorExpectation(); // Act & Assert Assert.IsAssignableFrom<IBehaviorExpectation>(expectation); } [Fact] public void VerifyNullCommandThrows() { // Arrange var expectation = new WhiteSpaceStringBehaviorExpectation(); // Act & Assert Assert.Throws<ArgumentNullException>(() => expectation.Verify(default)); } [Fact] public void VerifyExecutesCommandWhenRequestedTypeIsString() { // Arrange var commandExecuted = false; var command = new DelegatingGuardClauseCommand { OnExecute = (v) => { commandExecuted = true; throw new ArgumentException(string.Empty, "paramName"); }, RequestedType = typeof(string), RequestedParameterName = "paramName" }; var expectation = new WhiteSpaceStringBehaviorExpectation(); // Act expectation.Verify(command); // Assert Assert.True(commandExecuted); } [Theory] [InlineData(typeof(int))] [InlineData(typeof(Guid))] [InlineData(typeof(object))] [InlineData(typeof(Version))] [InlineData(typeof(decimal))] public void VerifyDoesNotExecuteCommandWhenRequestedTypeNotString(Type type) { // Arrange var commandExecuted = false; var command = new DelegatingGuardClauseCommand { OnExecute = (v) => commandExecuted = true, RequestedType = type }; var expectation = new WhiteSpaceStringBehaviorExpectation(); // Act expectation.Verify(command); // Assert Assert.False(commandExecuted); } [Fact] public void VerifyDoesNotThrowWhenCommandThrowsArgumentExceptionWithMatchingParameterName() { // Arrange var command = new DelegatingGuardClauseCommand { OnExecute = v => throw new ArgumentException(string.Empty, "paramName"), RequestedType = typeof(string), RequestedParameterName = "paramName" }; var expectation = new WhiteSpaceStringBehaviorExpectation(); // Act var actual = Record.Exception(() => expectation.Verify(command)); // Assert Assert.Null(actual); } [Fact] public void VerifyThrowsExpectedExceptionWhenCommandDoesNotThrow() { // Arrange var expected = new Exception(); var command = new DelegatingGuardClauseCommand { OnExecute = v => { }, OnCreateException = v => expected, RequestedType = typeof(string) }; var expectation = new WhiteSpaceStringBehaviorExpectation(); // Act var actual = Record.Exception(() => expectation.Verify(command)); // Assert Assert.Equal(expected, actual); } [Fact] public void VerifyThrowsExceptionWithExpectedValueWhenCommandDoesNotThrow() { // Arrange var command = new DelegatingGuardClauseCommand { OnExecute = v => { }, OnCreateException = v => new Exception(v), RequestedType = typeof(string) }; var expectation = new WhiteSpaceStringBehaviorExpectation(); // Act var actual = Record.Exception(() => expectation.Verify(command)); // Assert Assert.Equal("<white space>", actual.Message); } [Fact] public void VerifyThrowsExpectedExceptionWhenCommandThrowsNonArgumentException() { // Arrange var expected = new Exception(); var command = new DelegatingGuardClauseCommand { OnExecute = v => throw new Exception(), OnCreateExceptionWithInner = (v, e) => expected, RequestedType = typeof(string) }; var expectation = new WhiteSpaceStringBehaviorExpectation(); // Act var actual = Record.Exception(() => expectation.Verify(command)); // Assert Assert.Equal(expected, actual); } [Fact] public void VerifyThrowsWithExpectedValueWhenCommandThrowsNonArgumentException() { // Arrange var command = new DelegatingGuardClauseCommand { OnExecute = v => throw new Exception(), OnCreateExceptionWithInner = (v, e) => new Exception(v, e), RequestedType = typeof(string) }; var expectation = new WhiteSpaceStringBehaviorExpectation(); // Act var actual = Record.Exception(() => expectation.Verify(command)); // Assert Assert.Equal("<white space>", actual.Message); } [Fact] public void VerifyThrowsWithExpectedInnerExceptionWhenCommandThrowsNonArgumentException() { // Arrange var expected = new Exception(); var command = new DelegatingGuardClauseCommand { OnExecute = v => throw expected, OnCreateExceptionWithInner = (v, e) => new Exception(v, e), RequestedType = typeof(string) }; var expectation = new WhiteSpaceStringBehaviorExpectation(); // Act var actual = Record.Exception(() => expectation.Verify(command)); // Assert Assert.Equal(expected, actual.InnerException); } [Fact] public void VerifyThrowsExpectedExceptionWhenCommandThrowsArgumentExceptionWithWrongParameterName() { // Arrange var expected = new Exception(); var command = new DelegatingGuardClauseCommand { OnExecute = v => throw new ArgumentException(string.Empty, "wrongParamName"), OnCreateExceptionWithFailureReason = (v, m, e) => expected, RequestedType = typeof(string), RequestedParameterName = "expectedParamName" }; var expectation = new WhiteSpaceStringBehaviorExpectation(); // Act var actual = Record.Exception(() => expectation.Verify(command)); // Assert Assert.Equal(expected, actual); } [Fact] public void VerifyThrowsExceptionWithExpectedMessageWhenCommandThrowsArgumentExceptionWithWrongParameterName() { // Arrange var command = new DelegatingGuardClauseCommand { OnExecute = v => throw new ArgumentException(string.Empty, "wrongParamName"), OnCreateExceptionWithFailureReason = (v, m, e) => new Exception(m, e), RequestedType = typeof(string), RequestedParameterName = "expectedParamName" }; var expectation = new WhiteSpaceStringBehaviorExpectation(); // Act var actual = Record.Exception(() => expectation.Verify(command)); // Assert Assert.EndsWith( $"Expected parameter name: expectedParamName{Environment.NewLine}Actual parameter name: wrongParamName", actual.Message); } [Fact] public void VerifyThrowsExceptionWithExpectedInnerWhenCommandThrowsArgumentExceptionWithWrongParameterName() { // Arrange var expected = new ArgumentException(string.Empty, "wrongParamName"); var command = new DelegatingGuardClauseCommand { OnExecute = v => throw expected, OnCreateExceptionWithFailureReason = (v, m, e) => new Exception(m, e), RequestedType = typeof(string), RequestedParameterName = "expectedParamName" }; var expectation = new WhiteSpaceStringBehaviorExpectation(); // Act var actual = Record.Exception(() => expectation.Verify(command)); // Assert Assert.Equal(expected, actual.InnerException); } } }
// *********************************************************************** // Copyright (c) 2006 Charlie Poole, Rob Prouse // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using NUnit.Compatibility; using NUnit.Framework.Constraints; using NUnit.TestUtilities; using NUnit.TestUtilities.Collections; using NUnit.TestUtilities.Comparers; namespace NUnit.Framework.Assertions { /// <summary> /// Test Library for the NUnit CollectionAssert class. /// </summary> [TestFixture()] public class CollectionAssertTest { #region AllItemsAreInstancesOfType [Test()] public void ItemsOfType() { var collection = new SimpleObjectCollection("x", "y", "z"); CollectionAssert.AllItemsAreInstancesOfType(collection,typeof(string)); } [Test] public void ItemsOfTypeFailure() { var collection = new SimpleObjectCollection("x", "y", new object()); var expectedMessage = " Expected: all items instance of <System.String>" + Environment.NewLine + " But was: < \"x\", \"y\", <System.Object> >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreInstancesOfType(collection,typeof(string))); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } #endregion #region AllItemsAreNotNull [Test()] public void ItemsNotNull() { var collection = new SimpleObjectCollection("x", "y", "z"); CollectionAssert.AllItemsAreNotNull(collection); } [Test] public void ItemsNotNullFailure() { var collection = new SimpleObjectCollection("x", null, "z"); var expectedMessage = " Expected: all items not null" + Environment.NewLine + " But was: < \"x\", null, \"z\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreNotNull(collection)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } #endregion #region AllItemsAreUnique [Test] public void Unique_WithObjects() { CollectionAssert.AllItemsAreUnique( new SimpleObjectCollection(new object(), new object(), new object())); } [Test] public void Unique_WithStrings() { CollectionAssert.AllItemsAreUnique(new SimpleObjectCollection("x", "y", "z")); } [Test] public void Unique_WithNull() { CollectionAssert.AllItemsAreUnique(new SimpleObjectCollection("x", "y", null, "z")); } [Test] public void UniqueFailure() { var expectedMessage = " Expected: all items unique" + Environment.NewLine + " But was: < \"x\", \"y\", \"x\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AllItemsAreUnique(new SimpleObjectCollection("x", "y", "x"))); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void UniqueFailure_WithTwoNulls() { Assert.Throws<AssertionException>( () => CollectionAssert.AllItemsAreUnique(new SimpleObjectCollection("x", null, "y", null, "z"))); } static readonly IEnumerable<int> RANGE = Enumerable.Range(0, 10000); static readonly IEnumerable[] PerformanceData = { RANGE, new List<int>(RANGE), new List<double>(RANGE.Select(v => (double)v)), new List<string>(RANGE.Select(v => v.ToString())) }; [TestCaseSource(nameof(PerformanceData))] public void PerformanceTests(IEnumerable values) { Warn.Unless(() => CollectionAssert.AllItemsAreUnique(values), HelperConstraints.HasMaxTime(100)); } #endregion #region AreEqual [Test] public void AreEqual() { var set1 = new SimpleEnumerable("x", "y", "z"); var set2 = new SimpleEnumerable("x", "y", "z"); CollectionAssert.AreEqual(set1,set2); CollectionAssert.AreEqual(set1,set2,new TestComparer()); Assert.AreEqual(set1,set2); } [Test] public void AreEqualFailCount() { var set1 = new SimpleObjectList("x", "y", "z"); var set2 = new SimpleObjectList("x", "y", "z", "a"); var expectedMessage = " Expected is <NUnit.TestUtilities.Collections.SimpleObjectList> with 3 elements, actual is <NUnit.TestUtilities.Collections.SimpleObjectList> with 4 elements" + Environment.NewLine + " Values differ at index [3]" + Environment.NewLine + " Extra: < \"a\" >"; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEqual(set1, set2, new TestComparer())); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void AreEqualFail() { var set1 = new SimpleObjectList("x", "y", "z"); var set2 = new SimpleObjectList("x", "y", "a"); var expectedMessage = " Expected and actual are both <NUnit.TestUtilities.Collections.SimpleObjectList> with 3 elements" + Environment.NewLine + " Values differ at index [2]" + Environment.NewLine + " String lengths are both 1. Strings differ at index 0." + Environment.NewLine + " Expected: \"z\"" + Environment.NewLine + " But was: \"a\"" + Environment.NewLine + " -----------^" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEqual(set1,set2,new TestComparer())); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void AreEqual_HandlesNull() { object[] set1 = new object[3]; object[] set2 = new object[3]; CollectionAssert.AreEqual(set1,set2); CollectionAssert.AreEqual(set1,set2,new TestComparer()); } [Test] public void EnsureComparerIsUsed() { // Create two collections int[] array1 = new int[2]; int[] array2 = new int[2]; array1[0] = 4; array1[1] = 5; array2[0] = 99; array2[1] = -99; CollectionAssert.AreEqual(array1, array2, new AlwaysEqualComparer()); } [Test] public void AreEqual_UsingIterator() { int[] array = new int[] { 1, 2, 3 }; CollectionAssert.AreEqual(array, CountToThree()); } [Test] public void AreEqualFails_ObjsUsingIEquatable() { IEnumerable set1 = new SimpleEnumerableWithIEquatable("x", "y", "z"); IEnumerable set2 = new SimpleEnumerableWithIEquatable("x", "z", "z"); CollectionAssert.AreNotEqual(set1, set2); Assert.Throws<AssertionException>(() => CollectionAssert.AreEqual(set1, set2)); } [Test] public void IEnumerablesAreEqualWithCollectionsObjectsImplemetingIEquatable() { IEnumerable set1 = new SimpleEnumerable(new SimpleIEquatableObj()); IEnumerable set2 = new SimpleEnumerable(new SimpleIEquatableObj()); CollectionAssert.AreEqual(set1, set2); } [Test] public void ArraysAreEqualWithCollectionsObjectsImplementingIEquatable() { SimpleIEquatableObj[] set1 = new SimpleIEquatableObj[] { new SimpleIEquatableObj() }; SimpleIEquatableObj[] set2 = new SimpleIEquatableObj[] { new SimpleIEquatableObj() }; CollectionAssert.AreEqual(set1, set2); } IEnumerable CountToThree() { yield return 1; yield return 2; yield return 3; } [Test] public void AreEqual_UsingIterator_Fails() { int[] array = new int[] { 1, 3, 5 }; AssertionException ex = Assert.Throws<AssertionException>( delegate { CollectionAssert.AreEqual(array, CountToThree()); } ); Assert.That(ex.Message, Does.Contain("Values differ at index [1]").And. Contains("Expected: 3").And. Contains("But was: 2")); } #if !NET20 [Test] public void AreEqual_UsingLinqQuery() { int[] array = new int[] { 1, 2, 3 }; CollectionAssert.AreEqual(array, array.Select((item) => item)); } [Test] public void AreEqual_UsingLinqQuery_Fails() { int[] array = new int[] { 1, 2, 3 }; AssertionException ex = Assert.Throws<AssertionException>( delegate { CollectionAssert.AreEqual(array, array.Select((item) => item * 2)); } ); Assert.That(ex.Message, Does.Contain("Values differ at index [0]").And. Contains("Expected: 1").And. Contains("But was: 2")); } #endif [Test] public void AreEqual_IEquatableImplementationIsIgnored() { var x = new Constraints.EquatableWithEnumerableObject<int>(new[] { 1, 2, 3, 4, 5 }, 42); var y = new Constraints.EnumerableObject<int>(new[] { 1, 2, 3, 4, 5 }, 15); // They are not equal using Assert Assert.AreNotEqual(x, y, "Assert 1"); Assert.AreNotEqual(y, x, "Assert 2"); // Using CollectionAssert they are equal CollectionAssert.AreEqual(x, y, "CollectionAssert 1"); CollectionAssert.AreEqual(y, x, "CollectionAssert 2"); } #endregion #region AreEquivalent [Test] public void Equivalent() { ICollection set1 = new SimpleObjectCollection("x", "y", "z"); ICollection set2 = new SimpleObjectCollection("z", "y", "x"); CollectionAssert.AreEquivalent(set1,set2); } [Test] public void EquivalentFailOne() { ICollection set1 = new SimpleObjectCollection("x", "y", "z"); ICollection set2 = new SimpleObjectCollection("x", "y", "x"); var expectedMessage = " Expected: equivalent to < \"x\", \"y\", \"z\" >" + Environment.NewLine + " But was: < \"x\", \"y\", \"x\" >" + Environment.NewLine + " Missing (1): < \"z\" >" + Environment.NewLine + " Extra (1): < \"x\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEquivalent(set1,set2)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void EquivalentFailTwo() { ICollection set1 = new SimpleObjectCollection("x", "y", "x"); ICollection set2 = new SimpleObjectCollection("x", "y", "z"); var expectedMessage = " Expected: equivalent to < \"x\", \"y\", \"x\" >" + Environment.NewLine + " But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine + " Missing (1): < \"x\" >" + Environment.NewLine + " Extra (1): < \"z\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreEquivalent(set1,set2)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void AreEquivalentHandlesNull() { ICollection set1 = new SimpleObjectCollection(null, "x", null, "z"); ICollection set2 = new SimpleObjectCollection("z", null, "x", null); CollectionAssert.AreEquivalent(set1,set2); } #endregion #region AreNotEqual [Test] public void AreNotEqual() { var set1 = new SimpleObjectCollection("x", "y", "z"); var set2 = new SimpleObjectCollection("x", "y", "x"); CollectionAssert.AreNotEqual(set1,set2); CollectionAssert.AreNotEqual(set1,set2,new TestComparer()); CollectionAssert.AreNotEqual(set1,set2,"test"); CollectionAssert.AreNotEqual(set1,set2,new TestComparer(),"test"); CollectionAssert.AreNotEqual(set1,set2,"test {0}","1"); CollectionAssert.AreNotEqual(set1,set2,new TestComparer(),"test {0}","1"); } [Test] public void AreNotEqual_Fails() { var set1 = new SimpleObjectCollection("x", "y", "z"); var set2 = new SimpleObjectCollection("x", "y", "z"); var expectedMessage = " Expected: not equal to < \"x\", \"y\", \"z\" >" + Environment.NewLine + " But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreNotEqual(set1, set2)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void AreNotEqual_HandlesNull() { object[] set1 = new object[3]; var set2 = new SimpleObjectCollection("x", "y", "z"); CollectionAssert.AreNotEqual(set1,set2); CollectionAssert.AreNotEqual(set1,set2,new TestComparer()); } [Test] public void AreNotEqual_IEquatableImplementationIsIgnored() { var x = new Constraints.EquatableWithEnumerableObject<int>(new[] { 1, 2, 3, 4, 5 }, 42); var y = new Constraints.EnumerableObject<int>(new[] { 5, 4, 3, 2, 1 }, 42); // Equal using Assert Assert.AreEqual(x, y, "Assert 1"); Assert.AreEqual(y, x, "Assert 2"); // Not equal using CollectionAssert CollectionAssert.AreNotEqual(x, y, "CollectionAssert 1"); CollectionAssert.AreNotEqual(y, x, "CollectionAssert 2"); } #endregion #region AreNotEquivalent [Test] public void NotEquivalent() { var set1 = new SimpleObjectCollection("x", "y", "z"); var set2 = new SimpleObjectCollection("x", "y", "x"); CollectionAssert.AreNotEquivalent(set1,set2); } [Test] public void NotEquivalent_Fails() { var set1 = new SimpleObjectCollection("x", "y", "z"); var set2 = new SimpleObjectCollection("x", "z", "y"); var expectedMessage = " Expected: not equivalent to < \"x\", \"y\", \"z\" >" + Environment.NewLine + " But was: < \"x\", \"z\", \"y\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.AreNotEquivalent(set1,set2)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void NotEquivalentHandlesNull() { var set1 = new SimpleObjectCollection("x", null, "z"); var set2 = new SimpleObjectCollection("x", null, "x"); CollectionAssert.AreNotEquivalent(set1,set2); } #endregion #region Contains [Test] public void Contains_IList() { var list = new SimpleObjectList("x", "y", "z"); CollectionAssert.Contains(list, "x"); } [Test] public void Contains_ICollection() { var collection = new SimpleObjectCollection("x", "y", "z"); CollectionAssert.Contains(collection,"x"); } [Test] public void ContainsFails_ILIst() { var list = new SimpleObjectList("x", "y", "z"); var expectedMessage = " Expected: some item equal to \"a\"" + Environment.NewLine + " But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.Contains(list,"a")); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void ContainsFails_ICollection() { var collection = new SimpleObjectCollection("x", "y", "z"); var expectedMessage = " Expected: some item equal to \"a\"" + Environment.NewLine + " But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.Contains(collection,"a")); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void ContainsFails_EmptyIList() { var list = new SimpleObjectList(); var expectedMessage = " Expected: some item equal to \"x\"" + Environment.NewLine + " But was: <empty>" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.Contains(list,"x")); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void ContainsFails_EmptyICollection() { var ca = new SimpleObjectCollection(new object[0]); var expectedMessage = " Expected: some item equal to \"x\"" + Environment.NewLine + " But was: <empty>" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.Contains(ca,"x")); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void ContainsNull_IList() { Object[] oa = new object[] { 1, 2, 3, null, 4, 5 }; CollectionAssert.Contains( oa, null ); } [Test] public void ContainsNull_ICollection() { var ca = new SimpleObjectCollection(new object[] { 1, 2, 3, null, 4, 5 }); CollectionAssert.Contains( ca, null ); } #endregion #region DoesNotContain [Test] public void DoesNotContain() { var list = new SimpleObjectList(); CollectionAssert.DoesNotContain(list,"a"); } [Test] public void DoesNotContain_Empty() { var list = new SimpleObjectList(); CollectionAssert.DoesNotContain(list,"x"); } [Test] public void DoesNotContain_Fails() { var list = new SimpleObjectList("x", "y", "z"); var expectedMessage = " Expected: not some item equal to \"y\"" + Environment.NewLine + " But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.DoesNotContain(list,"y")); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } #endregion #region IsSubsetOf [Test] public void IsSubsetOf() { var set1 = new SimpleObjectList("x", "y", "z"); var set2 = new SimpleObjectList("y", "z"); CollectionAssert.IsSubsetOf(set2,set1); Assert.That(set2, Is.SubsetOf(set1)); } [Test] public void IsSubsetOf_Fails() { var set1 = new SimpleObjectList("x", "y", "z"); var set2 = new SimpleObjectList("y", "z", "a"); var expectedMessage = " Expected: subset of < \"y\", \"z\", \"a\" >" + Environment.NewLine + " But was: < \"x\", \"y\", \"z\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.IsSubsetOf(set1,set2)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void IsSubsetOfHandlesNull() { var set1 = new SimpleObjectList("x", null, "z"); var set2 = new SimpleObjectList(null, "z"); CollectionAssert.IsSubsetOf(set2,set1); Assert.That(set2, Is.SubsetOf(set1)); } #endregion #region IsNotSubsetOf [Test] public void IsNotSubsetOf() { var set1 = new SimpleObjectList("x", "y", "z"); var set2 = new SimpleObjectList("y", "z", "a"); CollectionAssert.IsNotSubsetOf(set1,set2); Assert.That(set1, Is.Not.SubsetOf(set2)); } [Test] public void IsNotSubsetOf_Fails() { var set1 = new SimpleObjectList("x", "y", "z"); var set2 = new SimpleObjectList("y", "z"); var expectedMessage = " Expected: not subset of < \"x\", \"y\", \"z\" >" + Environment.NewLine + " But was: < \"y\", \"z\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.IsNotSubsetOf(set2,set1)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void IsNotSubsetOfHandlesNull() { var set1 = new SimpleObjectList("x", null, "z"); var set2 = new SimpleObjectList(null, "z", "a"); CollectionAssert.IsNotSubsetOf(set1,set2); } #endregion #region IsOrdered [Test] public void IsOrdered() { var list = new SimpleObjectList("x", "y", "z"); CollectionAssert.IsOrdered(list); } [Test] public void IsOrdered_Fails() { var list = new SimpleObjectList("x", "z", "y"); var expectedMessage = " Expected: collection ordered" + Environment.NewLine + " But was: < \"x\", \"z\", \"y\" >" + Environment.NewLine; var ex = Assert.Throws<AssertionException>(() => CollectionAssert.IsOrdered(list)); Assert.That(ex.Message, Is.EqualTo(expectedMessage)); } [Test] public void IsOrdered_Allows_adjacent_equal_values() { var list = new SimpleObjectList("x", "x", "z"); CollectionAssert.IsOrdered(list); } [Test] public void IsOrdered_Handles_null() { var list = new SimpleObjectList(null, "x", "z"); Assert.That(list, Is.Ordered); } [Test] public void IsOrdered_ContainedTypesMustBeCompatible() { var list = new SimpleObjectList(1, "x"); Assert.Throws<ArgumentException>(() => CollectionAssert.IsOrdered(list)); } [Test] public void IsOrdered_TypesMustImplementIComparable() { var list = new SimpleObjectList(new object(), new object()); Assert.Throws<ArgumentException>(() => CollectionAssert.IsOrdered(list)); } [Test] public void IsOrdered_Handles_custom_comparison() { var list = new SimpleObjectList(new object(), new object()); CollectionAssert.IsOrdered(list, new AlwaysEqualComparer()); } [Test] public void IsOrdered_Handles_custom_comparison2() { var list = new SimpleObjectList(2, 1); CollectionAssert.IsOrdered(list, new TestComparer()); } #endregion #region Equals [Test] public void EqualsFailsWhenUsed() { var ex = Assert.Throws<InvalidOperationException>(() => CollectionAssert.Equals(string.Empty, string.Empty)); Assert.That(ex.Message, Does.StartWith("CollectionAssert.Equals should not be used for Assertions")); } [Test] public void ReferenceEqualsFailsWhenUsed() { var ex = Assert.Throws<InvalidOperationException>(() => CollectionAssert.ReferenceEquals(string.Empty, string.Empty)); Assert.That(ex.Message, Does.StartWith("CollectionAssert.ReferenceEquals should not be used for Assertions")); } #endregion } }
using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// To store one animations /// </summary> /// <remarks> /// This object can hold one or more animations, contained in OTAnimationFramesets. /// Using an OTAnimatingSprite, you can play the entire animation or just one animation frameset. /// /// Because of its multi frameset character, this object can hold many animations that can span across /// multiple spritesheets/atlases. /// </remarks> [ExecuteInEditMode] public class OTAnimation : MonoBehaviour { public string _name = ""; public float _fps = 30; public float _duration = 1; /// <summary> /// Array with animation frameset data. /// </summary> /// <remarks> /// An animation consists of one or more animation framesets. This way it is easy to span an /// animation over more than one container. It is even possible to repeat containers and/or use different /// start- and end-frames. /// <br></br><br></br> /// By programmaticly playing only parts of an animation, one could even put all animation sequences in one /// animation object and control manually what sequences will be played. /// </remarks> public OTAnimationFrameset[] framesets; bool registered = false; bool dirtyAnimation = true; Frame[] frames = { }; List<OTAnimationFramesetCheck> _framesets = new List<OTAnimationFramesetCheck>(); bool _isReady = false; float _fps_ = 30; float _duration_ = 1; float _framesetSize = 0; protected string _name_ = ""; /// <summary> /// Frames per second /// </summary> public float fps { get { return _fps; } set { _fps = value; Update(); } } /// <summary> /// Duration of this animation /// </summary> public float duration { get { return _duration; } set { _duration = value; Update(); } } /// <summary> /// Animation name for lookup purposes. /// </summary> new public string name { get { return _name; } set { string old = _name; _name = value; gameObject.name = _name; if (OT.isValid) { _name_ = _name; OT.RegisterAnimationLookup(this, old); } } } /// <summary> /// Stores data of a specific animation frame. /// </summary> public struct Frame { /// <summary> /// Frame's container /// </summary> public OTContainer container; /// <summary> /// Frame's container index /// </summary> public int frameIndex; //public Vector2 movement; //public float rotation; //public Vector2 scale; } /// <summary> /// Animation ready indicator. /// </summary> public bool isReady { get { return _isReady; } } public OTAnimationFrameset GetFrameset(string pName) { if (pName == "") return null; for (int f = 0; f < framesets.Length; f++) { if (framesets[f].name.ToLower() == pName.ToLower()) return framesets[f]; } return null; } public float GetDuration(OTAnimationFrameset frameset) { if (frameset != null) { return (frameset.singleDuration != 0) ? frameset.singleDuration : frameset.frameCount / fps; } else return duration; } /// <summary> /// Number of frames in this animation. /// </summary> public int frameCount { get { return frames.Length; } } /// <summary> /// Get number of frames in this animaation /// </summary> /// <remarks> /// If no <see cref="OTAnimationFrameset" /> is provided the number of frames of the entire animation is returned. If an OTAnimationFrameset is provided /// this method will return the number of frames of that particular frameset. /// </remarks> /// <param name="frameset">Get number of frames of a perticular animation frameset.</param> /// <returns>number of frames</returns> public int GetFrameCount(OTAnimationFrameset frameset) { if (frameset != null) return frameset.frameCount; else return frameCount; } int GetIndex(float time, int direction, OTAnimationFrameset frameset) { int index = 0; int fc = GetFrameCount(frameset); index = (int)Mathf.Floor((float)fc * (time / GetDuration(frameset))); while (index > fc - 1) index -= fc; if (direction == -1) index = fc - 1 - index; return index; } /// <summary> /// Retrieve the animation frame that is active at a specific time. /// </summary> /// <param name="time">Animation time in seconds.</param> /// <param name="direction">Animation direction, 1 = forward, -1 = backward</param> /// <param name="frameset">The animation frameset of which a frame is requested</param> /// <returns>Retrieved animation frame.</returns> public Frame GetFrame(float time, int direction, OTAnimationFrameset frameset) { if (frames.Length == 0) { return new Frame(); } else { if (frameset != null) { return frames[frameset.startIndex+GetIndex(time, direction, frameset)]; } else { return frames[GetIndex(time, direction, null)]; } } } protected void CheckModifications() { #if UNITY_EDITOR if (!Application.isPlaying) { UnityEditor.PropertyModification[] modifications = UnityEditor.PrefabUtility.GetPropertyModifications(this); if (modifications!=null && modifications.Length>0) UnityEditor.PrefabUtility.RecordPrefabInstancePropertyModifications(this); } #endif } protected void Awake() { if (name == "") _name = "Animation (id=" + this.gameObject.GetInstanceID() + ")"; _duration_ = _duration; _fps_ = _fps; _name_ = name; RegisterAnimation(); CheckModifications(); } // Use this for initialization void Start() { if (gameObject.name!= name) gameObject.name = name; } protected Frame[] GetFrames() { List<Frame> frames = new List<Frame>(); if (framesets.Length > 0) { int index = 0; for (int f = 0; f < framesets.Length; f++) { OTAnimationFrameset fs = framesets[f]; fs.startIndex = index; index += fs.frameCount; int[] framesetFrames = fs.frameNumbers; foreach (int frameIndex in framesetFrames) { Frame curFrame = new Frame(); curFrame.container = fs.container; curFrame.frameIndex = frameIndex; frames.Add(curFrame); } } } return frames.ToArray(); } void RegisterAnimation() { if (OT.AnimationByName(name) == null) { OT.RegisterAnimation(this); gameObject.name = name; registered = true; } if (_name_ != name) { OT.RegisterAnimationLookup(this, _name_); _name_ = name; gameObject.name = name; } if (name != gameObject.name) { name = gameObject.name; OT.RegisterAnimationLookup(this, _name_); _name_ = name; CheckModifications(); } } bool Ready() { if (!isReady) { _isReady = true; for (int f = 0; f < framesets.Length; f++) { OTAnimationFrameset fs = framesets[f]; if (fs.container != null) { if (fs.container.texture == null) continue; else if (!fs.container.isReady) _isReady = false; } } } return _isReady; } void CheckEditorSettings() { if (frameCount == 0 && framesets.Length > 0 && !dirtyAnimation) { dirtyAnimation = true; } if (framesets.Length > 0) { if (_framesetSize != framesets.Length) { _framesetSize = framesets.Length; dirtyAnimation = true; } int _frameCount = 0; for (int f = 0; f < framesets.Length; f++) { OTAnimationFrameset fs = framesets[f]; if (fs.container != null) { if (f <= _framesets.Count - 1) { dirtyAnimation = _framesets[f].isChanged; _framesets[f].Assign(); } else { _framesets.Add(new OTAnimationFramesetCheck(fs)); dirtyAnimation = true; } if (fs.container!=null) fs._containerName = fs.container.name; if (fs.container.isReady) { if (fs.startFrame < 0) fs.startFrame = 0; else if (fs.startFrame >= fs.container.frameCount) fs.startFrame = fs.container.frameCount - 1; if (fs.endFrame < 0) fs.endFrame = 0; else if (fs.endFrame >= fs.container.frameCount) fs.endFrame = fs.container.frameCount - 1; _frameCount += fs.frameCount; } } else { if (fs._containerName=="") { fs.startFrame = -1; fs.endFrame = -1; } } if (fs.playCount < 1) fs.playCount = 1; } if (frames != null) { if (_frameCount != frames.Length) { dirtyAnimation = true; } } while (framesets.Length < _framesets.Count) _framesets.RemoveAt(_framesets.Count - 1); } } // Update is called once per frame void Update() { if (!OT.isValid || !Ready()) return; if (!registered || !Application.isPlaying) RegisterAnimation(); if (!Application.isPlaying) CheckEditorSettings(); else { if (OT.dirtyChecks && framesets.Length > 0) { if (_framesetSize != framesets.Length) { _framesetSize = framesets.Length; dirtyAnimation = true; } } } if (dirtyAnimation) { bool isOk = true; for (int f = 0; f < framesets.Length; f++) { OTAnimationFrameset fs = framesets[f]; if (fs.container == null && fs._containerName!="") { OTContainer c = OT.ContainerByName(fs._containerName); if (c!=null && c.isReady) fs.container = c; else { isOk = false; break; } } } if (isOk) { frames = GetFrames(); dirtyAnimation = false; if (_duration == _duration_) { _duration = (float)frames.Length / _fps; _duration_ = _duration; } } } if (!Application.isPlaying || OT.dirtyChecks) { if (_duration > 0) { if (_duration_ != _duration) { _duration_ = _duration; _fps = (float)frames.Length / _duration; _fps_ = _fps; } } if (_fps > 0) { if (_fps_ != _fps) { _fps_ = _fps; _duration = (float)frames.Length / _fps; _duration_ = _duration; } } } } public virtual void Reset() { dirtyAnimation=true; Update(); } void OnDestroy() { if (OT.isValid) OT.RemoveAnimation(this); } } class OTAnimationFramesetCheck { OTAnimationFrameset fs; public OTContainer container; public string frameNameMask; public bool nameSort; public bool isChanged { get { return (fs.container != container || fs.frameNameMask != frameNameMask || fs.sortFrameNames != nameSort); } } public void Assign() { this.container = fs.container; frameNameMask = fs.frameNameMask; nameSort = fs.sortFrameNames; } public OTAnimationFramesetCheck(OTAnimationFrameset fs) { this.fs = fs; Assign(); } }
using System; using System.IO; using System.Configuration; using System.Collections; using TidyNet.Dom; /* HTML parser and pretty printer Copyright (c) 1998-2000 World Wide Web Consortium (Massachusetts Institute of Technology, Institut National de Recherche en Informatique et en Automatique, Keio University). All Rights Reserved. Contributing Author(s): Dave Raggett <dsr@w3.org> Andy Quick <ac.quick@sympatico.ca> (translation to Java) The contributing author(s) would like to thank all those who helped with testing, bug fixes, and patience. This wouldn't have been possible without all of you. COPYRIGHT NOTICE: This software and documentation is provided "as is," and the copyright holders and contributing author(s) make no representations or warranties, express or implied, including but not limited to, warranties of merchantability or fitness for any particular purpose or that the use of the software or documentation will not infringe any third party patents, copyrights, trademarks or other rights. The copyright holders and contributing author(s) will not be liable for any direct, indirect, special or consequential damages arising out of any use of the software or documentation, even if advised of the possibility of such damage. Permission is hereby granted to use, copy, modify, and distribute this source code, or portions hereof, documentation and executables, for any purpose, without fee, subject to the following restrictions: 1. The origin of this source code must not be misrepresented. 2. Altered versions must be plainly marked as such and must not be misrepresented as being the original source. 3. This Copyright notice may not be removed or altered from any source or altered source distribution. The copyright holders and contributing author(s) specifically permit, without fee, and encourage the use of this source code as a component for supporting the Hypertext Markup Language in commercial products. If you use this source code in a product, acknowledgment is not required but would be appreciated. */ namespace TidyNet { /// <summary> /// <p>HTML parser and pretty printer</p> /// /// <p> /// (c) 1998-2000 (W3C) MIT, INRIA, Keio University /// See Tidy.cs for the copyright notice. /// Derived from <a href="http://www.w3.org/People/Raggett/tidy"> /// HTML Tidy Release 4 Aug 2000</a> /// </p> /// /// <p> /// Copyright (c) 1998-2000 World Wide Web Consortium (Massachusetts /// Institute of Technology, Institut National de Recherche en /// Informatique et en Automatique, Keio University). All Rights /// Reserved. /// </p> /// /// <p> /// Contributing Author(s):<br> /// <a href="mailto:dsr@w3.org">Dave Raggett</a><br> /// <a href="mailto:ac.quick@sympatico.ca">Andy Quick</a> (translation to Java) /// <a href="mailto:seth_yates@hotmail.com">Seth Yates</a> (translation to C#) /// </p> /// /// <p> /// The contributing author(s) would like to thank all those who /// helped with testing, bug fixes, and patience. This wouldn't /// have been possible without all of you. /// </p> /// /// <p> /// COPYRIGHT NOTICE:<br> /// /// This software and documentation is provided "as is," and /// the copyright holders and contributing author(s) make no /// representations or warranties, express or implied, including /// but not limited to, warranties of merchantability or fitness /// for any particular purpose or that the use of the software or /// documentation will not infringe any third party patents, /// copyrights, trademarks or other rights. /// </p> /// /// <p> /// The copyright holders and contributing author(s) will not be /// liable for any direct, indirect, special or consequential damages /// arising out of any use of the software or documentation, even if /// advised of the possibility of such damage. /// </p> /// /// <p> /// Permission is hereby granted to use, copy, modify, and distribute /// this source code, or portions hereof, documentation and executables, /// for any purpose, without fee, subject to the following restrictions: /// </p> /// /// <p> /// <ol> /// <li>The origin of this source code must not be misrepresented.</li> /// <li>Altered versions must be plainly marked as such and must /// not be misrepresented as being the original source.</li> /// <li>This Copyright notice may not be removed or altered from any /// source or altered source distribution.</li> /// </ol> /// </p> /// /// <p> /// The copyright holders and contributing author(s) specifically /// permit, without fee, and encourage the use of this source code /// as a component for supporting the Hypertext Markup Language in /// commercial products. If you use this source code in a product, /// acknowledgment is not required but would be appreciated. /// </p> /// /// </summary> /// <author>Dave Raggett &lt;dsr@w3.org&gt;</author> /// <author>Andy Quick &lt;ac.quick@sympatico.ca&gt; (translation to Java)</author> /// <author>Seth Yates &lt;seth_yates@hotmail.com&gt; (translation to C#)</author> /// <version>1.0, 1999/05/22</version> /// <version>1.0.1, 1999/05/29</version> /// <version>1.1, 1999/06/18 Java Bean</version> /// <version>1.2, 1999/07/10 Tidy Release 7 Jul 1999</version> /// <version>1.3, 1999/07/30 Tidy Release 26 Jul 1999</version> /// <version>1.4, 1999/09/04 DOM support</version> /// <version>1.5, 1999/10/23 Tidy Release 27 Sep 1999</version> /// <version>1.6, 1999/11/01 Tidy Release 22 Oct 1999</version> /// <version>1.7, 1999/12/06 Tidy Release 30 Nov 1999</version> /// <version>1.8, 2000/01/22 Tidy Release 13 Jan 2000</version> /// <version>1.9, 2000/06/03 Tidy Release 30 Apr 2000</version> /// <version>1.10, 2000/07/22 Tidy Release 8 Jul 2000</version> /// <version>1.11, 2000/08/16 Tidy Release 4 Aug 2000</version> [Serializable] public class Tidy { public Tidy() { _options = new TidyOptions(); AttributeTable at = AttributeTable.DefaultAttributeTable; if (at == null) { return; } TagTable tt = new TagTable(); if (tt == null) { return; } tt.Options = _options; _options.tt = tt; EntityTable et = EntityTable.DefaultEntityTable; if (et == null) { return; } } public TidyOptions Options { get { return _options; } } /// <summary> /// Parses the input stream and writes to the output. /// </summary> /// <param name="input">The input stream</param> /// <param name="Output">The output stream</param> /// <param name="messages">The messages</param> public virtual void Parse(Stream input, Stream output, TidyMessageCollection messages) { try { Parse(input, null, output, messages); } catch (FileNotFoundException) { } catch (IOException) { } } /// <summary> /// Parses the input stream or file and writes to the output. /// </summary> /// <param name="input">The input stream</param> /// <param name="file">The input file</param> /// <param name="Output">The output stream</param> /// <param name="messages">The messages</param> public void Parse(Stream input, string file, Stream Output, TidyMessageCollection messages) { ParseInternal(input, file, Output, messages); } /// <summary> Parses InputStream in and returns the root Node. /// If out is non-null, pretty prints to OutputStream out. /// </summary> internal virtual Node ParseInternal(Stream input, Stream output, TidyMessageCollection messages) { Node document = null; try { document = ParseInternal(input, null, output, messages); } catch (FileNotFoundException) { } catch (IOException) { } return document; } /// <summary> Internal routine that actually does the parsing. The caller /// can pass either an InputStream or file name. If both are passed, /// the file name is preferred. /// </summary> internal Node ParseInternal(Stream input, string file, Stream Output, TidyMessageCollection messages) { Lexer lexer; Node document = null; Node doctype; Out o = new OutImpl(); /* normal output stream */ PPrint pprint; /* ensure config is self-consistent */ _options.Adjust(); if (file != null) { input = new FileStream(file, FileMode.Open, FileAccess.Read); } else if (input == null) { input = Console.OpenStandardInput(); } if (input != null) { lexer = new Lexer(new ClsStreamInImpl(input, _options.CharEncoding, _options.TabSize), _options); lexer.messages = messages; /* store pointer to lexer in input stream to allow character encoding errors to be reported */ lexer.input.Lexer = lexer; /* Tidy doesn't alter the doctype for generic XML docs */ if (_options.XmlTags) { document = ParserImpl.parseXMLDocument(lexer); } else { document = ParserImpl.parseDocument(lexer); if (!document.CheckNodeIntegrity()) { Report.BadTree(lexer); return null; } Clean cleaner = new Clean(_options.tt); /* simplifies <b><b> ... </b> ...</b> etc. */ cleaner.NestedEmphasis(document); /* cleans up <dir>indented text</dir> etc. */ cleaner.List2BQ(document); cleaner.BQ2Div(document); /* replaces i by em and b by strong */ if (_options.LogicalEmphasis) { cleaner.EmFromI(document); } if (_options.Word2000 && cleaner.IsWord2000(document, _options.tt)) { /* prune Word2000's <![if ...]> ... <![endif]> */ cleaner.DropSections(lexer, document); /* drop style & class attributes and empty p, span elements */ cleaner.CleanWord2000(lexer, document); } /* replaces presentational markup by style rules */ if (_options.MakeClean || _options.DropFontTags) { cleaner.CleanTree(lexer, document); } if (!document.CheckNodeIntegrity()) { Report.BadTree(lexer); return null; } doctype = document.FindDocType(); if (document.Content != null) { if (_options.Xhtml) { lexer.SetXhtmlDocType(document); } else { lexer.FixDocType(document); } if (_options.TidyMark) { lexer.AddGenerator(document); } } /* ensure presence of initial <?XML version="1.0"?> */ if (_options.XmlOut && _options.XmlPi) { lexer.FixXmlPI(document); } if (document.Content != null) { Report.ReportVersion(lexer, doctype); Report.ReportNumWarnings(lexer); } } // Try to close the InputStream but only if if we created it. if ((file != null) && (input != Console.OpenStandardOutput())) { try { input.Close(); } catch (IOException) { } } if (lexer.messages.Errors > 0) { Report.NeedsAuthorIntervention(lexer); } o.State = StreamIn.FSM_ASCII; o.Encoding = _options.CharEncoding; if (lexer.messages.Errors == 0) { if (_options.BurstSlides) { Node body; body = null; /* remove doctype to avoid potential clash with markup introduced when bursting into slides */ /* discard the document type */ doctype = document.FindDocType(); if (doctype != null) { Node.DiscardElement(doctype); } /* slides use transitional features */ lexer.versions |= HtmlVersion.Html40Loose; /* and patch up doctype to match */ if (_options.Xhtml) { lexer.SetXhtmlDocType(document); } else { lexer.FixDocType(document); } /* find the body element which may be implicit */ body = document.FindBody(_options.tt); if (body != null) { pprint = new PPrint(_options); Report.ReportNumberOfSlides(lexer, pprint.CountSlides(body)); pprint.CreateSlides(lexer, document); } else { Report.MissingBody(lexer); } } else if (Output != null) { pprint = new PPrint(_options); o.Output = Output; if (_options.XmlTags) { pprint.PrintXmlTree(o, (short) 0, 0, lexer, document); } else { pprint.PrintTree(o, (short) 0, 0, lexer, document); } pprint.FlushLine(o, 0); } } Report.ErrorSummary(lexer); } return document; } /// <summary> Parses InputStream in and returns a DOM Document node. /// If out is non-null, pretty prints to OutputStream out. /// </summary> internal virtual IDocument ParseDom(Stream input, Stream Output, TidyMessageCollection messages) { Node document = ParseInternal(input, Output, messages); if (document != null) { return (IDocument) document.Adapter; } else { return null; } } /// <summary> Creates an empty DOM Document.</summary> internal static IDocument CreateEmptyDocument() { Node document = new Node(Node.RootNode, new byte[0], 0, 0); Node node = new Node(Node.StartTag, new byte[0], 0, 0, "html", new TagTable()); if (document != null && node != null) { Node.InsertNodeAtStart(document, node); return (IDocument)document.Adapter; } else { return null; } } /// <summary>Pretty-prints a DOM Document.</summary> internal virtual void PrettyPrint(IDocument doc, Stream Output) { Out o = new OutImpl(); PPrint pprint; Node document; if (!(doc is DomDocumentImpl)) { return; } document = ((DomDocumentImpl)doc).Adaptee; o.State = StreamIn.FSM_ASCII; o.Encoding = _options.CharEncoding; if (Output != null) { pprint = new PPrint(_options); o.Output = Output; if (_options.XmlTags) { pprint.PrintXmlTree(o, (short) 0, 0, null, document); } else { pprint.PrintTree(o, (short) 0, 0, null, document); } pprint.FlushLine(o, 0); } } private TidyOptions _options = new TidyOptions(); } }
/******************************************************************************************** Copyright (c) Microsoft Corporation All rights reserved. Microsoft Public License: This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 1. Definitions The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to the software. A "contributor" is any person that distributes its contribution under this license. "Licensed patents" are a contributor's patent claims that read directly on its contribution. 2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. 3. Conditions and Limitations (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. ********************************************************************************************/ using System; using System.Windows.Forms.Design; using System.Collections.Generic; using System.Collections.Concurrent; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Text; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Windows.Threading; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.Win32; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace Microsoft.VisualStudio.Project { /// <summary> /// This class implements an MSBuild logger that output events to VS outputwindow and tasklist. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "IDE")] internal class IDEBuildLogger : Logger { #region fields // TODO: Remove these constants when we have a version that supports getting the verbosity using automation. private string buildVerbosityRegistryRoot = @"Software\Microsoft\VisualStudio\10.0"; private const string buildVerbosityRegistrySubKey = @"General"; private const string buildVerbosityRegistryKey = "MSBuildLoggerVerbosity"; private int currentIndent; private IVsOutputWindowPane outputWindowPane; private string errorString = SR.GetString(SR.Error, CultureInfo.CurrentUICulture); private string warningString = SR.GetString(SR.Warning, CultureInfo.CurrentUICulture); private TaskProvider taskProvider; private IVsHierarchy hierarchy; private IServiceProvider serviceProvider; private Dispatcher dispatcher; private bool haveCachedVerbosity = false; // Queues to manage Tasks and Error output plus message logging private ConcurrentQueue<Func<ErrorTask>> taskQueue; private ConcurrentQueue<string> outputQueue; #endregion #region properties public IServiceProvider ServiceProvider { get { return this.serviceProvider; } } public string WarningString { get { return this.warningString; } set { this.warningString = value; } } public string ErrorString { get { return this.errorString; } set { this.errorString = value; } } /// <summary> /// When the build is not a "design time" (background or secondary) build this is True /// </summary> /// <remarks> /// The only known way to detect an interactive build is to check this.outputWindowPane for null. /// </remarks> protected bool InteractiveBuild { get { return this.outputWindowPane != null; } } /// <summary> /// When building from within VS, setting this will /// enable the logger to retrive the verbosity from /// the correct registry hive. /// </summary> internal string BuildVerbosityRegistryRoot { get { return this.buildVerbosityRegistryRoot; } set { this.buildVerbosityRegistryRoot = value; } } /// <summary> /// Set to null to avoid writing to the output window /// </summary> internal IVsOutputWindowPane OutputWindowPane { get { return this.outputWindowPane; } set { this.outputWindowPane = value; } } #endregion #region ctors /// <summary> /// Constructor. Inititialize member data. /// </summary> public IDEBuildLogger(IVsOutputWindowPane output, TaskProvider taskProvider, IVsHierarchy hierarchy) { if (taskProvider == null) throw new ArgumentNullException("taskProvider"); if (hierarchy == null) throw new ArgumentNullException("hierarchy"); Trace.WriteLineIf(Thread.CurrentThread.GetApartmentState() != ApartmentState.STA, "WARNING: IDEBuildLogger constructor running on the wrong thread."); IOleServiceProvider site; Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(hierarchy.GetSite(out site)); this.taskProvider = taskProvider; this.outputWindowPane = output; this.hierarchy = hierarchy; this.serviceProvider = new ServiceProvider(site); this.dispatcher = Dispatcher.CurrentDispatcher; } #endregion #region overridden methods /// <summary> /// Overridden from the Logger class. /// </summary> public override void Initialize(IEventSource eventSource) { if (null == eventSource) { throw new ArgumentNullException("eventSource"); } this.taskQueue = new ConcurrentQueue<Func<ErrorTask>>(); this.outputQueue = new ConcurrentQueue<string>(); eventSource.BuildStarted += new BuildStartedEventHandler(BuildStartedHandler); eventSource.BuildFinished += new BuildFinishedEventHandler(BuildFinishedHandler); eventSource.ProjectStarted += new ProjectStartedEventHandler(ProjectStartedHandler); eventSource.ProjectFinished += new ProjectFinishedEventHandler(ProjectFinishedHandler); eventSource.TargetStarted += new TargetStartedEventHandler(TargetStartedHandler); eventSource.TargetFinished += new TargetFinishedEventHandler(TargetFinishedHandler); eventSource.TaskStarted += new TaskStartedEventHandler(TaskStartedHandler); eventSource.TaskFinished += new TaskFinishedEventHandler(TaskFinishedHandler); eventSource.CustomEventRaised += new CustomBuildEventHandler(CustomHandler); eventSource.ErrorRaised += new BuildErrorEventHandler(ErrorHandler); eventSource.WarningRaised += new BuildWarningEventHandler(WarningHandler); eventSource.MessageRaised += new BuildMessageEventHandler(MessageHandler); } #endregion #region event delegates /// <summary> /// This is the delegate for BuildStartedHandler events. /// </summary> protected virtual void BuildStartedHandler(object sender, BuildStartedEventArgs buildEvent) { // NOTE: This may run on a background thread! ClearCachedVerbosity(); ClearQueuedOutput(); ClearQueuedTasks(); QueueOutputEvent(MessageImportance.Low, buildEvent); } /// <summary> /// This is the delegate for BuildFinishedHandler events. /// </summary> /// <param name="sender"></param> /// <param name="buildEvent"></param> protected virtual void BuildFinishedHandler(object sender, BuildFinishedEventArgs buildEvent) { // NOTE: This may run on a background thread! MessageImportance importance = buildEvent.Succeeded ? MessageImportance.Low : MessageImportance.High; QueueOutputText(importance, Environment.NewLine); QueueOutputEvent(importance, buildEvent); // flush output and error queues ReportQueuedOutput(); ReportQueuedTasks(); } /// <summary> /// This is the delegate for ProjectStartedHandler events. /// </summary> protected virtual void ProjectStartedHandler(object sender, ProjectStartedEventArgs buildEvent) { // NOTE: This may run on a background thread! QueueOutputEvent(MessageImportance.Low, buildEvent); } /// <summary> /// This is the delegate for ProjectFinishedHandler events. /// </summary> protected virtual void ProjectFinishedHandler(object sender, ProjectFinishedEventArgs buildEvent) { // NOTE: This may run on a background thread! QueueOutputEvent(buildEvent.Succeeded ? MessageImportance.Low : MessageImportance.High, buildEvent); } /// <summary> /// This is the delegate for TargetStartedHandler events. /// </summary> protected virtual void TargetStartedHandler(object sender, TargetStartedEventArgs buildEvent) { // NOTE: This may run on a background thread! QueueOutputEvent(MessageImportance.Low, buildEvent); IndentOutput(); } /// <summary> /// This is the delegate for TargetFinishedHandler events. /// </summary> protected virtual void TargetFinishedHandler(object sender, TargetFinishedEventArgs buildEvent) { // NOTE: This may run on a background thread! UnindentOutput(); QueueOutputEvent(MessageImportance.Low, buildEvent); } /// <summary> /// This is the delegate for TaskStartedHandler events. /// </summary> protected virtual void TaskStartedHandler(object sender, TaskStartedEventArgs buildEvent) { // NOTE: This may run on a background thread! QueueOutputEvent(MessageImportance.Low, buildEvent); IndentOutput(); } /// <summary> /// This is the delegate for TaskFinishedHandler events. /// </summary> protected virtual void TaskFinishedHandler(object sender, TaskFinishedEventArgs buildEvent) { // NOTE: This may run on a background thread! UnindentOutput(); QueueOutputEvent(MessageImportance.Low, buildEvent); } /// <summary> /// This is the delegate for CustomHandler events. /// </summary> /// <param name="sender"></param> /// <param name="buildEvent"></param> protected virtual void CustomHandler(object sender, CustomBuildEventArgs buildEvent) { // NOTE: This may run on a background thread! QueueOutputEvent(MessageImportance.High, buildEvent); } /// <summary> /// This is the delegate for error events. /// </summary> protected virtual void ErrorHandler(object sender, BuildErrorEventArgs errorEvent) { // NOTE: This may run on a background thread! QueueOutputText(GetFormattedErrorMessage(errorEvent.File, errorEvent.LineNumber, errorEvent.ColumnNumber, false, errorEvent.Code, errorEvent.Message)); QueueTaskEvent(errorEvent); } /// <summary> /// This is the delegate for warning events. /// </summary> protected virtual void WarningHandler(object sender, BuildWarningEventArgs warningEvent) { // NOTE: This may run on a background thread! QueueOutputText(MessageImportance.High, GetFormattedErrorMessage(warningEvent.File, warningEvent.LineNumber, warningEvent.ColumnNumber, true, warningEvent.Code, warningEvent.Message)); QueueTaskEvent(warningEvent); } /// <summary> /// This is the delegate for Message event types /// </summary> protected virtual void MessageHandler(object sender, BuildMessageEventArgs messageEvent) { // NOTE: This may run on a background thread! QueueOutputEvent(messageEvent.Importance, messageEvent); } #endregion #region output queue protected void QueueOutputEvent(MessageImportance importance, BuildEventArgs buildEvent) { // NOTE: This may run on a background thread! if (LogAtImportance(importance) && !string.IsNullOrEmpty(buildEvent.Message)) { StringBuilder message = new StringBuilder(this.currentIndent + buildEvent.Message.Length); if (this.currentIndent > 0) { message.Append('\t', this.currentIndent); } message.AppendLine(buildEvent.Message); QueueOutputText(message.ToString()); } } protected void QueueOutputText(MessageImportance importance, string text) { // NOTE: This may run on a background thread! if (LogAtImportance(importance)) { QueueOutputText(text); } } protected void QueueOutputText(string text) { // NOTE: This may run on a background thread! if (this.OutputWindowPane != null) { // Enqueue the output text this.outputQueue.Enqueue(text); // We want to interactively report the output. But we dont want to dispatch // more than one at a time, otherwise we might overflow the main thread's // message queue. So, we only report the output if the queue was empty. if (this.outputQueue.Count == 1) { ReportQueuedOutput(); } } } private void IndentOutput() { // NOTE: This may run on a background thread! this.currentIndent++; } private void UnindentOutput() { // NOTE: This may run on a background thread! this.currentIndent--; } private void ReportQueuedOutput() { // NOTE: This may run on a background thread! // We need to output this on the main thread. We must use BeginInvoke because the main thread may not be pumping events yet. BeginInvokeWithErrorMessage(this.serviceProvider, this.dispatcher, () => { if (this.OutputWindowPane != null) { string outputString; while (this.outputQueue.TryDequeue(out outputString)) { Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(this.OutputWindowPane.OutputString(outputString)); } } }); } private void ClearQueuedOutput() { // NOTE: This may run on a background thread! this.outputQueue = new ConcurrentQueue<string>(); } #endregion output queue #region task queue protected void QueueTaskEvent(BuildEventArgs errorEvent) { this.taskQueue.Enqueue(() => { ErrorTask task = new ErrorTask(); if (errorEvent is BuildErrorEventArgs) { BuildErrorEventArgs errorArgs = (BuildErrorEventArgs)errorEvent; task.Document = errorArgs.File; task.ErrorCategory = TaskErrorCategory.Error; task.Line = errorArgs.LineNumber - 1; // The task list does +1 before showing this number. task.Column = errorArgs.ColumnNumber; task.Priority = TaskPriority.High; } else if (errorEvent is BuildWarningEventArgs) { BuildWarningEventArgs warningArgs = (BuildWarningEventArgs)errorEvent; task.Document = warningArgs.File; task.ErrorCategory = TaskErrorCategory.Warning; task.Line = warningArgs.LineNumber - 1; // The task list does +1 before showing this number. task.Column = warningArgs.ColumnNumber; task.Priority = TaskPriority.Normal; } task.Text = errorEvent.Message; task.Category = TaskCategory.BuildCompile; task.HierarchyItem = hierarchy; return task; }); // NOTE: Unlike output we dont want to interactively report the tasks. So we never queue // call ReportQueuedTasks here. We do this when the build finishes. } private void ReportQueuedTasks() { // NOTE: This may run on a background thread! // We need to output this on the main thread. We must use BeginInvoke because the main thread may not be pumping events yet. BeginInvokeWithErrorMessage(this.serviceProvider, this.dispatcher, () => { this.taskProvider.SuspendRefresh(); try { Func<ErrorTask> taskFunc; while (this.taskQueue.TryDequeue(out taskFunc)) { // Create the error task ErrorTask task = taskFunc(); // Log the task this.taskProvider.Tasks.Add(task); } } finally { this.taskProvider.ResumeRefresh(); } }); } private void ClearQueuedTasks() { // NOTE: This may run on a background thread! this.taskQueue = new ConcurrentQueue<Func<ErrorTask>>(); if (this.InteractiveBuild) { // We need to clear this on the main thread. We must use BeginInvoke because the main thread may not be pumping events yet. BeginInvokeWithErrorMessage(this.serviceProvider, this.dispatcher, () => { this.taskProvider.Tasks.Clear(); }); } } #endregion task queue #region helpers /// <summary> /// This method takes a MessageImportance and returns true if messages /// at importance i should be loggeed. Otherwise return false. /// </summary> private bool LogAtImportance(MessageImportance importance) { // If importance is too low for current settings, ignore the event bool logIt = false; this.SetVerbosity(); switch (this.Verbosity) { case LoggerVerbosity.Quiet: logIt = false; break; case LoggerVerbosity.Minimal: logIt = (importance == MessageImportance.High); break; case LoggerVerbosity.Normal: // Falling through... case LoggerVerbosity.Detailed: logIt = (importance != MessageImportance.Low); break; case LoggerVerbosity.Diagnostic: logIt = true; break; default: Debug.Fail("Unknown Verbosity level. Ignoring will cause everything to be logged"); break; } return logIt; } /// <summary> /// Format error messages for the task list /// </summary> private string GetFormattedErrorMessage( string fileName, int line, int column, bool isWarning, string errorNumber, string errorText) { string errorCode = isWarning ? this.WarningString : this.ErrorString; StringBuilder message = new StringBuilder(); if (!string.IsNullOrEmpty(fileName)) { message.AppendFormat(CultureInfo.CurrentCulture, "{0}({1},{2}):", fileName, line, column); } message.AppendFormat(CultureInfo.CurrentCulture, " {0} {1}: {2}", errorCode, errorNumber, errorText); message.AppendLine(); return message.ToString(); } /// <summary> /// Sets the verbosity level. /// </summary> private void SetVerbosity() { // TODO: This should be replaced when we have a version that supports automation. if (!this.haveCachedVerbosity) { string verbosityKey = String.Format(CultureInfo.InvariantCulture, @"{0}\{1}", BuildVerbosityRegistryRoot, buildVerbosityRegistrySubKey); using (RegistryKey subKey = Registry.CurrentUser.OpenSubKey(verbosityKey)) { if (subKey != null) { object valueAsObject = subKey.GetValue(buildVerbosityRegistryKey); if (valueAsObject != null) { this.Verbosity = (LoggerVerbosity)((int)valueAsObject); } } } this.haveCachedVerbosity = true; } } /// <summary> /// Clear the cached verbosity, so that it will be re-evaluated from the build verbosity registry key. /// </summary> private void ClearCachedVerbosity() { this.haveCachedVerbosity = false; } #endregion helpers #region exception handling helpers /// <summary> /// Call Dispatcher.BeginInvoke, showing an error message if there was a non-critical exception. /// </summary> /// <param name="serviceProvider">service provider</param> /// <param name="dispatcher">dispatcher</param> /// <param name="action">action to invoke</param> private static void BeginInvokeWithErrorMessage(IServiceProvider serviceProvider, Dispatcher dispatcher, Action action) { dispatcher.BeginInvoke(new Action(() => CallWithErrorMessage(serviceProvider, action))); } /// <summary> /// Show error message if exception is caught when invoking a method /// </summary> /// <param name="serviceProvider">service provider</param> /// <param name="action">action to invoke</param> private static void CallWithErrorMessage(IServiceProvider serviceProvider, Action action) { try { action(); } catch (Exception ex) { if (Microsoft.VisualStudio.ErrorHandler.IsCriticalException(ex)) { throw; } ShowErrorMessage(serviceProvider, ex); } } /// <summary> /// Show error window about the exception /// </summary> /// <param name="serviceProvider">service provider</param> /// <param name="exception">exception</param> private static void ShowErrorMessage(IServiceProvider serviceProvider, Exception exception) { IUIService UIservice = (IUIService)serviceProvider.GetService(typeof(IUIService)); if (UIservice != null && exception != null) { UIservice.ShowError(exception); } } #endregion exception handling helpers } }
using UnityEngine; using UnityEditor; using System.Collections; public class RagePixelColorPickerGUI { public bool visible = false; public bool gizmoVisible = false; public bool isDirty = false; public int gizmoPositionX = 0; public int gizmoPositionY = 0; public int gizmoPixelWidth = 32; public int gizmoPixelHeight = 32; public int positionX = 0; public int positionY = 0; public int pixelWidth = 128; public int pixelHeight = 128; public int splitSize = 16; public int marginSize = 5; public enum GUIArea { None = 0, Color, Hue, Alpha }; public GUIArea activeArea = GUIArea.None; private Color _selectedColor = new Color(0.9f,0.5f,0f); public Rect gizmoBounds { get { return new Rect(gizmoPositionX, gizmoPositionY, gizmoPixelWidth, gizmoPixelHeight); } } public Rect bounds { get { return new Rect(positionX, positionY, pixelWidth, pixelHeight); } } public Color selectedColor { get { return _selectedColor; } set { if (_selectedColor != value) { isDirty = true; } _selectedColor = value; } } private Texture2D _colorPickerTexture; public Texture2D colorPickerTexture { get { if (_colorPickerTexture == null) { CreateNewTextureInstance(); isDirty = true; } if (isDirty) { Refresh(); isDirty = false; } return _colorPickerTexture; } } private Texture2D _colorGizmoTexture; public Texture2D colorGizmoTexture { get { if (_colorGizmoTexture == null) { CreateNewTextureInstance(); isDirty = true; } if (isDirty) { Refresh(); isDirty = false; } return _colorGizmoTexture; } } private void CreateNewTextureInstance() { if (_colorPickerTexture != null) { Object.DestroyImmediate(_colorPickerTexture, false); } _colorPickerTexture = new Texture2D( pixelWidth, pixelHeight ); _colorPickerTexture.hideFlags = HideFlags.HideAndDontSave; if (_colorGizmoTexture != null) { Object.DestroyImmediate(_colorGizmoTexture, false); } _colorGizmoTexture = new Texture2D( 32, 32 ); _colorGizmoTexture.hideFlags = HideFlags.HideAndDontSave; } public void Refresh() { renderColorGizmoTexture(_colorGizmoTexture); renderColorPickerTexture(_colorPickerTexture); } public bool HandleGUIEvent(Event ev) { bool used = false; if (visible) { Vector2 localMousePos = ev.mousePosition - new Vector2(bounds.xMin, bounds.yMin) - new Vector2(marginSize, marginSize); Rect sbBounds = new Rect(0, 0, pixelWidth - marginSize * 2 - splitSize, pixelHeight - marginSize * 2 - splitSize); Rect aBounds = new Rect(0, pixelWidth - marginSize - splitSize, pixelHeight - marginSize * 2, splitSize); Rect hBounds = new Rect(pixelWidth - marginSize * 2 - splitSize, 0, splitSize, pixelHeight - marginSize * 2 - splitSize); if (bounds.Contains(ev.mousePosition)) { if (ev.type == EventType.mouseUp) { activeArea = GUIArea.None; used = true; } else if (ev.type == EventType.mouseDown) { if (sbBounds.Contains(localMousePos)) { activeArea = GUIArea.Color; } else if (hBounds.Contains(localMousePos)) { activeArea = GUIArea.Hue; } else if (aBounds.Contains(localMousePos)) { activeArea = GUIArea.Alpha; } else { activeArea = GUIArea.None; } used = true; } } else { if (Event.current.type == EventType.mouseDown) { activeArea = GUIArea.None; } } if ((Event.current.type == EventType.mouseDrag || Event.current.type == EventType.mouseDown) && activeArea != GUIArea.None) { RagePixelHSBColor hsbcolor = new RagePixelHSBColor(selectedColor); switch (activeArea) { case GUIArea.Color: hsbcolor.s = Mathf.Clamp(localMousePos.x, 0.001f, sbBounds.width - 0.001f) / (sbBounds.width); hsbcolor.b = 1f - Mathf.Clamp(localMousePos.y, 0.001f, sbBounds.height - 0.001f) / (sbBounds.height); break; case GUIArea.Hue: hsbcolor.h = 1f - Mathf.Clamp(localMousePos.y, 0.001f, hBounds.height - 0.001f) / (hBounds.height); break; case GUIArea.Alpha: hsbcolor.a = Mathf.Clamp(localMousePos.x, 0.001f, aBounds.width - 0.001f) / (aBounds.width); break; } selectedColor = hsbcolor.ToColor(); used = true; } } return used; } private void renderColorGizmoTexture(Texture2D texture) { for (int pY = 0; pY < texture.height; pY++) { for (int pX = 0; pX < texture.width; pX++) { texture.SetPixel(pX, pY, selectedColor); } } texture.filterMode = FilterMode.Point; for (int pY = 0; pY < texture.height; pY++) { for (int pX = 0; pX < texture.width; pX++) { if (pX == 0 || pX == texture.width - 1 || pY == 0 || pY == texture.height - 1) { texture.SetPixel(pX, pY, new Color(0f, 0f, 0f, 1f)); } } } texture.Apply(); } private void renderColorPickerTexture(Texture2D texture) { for (int pY = 0; pY < texture.height; pY++) { for (int pX = 0; pX < texture.width; pX++) { texture.SetPixel(pX, pY, new Color(0f, 0f, 0f, 0f)); if ((pY < marginSize && pX > marginSize + 5) || (pX > texture.width - marginSize && pY < texture.height - marginSize - 5)) { texture.SetPixel(pX, pY, new Color(0f, 0f, 0f, 0.1f)); } } } for (int pY = splitSize + marginSize; pY < texture.height - marginSize; pY++) { for (int pX = marginSize; pX < texture.width - splitSize - marginSize; pX++) { RagePixelHSBColor hsb = new RagePixelHSBColor(new RagePixelHSBColor(selectedColor).h, (float)(pX - marginSize) / ((float)texture.width - splitSize - marginSize * 2f), (float)(pY - splitSize - marginSize) / (float)(texture.height - splitSize - marginSize * 2)); texture.SetPixel(pX, pY, hsb.ToColor()); } } for (int pY = splitSize + marginSize; pY < texture.height - marginSize; pY++) { for (int pX = texture.width - splitSize - marginSize; pX < texture.width - marginSize; pX++) { RagePixelHSBColor hsb = new RagePixelHSBColor((float)(pY - splitSize - marginSize) / (float)(texture.height - splitSize - marginSize * 2f), 1f, 1f); texture.SetPixel(pX, pY, hsb.ToColor()); } } for (int pY = marginSize; pY < splitSize + marginSize; pY++) { for (int pX = marginSize; pX < texture.width - marginSize; pX++) { RagePixelHSBColor hsb = new RagePixelHSBColor(0f, 0f, (float)(pX - marginSize) / (float)(texture.width - marginSize * 2f)); texture.SetPixel(pX, pY, hsb.ToColor()); } } for (int pY = marginSize; pY < texture.height - marginSize; pY++) { for (int pX = marginSize; pX < texture.width - marginSize; pX++) { if (pX == marginSize || pX == texture.width - marginSize - 1 || pY == marginSize || pY == texture.height - marginSize - 1) { texture.SetPixel(pX, pY, new Color(0.75f, 0.75f, 0.75f, 1f)); } } } RagePixelHSBColor pColor = new RagePixelHSBColor(selectedColor); int hueY = marginSize + splitSize + Mathf.RoundToInt((texture.height - marginSize * 2 - splitSize) * (pColor.h)); for (int pX = texture.width - marginSize; pX < texture.width; pX++) { texture.SetPixel(pX, hueY, new Color(1f, 1f, 1f, 0.33f)); } for (int pX = texture.width - marginSize + 1; pX < texture.width; pX++) { texture.SetPixel(pX, hueY - 1, new Color(1f, 1f, 1f, 0.33f)); texture.SetPixel(pX, hueY + 1, new Color(1f, 1f, 1f, 0.33f)); } for (int pX = texture.width - marginSize + 2; pX < texture.width; pX++) { texture.SetPixel(pX, hueY - 2, new Color(1f, 1f, 1f, 0.33f)); texture.SetPixel(pX, hueY + 2, new Color(1f, 1f, 1f, 0.33f)); } for (int pX = texture.width - marginSize + 3; pX < texture.width; pX++) { texture.SetPixel(pX, hueY - 3, new Color(1f, 1f, 1f, 0.33f)); texture.SetPixel(pX, hueY + 3, new Color(1f, 1f, 1f, 0.33f)); } int alphaX = marginSize + Mathf.RoundToInt((texture.width - marginSize * 2f) * Mathf.Clamp01(pColor.a)); for (int pY = 0; pY < marginSize; pY++) { texture.SetPixel(alphaX, pY, new Color(1f, 1f, 1f, 0.33f)); } for (int pY = 0; pY < marginSize - 1; pY++) { texture.SetPixel(alphaX - 1, pY, new Color(1f, 1f, 1f, 0.33f)); texture.SetPixel(alphaX + 1, pY, new Color(1f, 1f, 1f, 0.33f)); } for (int pY = 0; pY < marginSize - 2; pY++) { texture.SetPixel(alphaX - 2, pY, new Color(1f, 1f, 1f, 0.33f)); texture.SetPixel(alphaX + 2, pY, new Color(1f, 1f, 1f, 0.33f)); } for (int pY = 0; pY < marginSize - 3; pY++) { texture.SetPixel(alphaX - 3, pY, new Color(1f, 1f, 1f, 0.33f)); texture.SetPixel(alphaX + 3, pY, new Color(1f, 1f, 1f, 0.33f)); } int pickerX = marginSize + Mathf.RoundToInt((texture.width - marginSize * 2f - splitSize) * (pColor.s)); int pickerY = marginSize + splitSize + Mathf.RoundToInt((texture.height - marginSize * 2f - splitSize) * (pColor.b)); texture.SetPixel(pickerX, pickerY + 3, new Color(0.5f, 0.5f, 0.5f, 1f)); texture.SetPixel(pickerX + 1, pickerY + 3, new Color(0.5f, 0.5f, 0.5f, 1f)); texture.SetPixel(pickerX + 2, pickerY + 2, new Color(0.5f, 0.5f, 0.5f, 1f)); texture.SetPixel(pickerX + 3, pickerY + 1, new Color(0.5f, 0.5f, 0.5f, 1f)); texture.SetPixel(pickerX + 3, pickerY, new Color(0.5f, 0.5f, 0.5f, 1f)); texture.SetPixel(pickerX + 3, pickerY - 1, new Color(0.5f, 0.5f, 0.5f, 1f)); texture.SetPixel(pickerX + 2, pickerY - 2, new Color(0.5f, 0.5f, 0.5f, 1f)); texture.SetPixel(pickerX + 1, pickerY - 3, new Color(0.5f, 0.5f, 0.5f, 1f)); texture.SetPixel(pickerX, pickerY - 3, new Color(0.5f, 0.5f, 0.5f, 1f)); texture.SetPixel(pickerX - 1, pickerY - 3, new Color(0.5f, 0.5f, 0.5f, 1f)); texture.SetPixel(pickerX - 2, pickerY - 2, new Color(0.5f, 0.5f, 0.5f, 1f)); texture.SetPixel(pickerX - 3, pickerY - 1, new Color(0.5f, 0.5f, 0.5f, 1f)); texture.SetPixel(pickerX - 3, pickerY, new Color(0.5f, 0.5f, 0.5f, 1f)); texture.SetPixel(pickerX - 3, pickerY + 1, new Color(0.5f, 0.5f, 0.5f, 1f)); texture.SetPixel(pickerX - 2, pickerY + 2, new Color(0.5f, 0.5f, 0.5f, 1f)); texture.SetPixel(pickerX - 1, pickerY + 3, new Color(0.5f, 0.5f, 0.5f, 1f)); texture.filterMode = FilterMode.Point; texture.Apply(); } public void CleanExit() { Object.DestroyImmediate(_colorPickerTexture, false); Object.DestroyImmediate(_colorGizmoTexture, 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. namespace System.Runtime.Serialization { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Xml; using System.Xml.Serialization; using System.Security; using DataContractDictionary = System.Collections.Generic.Dictionary<System.Xml.XmlQualifiedName, DataContract>; #if USE_REFEMIT || NET_NATIVE public class XmlObjectSerializerReadContext : XmlObjectSerializerContext #else internal class XmlObjectSerializerReadContext : XmlObjectSerializerContext #endif { internal Attributes attributes; private HybridObjectCache _deserializedObjects; private XmlSerializableReader _xmlSerializableReader; private XmlDocument _xmlDocument; private Attributes _attributesInXmlData; private object _getOnlyCollectionValue; private bool _isGetOnlyCollection; private HybridObjectCache DeserializedObjects { get { if (_deserializedObjects == null) _deserializedObjects = new HybridObjectCache(); return _deserializedObjects; } } private XmlDocument Document => _xmlDocument ?? (_xmlDocument = new XmlDocument()); internal override bool IsGetOnlyCollection { get { return _isGetOnlyCollection; } set { _isGetOnlyCollection = value; } } #if USE_REFEMIT public object GetCollectionMember() #else internal object GetCollectionMember() #endif { return _getOnlyCollectionValue; } #if USE_REFEMIT public void StoreCollectionMemberInfo(object collectionMember) #else internal void StoreCollectionMemberInfo(object collectionMember) #endif { _getOnlyCollectionValue = collectionMember; _isGetOnlyCollection = true; } #if USE_REFEMIT public static void ThrowNullValueReturnedForGetOnlyCollectionException(Type type) #else internal static void ThrowNullValueReturnedForGetOnlyCollectionException(Type type) #endif { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NullValueReturnedForGetOnlyCollection, DataContract.GetClrTypeFullName(type)))); } #if USE_REFEMIT public static void ThrowArrayExceededSizeException(int arraySize, Type type) #else internal static void ThrowArrayExceededSizeException(int arraySize, Type type) #endif { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayExceededSize, arraySize, DataContract.GetClrTypeFullName(type)))); } internal static XmlObjectSerializerReadContext CreateContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) { return (serializer.PreserveObjectReferences || serializer.SerializationSurrogateProvider != null) ? new XmlObjectSerializerReadContextComplex(serializer, rootTypeDataContract, dataContractResolver) : new XmlObjectSerializerReadContext(serializer, rootTypeDataContract, dataContractResolver); } internal XmlObjectSerializerReadContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject) : base(serializer, maxItemsInObjectGraph, streamingContext, ignoreExtensionDataObject) { } internal XmlObjectSerializerReadContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) : base(serializer, rootTypeDataContract, dataContractResolver) { this.attributes = new Attributes(); } #if USE_REFEMIT public virtual object InternalDeserialize(XmlReaderDelegator xmlReader, int id, RuntimeTypeHandle declaredTypeHandle, string name, string ns) #else internal virtual object InternalDeserialize(XmlReaderDelegator xmlReader, int id, RuntimeTypeHandle declaredTypeHandle, string name, string ns) #endif { DataContract dataContract = GetDataContract(id, declaredTypeHandle); return InternalDeserialize(xmlReader, name, ns, ref dataContract); } internal virtual object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, string name, string ns) { DataContract dataContract = GetDataContract(declaredType); return InternalDeserialize(xmlReader, name, ns, ref dataContract); } internal virtual object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, string name, string ns) { if (dataContract == null) GetDataContract(declaredType); return InternalDeserialize(xmlReader, name, ns, ref dataContract); } protected bool TryHandleNullOrRef(XmlReaderDelegator reader, Type declaredType, string name, string ns, ref object retObj) { ReadAttributes(reader); if (attributes.Ref != Globals.NewObjectId) { if (_isGetOnlyCollection) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ErrorDeserializing, SR.Format(SR.ErrorTypeInfo, DataContract.GetClrTypeFullName(declaredType)), SR.Format(SR.XmlStartElementExpected, Globals.RefLocalName)))); } else { retObj = GetExistingObject(attributes.Ref, declaredType, name, ns); reader.Skip(); return true; } } else if (attributes.XsiNil) { reader.Skip(); return true; } return false; } protected object InternalDeserialize(XmlReaderDelegator reader, string name, string ns, ref DataContract dataContract) { object retObj = null; if (TryHandleNullOrRef(reader, dataContract.UnderlyingType, name, ns, ref retObj)) return retObj; bool knownTypesAddedInCurrentScope = false; if (dataContract.KnownDataContracts != null) { scopedKnownTypes.Push(dataContract.KnownDataContracts); knownTypesAddedInCurrentScope = true; } if (attributes.XsiTypeName != null) { dataContract = ResolveDataContractFromKnownTypes(attributes.XsiTypeName, attributes.XsiTypeNamespace, dataContract); if (dataContract == null) { if (DataContractResolver == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(reader, SR.Format(SR.DcTypeNotFoundOnDeserialize, attributes.XsiTypeNamespace, attributes.XsiTypeName, reader.NamespaceURI, reader.LocalName)))); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(reader, SR.Format(SR.DcTypeNotResolvedOnDeserialize, attributes.XsiTypeNamespace, attributes.XsiTypeName, reader.NamespaceURI, reader.LocalName)))); } knownTypesAddedInCurrentScope = ReplaceScopedKnownTypesTop(dataContract.KnownDataContracts, knownTypesAddedInCurrentScope); } if (knownTypesAddedInCurrentScope) { object obj = ReadDataContractValue(dataContract, reader); scopedKnownTypes.Pop(); return obj; } else { return ReadDataContractValue(dataContract, reader); } } private bool ReplaceScopedKnownTypesTop(DataContractDictionary knownDataContracts, bool knownTypesAddedInCurrentScope) { if (knownTypesAddedInCurrentScope) { scopedKnownTypes.Pop(); knownTypesAddedInCurrentScope = false; } if (knownDataContracts != null) { scopedKnownTypes.Push(knownDataContracts); knownTypesAddedInCurrentScope = true; } return knownTypesAddedInCurrentScope; } #if USE_REFEMIT public static bool MoveToNextElement(XmlReaderDelegator xmlReader) #else internal static bool MoveToNextElement(XmlReaderDelegator xmlReader) #endif { return (xmlReader.MoveToContent() != XmlNodeType.EndElement); } #if USE_REFEMIT public int GetMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, ExtensionDataObject extensionData) #else internal int GetMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, ExtensionDataObject extensionData) #endif { for (int i = memberIndex + 1; i < memberNames.Length; i++) { if (xmlReader.IsStartElement(memberNames[i], memberNamespaces[i])) return i; } HandleMemberNotFound(xmlReader, extensionData, memberIndex); return memberNames.Length; } #if USE_REFEMIT public int GetMemberIndexWithRequiredMembers(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, int requiredIndex, ExtensionDataObject extensionData) #else internal int GetMemberIndexWithRequiredMembers(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, int requiredIndex, ExtensionDataObject extensionData) #endif { for (int i = memberIndex + 1; i < memberNames.Length; i++) { if (xmlReader.IsStartElement(memberNames[i], memberNamespaces[i])) { if (requiredIndex < i) ThrowRequiredMemberMissingException(xmlReader, memberIndex, requiredIndex, memberNames); return i; } } HandleMemberNotFound(xmlReader, extensionData, memberIndex); return memberNames.Length; } #if USE_REFEMIT public static void ThrowRequiredMemberMissingException(XmlReaderDelegator xmlReader, int memberIndex, int requiredIndex, XmlDictionaryString[] memberNames) #else internal static void ThrowRequiredMemberMissingException(XmlReaderDelegator xmlReader, int memberIndex, int requiredIndex, XmlDictionaryString[] memberNames) #endif { StringBuilder stringBuilder = new StringBuilder(); if (requiredIndex == memberNames.Length) requiredIndex--; for (int i = memberIndex + 1; i <= requiredIndex; i++) { if (stringBuilder.Length != 0) stringBuilder.Append(" | "); stringBuilder.Append(memberNames[i].Value); } throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.Format(SR.UnexpectedElementExpectingElements, xmlReader.NodeType, xmlReader.LocalName, xmlReader.NamespaceURI, stringBuilder.ToString())))); } #if NET_NATIVE public static void ThrowMissingRequiredMembers(object obj, XmlDictionaryString[] memberNames, byte[] expectedElements, byte[] requiredElements) { StringBuilder stringBuilder = new StringBuilder(); int missingMembersCount = 0; for (int i = 0; i < memberNames.Length; i++) { if (IsBitSet(expectedElements, i) && IsBitSet(requiredElements, i)) { if (stringBuilder.Length != 0) stringBuilder.Append(", "); stringBuilder.Append(memberNames[i]); missingMembersCount++; } } if (missingMembersCount == 1) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.JsonOneRequiredMemberNotFound, DataContract.GetClrTypeFullName(obj.GetType()), stringBuilder.ToString()))); } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.JsonRequiredMembersNotFound, DataContract.GetClrTypeFullName(obj.GetType()), stringBuilder.ToString()))); } } public static void ThrowDuplicateMemberException(object obj, XmlDictionaryString[] memberNames, int memberIndex) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.JsonDuplicateMemberInInput, DataContract.GetClrTypeFullName(obj.GetType()), memberNames[memberIndex]))); } private static bool IsBitSet(byte[] bytes, int bitIndex) { throw new NotImplementedException(); //return BitFlagsGenerator.IsBitSet(bytes, bitIndex); } #endif protected void HandleMemberNotFound(XmlReaderDelegator xmlReader, ExtensionDataObject extensionData, int memberIndex) { xmlReader.MoveToContent(); if (xmlReader.NodeType != XmlNodeType.Element) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); if (IgnoreExtensionDataObject || extensionData == null) SkipUnknownElement(xmlReader); else HandleUnknownElement(xmlReader, extensionData, memberIndex); } internal void HandleUnknownElement(XmlReaderDelegator xmlReader, ExtensionDataObject extensionData, int memberIndex) { if (extensionData.Members == null) extensionData.Members = new List<ExtensionDataMember>(); extensionData.Members.Add(ReadExtensionDataMember(xmlReader, memberIndex)); } #if USE_REFEMIT public void SkipUnknownElement(XmlReaderDelegator xmlReader) #else internal void SkipUnknownElement(XmlReaderDelegator xmlReader) #endif { ReadAttributes(xmlReader); xmlReader.Skip(); } #if USE_REFEMIT public string ReadIfNullOrRef(XmlReaderDelegator xmlReader, Type memberType, bool isMemberTypeSerializable) #else internal string ReadIfNullOrRef(XmlReaderDelegator xmlReader, Type memberType, bool isMemberTypeSerializable) #endif { if (attributes.Ref != Globals.NewObjectId) { CheckIfTypeSerializable(memberType, isMemberTypeSerializable); xmlReader.Skip(); return attributes.Ref; } else if (attributes.XsiNil) { CheckIfTypeSerializable(memberType, isMemberTypeSerializable); xmlReader.Skip(); return Globals.NullObjectId; } return Globals.NewObjectId; } #if USE_REFEMIT public virtual void ReadAttributes(XmlReaderDelegator xmlReader) #else internal virtual void ReadAttributes(XmlReaderDelegator xmlReader) #endif { if (attributes == null) attributes = new Attributes(); attributes.Read(xmlReader); } #if USE_REFEMIT public void ResetAttributes() #else internal void ResetAttributes() #endif { if (attributes != null) attributes.Reset(); } #if USE_REFEMIT public string GetObjectId() #else internal string GetObjectId() #endif { return attributes.Id; } #if USE_REFEMIT public virtual int GetArraySize() #else internal virtual int GetArraySize() #endif { return -1; } #if USE_REFEMIT public void AddNewObject(object obj) #else internal void AddNewObject(object obj) #endif { AddNewObjectWithId(attributes.Id, obj); } #if USE_REFEMIT public void AddNewObjectWithId(string id, object obj) #else internal void AddNewObjectWithId(string id, object obj) #endif { if (id != Globals.NewObjectId) DeserializedObjects.Add(id, obj); } public void ReplaceDeserializedObject(string id, object oldObj, object newObj) { if (object.ReferenceEquals(oldObj, newObj)) return; if (id != Globals.NewObjectId) { // In certain cases (IObjectReference, SerializationSurrogate or DataContractSurrogate), // an object can be replaced with a different object once it is deserialized. If the // object happens to be referenced from within itself, that reference needs to be updated // with the new instance. BinaryFormatter supports this by fixing up such references later. // These XmlObjectSerializer implementations do not currently support fix-ups. Hence we // throw in such cases to allow us add fix-up support in the future if we need to. if (DeserializedObjects.IsObjectReferenced(id)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.FactoryObjectContainsSelfReference, DataContract.GetClrTypeFullName(oldObj.GetType()), DataContract.GetClrTypeFullName(newObj.GetType()), id))); DeserializedObjects.Remove(id); DeserializedObjects.Add(id, newObj); } } #if USE_REFEMIT public object GetExistingObject(string id, Type type, string name, string ns) #else internal object GetExistingObject(string id, Type type, string name, string ns) #endif { object retObj = DeserializedObjects.GetObject(id); if (retObj == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DeserializedObjectWithIdNotFound, id))); return retObj; } private object GetExistingObjectOrExtensionData(string id) { object retObj = DeserializedObjects.GetObject(id); if (retObj == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DeserializedObjectWithIdNotFound, id))); } return retObj; } #if USE_REFEMIT public static void Read(XmlReaderDelegator xmlReader) #else internal static void Read(XmlReaderDelegator xmlReader) #endif { if (!xmlReader.Read()) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.UnexpectedEndOfFile))); } internal static void ParseQualifiedName(string qname, XmlReaderDelegator xmlReader, out string name, out string ns, out string prefix) { int colon = qname.IndexOf(':'); prefix = ""; if (colon >= 0) prefix = qname.Substring(0, colon); name = qname.Substring(colon + 1); ns = xmlReader.LookupNamespace(prefix); } #if USE_REFEMIT public static T[] EnsureArraySize<T>(T[] array, int index) #else internal static T[] EnsureArraySize<T>(T[] array, int index) #endif { if (array.Length <= index) { if (index == Int32.MaxValue) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( XmlObjectSerializer.CreateSerializationException( SR.Format(SR.MaxArrayLengthExceeded, Int32.MaxValue, DataContract.GetClrTypeFullName(typeof(T))))); } int newSize = (index < Int32.MaxValue / 2) ? index * 2 : Int32.MaxValue; T[] newArray = new T[newSize]; Array.Copy(array, 0, newArray, 0, array.Length); array = newArray; } return array; } #if USE_REFEMIT public static T[] TrimArraySize<T>(T[] array, int size) #else internal static T[] TrimArraySize<T>(T[] array, int size) #endif { if (size != array.Length) { T[] newArray = new T[size]; Array.Copy(array, 0, newArray, 0, size); array = newArray; } return array; } #if USE_REFEMIT public void CheckEndOfArray(XmlReaderDelegator xmlReader, int arraySize, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) #else internal void CheckEndOfArray(XmlReaderDelegator xmlReader, int arraySize, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) #endif { if (xmlReader.NodeType == XmlNodeType.EndElement) return; while (xmlReader.IsStartElement()) { if (xmlReader.IsStartElement(itemName, itemNamespace)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayExceededSizeAttribute, arraySize, itemName.Value, itemNamespace.Value))); SkipUnknownElement(xmlReader); } if (xmlReader.NodeType != XmlNodeType.EndElement) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.EndElement, xmlReader)); } internal object ReadIXmlSerializable(XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType) { if (_xmlSerializableReader == null) _xmlSerializableReader = new XmlSerializableReader(); return ReadIXmlSerializable(_xmlSerializableReader, xmlReader, xmlDataContract, isMemberType); } internal static object ReadRootIXmlSerializable(XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType) { return ReadIXmlSerializable(new XmlSerializableReader(), xmlReader, xmlDataContract, isMemberType); } internal static object ReadIXmlSerializable(XmlSerializableReader xmlSerializableReader, XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType) { object obj = null; xmlSerializableReader.BeginRead(xmlReader); if (isMemberType && !xmlDataContract.HasRoot) { xmlReader.Read(); xmlReader.MoveToContent(); } if (xmlDataContract.UnderlyingType == Globals.TypeOfXmlElement) { if (!xmlReader.IsStartElement()) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); XmlDocument xmlDoc = new XmlDocument(); obj = (XmlElement)xmlDoc.ReadNode(xmlSerializableReader); } else if (xmlDataContract.UnderlyingType == Globals.TypeOfXmlNodeArray) { obj = XmlSerializableServices.ReadNodes(xmlSerializableReader); } else { IXmlSerializable xmlSerializable = xmlDataContract.CreateXmlSerializableDelegate(); xmlSerializable.ReadXml(xmlSerializableReader); obj = xmlSerializable; } xmlSerializableReader.EndRead(); return obj; } public SerializationInfo ReadSerializationInfo(XmlReaderDelegator xmlReader, Type type) { var serInfo = new SerializationInfo(type, XmlObjectSerializer.FormatterConverter); XmlNodeType nodeType; while ((nodeType = xmlReader.MoveToContent()) != XmlNodeType.EndElement) { if (nodeType != XmlNodeType.Element) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); } if (xmlReader.NamespaceURI.Length != 0) { SkipUnknownElement(xmlReader); continue; } string name = XmlConvert.DecodeName(xmlReader.LocalName); IncrementItemCount(1); ReadAttributes(xmlReader); object value; if (attributes.Ref != Globals.NewObjectId) { xmlReader.Skip(); value = GetExistingObject(attributes.Ref, null, name, String.Empty); } else if (attributes.XsiNil) { xmlReader.Skip(); value = null; } else { value = InternalDeserialize(xmlReader, Globals.TypeOfObject, name, String.Empty); } serInfo.AddValue(name, value); } return serInfo; } protected virtual DataContract ResolveDataContractFromTypeName() { return (attributes.XsiTypeName == null) ? null : ResolveDataContractFromKnownTypes(attributes.XsiTypeName, attributes.XsiTypeNamespace, null /*memberTypeContract*/); } private ExtensionDataMember ReadExtensionDataMember(XmlReaderDelegator xmlReader, int memberIndex) { var member = new ExtensionDataMember { Name = xmlReader.LocalName, Namespace = xmlReader.NamespaceURI, MemberIndex = memberIndex }; member.Value = xmlReader.UnderlyingExtensionDataReader != null ? xmlReader.UnderlyingExtensionDataReader.GetCurrentNode() : ReadExtensionDataValue(xmlReader); return member; } public IDataNode ReadExtensionDataValue(XmlReaderDelegator xmlReader) { ReadAttributes(xmlReader); IncrementItemCount(1); IDataNode dataNode = null; if (attributes.Ref != Globals.NewObjectId) { xmlReader.Skip(); object o = GetExistingObjectOrExtensionData(attributes.Ref); dataNode = (o is IDataNode) ? (IDataNode)o : new DataNode<object>(o); dataNode.Id = attributes.Ref; } else if (attributes.XsiNil) { xmlReader.Skip(); dataNode = null; } else { string dataContractName = null; string dataContractNamespace = null; if (attributes.XsiTypeName != null) { dataContractName = attributes.XsiTypeName; dataContractNamespace = attributes.XsiTypeNamespace; } if (IsReadingCollectionExtensionData(xmlReader)) { Read(xmlReader); dataNode = ReadUnknownCollectionData(xmlReader, dataContractName, dataContractNamespace); } else if (attributes.FactoryTypeName != null) { Read(xmlReader); dataNode = ReadUnknownISerializableData(xmlReader, dataContractName, dataContractNamespace); } else if (IsReadingClassExtensionData(xmlReader)) { Read(xmlReader); dataNode = ReadUnknownClassData(xmlReader, dataContractName, dataContractNamespace); } else { DataContract dataContract = ResolveDataContractFromTypeName(); if (dataContract == null) dataNode = ReadExtensionDataValue(xmlReader, dataContractName, dataContractNamespace); else if (dataContract is XmlDataContract) dataNode = ReadUnknownXmlData(xmlReader, dataContractName, dataContractNamespace); else { if (dataContract.IsISerializable) { Read(xmlReader); dataNode = ReadUnknownISerializableData(xmlReader, dataContractName, dataContractNamespace); } else if (dataContract is PrimitiveDataContract) { if (attributes.Id == Globals.NewObjectId) { Read(xmlReader); xmlReader.MoveToContent(); dataNode = ReadUnknownPrimitiveData(xmlReader, dataContract.UnderlyingType, dataContractName, dataContractNamespace); xmlReader.ReadEndElement(); } else { dataNode = new DataNode<object>(xmlReader.ReadElementContentAsAnyType(dataContract.UnderlyingType)); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); } } else if (dataContract is EnumDataContract) { dataNode = new DataNode<object>(((EnumDataContract)dataContract).ReadEnumValue(xmlReader)); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); } else if (dataContract is ClassDataContract) { Read(xmlReader); dataNode = ReadUnknownClassData(xmlReader, dataContractName, dataContractNamespace); } else if (dataContract is CollectionDataContract) { Read(xmlReader); dataNode = ReadUnknownCollectionData(xmlReader, dataContractName, dataContractNamespace); } } } } return dataNode; } protected virtual void StartReadExtensionDataValue(XmlReaderDelegator xmlReader) { } private IDataNode ReadExtensionDataValue(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) { StartReadExtensionDataValue(xmlReader); if (attributes.UnrecognizedAttributesFound) return ReadUnknownXmlData(xmlReader, dataContractName, dataContractNamespace); IDictionary<string, string> namespacesInScope = xmlReader.GetNamespacesInScope(XmlNamespaceScope.ExcludeXml); Read(xmlReader); xmlReader.MoveToContent(); switch (xmlReader.NodeType) { case XmlNodeType.Text: return ReadPrimitiveExtensionDataValue(xmlReader, dataContractName, dataContractNamespace); case XmlNodeType.Element: if (xmlReader.NamespaceURI.StartsWith(Globals.DataContractXsdBaseNamespace, StringComparison.Ordinal)) return ReadUnknownClassData(xmlReader, dataContractName, dataContractNamespace); else return ReadAndResolveUnknownXmlData(xmlReader, namespacesInScope, dataContractName, dataContractNamespace); case XmlNodeType.EndElement: { // NOTE: cannot distinguish between empty class or IXmlSerializable and typeof(object) IDataNode objNode = ReadUnknownPrimitiveData(xmlReader, Globals.TypeOfObject, dataContractName, dataContractNamespace); xmlReader.ReadEndElement(); objNode.IsFinalValue = false; return objNode; } default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); } } protected virtual IDataNode ReadPrimitiveExtensionDataValue(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) { Type valueType = xmlReader.ValueType; if (valueType == Globals.TypeOfString) { // NOTE: cannot distinguish other primitives from string (default XmlReader ValueType) IDataNode stringNode = new DataNode<object>(xmlReader.ReadContentAsString()); InitializeExtensionDataNode(stringNode, dataContractName, dataContractNamespace); stringNode.IsFinalValue = false; xmlReader.ReadEndElement(); return stringNode; } IDataNode objNode = ReadUnknownPrimitiveData(xmlReader, valueType, dataContractName, dataContractNamespace); xmlReader.ReadEndElement(); return objNode; } protected void InitializeExtensionDataNode(IDataNode dataNode, string dataContractName, string dataContractNamespace) { dataNode.DataContractName = dataContractName; dataNode.DataContractNamespace = dataContractNamespace; dataNode.ClrAssemblyName = attributes.ClrAssembly; dataNode.ClrTypeName = attributes.ClrType; AddNewObject(dataNode); dataNode.Id = attributes.Id; } private IDataNode ReadUnknownPrimitiveData(XmlReaderDelegator xmlReader, Type type, string dataContractName, string dataContractNamespace) { IDataNode dataNode = xmlReader.ReadExtensionData(type); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); return dataNode; } private ClassDataNode ReadUnknownClassData(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) { var dataNode = new ClassDataNode(); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); int memberIndex = 0; XmlNodeType nodeType; while ((nodeType = xmlReader.MoveToContent()) != XmlNodeType.EndElement) { if (nodeType != XmlNodeType.Element) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); if (dataNode.Members == null) dataNode.Members = new List<ExtensionDataMember>(); dataNode.Members.Add(ReadExtensionDataMember(xmlReader, memberIndex++)); } xmlReader.ReadEndElement(); return dataNode; } private CollectionDataNode ReadUnknownCollectionData(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) { var dataNode = new CollectionDataNode(); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); int arraySize = attributes.ArraySZSize; XmlNodeType nodeType; while ((nodeType = xmlReader.MoveToContent()) != XmlNodeType.EndElement) { if (nodeType != XmlNodeType.Element) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); if (dataNode.ItemName == null) { dataNode.ItemName = xmlReader.LocalName; dataNode.ItemNamespace = xmlReader.NamespaceURI; } if (xmlReader.IsStartElement(dataNode.ItemName, dataNode.ItemNamespace)) { if (dataNode.Items == null) dataNode.Items = new List<IDataNode>(); dataNode.Items.Add(ReadExtensionDataValue(xmlReader)); } else SkipUnknownElement(xmlReader); } xmlReader.ReadEndElement(); if (arraySize != -1) { dataNode.Size = arraySize; if (dataNode.Items == null) { if (dataNode.Size > 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArraySizeAttributeIncorrect, arraySize, 0))); } else if (dataNode.Size != dataNode.Items.Count) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArraySizeAttributeIncorrect, arraySize, dataNode.Items.Count))); } else { if (dataNode.Items != null) { dataNode.Size = dataNode.Items.Count; } else { dataNode.Size = 0; } } return dataNode; } private ISerializableDataNode ReadUnknownISerializableData(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) { var dataNode = new ISerializableDataNode(); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); dataNode.FactoryTypeName = attributes.FactoryTypeName; dataNode.FactoryTypeNamespace = attributes.FactoryTypeNamespace; XmlNodeType nodeType; while ((nodeType = xmlReader.MoveToContent()) != XmlNodeType.EndElement) { if (nodeType != XmlNodeType.Element) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); if (xmlReader.NamespaceURI.Length != 0) { SkipUnknownElement(xmlReader); continue; } var member = new ISerializableDataMember(); member.Name = xmlReader.LocalName; member.Value = ReadExtensionDataValue(xmlReader); if (dataNode.Members == null) dataNode.Members = new List<ISerializableDataMember>(); dataNode.Members.Add(member); } xmlReader.ReadEndElement(); return dataNode; } private IDataNode ReadUnknownXmlData(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) { XmlDataNode dataNode = new XmlDataNode(); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); dataNode.OwnerDocument = Document; if (xmlReader.NodeType == XmlNodeType.EndElement) return dataNode; IList<XmlAttribute> xmlAttributes = null; IList<XmlNode> xmlChildNodes = null; XmlNodeType nodeType = xmlReader.MoveToContent(); if (nodeType != XmlNodeType.Text) { while (xmlReader.MoveToNextAttribute()) { string ns = xmlReader.NamespaceURI; if (ns != Globals.SerializationNamespace && ns != Globals.SchemaInstanceNamespace) { if (xmlAttributes == null) xmlAttributes = new List<XmlAttribute>(); xmlAttributes.Add((XmlAttribute)Document.ReadNode(xmlReader.UnderlyingReader)); } } Read(xmlReader); } while ((nodeType = xmlReader.MoveToContent()) != XmlNodeType.EndElement) { if (xmlReader.EOF) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.UnexpectedEndOfFile))); if (xmlChildNodes == null) xmlChildNodes = new List<XmlNode>(); xmlChildNodes.Add(Document.ReadNode(xmlReader.UnderlyingReader)); } xmlReader.ReadEndElement(); dataNode.XmlAttributes = xmlAttributes; dataNode.XmlChildNodes = xmlChildNodes; return dataNode; } // Pattern-recognition logic: the method reads XML elements into DOM. To recognize as an array, it requires that // all items have the same name and namespace. To recognize as an ISerializable type, it requires that all // items be unqualified. If the XML only contains elements (no attributes or other nodes) is recognized as a // class/class hierarchy. Otherwise it is deserialized as XML. private IDataNode ReadAndResolveUnknownXmlData(XmlReaderDelegator xmlReader, IDictionary<string, string> namespaces, string dataContractName, string dataContractNamespace) { bool couldBeISerializableData = true; bool couldBeCollectionData = true; bool couldBeClassData = true; string elementNs = null, elementName = null; var xmlChildNodes = new List<XmlNode>(); IList<XmlAttribute> xmlAttributes = null; if (namespaces != null) { xmlAttributes = new List<XmlAttribute>(); foreach (KeyValuePair<string, string> prefixNsPair in namespaces) { xmlAttributes.Add(AddNamespaceDeclaration(prefixNsPair.Key, prefixNsPair.Value)); } } XmlNodeType nodeType; while ((nodeType = xmlReader.NodeType) != XmlNodeType.EndElement) { if (nodeType == XmlNodeType.Element) { string ns = xmlReader.NamespaceURI; string name = xmlReader.LocalName; if (couldBeISerializableData) couldBeISerializableData = (ns.Length == 0); if (couldBeCollectionData) { if (elementName == null) { elementName = name; elementNs = ns; } else couldBeCollectionData = (String.CompareOrdinal(elementName, name) == 0) && (String.CompareOrdinal(elementNs, ns) == 0); } } else if (xmlReader.EOF) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.UnexpectedEndOfFile))); else if (IsContentNode(xmlReader.NodeType)) couldBeClassData = couldBeISerializableData = couldBeCollectionData = false; if (_attributesInXmlData == null) _attributesInXmlData = new Attributes(); _attributesInXmlData.Read(xmlReader); XmlNode childNode = Document.ReadNode(xmlReader.UnderlyingReader); xmlChildNodes.Add(childNode); if (namespaces == null) { if (_attributesInXmlData.XsiTypeName != null) childNode.Attributes.Append(AddNamespaceDeclaration(_attributesInXmlData.XsiTypePrefix, _attributesInXmlData.XsiTypeNamespace)); if (_attributesInXmlData.FactoryTypeName != null) childNode.Attributes.Append(AddNamespaceDeclaration(_attributesInXmlData.FactoryTypePrefix, _attributesInXmlData.FactoryTypeNamespace)); } } xmlReader.ReadEndElement(); if (elementName != null && couldBeCollectionData) return ReadUnknownCollectionData(CreateReaderOverChildNodes(xmlAttributes, xmlChildNodes), dataContractName, dataContractNamespace); else if (couldBeISerializableData) return ReadUnknownISerializableData(CreateReaderOverChildNodes(xmlAttributes, xmlChildNodes), dataContractName, dataContractNamespace); else if (couldBeClassData) return ReadUnknownClassData(CreateReaderOverChildNodes(xmlAttributes, xmlChildNodes), dataContractName, dataContractNamespace); else { XmlDataNode dataNode = new XmlDataNode(); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); dataNode.OwnerDocument = Document; dataNode.XmlChildNodes = xmlChildNodes; dataNode.XmlAttributes = xmlAttributes; return dataNode; } } private bool IsContentNode(XmlNodeType nodeType) { switch (nodeType) { case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.Comment: case XmlNodeType.ProcessingInstruction: case XmlNodeType.DocumentType: return false; default: return true; } } internal XmlReaderDelegator CreateReaderOverChildNodes(IList<XmlAttribute> xmlAttributes, IList<XmlNode> xmlChildNodes) { XmlNode wrapperElement = CreateWrapperXmlElement(Document, xmlAttributes, xmlChildNodes, null, null, null); XmlReaderDelegator nodeReader = CreateReaderDelegatorForReader(new XmlNodeReader(wrapperElement)); nodeReader.MoveToContent(); Read(nodeReader); return nodeReader; } internal static XmlNode CreateWrapperXmlElement(XmlDocument document, IList<XmlAttribute> xmlAttributes, IList<XmlNode> xmlChildNodes, string prefix, string localName, string ns) { localName = localName ?? "wrapper"; ns = ns ?? string.Empty; XmlNode wrapperElement = document.CreateElement(prefix, localName, ns); if (xmlAttributes != null) { for (int i = 0; i < xmlAttributes.Count; i++) { wrapperElement.Attributes.Append((XmlAttribute) xmlAttributes[i]); } } if (xmlChildNodes != null) { for (int i = 0; i < xmlChildNodes.Count; i++) { wrapperElement.AppendChild(xmlChildNodes[i]); } } return wrapperElement; } private XmlAttribute AddNamespaceDeclaration(string prefix, string ns) { XmlAttribute attribute = (prefix == null || prefix.Length == 0) ? Document.CreateAttribute(null, Globals.XmlnsPrefix, Globals.XmlnsNamespace) : Document.CreateAttribute(Globals.XmlnsPrefix, prefix, Globals.XmlnsNamespace); attribute.Value = ns; return attribute; } #if USE_REFEMIT public static Exception CreateUnexpectedStateException(XmlNodeType expectedState, XmlReaderDelegator xmlReader) #else internal static Exception CreateUnexpectedStateException(XmlNodeType expectedState, XmlReaderDelegator xmlReader) #endif { return XmlObjectSerializer.CreateSerializationExceptionWithReaderDetails(SR.Format(SR.ExpectingState, expectedState), xmlReader); } //Silverlight only helper function to create SerializationException #if USE_REFEMIT public static Exception CreateSerializationException(string message) #else internal static Exception CreateSerializationException(string message) #endif { return XmlObjectSerializer.CreateSerializationException(message); } protected virtual object ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader) { return dataContract.ReadXmlValue(reader, this); } protected virtual XmlReaderDelegator CreateReaderDelegatorForReader(XmlReader xmlReader) { return new XmlReaderDelegator(xmlReader); } protected virtual bool IsReadingCollectionExtensionData(XmlReaderDelegator xmlReader) { return (attributes.ArraySZSize != -1); } protected virtual bool IsReadingClassExtensionData(XmlReaderDelegator xmlReader) { return false; } } }
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // 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. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1995 { /// <summary> /// Section 5.3.6.8. Request for data from an entity /// </summary> [Serializable] [XmlRoot] [XmlInclude(typeof(FixedDatum))] [XmlInclude(typeof(VariableDatum))] public partial class DataQueryPdu : SimulationManagementPdu, IEquatable<DataQueryPdu> { /// <summary> /// ID of request /// </summary> private uint _requestID; /// <summary> /// time issues between issues of Data PDUs. Zero means send once only. /// </summary> private uint _timeInterval; /// <summary> /// Number of fixed datum records /// </summary> private uint _fixedDatumRecordCount; /// <summary> /// Number of variable datum records /// </summary> private uint _variableDatumRecordCount; /// <summary> /// variable length list of fixed datums /// </summary> private List<FixedDatum> _fixedDatums = new List<FixedDatum>(); /// <summary> /// variable length list of variable length datums /// </summary> private List<VariableDatum> _variableDatums = new List<VariableDatum>(); /// <summary> /// Initializes a new instance of the <see cref="DataQueryPdu"/> class. /// </summary> public DataQueryPdu() { PduType = (byte)18; } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(DataQueryPdu left, DataQueryPdu right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(DataQueryPdu left, DataQueryPdu right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public override int GetMarshalledSize() { int marshalSize = 0; marshalSize = base.GetMarshalledSize(); marshalSize += 4; // this._requestID marshalSize += 4; // this._timeInterval marshalSize += 4; // this._fixedDatumRecordCount marshalSize += 4; // this._variableDatumRecordCount for (int idx = 0; idx < this._fixedDatums.Count; idx++) { FixedDatum listElement = (FixedDatum)this._fixedDatums[idx]; marshalSize += listElement.GetMarshalledSize(); } for (int idx = 0; idx < this._variableDatums.Count; idx++) { VariableDatum listElement = (VariableDatum)this._variableDatums[idx]; marshalSize += listElement.GetMarshalledSize(); } return marshalSize; } /// <summary> /// Gets or sets the ID of request /// </summary> [XmlElement(Type = typeof(uint), ElementName = "requestID")] public uint RequestID { get { return this._requestID; } set { this._requestID = value; } } /// <summary> /// Gets or sets the time issues between issues of Data PDUs. Zero means send once only. /// </summary> [XmlElement(Type = typeof(uint), ElementName = "timeInterval")] public uint TimeInterval { get { return this._timeInterval; } set { this._timeInterval = value; } } /// <summary> /// Gets or sets the Number of fixed datum records /// </summary> /// <remarks> /// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose. /// The getfixedDatumRecordCount method will also be based on the actual list length rather than this value. /// The method is simply here for completeness and should not be used for any computations. /// </remarks> [XmlElement(Type = typeof(uint), ElementName = "fixedDatumRecordCount")] public uint FixedDatumRecordCount { get { return this._fixedDatumRecordCount; } set { this._fixedDatumRecordCount = value; } } /// <summary> /// Gets or sets the Number of variable datum records /// </summary> /// <remarks> /// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose. /// The getvariableDatumRecordCount method will also be based on the actual list length rather than this value. /// The method is simply here for completeness and should not be used for any computations. /// </remarks> [XmlElement(Type = typeof(uint), ElementName = "variableDatumRecordCount")] public uint VariableDatumRecordCount { get { return this._variableDatumRecordCount; } set { this._variableDatumRecordCount = value; } } /// <summary> /// Gets the variable length list of fixed datums /// </summary> [XmlElement(ElementName = "fixedDatumsList", Type = typeof(List<FixedDatum>))] public List<FixedDatum> FixedDatums { get { return this._fixedDatums; } } /// <summary> /// Gets the variable length list of variable length datums /// </summary> [XmlElement(ElementName = "variableDatumsList", Type = typeof(List<VariableDatum>))] public List<VariableDatum> VariableDatums { get { return this._variableDatums; } } /// <summary> /// Automatically sets the length of the marshalled data, then calls the marshal method. /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> public override void MarshalAutoLengthSet(DataOutputStream dos) { // Set the length prior to marshalling data this.Length = (ushort)this.GetMarshalledSize(); this.Marshal(dos); } /// <summary> /// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Marshal(DataOutputStream dos) { base.Marshal(dos); if (dos != null) { try { dos.WriteUnsignedInt((uint)this._requestID); dos.WriteUnsignedInt((uint)this._timeInterval); dos.WriteUnsignedInt((uint)this._fixedDatums.Count); dos.WriteUnsignedInt((uint)this._variableDatums.Count); for (int idx = 0; idx < this._fixedDatums.Count; idx++) { FixedDatum aFixedDatum = (FixedDatum)this._fixedDatums[idx]; aFixedDatum.Marshal(dos); } for (int idx = 0; idx < this._variableDatums.Count; idx++) { VariableDatum aVariableDatum = (VariableDatum)this._variableDatums[idx]; aVariableDatum.Marshal(dos); } } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Unmarshal(DataInputStream dis) { base.Unmarshal(dis); if (dis != null) { try { this._requestID = dis.ReadUnsignedInt(); this._timeInterval = dis.ReadUnsignedInt(); this._fixedDatumRecordCount = dis.ReadUnsignedInt(); this._variableDatumRecordCount = dis.ReadUnsignedInt(); for (int idx = 0; idx < this.FixedDatumRecordCount; idx++) { FixedDatum anX = new FixedDatum(); anX.Unmarshal(dis); this._fixedDatums.Add(anX); } for (int idx = 0; idx < this.VariableDatumRecordCount; idx++) { VariableDatum anX = new VariableDatum(); anX.Unmarshal(dis); this._variableDatums.Add(anX); } } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } /// <summary> /// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging. /// This will be modified in the future to provide a better display. Usage: /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb }); /// where pdu is an object representing a single pdu and sb is a StringBuilder. /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality /// </summary> /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Reflection(StringBuilder sb) { sb.AppendLine("<DataQueryPdu>"); base.Reflection(sb); try { sb.AppendLine("<requestID type=\"uint\">" + this._requestID.ToString(CultureInfo.InvariantCulture) + "</requestID>"); sb.AppendLine("<timeInterval type=\"uint\">" + this._timeInterval.ToString(CultureInfo.InvariantCulture) + "</timeInterval>"); sb.AppendLine("<fixedDatums type=\"uint\">" + this._fixedDatums.Count.ToString(CultureInfo.InvariantCulture) + "</fixedDatums>"); sb.AppendLine("<variableDatums type=\"uint\">" + this._variableDatums.Count.ToString(CultureInfo.InvariantCulture) + "</variableDatums>"); for (int idx = 0; idx < this._fixedDatums.Count; idx++) { sb.AppendLine("<fixedDatums" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"FixedDatum\">"); FixedDatum aFixedDatum = (FixedDatum)this._fixedDatums[idx]; aFixedDatum.Reflection(sb); sb.AppendLine("</fixedDatums" + idx.ToString(CultureInfo.InvariantCulture) + ">"); } for (int idx = 0; idx < this._variableDatums.Count; idx++) { sb.AppendLine("<variableDatums" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"VariableDatum\">"); VariableDatum aVariableDatum = (VariableDatum)this._variableDatums[idx]; aVariableDatum.Reflection(sb); sb.AppendLine("</variableDatums" + idx.ToString(CultureInfo.InvariantCulture) + ">"); } sb.AppendLine("</DataQueryPdu>"); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return this == obj as DataQueryPdu; } /// <summary> /// Compares for reference AND value equality. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public bool Equals(DataQueryPdu obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } ivarsEqual = base.Equals(obj); if (this._requestID != obj._requestID) { ivarsEqual = false; } if (this._timeInterval != obj._timeInterval) { ivarsEqual = false; } if (this._fixedDatumRecordCount != obj._fixedDatumRecordCount) { ivarsEqual = false; } if (this._variableDatumRecordCount != obj._variableDatumRecordCount) { ivarsEqual = false; } if (this._fixedDatums.Count != obj._fixedDatums.Count) { ivarsEqual = false; } if (ivarsEqual) { for (int idx = 0; idx < this._fixedDatums.Count; idx++) { if (!this._fixedDatums[idx].Equals(obj._fixedDatums[idx])) { ivarsEqual = false; } } } if (this._variableDatums.Count != obj._variableDatums.Count) { ivarsEqual = false; } if (ivarsEqual) { for (int idx = 0; idx < this._variableDatums.Count; idx++) { if (!this._variableDatums[idx].Equals(obj._variableDatums[idx])) { ivarsEqual = false; } } } return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; result = GenerateHash(result) ^ base.GetHashCode(); result = GenerateHash(result) ^ this._requestID.GetHashCode(); result = GenerateHash(result) ^ this._timeInterval.GetHashCode(); result = GenerateHash(result) ^ this._fixedDatumRecordCount.GetHashCode(); result = GenerateHash(result) ^ this._variableDatumRecordCount.GetHashCode(); if (this._fixedDatums.Count > 0) { for (int idx = 0; idx < this._fixedDatums.Count; idx++) { result = GenerateHash(result) ^ this._fixedDatums[idx].GetHashCode(); } } if (this._variableDatums.Count > 0) { for (int idx = 0; idx < this._variableDatums.Count; idx++) { result = GenerateHash(result) ^ this._variableDatums[idx].GetHashCode(); } } return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using GoCardless.Internals; using GoCardless.Resources; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace GoCardless.Services { /// <summary> /// Service class for working with mandate pdf resources. /// /// Mandate PDFs allow you to easily display [scheme-rules /// compliant](#appendix-compliance-requirements) Direct Debit mandates to /// your customers. /// </summary> public class MandatePdfService { private readonly GoCardlessClient _goCardlessClient; /// <summary> /// Constructor. Users of this library should not call this. An instance of this /// class can be accessed through an initialised GoCardlessClient. /// </summary> public MandatePdfService(GoCardlessClient goCardlessClient) { _goCardlessClient = goCardlessClient; } /// <summary> /// Generates a PDF mandate and returns its temporary URL. /// /// Customer and bank account details can be left blank (for a blank /// mandate), provided manually, or inferred from the ID of an existing /// [mandate](#core-endpoints-mandates). /// /// By default, we'll generate PDF mandates in English. /// /// To generate a PDF mandate in another language, set the /// `Accept-Language` header when creating the PDF mandate to the /// relevant [ISO /// 639-1](http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) /// language code supported for the scheme. /// /// | Scheme | Supported languages /// /// | /// | :--------------- | /// :------------------------------------------------------------------------------------------------------------------------------------------- /// | /// | ACH | English (`en`) /// /// | /// | Autogiro | English (`en`), Swedish (`sv`) /// /// | /// | Bacs | English (`en`) /// /// | /// | BECS | English (`en`) /// /// | /// | BECS NZ | English (`en`) /// /// | /// | Betalingsservice | Danish (`da`), English (`en`) /// /// | /// | PAD | English (`en`) /// /// | /// | SEPA Core | Danish (`da`), Dutch (`nl`), English (`en`), /// French (`fr`), German (`de`), Italian (`it`), Portuguese (`pt`), /// Spanish (`es`), Swedish (`sv`) | /// </summary> /// <param name="request">An optional `MandatePdfCreateRequest` representing the body for this create request.</param> /// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param> /// <returns>A single mandate pdf resource</returns> public Task<MandatePdfResponse> CreateAsync(MandatePdfCreateRequest request = null, RequestSettings customiseRequestMessage = null) { request = request ?? new MandatePdfCreateRequest(); var urlParams = new List<KeyValuePair<string, object>> {}; return _goCardlessClient.ExecuteAsync<MandatePdfResponse>("POST", "/mandate_pdfs", urlParams, request, null, "mandate_pdfs", customiseRequestMessage); } } /// <summary> /// Generates a PDF mandate and returns its temporary URL. /// /// Customer and bank account details can be left blank (for a blank /// mandate), provided manually, or inferred from the ID of an existing /// [mandate](#core-endpoints-mandates). /// /// By default, we'll generate PDF mandates in English. /// /// To generate a PDF mandate in another language, set the `Accept-Language` /// header when creating the PDF mandate to the relevant [ISO /// 639-1](http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) language /// code supported for the scheme. /// /// | Scheme | Supported languages /// /// | /// | :--------------- | /// :------------------------------------------------------------------------------------------------------------------------------------------- /// | /// | ACH | English (`en`) /// /// | /// | Autogiro | English (`en`), Swedish (`sv`) /// /// | /// | Bacs | English (`en`) /// /// | /// | BECS | English (`en`) /// /// | /// | BECS NZ | English (`en`) /// /// | /// | Betalingsservice | Danish (`da`), English (`en`) /// /// | /// | PAD | English (`en`) /// /// | /// | SEPA Core | Danish (`da`), Dutch (`nl`), English (`en`), French /// (`fr`), German (`de`), Italian (`it`), Portuguese (`pt`), Spanish /// (`es`), Swedish (`sv`) | /// </summary> public class MandatePdfCreateRequest { /// <summary> /// Name of the account holder, as known by the bank. Usually this /// matches the name of the [customer](#core-endpoints-customers). This /// field cannot exceed 18 characters. /// </summary> [JsonProperty("account_holder_name")] public string AccountHolderName { get; set; } /// <summary> /// Bank account number - see [local /// details](#appendix-local-bank-details) for more information. /// Alternatively you can provide an `iban`. /// </summary> [JsonProperty("account_number")] public string AccountNumber { get; set; } /// <summary> /// Bank account type. Required for USD-denominated bank accounts. Must /// not be provided for bank accounts in other currencies. See [local /// details](#local-bank-details-united-states) for more information. /// </summary> [JsonProperty("account_type")] public MandatePdfAccountType? AccountType { get; set; } /// <summary> /// Bank account type. Required for USD-denominated bank accounts. Must /// not be provided for bank accounts in other currencies. See [local /// details](#local-bank-details-united-states) for more information. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum MandatePdfAccountType { /// <summary>`account_type` with a value of "savings"</summary> [EnumMember(Value = "savings")] Savings, /// <summary>`account_type` with a value of "checking"</summary> [EnumMember(Value = "checking")] Checking, } /// <summary> /// The first line of the customer's address. /// </summary> [JsonProperty("address_line1")] public string AddressLine1 { get; set; } /// <summary> /// The second line of the customer's address. /// </summary> [JsonProperty("address_line2")] public string AddressLine2 { get; set; } /// <summary> /// The third line of the customer's address. /// </summary> [JsonProperty("address_line3")] public string AddressLine3 { get; set; } /// <summary> /// Bank code - see [local details](#appendix-local-bank-details) for /// more information. Alternatively you can provide an `iban`. /// </summary> [JsonProperty("bank_code")] public string BankCode { get; set; } /// <summary> /// SWIFT BIC. Will be derived automatically if a valid `iban` or [local /// details](#appendix-local-bank-details) are provided. /// </summary> [JsonProperty("bic")] public string Bic { get; set; } /// <summary> /// Branch code - see [local details](#appendix-local-bank-details) for /// more information. Alternatively you can provide an `iban`. /// </summary> [JsonProperty("branch_code")] public string BranchCode { get; set; } /// <summary> /// The city of the customer's address. /// </summary> [JsonProperty("city")] public string City { get; set; } /// <summary> /// [ISO /// 3166-1](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements) /// alpha-2 code. Required if providing local details. /// </summary> [JsonProperty("country_code")] public string CountryCode { get; set; } /// <summary> /// For Danish customers only. The civic/company number (CPR or CVR) of /// the customer. Should only be supplied for Betalingsservice mandates. /// </summary> [JsonProperty("danish_identity_number")] public string DanishIdentityNumber { get; set; } /// <summary> /// International Bank Account Number. Alternatively you can provide /// [local details](#appendix-local-bank-details). IBANs cannot be /// provided for Autogiro mandates. /// </summary> [JsonProperty("iban")] public string Iban { get; set; } /// <summary> /// Linked resources. /// </summary> [JsonProperty("links")] public MandatePdfLinks Links { get; set; } /// <summary> /// Linked resources for a MandatePdf. /// </summary> public class MandatePdfLinks { /// <summary> /// ID of an existing [mandate](#core-endpoints-mandates) to build /// the PDF from. The customer's bank details will be censored in /// the generated PDF. No other parameters may be provided alongside /// this. /// </summary> [JsonProperty("mandate")] public string Mandate { get; set; } } /// <summary> /// Unique 6 to 18 character reference. This may be left blank at the /// point of signing. /// </summary> [JsonProperty("mandate_reference")] public string MandateReference { get; set; } /// <summary> /// For American customers only. IP address of the computer used by the /// customer to set up the mandate. This is required in order to create /// compliant Mandate PDFs according to the ACH scheme rules. /// </summary> [JsonProperty("payer_ip_address")] public string PayerIpAddress { get; set; } /// <summary> /// The customer phone number. Should only be provided for BECS NZ /// mandates. /// </summary> [JsonProperty("phone_number")] public string PhoneNumber { get; set; } /// <summary> /// The customer's postal code. /// </summary> [JsonProperty("postal_code")] public string PostalCode { get; set; } /// <summary> /// The customer's address region, county or department. For US /// customers a 2 letter /// [ISO3166-2:US](https://en.wikipedia.org/wiki/ISO_3166-2:US) state /// code is required (e.g. `CA` for California). /// </summary> [JsonProperty("region")] public string Region { get; set; } /// <summary> /// Direct Debit scheme. Can be supplied or automatically detected from /// the bank account details provided. If you do not provide a scheme, /// you must provide either a mandate, an `iban`, or [local /// details](#appendix-local-bank-details) including a `country_code`. /// </summary> [JsonProperty("scheme")] public string Scheme { get; set; } /// <summary> /// If provided, a form will be generated with this date and no /// signature field. /// </summary> [JsonProperty("signature_date")] public string SignatureDate { get; set; } /// <summary> /// For American customers only. Subscription amount being authorised by /// the mandate. In the lowest denomination for the currency (cents in /// USD). Is required if `subscription_frequency` has been provided. /// </summary> [JsonProperty("subscription_amount")] public int? SubscriptionAmount { get; set; } /// <summary> /// For American customers only. Frequency of the subscription being /// authorised by the mandate. One of `weekly`, `monthly` or `yearly`. /// Is required if `subscription_amount` has been provided. /// </summary> [JsonProperty("subscription_frequency")] public string SubscriptionFrequency { get; set; } /// <summary> /// For American customers only. Frequency of the subscription being /// authorised by the mandate. One of `weekly`, `monthly` or `yearly`. /// Is required if `subscription_amount` has been provided. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum MandatePdfSubscriptionFrequency { /// <summary>`subscription_frequency` with a value of "weekly"</summary> [EnumMember(Value = "weekly")] Weekly, /// <summary>`subscription_frequency` with a value of "monthly"</summary> [EnumMember(Value = "monthly")] Monthly, /// <summary>`subscription_frequency` with a value of "yearly"</summary> [EnumMember(Value = "yearly")] Yearly, } /// <summary> /// For Swedish customers only. The civic/company number (personnummer, /// samordningsnummer, or organisationsnummer) of the customer. Should /// only be supplied for Autogiro mandates. /// </summary> [JsonProperty("swedish_identity_number")] public string SwedishIdentityNumber { get; set; } } /// <summary> /// An API response for a request returning a single mandate pdf. /// </summary> public class MandatePdfResponse : ApiResponse { /// <summary> /// The mandate pdf from the response. /// </summary> [JsonProperty("mandate_pdfs")] public MandatePdf MandatePdf { get; private set; } } }
#if !UNITY_WINRT || UNITY_EDITOR || (UNITY_WP8 && !UNITY_WP_8_1) #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Reflection; using System.Collections; using System.Linq; using System.Globalization; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Text; using System.Text.RegularExpressions; namespace Newtonsoft.Json.Utilities { public delegate object D1(); internal static class ReflectionUtils { public static bool IsVirtual(this PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, "propertyInfo"); MethodInfo m = propertyInfo.GetGetMethod(); if (m != null && m.IsVirtual) return true; m = propertyInfo.GetSetMethod(); if (m != null && m.IsVirtual) return true; return false; } public static Type GetObjectType(object v) { return (v != null) ? v.GetType() : null; } #pragma warning disable 436 public static string GetTypeName(Type t, FormatterAssemblyStyle assemblyFormat) { return GetTypeName(t, assemblyFormat, null); } public static string GetTypeName(Type t, FormatterAssemblyStyle assemblyFormat, SerializationBinder binder) { string fullyQualifiedTypeName; fullyQualifiedTypeName = t.AssemblyQualifiedName; switch (assemblyFormat) { case FormatterAssemblyStyle.Simple: return RemoveAssemblyDetails(fullyQualifiedTypeName); case FormatterAssemblyStyle.Full: return t.AssemblyQualifiedName; default: throw new ArgumentOutOfRangeException(); } } #pragma warning restore 436 private static string RemoveAssemblyDetails(string fullyQualifiedTypeName) { StringBuilder builder = new StringBuilder(); // loop through the type name and filter out qualified assembly details from nested type names bool writingAssemblyName = false; bool skippingAssemblyDetails = false; for (int i = 0; i < fullyQualifiedTypeName.Length; i++) { char current = fullyQualifiedTypeName[i]; switch (current) { case '[': writingAssemblyName = false; skippingAssemblyDetails = false; builder.Append(current); break; case ']': writingAssemblyName = false; skippingAssemblyDetails = false; builder.Append(current); break; case ',': if (!writingAssemblyName) { writingAssemblyName = true; builder.Append(current); } else { skippingAssemblyDetails = true; } break; default: if (!skippingAssemblyDetails) builder.Append(current); break; } } return builder.ToString(); } public static bool IsInstantiatableType(Type t) { ValidationUtils.ArgumentNotNull(t, "t"); if (t.IsAbstract || t.IsInterface || t.IsArray || t.IsGenericTypeDefinition || t == typeof(void)) return false; if (!HasDefaultConstructor(t)) return false; return true; } public static bool HasDefaultConstructor(Type t) { return HasDefaultConstructor(t, false); } public static bool HasDefaultConstructor(Type t, bool nonPublic) { ValidationUtils.ArgumentNotNull(t, "t"); if (t.IsValueType) return true; return (GetDefaultConstructor(t, nonPublic) != null); } public static ConstructorInfo GetDefaultConstructor(Type t) { return GetDefaultConstructor(t, false); } public static ConstructorInfo GetDefaultConstructor(Type t, bool nonPublic) { BindingFlags accessModifier = BindingFlags.Public; if (nonPublic) accessModifier = accessModifier | BindingFlags.NonPublic; return t.GetConstructor(accessModifier | BindingFlags.Instance, null, new Type[0], null); } public static bool IsNullable(Type t) { ValidationUtils.ArgumentNotNull(t, "t"); if (t.IsValueType) return IsNullableType(t); return true; } public static bool IsNullableType(Type t) { ValidationUtils.ArgumentNotNull(t, "t"); return (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)); } public static Type EnsureNotNullableType(Type t) { return (IsNullableType(t)) ? Nullable.GetUnderlyingType(t) : t; } //public static bool IsValueTypeUnitializedValue(ValueType value) //{ // if (value == null) // return true; // return value.Equals(CreateUnitializedValue(value.GetType())); //} public static bool IsUnitializedValue(object value) { if (value == null) { return true; } else { object unitializedValue = CreateUnitializedValue(value.GetType()); return value.Equals(unitializedValue); } } public static object CreateUnitializedValue(Type type) { ValidationUtils.ArgumentNotNull(type, "type"); if (type.IsGenericTypeDefinition) throw new ArgumentException("Type {0} is a generic type definition and cannot be instantiated.".FormatWith(CultureInfo.InvariantCulture, type), "type"); if (type.IsClass || type.IsInterface || type == typeof(void)) return null; else if (type.IsValueType) return Activator.CreateInstance(type); else throw new ArgumentException("Type {0} cannot be instantiated.".FormatWith(CultureInfo.InvariantCulture, type), "type"); } public static bool IsPropertyIndexed(PropertyInfo property) { ValidationUtils.ArgumentNotNull(property, "property"); return !CollectionUtils.IsNullOrEmpty<ParameterInfo>(property.GetIndexParameters()); } public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition) { Type implementingType; return ImplementsGenericDefinition(type, genericInterfaceDefinition, out implementingType); } public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition, out Type implementingType) { ValidationUtils.ArgumentNotNull(type, "type"); ValidationUtils.ArgumentNotNull(genericInterfaceDefinition, "genericInterfaceDefinition"); if (!genericInterfaceDefinition.IsInterface || !genericInterfaceDefinition.IsGenericTypeDefinition) throw new ArgumentNullException("'{0}' is not a generic interface definition.".FormatWith(CultureInfo.InvariantCulture, genericInterfaceDefinition)); if (type.IsInterface) { if (type.IsGenericType) { Type interfaceDefinition = type.GetGenericTypeDefinition(); if (genericInterfaceDefinition == interfaceDefinition) { implementingType = type; return true; } } } foreach (Type i in type.GetInterfaces()) { if (i.IsGenericType) { Type interfaceDefinition = i.GetGenericTypeDefinition(); if (genericInterfaceDefinition == interfaceDefinition) { implementingType = i; return true; } } } implementingType = null; return false; } public static bool AssignableToTypeName(this Type type, string fullTypeName, out Type match) { Type current = type; while (current != null) { if (string.Equals(current.FullName, fullTypeName, StringComparison.Ordinal)) { match = current; return true; } current = current.BaseType; } foreach (Type i in type.GetInterfaces()) { if (string.Equals(i.Name, fullTypeName, StringComparison.Ordinal)) { match = type; return true; } } match = null; return false; } public static bool AssignableToTypeName(this Type type, string fullTypeName) { Type match; return type.AssignableToTypeName(fullTypeName, out match); } public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition) { Type implementingType; return InheritsGenericDefinition(type, genericClassDefinition, out implementingType); } public static bool InheritsGenericDefinition(Type type, Type genericClassDefinition, out Type implementingType) { ValidationUtils.ArgumentNotNull(type, "type"); ValidationUtils.ArgumentNotNull(genericClassDefinition, "genericClassDefinition"); if (!genericClassDefinition.IsClass || !genericClassDefinition.IsGenericTypeDefinition) throw new ArgumentNullException("'{0}' is not a generic class definition.".FormatWith(CultureInfo.InvariantCulture, genericClassDefinition)); return InheritsGenericDefinitionInternal(type, genericClassDefinition, out implementingType); } private static bool InheritsGenericDefinitionInternal(Type currentType, Type genericClassDefinition, out Type implementingType) { if (currentType.IsGenericType) { Type currentGenericClassDefinition = currentType.GetGenericTypeDefinition(); if (genericClassDefinition == currentGenericClassDefinition) { implementingType = currentType; return true; } } if (currentType.BaseType == null) { implementingType = null; return false; } return InheritsGenericDefinitionInternal(currentType.BaseType, genericClassDefinition, out implementingType); } /// <summary> /// Gets the type of the typed collection's items. /// </summary> /// <param name="type">The type.</param> /// <returns>The type of the typed collection's items.</returns> public static Type GetCollectionItemType(Type type) { ValidationUtils.ArgumentNotNull(type, "type"); Type genericListType; if (type.IsArray) { return type.GetElementType(); } else if (ImplementsGenericDefinition(type, typeof(IEnumerable<>), out genericListType)) { if (genericListType.IsGenericTypeDefinition) throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type)); return genericListType.GetGenericArguments()[0]; } else if (typeof(IEnumerable).IsAssignableFrom(type)) { return null; } else { throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type)); } } public static void GetDictionaryKeyValueTypes(Type dictionaryType, out Type keyType, out Type valueType) { ValidationUtils.ArgumentNotNull(dictionaryType, "type"); Type genericDictionaryType; if (ImplementsGenericDefinition(dictionaryType, typeof(IDictionary<,>), out genericDictionaryType)) { if (genericDictionaryType.IsGenericTypeDefinition) throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType)); Type[] dictionaryGenericArguments = genericDictionaryType.GetGenericArguments(); keyType = dictionaryGenericArguments[0]; valueType = dictionaryGenericArguments[1]; return; } else if (typeof(IDictionary).IsAssignableFrom(dictionaryType)) { keyType = null; valueType = null; return; } else { throw new Exception("Type {0} is not a dictionary.".FormatWith(CultureInfo.InvariantCulture, dictionaryType)); } } public static Type GetDictionaryValueType(Type dictionaryType) { Type keyType; Type valueType; GetDictionaryKeyValueTypes(dictionaryType, out keyType, out valueType); return valueType; } public static Type GetDictionaryKeyType(Type dictionaryType) { Type keyType; Type valueType; GetDictionaryKeyValueTypes(dictionaryType, out keyType, out valueType); return keyType; } /// <summary> /// Tests whether the list's items are their unitialized value. /// </summary> /// <param name="list">The list.</param> /// <returns>Whether the list's items are their unitialized value</returns> public static bool ItemsUnitializedValue<T>(IList<T> list) { ValidationUtils.ArgumentNotNull(list, "list"); Type elementType = GetCollectionItemType(list.GetType()); if (elementType.IsValueType) { object unitializedValue = CreateUnitializedValue(elementType); for (int i = 0; i < list.Count; i++) { if (!list[i].Equals(unitializedValue)) return false; } } else if (elementType.IsClass) { for (int i = 0; i < list.Count; i++) { object value = list[i]; if (value != null) return false; } } else { throw new Exception("Type {0} is neither a ValueType or a Class.".FormatWith(CultureInfo.InvariantCulture, elementType)); } return true; } /// <summary> /// Gets the member's underlying type. /// </summary> /// <param name="member">The member.</param> /// <returns>The underlying type of the member.</returns> public static Type GetMemberUnderlyingType(MemberInfo member) { ValidationUtils.ArgumentNotNull(member, "member"); switch (member.MemberType) { case MemberTypes.Field: return ((FieldInfo)member).FieldType; case MemberTypes.Property: return ((PropertyInfo)member).PropertyType; case MemberTypes.Event: return ((EventInfo)member).EventHandlerType; default: throw new ArgumentException("MemberInfo must be of type FieldInfo, PropertyInfo or EventInfo", "member"); } } /// <summary> /// Determines whether the member is an indexed property. /// </summary> /// <param name="member">The member.</param> /// <returns> /// <c>true</c> if the member is an indexed property; otherwise, <c>false</c>. /// </returns> public static bool IsIndexedProperty(MemberInfo member) { ValidationUtils.ArgumentNotNull(member, "member"); PropertyInfo propertyInfo = member as PropertyInfo; if (propertyInfo != null) return IsIndexedProperty(propertyInfo); else return false; } /// <summary> /// Determines whether the property is an indexed property. /// </summary> /// <param name="property">The property.</param> /// <returns> /// <c>true</c> if the property is an indexed property; otherwise, <c>false</c>. /// </returns> public static bool IsIndexedProperty(PropertyInfo property) { ValidationUtils.ArgumentNotNull(property, "property"); return (property.GetIndexParameters().Length > 0); } /// <summary> /// Gets the member's value on the object. /// </summary> /// <param name="member">The member.</param> /// <param name="target">The target object.</param> /// <returns>The member's value on the object.</returns> public static object GetMemberValue(MemberInfo member, object target) { ValidationUtils.ArgumentNotNull(member, "member"); ValidationUtils.ArgumentNotNull(target, "target"); switch (member.MemberType) { case MemberTypes.Field: return ((FieldInfo)member).GetValue(target); case MemberTypes.Property: try { #if !(UNITY_IOS || UNITY_WEBGL || UNITY_XBOXONE || UNITY_XBOX360 || UNITY_PS4 || UNITY_PS3 || UNITY_WII || UNITY_IPHONE) return ((PropertyInfo)member).GetValue(target, null); #else var getMethod = ((PropertyInfo) member).GetGetMethod(true); return getMethod.Invoke(target, null); #endif } catch (TargetParameterCountException e) { throw new ArgumentException("MemberInfo '{0}' has index parameters".FormatWith(CultureInfo.InvariantCulture, member.Name), e); } default: throw new ArgumentException("MemberInfo '{0}' is not of type FieldInfo or PropertyInfo".FormatWith(CultureInfo.InvariantCulture, CultureInfo.InvariantCulture, member.Name), "member"); } } /// <summary> /// Sets the member's value on the target object. /// </summary> /// <param name="member">The member.</param> /// <param name="target">The target.</param> /// <param name="value">The value.</param> public static void SetMemberValue(MemberInfo member, object target, object value) { ValidationUtils.ArgumentNotNull(member, "member"); ValidationUtils.ArgumentNotNull(target, "target"); switch (member.MemberType) { case MemberTypes.Field: ((FieldInfo)member).SetValue(target, value); break; case MemberTypes.Property: ((PropertyInfo)member).SetValue(target, value, null); break; default: throw new ArgumentException("MemberInfo '{0}' must be of type FieldInfo or PropertyInfo".FormatWith(CultureInfo.InvariantCulture, member.Name), "member"); } } /// <summary> /// Determines whether the specified MemberInfo can be read. /// </summary> /// <param name="member">The MemberInfo to determine whether can be read.</param> /// /// <param name="nonPublic">if set to <c>true</c> then allow the member to be gotten non-publicly.</param> /// <returns> /// <c>true</c> if the specified MemberInfo can be read; otherwise, <c>false</c>. /// </returns> public static bool CanReadMemberValue(MemberInfo member, bool nonPublic) { switch (member.MemberType) { case MemberTypes.Field: FieldInfo fieldInfo = (FieldInfo)member; if (nonPublic) return true; else if (fieldInfo.IsPublic) return true; return false; case MemberTypes.Property: PropertyInfo propertyInfo = (PropertyInfo) member; if (!propertyInfo.CanRead) return false; if (nonPublic) return true; return (propertyInfo.GetGetMethod(nonPublic) != null); default: return false; } } /// <summary> /// Determines whether the specified MemberInfo can be set. /// </summary> /// <param name="member">The MemberInfo to determine whether can be set.</param> /// <param name="nonPublic">if set to <c>true</c> then allow the member to be set non-publicly.</param> /// <param name="canSetReadOnly">if set to <c>true</c> then allow the member to be set if read-only.</param> /// <returns> /// <c>true</c> if the specified MemberInfo can be set; otherwise, <c>false</c>. /// </returns> public static bool CanSetMemberValue(MemberInfo member, bool nonPublic, bool canSetReadOnly) { switch (member.MemberType) { case MemberTypes.Field: FieldInfo fieldInfo = (FieldInfo)member; if (fieldInfo.IsInitOnly && !canSetReadOnly) return false; if (nonPublic) return true; else if (fieldInfo.IsPublic) return true; return false; case MemberTypes.Property: PropertyInfo propertyInfo = (PropertyInfo)member; if (!propertyInfo.CanWrite) return false; if (nonPublic) return true; return (propertyInfo.GetSetMethod(nonPublic) != null); default: return false; } } public static List<MemberInfo> GetFieldsAndProperties<T>(BindingFlags bindingAttr) { return GetFieldsAndProperties(typeof(T), bindingAttr); } public static List<MemberInfo> GetFieldsAndProperties(Type type, BindingFlags bindingAttr) { List<MemberInfo> targetMembers = new List<MemberInfo>(); targetMembers.AddRange(GetFields(type, bindingAttr)); targetMembers.AddRange(GetProperties(type, bindingAttr)); // for some reason .NET returns multiple members when overriding a generic member on a base class // http://forums.msdn.microsoft.com/en-US/netfxbcl/thread/b5abbfee-e292-4a64-8907-4e3f0fb90cd9/ // filter members to only return the override on the topmost class // update: I think this is fixed in .NET 3.5 SP1 - leave this in for now... List<MemberInfo> distinctMembers = new List<MemberInfo>(targetMembers.Count); var groupedMembers = targetMembers.GroupBy(m => m.Name).Select(g => new { Count = g.Count(), Members = g.Cast<MemberInfo>() }); foreach (var groupedMember in groupedMembers) { if (groupedMember.Count == 1) { distinctMembers.Add(groupedMember.Members.First()); } else { var members = groupedMember.Members.Where(m => !IsOverridenGenericMember(m, bindingAttr) || m.Name == "Item"); distinctMembers.AddRange(members); } } return distinctMembers; } private static bool IsOverridenGenericMember(MemberInfo memberInfo, BindingFlags bindingAttr) { if (memberInfo.MemberType != MemberTypes.Field && memberInfo.MemberType != MemberTypes.Property) throw new ArgumentException("Member must be a field or property."); Type declaringType = memberInfo.DeclaringType; if (!declaringType.IsGenericType) return false; Type genericTypeDefinition = declaringType.GetGenericTypeDefinition(); if (genericTypeDefinition == null) return false; MemberInfo[] members = genericTypeDefinition.GetMember(memberInfo.Name, bindingAttr); if (members.Length == 0) return false; Type memberUnderlyingType = GetMemberUnderlyingType(members[0]); if (!memberUnderlyingType.IsGenericParameter) return false; return true; } public static T GetAttribute<T>(ICustomAttributeProvider attributeProvider) where T : System.Attribute { return GetAttribute<T>(attributeProvider, true); } public static T GetAttribute<T>(ICustomAttributeProvider attributeProvider, bool inherit) where T : System.Attribute { T[] attributes = GetAttributes<T>(attributeProvider, inherit); return CollectionUtils.GetSingleItem(attributes, true); } public static T[] GetAttributes<T>(ICustomAttributeProvider attributeProvider, bool inherit) where T : System.Attribute { ValidationUtils.ArgumentNotNull(attributeProvider, "attributeProvider"); // http://hyperthink.net/blog/getcustomattributes-gotcha/ // ICustomAttributeProvider doesn't do inheritance if (attributeProvider is Type) return (T[])((Type)attributeProvider).GetCustomAttributes(typeof(T), inherit); if (attributeProvider is Assembly) return (T[])System.Attribute.GetCustomAttributes((Assembly)attributeProvider, typeof(T), inherit); if (attributeProvider is MemberInfo) return (T[])System.Attribute.GetCustomAttributes((MemberInfo)attributeProvider, typeof(T), inherit); if (attributeProvider is Module) return (T[])System.Attribute.GetCustomAttributes((Module)attributeProvider, typeof(T), inherit); if (attributeProvider is ParameterInfo) return (T[])System.Attribute.GetCustomAttributes((ParameterInfo)attributeProvider, typeof(T), inherit); return (T[])attributeProvider.GetCustomAttributes(typeof(T), inherit); } public static string GetNameAndAssessmblyName(Type t) { ValidationUtils.ArgumentNotNull(t, "t"); return t.FullName + ", " + t.Assembly.GetName().Name; } public static Type MakeGenericType(Type genericTypeDefinition, params Type[] innerTypes) { ValidationUtils.ArgumentNotNull(genericTypeDefinition, "genericTypeDefinition"); ValidationUtils.ArgumentNotNullOrEmpty<Type>(innerTypes, "innerTypes"); ValidationUtils.ArgumentConditionTrue(genericTypeDefinition.IsGenericTypeDefinition, "genericTypeDefinition", "Type {0} is not a generic type definition.".FormatWith(CultureInfo.InvariantCulture, genericTypeDefinition)); return genericTypeDefinition.MakeGenericType(innerTypes); } public static object CreateGeneric(Type genericTypeDefinition, Type innerType, params object[] args) { return CreateGeneric(genericTypeDefinition, new [] { innerType }, args); } public static object CreateGeneric(Type genericTypeDefinition, IList<Type> innerTypes, params object[] args) { return CreateGeneric(genericTypeDefinition, innerTypes, (t, a) => CreateInstance(t, a.ToArray()), args); } public static object CreateGeneric(Type genericTypeDefinition, IList<Type> innerTypes, Func<Type, IList<object>, object> instanceCreator, params object[] args) { ValidationUtils.ArgumentNotNull(genericTypeDefinition, "genericTypeDefinition"); ValidationUtils.ArgumentNotNullOrEmpty(innerTypes, "innerTypes"); ValidationUtils.ArgumentNotNull(instanceCreator, "createInstance"); Type specificType = MakeGenericType(genericTypeDefinition, innerTypes.ToArray()); return instanceCreator(specificType, args); } public static bool IsCompatibleValue(object value, Type type) { if (value == null) return IsNullable(type); if (type.IsAssignableFrom(value.GetType())) return true; return false; } public static object CreateInstance(Type type, params object[] args) { ValidationUtils.ArgumentNotNull(type, "type"); return Activator.CreateInstance(type, args); } public static void SplitFullyQualifiedTypeName(string fullyQualifiedTypeName, out string typeName, out string assemblyName) { int? assemblyDelimiterIndex = GetAssemblyDelimiterIndex(fullyQualifiedTypeName); if (assemblyDelimiterIndex != null) { typeName = fullyQualifiedTypeName.Substring(0, assemblyDelimiterIndex.Value).Trim(); assemblyName = fullyQualifiedTypeName.Substring(assemblyDelimiterIndex.Value + 1, fullyQualifiedTypeName.Length - assemblyDelimiterIndex.Value - 1).Trim(); } else { typeName = fullyQualifiedTypeName; assemblyName = null; } } private static int? GetAssemblyDelimiterIndex(string fullyQualifiedTypeName) { // we need to get the first comma following all surrounded in brackets because of generic types // e.g. System.Collections.Generic.Dictionary`2[[System.String, mscorlib,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 int scope = 0; for (int i = 0; i < fullyQualifiedTypeName.Length; i++) { char current = fullyQualifiedTypeName[i]; switch (current) { case '[': scope++; break; case ']': scope--; break; case ',': if (scope == 0) return i; break; } } return null; } public static MemberInfo GetMemberInfoFromType(Type targetType, MemberInfo memberInfo) { BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; switch (memberInfo.MemberType) { case MemberTypes.Property: PropertyInfo propertyInfo = (PropertyInfo) memberInfo; Type[] types = propertyInfo.GetIndexParameters().Select(p => p.ParameterType).ToArray(); return targetType.GetProperty(propertyInfo.Name, bindingAttr, null, propertyInfo.PropertyType, types, null); default: return targetType.GetMember(memberInfo.Name, memberInfo.MemberType, bindingAttr).SingleOrDefault(); } } public static IEnumerable<FieldInfo> GetFields(Type targetType, BindingFlags bindingAttr) { ValidationUtils.ArgumentNotNull(targetType, "targetType"); List<MemberInfo> fieldInfos = new List<MemberInfo>(targetType.GetFields(bindingAttr)); // Type.GetFields doesn't return inherited private fields // manually find private fields from base class GetChildPrivateFields(fieldInfos, targetType, bindingAttr); return fieldInfos.Cast<FieldInfo>(); } private static void GetChildPrivateFields(IList<MemberInfo> initialFields, Type targetType, BindingFlags bindingAttr) { // fix weirdness with private FieldInfos only being returned for the current Type // find base type fields and add them to result if ((bindingAttr & BindingFlags.NonPublic) != 0) { // modify flags to not search for public fields BindingFlags nonPublicBindingAttr = bindingAttr.RemoveFlag(BindingFlags.Public); while ((targetType = targetType.BaseType) != null) { // filter out protected fields IEnumerable<MemberInfo> childPrivateFields = targetType.GetFields(nonPublicBindingAttr).Where(f => f.IsPrivate).Cast<MemberInfo>(); initialFields.AddRange(childPrivateFields); } } } public static IEnumerable<PropertyInfo> GetProperties(Type targetType, BindingFlags bindingAttr) { ValidationUtils.ArgumentNotNull(targetType, "targetType"); List<PropertyInfo> propertyInfos = new List<PropertyInfo>(targetType.GetProperties(bindingAttr)); GetChildPrivateProperties(propertyInfos, targetType, bindingAttr); // a base class private getter/setter will be inaccessable unless the property was gotten from the base class for (int i = 0; i < propertyInfos.Count; i++) { PropertyInfo member = propertyInfos[i]; if (member.DeclaringType != targetType) { PropertyInfo declaredMember = (PropertyInfo)GetMemberInfoFromType(member.DeclaringType, member); propertyInfos[i] = declaredMember; } } return propertyInfos; } public static BindingFlags RemoveFlag(this BindingFlags bindingAttr, BindingFlags flag) { return ((bindingAttr & flag) == flag) ? bindingAttr ^ flag : bindingAttr; } private static void GetChildPrivateProperties(IList<PropertyInfo> initialProperties, Type targetType, BindingFlags bindingAttr) { // fix weirdness with private PropertyInfos only being returned for the current Type // find base type properties and add them to result if ((bindingAttr & BindingFlags.NonPublic) != 0) { // modify flags to not search for public fields BindingFlags nonPublicBindingAttr = bindingAttr.RemoveFlag(BindingFlags.Public); while ((targetType = targetType.BaseType) != null) { foreach (PropertyInfo propertyInfo in targetType.GetProperties(nonPublicBindingAttr)) { PropertyInfo nonPublicProperty = propertyInfo; // have to test on name rather than reference because instances are different // depending on the type that GetProperties was called on int index = initialProperties.IndexOf(p => p.Name == nonPublicProperty.Name); if (index == -1) { initialProperties.Add(nonPublicProperty); } else { // replace nonpublic properties for a child, but gotten from // the parent with the one from the child // the property gotten from the child will have access to private getter/setter initialProperties[index] = nonPublicProperty; } } } } } } } #endif
//----------------------------------------------------------------------- // <copyright file="FormatterEmitter.cs" company="Sirenix IVS"> // Copyright (c) 2018 Sirenix IVS // // 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_EDITOR || UNITY_STANDALONE) && !ENABLE_IL2CPP #define CAN_EMIT #endif namespace Stratus.OdinSerializer { using Stratus.OdinSerializer.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEngine; #if CAN_EMIT using System.Reflection.Emit; #endif /// <summary> /// Utility class for emitting formatters using the <see cref="System.Reflection.Emit"/> namespace. /// <para /> /// NOTE: Some platforms do not support emitting. Check whether you can emit on the current platform using <see cref="EmitUtilities.CanEmit"/>. /// </summary> public static class FormatterEmitter { /// <summary> /// The name of the pre-generated assembly that contains pre-emitted formatters for use on AOT platforms where emitting is not supported. Note that this assembly is not always present. /// </summary> public const string PRE_EMITTED_ASSEMBLY_NAME = "OdinSerializer.AOTGenerated"; /// <summary> /// The name of the runtime-generated assembly that contains runtime-emitted formatters for use on non-AOT platforms where emitting is supported. Note that this assembly is not always present. /// </summary> public const string RUNTIME_EMITTED_ASSEMBLY_NAME = "OdinSerializer.RuntimeEmitted"; /// <summary> /// Base type for all AOT-emitted formatters. /// </summary> [EmittedFormatter] public abstract class AOTEmittedFormatter<T> : EasyBaseFormatter<T> { } /// <summary> /// Shortcut class that makes it easier to emit empty AOT formatters. /// </summary> public abstract class EmptyAOTEmittedFormatter<T> : AOTEmittedFormatter<T> { /// <summary> /// Skips the entry to read. /// </summary> protected override void ReadDataEntry(ref T value, string entryName, EntryType entryType, IDataReader reader) { reader.SkipEntry(); } /// <summary> /// Does nothing at all. /// </summary> protected override void WriteDataEntries(ref T value, IDataWriter writer) { } } #if CAN_EMIT private static readonly object LOCK = new object(); private static readonly DoubleLookupDictionary<ISerializationPolicy, Type, IFormatter> Formatters = new DoubleLookupDictionary<ISerializationPolicy, Type, IFormatter>(); private static AssemblyBuilder runtimeEmittedAssembly; private static ModuleBuilder runtimeEmittedModule; public delegate void ReadDataEntryMethodDelegate<T>(ref T value, string entryName, EntryType entryType, IDataReader reader); public delegate void WriteDataEntriesMethodDelegate<T>(ref T value, IDataWriter writer); [EmittedFormatter] public sealed class RuntimeEmittedFormatter<T> : EasyBaseFormatter<T> { public readonly ReadDataEntryMethodDelegate<T> Read; public readonly WriteDataEntriesMethodDelegate<T> Write; public RuntimeEmittedFormatter(ReadDataEntryMethodDelegate<T> read, WriteDataEntriesMethodDelegate<T> write) { this.Read = read; this.Write = write; } protected override void ReadDataEntry(ref T value, string entryName, EntryType entryType, IDataReader reader) { this.Read(ref value, entryName, entryType, reader); } protected override void WriteDataEntries(ref T value, IDataWriter writer) { this.Write(ref value, writer); } } #endif /// <summary> /// Gets an emitted formatter for a given type. /// <para /> /// NOTE: Some platforms do not support emitting. On such platforms, this method logs an error and returns null. Check whether you can emit on the current platform using <see cref="EmitUtilities.CanEmit"/>. /// </summary> /// <param name="type">The type to emit a formatter for.</param> /// <param name="policy">The serialization policy to use to determine which members the emitted formatter should serialize. If null, <see cref="SerializationPolicies.Strict"/> is used.</param> /// <returns>The type of the emitted formatter.</returns> /// <exception cref="System.ArgumentNullException">The type argument is null.</exception> public static IFormatter GetEmittedFormatter(Type type, ISerializationPolicy policy) { #if !CAN_EMIT Debug.LogError("Cannot use Reflection.Emit on the current platform. The FormatterEmitter class is currently disabled. Check whether emitting is currently possible with EmitUtilities.CanEmit."); return null; #else if (type == null) { throw new ArgumentNullException("type"); } if (policy == null) { policy = SerializationPolicies.Strict; } IFormatter result = null; if (Formatters.TryGetInnerValue(policy, type, out result) == false) { lock (LOCK) { if (Formatters.TryGetInnerValue(policy, type, out result) == false) { EnsureRuntimeAssembly(); try { result = CreateGenericFormatter(type, runtimeEmittedModule, policy); } catch (Exception ex) { Debug.LogError("The following error occurred while emitting a formatter for the type " + type.Name); Debug.LogException(ex); } Formatters.AddInner(policy, type, result); } } } return result; #endif } #if CAN_EMIT private static void EnsureRuntimeAssembly() { // We always hold the lock in this method if (runtimeEmittedAssembly == null) { var assemblyName = new AssemblyName(RUNTIME_EMITTED_ASSEMBLY_NAME); assemblyName.CultureInfo = System.Globalization.CultureInfo.InvariantCulture; assemblyName.Flags = AssemblyNameFlags.None; assemblyName.ProcessorArchitecture = ProcessorArchitecture.MSIL; assemblyName.VersionCompatibility = System.Configuration.Assemblies.AssemblyVersionCompatibility.SameDomain; runtimeEmittedAssembly = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run); } if (runtimeEmittedModule == null) { bool emitSymbolInfo; #if UNITY_EDITOR emitSymbolInfo = true; #else // Builds cannot emit symbol info emitSymbolInfo = false; #endif runtimeEmittedModule = runtimeEmittedAssembly.DefineDynamicModule(RUNTIME_EMITTED_ASSEMBLY_NAME, emitSymbolInfo); } } /// <summary> /// Emits a formatter for a given type into a given module builder, using a given serialization policy to determine which members to serialize. /// </summary> /// <param name="formattedType">Type to create a formatter for.</param> /// <param name="moduleBuilder">The module builder to emit a formatter into.</param> /// <param name="policy">The serialization policy to use for creating the formatter.</param> /// <returns>The fully constructed, emitted formatter type.</returns> public static Type EmitAOTFormatter(Type formattedType, ModuleBuilder moduleBuilder, ISerializationPolicy policy) { Dictionary<string, MemberInfo> serializableMembers = FormatterUtilities.GetSerializableMembersMap(formattedType, policy); string formatterName = moduleBuilder.Name + "." + formattedType.GetCompilableNiceFullName() + "__AOTFormatter"; string formatterHelperName = moduleBuilder.Name + "." + formattedType.GetCompilableNiceFullName() + "__FormatterHelper"; if (serializableMembers.Count == 0) { return moduleBuilder.DefineType( formatterName, TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Class, typeof(EmptyAOTEmittedFormatter<>).MakeGenericType(formattedType) ).CreateType(); } Dictionary<Type, MethodInfo> serializerReadMethods; Dictionary<Type, MethodInfo> serializerWriteMethods; Dictionary<Type, FieldBuilder> serializerFields; FieldBuilder dictField; Dictionary<MemberInfo, List<string>> memberNames; BuildHelperType( moduleBuilder, formatterHelperName, formattedType, serializableMembers, out serializerReadMethods, out serializerWriteMethods, out serializerFields, out dictField, out memberNames ); TypeBuilder formatterType = moduleBuilder.DefineType( formatterName, TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Class, typeof(AOTEmittedFormatter<>).MakeGenericType(formattedType) ); // Read { MethodInfo readBaseMethod = formatterType.BaseType.GetMethod("ReadDataEntry", Flags.InstanceAnyVisibility); MethodBuilder readMethod = formatterType.DefineMethod( readBaseMethod.Name, MethodAttributes.Family | MethodAttributes.Virtual, readBaseMethod.ReturnType, readBaseMethod.GetParameters().Select(n => n.ParameterType).ToArray() ); readBaseMethod.GetParameters().ForEach(n => readMethod.DefineParameter(n.Position, n.Attributes, n.Name)); EmitReadMethodContents(readMethod.GetILGenerator(), formattedType, dictField, serializerFields, memberNames, serializerReadMethods); } // Write { MethodInfo writeBaseMethod = formatterType.BaseType.GetMethod("WriteDataEntries", Flags.InstanceAnyVisibility); MethodBuilder dynamicWriteMethod = formatterType.DefineMethod( writeBaseMethod.Name, MethodAttributes.Family | MethodAttributes.Virtual, writeBaseMethod.ReturnType, writeBaseMethod.GetParameters().Select(n => n.ParameterType).ToArray() ); writeBaseMethod.GetParameters().ForEach(n => dynamicWriteMethod.DefineParameter(n.Position + 1, n.Attributes, n.Name)); EmitWriteMethodContents(dynamicWriteMethod.GetILGenerator(), formattedType, serializerFields, memberNames, serializerWriteMethods); } var result = formatterType.CreateType(); // Register the formatter on the assembly ((AssemblyBuilder)moduleBuilder.Assembly).SetCustomAttribute(new CustomAttributeBuilder(typeof(RegisterFormatterAttribute).GetConstructor(new Type[] { typeof(Type), typeof(int) }), new object[] { formatterType, -1 })); return result; } private static IFormatter CreateGenericFormatter(Type formattedType, ModuleBuilder moduleBuilder, ISerializationPolicy policy) { Dictionary<string, MemberInfo> serializableMembers = FormatterUtilities.GetSerializableMembersMap(formattedType, policy); if (serializableMembers.Count == 0) { return (IFormatter)Activator.CreateInstance(typeof(EmptyTypeFormatter<>).MakeGenericType(formattedType)); } string helperTypeName = moduleBuilder.Name + "." + formattedType.GetCompilableNiceFullName() + "___" + formattedType.Assembly.GetName().Name + "___FormatterHelper___" + Guid.NewGuid().ToString(); Dictionary<Type, MethodInfo> serializerReadMethods; Dictionary<Type, MethodInfo> serializerWriteMethods; Dictionary<Type, FieldBuilder> serializerFields; FieldBuilder dictField; Dictionary<MemberInfo, List<string>> memberNames; BuildHelperType( moduleBuilder, helperTypeName, formattedType, serializableMembers, out serializerReadMethods, out serializerWriteMethods, out serializerFields, out dictField, out memberNames ); Type formatterType = typeof(RuntimeEmittedFormatter<>).MakeGenericType(formattedType); Delegate del1, del2; // Read { Type readDelegateType = typeof(ReadDataEntryMethodDelegate<>).MakeGenericType(formattedType); MethodInfo readDataEntryMethod = formatterType.GetMethod("ReadDataEntry", Flags.InstanceAnyVisibility); DynamicMethod dynamicReadMethod = new DynamicMethod("Dynamic_" + formattedType.GetCompilableNiceFullName(), null, readDataEntryMethod.GetParameters().Select(n => n.ParameterType).ToArray(), true); readDataEntryMethod.GetParameters().ForEach(n => dynamicReadMethod.DefineParameter(n.Position, n.Attributes, n.Name)); EmitReadMethodContents(dynamicReadMethod.GetILGenerator(), formattedType, dictField, serializerFields, memberNames, serializerReadMethods); del1 = dynamicReadMethod.CreateDelegate(readDelegateType); } // Write { Type writeDelegateType = typeof(WriteDataEntriesMethodDelegate<>).MakeGenericType(formattedType); MethodInfo writeDataEntriesMethod = formatterType.GetMethod("WriteDataEntries", Flags.InstanceAnyVisibility); DynamicMethod dynamicWriteMethod = new DynamicMethod("Dynamic_Write_" + formattedType.GetCompilableNiceFullName(), null, writeDataEntriesMethod.GetParameters().Select(n => n.ParameterType).ToArray(), true); writeDataEntriesMethod.GetParameters().ForEach(n => dynamicWriteMethod.DefineParameter(n.Position + 1, n.Attributes, n.Name)); EmitWriteMethodContents(dynamicWriteMethod.GetILGenerator(), formattedType, serializerFields, memberNames, serializerWriteMethods); del2 = dynamicWriteMethod.CreateDelegate(writeDelegateType); } return (IFormatter)Activator.CreateInstance(formatterType, del1, del2); } private static Type BuildHelperType( ModuleBuilder moduleBuilder, string helperTypeName, Type formattedType, Dictionary<string, MemberInfo> serializableMembers, out Dictionary<Type, MethodInfo> serializerReadMethods, out Dictionary<Type, MethodInfo> serializerWriteMethods, out Dictionary<Type, FieldBuilder> serializerFields, out FieldBuilder dictField, out Dictionary<MemberInfo, List<string>> memberNames) { TypeBuilder helperTypeBuilder = moduleBuilder.DefineType(helperTypeName, TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.Class); memberNames = new Dictionary<MemberInfo, List<string>>(); foreach (var entry in serializableMembers) { List<string> list; if (memberNames.TryGetValue(entry.Value, out list) == false) { list = new List<string>(); memberNames.Add(entry.Value, list); } list.Add(entry.Key); } dictField = helperTypeBuilder.DefineField("SwitchLookup", typeof(Dictionary<string, int>), FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.InitOnly); List<Type> neededSerializers = memberNames.Keys.Select(n => FormatterUtilities.GetContainedType(n)).Distinct().ToList(); serializerReadMethods = new Dictionary<Type, MethodInfo>(neededSerializers.Count); serializerWriteMethods = new Dictionary<Type, MethodInfo>(neededSerializers.Count); serializerFields = new Dictionary<Type, FieldBuilder>(neededSerializers.Count); foreach (var t in neededSerializers) { string name = t.GetCompilableNiceFullName() + "__Serializer"; int counter = 1; while (serializerFields.Values.Any(n => n.Name == name)) { counter++; name = t.GetCompilableNiceFullName() + "__Serializer" + counter; } Type serializerType = typeof(Serializer<>).MakeGenericType(t); serializerReadMethods.Add(t, serializerType.GetMethod("ReadValue", Flags.InstancePublicDeclaredOnly)); serializerWriteMethods.Add(t, serializerType.GetMethod("WriteValue", Flags.InstancePublicDeclaredOnly, null, new[] { typeof(string), t, typeof(IDataWriter) }, null)); serializerFields.Add(t, helperTypeBuilder.DefineField(name, serializerType, FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.InitOnly)); } //FieldBuilder readMethodFieldBuilder = helperTypeBuilder.DefineField("ReadMethod", readDelegateType, FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.InitOnly); //FieldBuilder writeMethodFieldBuilder = helperTypeBuilder.DefineField("WriteMethod", writeDelegateType, FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.InitOnly); // We generate a static constructor for our formatter helper type that initializes our switch lookup dictionary and our needed Serializer references { var addMethod = typeof(Dictionary<string, int>).GetMethod("Add", Flags.InstancePublic); var dictionaryConstructor = typeof(Dictionary<string, int>).GetConstructor(Type.EmptyTypes); var serializerGetMethod = typeof(Serializer).GetMethod("Get", Flags.StaticPublic, null, new[] { typeof(Type) }, null); var typeOfMethod = typeof(Type).GetMethod("GetTypeFromHandle", Flags.StaticPublic, null, new Type[] { typeof(RuntimeTypeHandle) }, null); ConstructorBuilder staticConstructor = helperTypeBuilder.DefineTypeInitializer(); ILGenerator gen = staticConstructor.GetILGenerator(); gen.Emit(OpCodes.Newobj, dictionaryConstructor); // Create new dictionary int count = 0; foreach (var entry in memberNames) { foreach (var name in entry.Value) { gen.Emit(OpCodes.Dup); // Load duplicate dictionary value gen.Emit(OpCodes.Ldstr, name); // Load entry name gen.Emit(OpCodes.Ldc_I4, count); // Load entry index gen.Emit(OpCodes.Call, addMethod); // Call dictionary add } count++; } gen.Emit(OpCodes.Stsfld, dictField); // Set static dictionary field to dictionary value foreach (var entry in serializerFields) { gen.Emit(OpCodes.Ldtoken, entry.Key); // Load type token gen.Emit(OpCodes.Call, typeOfMethod); // Call typeof method (this pushes a type value onto the stack) gen.Emit(OpCodes.Call, serializerGetMethod); // Call Serializer.Get(Type type) method gen.Emit(OpCodes.Stsfld, entry.Value); // Set static serializer field to result of get method } gen.Emit(OpCodes.Ret); // Return } // Now we need to actually create the serializer container type so we can generate the dynamic methods below without getting TypeLoadExceptions up the wazoo return helperTypeBuilder.CreateType(); } private static void EmitReadMethodContents( ILGenerator gen, Type formattedType, FieldInfo dictField, Dictionary<Type, FieldBuilder> serializerFields, Dictionary<MemberInfo, List<string>> memberNames, Dictionary<Type, MethodInfo> serializerReadMethods) { MethodInfo skipMethod = typeof(IDataReader).GetMethod("SkipEntry", Flags.InstancePublic); MethodInfo tryGetValueMethod = typeof(Dictionary<string, int>).GetMethod("TryGetValue", Flags.InstancePublic); //methodBuilder.DefineParameter(5, ParameterAttributes.None, "switchLookup"); LocalBuilder lookupResult = gen.DeclareLocal(typeof(int)); Label defaultLabel = gen.DefineLabel(); Label switchLabel = gen.DefineLabel(); Label endLabel = gen.DefineLabel(); Label[] switchLabels = memberNames.Select(n => gen.DefineLabel()).ToArray(); gen.Emit(OpCodes.Ldarg_1); // Load entryName string gen.Emit(OpCodes.Ldnull); // Load null gen.Emit(OpCodes.Ceq); // Equality check gen.Emit(OpCodes.Brtrue, defaultLabel); // If entryName is null, go to default case //gen.Emit(OpCodes.Ldarg, (short)4); // Load lookup dictionary argument (OLD CODE) gen.Emit(OpCodes.Ldsfld, dictField); // Load lookup dictionary from static field on helper type gen.Emit(OpCodes.Ldarg_1); // Load entryName string gen.Emit(OpCodes.Ldloca, (short)lookupResult.LocalIndex); // Load address of lookupResult gen.Emit(OpCodes.Callvirt, tryGetValueMethod); // Call TryGetValue on the dictionary gen.Emit(OpCodes.Brtrue, switchLabel); // If TryGetValue returned true, go to the switch case gen.Emit(OpCodes.Br, defaultLabel); // Else, go to the default case gen.MarkLabel(switchLabel); // Switch starts here gen.Emit(OpCodes.Ldloc, lookupResult); // Load lookupResult gen.Emit(OpCodes.Switch, switchLabels); // Perform switch on switchLabels int count = 0; foreach (var member in memberNames.Keys) { var memberType = FormatterUtilities.GetContainedType(member); var propInfo = member as PropertyInfo; var fieldInfo = member as FieldInfo; gen.MarkLabel(switchLabels[count]); // Switch case for [count] starts here // Now we load the instance that we have to set the value on gen.Emit(OpCodes.Ldarg_0); // Load value reference if (formattedType.IsValueType == false) { gen.Emit(OpCodes.Ldind_Ref); // Indirectly load value of reference } // Now we deserialize the value itself gen.Emit(OpCodes.Ldsfld, serializerFields[memberType]); // Load serializer from serializer container type gen.Emit(OpCodes.Ldarg, (short)3); // Load reader argument gen.Emit(OpCodes.Callvirt, serializerReadMethods[memberType]); // Call Serializer.ReadValue(IDataReader reader) // The stack now contains the formatted instance and the deserialized value to set the member to // Now we set the value if (fieldInfo != null) { gen.Emit(OpCodes.Stfld, fieldInfo.DeAliasField()); // Set field } else if (propInfo != null) { gen.Emit(OpCodes.Callvirt, propInfo.DeAliasProperty().GetSetMethod(true)); // Call property setter } else { throw new NotImplementedException(); } gen.Emit(OpCodes.Br, endLabel); // Jump to end of method count++; } gen.MarkLabel(defaultLabel); // Default case starts here gen.Emit(OpCodes.Ldarg, (short)3); // Load reader argument gen.Emit(OpCodes.Callvirt, skipMethod); // Call IDataReader.SkipEntry gen.MarkLabel(endLabel); // Method end starts here gen.Emit(OpCodes.Ret); // Return method } private static void EmitWriteMethodContents( ILGenerator gen, Type formattedType, Dictionary<Type, FieldBuilder> serializerFields, Dictionary<MemberInfo, List<string>> memberNames, Dictionary<Type, MethodInfo> serializerWriteMethods) { foreach (var member in memberNames.Keys) { var memberType = FormatterUtilities.GetContainedType(member); gen.Emit(OpCodes.Ldsfld, serializerFields[memberType]); // Load serializer instance for type gen.Emit(OpCodes.Ldstr, member.Name); // Load member name string // Now we load the value of the actual member if (member is FieldInfo) { var fieldInfo = member as FieldInfo; if (formattedType.IsValueType) { gen.Emit(OpCodes.Ldarg_0); // Load value argument gen.Emit(OpCodes.Ldfld, fieldInfo.DeAliasField()); // Load value of field } else { gen.Emit(OpCodes.Ldarg_0); // Load value argument reference gen.Emit(OpCodes.Ldind_Ref); // Indirectly load value of reference gen.Emit(OpCodes.Ldfld, fieldInfo.DeAliasField()); // Load value of field } } else if (member is PropertyInfo) { var propInfo = member as PropertyInfo; if (formattedType.IsValueType) { gen.Emit(OpCodes.Ldarg_0); // Load value argument gen.Emit(OpCodes.Call, propInfo.DeAliasProperty().GetGetMethod(true)); // Call property getter } else { gen.Emit(OpCodes.Ldarg_0); // Load value argument reference gen.Emit(OpCodes.Ldind_Ref); // Indirectly load value of reference gen.Emit(OpCodes.Callvirt, propInfo.DeAliasProperty().GetGetMethod(true)); // Call property getter } } else { throw new NotImplementedException(); } gen.Emit(OpCodes.Ldarg_1); // Load writer argument gen.Emit(OpCodes.Callvirt, serializerWriteMethods[memberType]); // Call Serializer.WriteValue(string name, T value, IDataWriter writer) } gen.Emit(OpCodes.Ret); // Return method } #endif } }
// 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.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; namespace Microsoft.ApiDesignGuidelines.Analyzers { /// <summary> /// CA1711: Identifiers should not have incorrect suffix /// </summary> [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class IdentifiersShouldNotHaveIncorrectSuffixAnalyzer : DiagnosticAnalyzer { internal const string RuleId = "CA1711"; private static readonly LocalizableString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotHaveIncorrectSuffixTitle), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageTypeNoAlternate = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotHaveIncorrectSuffixMessageTypeNoAlternate), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageMemberNewerVersion = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotHaveIncorrectSuffixMessageMemberNewerVersion), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageTypeNewerVersion = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotHaveIncorrectSuffixMessageTypeNewerVersion), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableMessageMemberWithAlternate = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotHaveIncorrectSuffixMessageMemberWithAlternate), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private static readonly LocalizableString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftApiDesignGuidelinesAnalyzersResources.IdentifiersShouldNotHaveIncorrectSuffixDescription), MicrosoftApiDesignGuidelinesAnalyzersResources.ResourceManager, typeof(MicrosoftApiDesignGuidelinesAnalyzersResources)); private const string HelpLinkUri = "https://msdn.microsoft.com/en-us/library/ms182247.aspx"; internal static DiagnosticDescriptor TypeNoAlternateRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageTypeNoAlternate, DiagnosticCategory.Naming, DiagnosticSeverity.Warning, isEnabledByDefault: false, description: s_localizableDescription, helpLinkUri: HelpLinkUri, customTags: WellKnownDiagnosticTags.Telemetry); internal static DiagnosticDescriptor MemberNewerVersionRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageMemberNewerVersion, DiagnosticCategory.Naming, DiagnosticSeverity.Warning, isEnabledByDefault: false, description: s_localizableDescription, helpLinkUri: HelpLinkUri, customTags: WellKnownDiagnosticTags.Telemetry); internal static DiagnosticDescriptor TypeNewerVersionRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageTypeNewerVersion, DiagnosticCategory.Naming, DiagnosticSeverity.Warning, isEnabledByDefault: false, description: s_localizableDescription, helpLinkUri: HelpLinkUri, customTags: WellKnownDiagnosticTags.Telemetry); internal static DiagnosticDescriptor MemberWithAlternateRule = new DiagnosticDescriptor(RuleId, s_localizableTitle, s_localizableMessageMemberWithAlternate, DiagnosticCategory.Naming, DiagnosticSeverity.Warning, isEnabledByDefault: false, description: s_localizableDescription, helpLinkUri: HelpLinkUri, customTags: WellKnownDiagnosticTags.Telemetry); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create( TypeNoAlternateRule, MemberNewerVersionRule, TypeNewerVersionRule, MemberWithAlternateRule); internal const string AttributeSuffix = "Attribute"; internal const string CollectionSuffix = "Collection"; internal const string DictionarySuffix = "Dictionary"; internal const string EventArgsSuffix = "EventArgs"; internal const string EventHandlerSuffix = "EventHandler"; internal const string ExSuffix = "Ex"; internal const string ExceptionSuffix = "Exception"; internal const string NewSuffix = "New"; internal const string PermissionSuffix = "Permission"; internal const string StreamSuffix = "Stream"; internal const string DelegateSuffix = "Delegate"; internal const string EnumSuffix = "Enum"; internal const string ImplSuffix = "Impl"; internal const string CoreSuffix = "Core"; internal const string QueueSuffix = "Queue"; internal const string StackSuffix = "Stack"; // Dictionary that maps from a type name suffix to the set of base types from which // a type with that suffix is permitted to derive. private static readonly ImmutableDictionary<string, ImmutableArray<string>> s_suffixToBaseTypeNamesDictionary = ImmutableDictionary.CreateRange( new Dictionary<string, ImmutableArray<string>> { [AttributeSuffix] = ImmutableArray.CreateRange(new[] { "System.Attribute" }), [CollectionSuffix] = ImmutableArray.CreateRange(new[] { "System.Collections.IEnumerable" }), [DictionarySuffix] = ImmutableArray.CreateRange(new[] { "System.Collections.IDictionary", "System.Collections.Generic.IReadOnlyDictionary`2" }), [EventArgsSuffix] = ImmutableArray.CreateRange(new[] { "System.EventArgs" }), [ExceptionSuffix] = ImmutableArray.CreateRange(new[] { "System.Exception" }), [PermissionSuffix] = ImmutableArray.CreateRange(new[] { "System.Security.IPermission" }), [StreamSuffix] = ImmutableArray.CreateRange(new[] { "System.IO.Stream" }), [QueueSuffix] = ImmutableArray.CreateRange(new[] { "System.Collections.Queue", "System.Collections.Generic.Queue`1" }), [StackSuffix] = ImmutableArray.CreateRange(new[] { "System.Collections.Stack", "System.Collections.Generic.Stack`1" }) }); // Dictionary from type name suffix to an array containing the only types that are // allowed to have that suffix. private static readonly ImmutableDictionary<string, ImmutableArray<string>> s_suffixToAllowedTypesDictionary = ImmutableDictionary.CreateRange( new Dictionary<string, ImmutableArray<string>> { [DelegateSuffix] = ImmutableArray.CreateRange(new[] { "System.Delegate", "System.MulticastDelegate" }), [EventHandlerSuffix] = ImmutableArray.CreateRange(new[] { "System.EventHandler" }), [EnumSuffix] = ImmutableArray.CreateRange(new[] { "System.Enum" }) }); public override void Initialize(AnalysisContext analysisContext) { analysisContext.EnableConcurrentExecution(); analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); // Analyze type names. analysisContext.RegisterCompilationStartAction( compilationStartAnalysisContext => { var suffixToBaseTypeDictionaryBuilder = ImmutableDictionary.CreateBuilder<string, ImmutableArray<INamedTypeSymbol>>(); foreach (string suffix in s_suffixToBaseTypeNamesDictionary.Keys) { ImmutableArray<string> typeNames = s_suffixToBaseTypeNamesDictionary[suffix]; ImmutableArray<INamedTypeSymbol> namedTypeSymbolArray = ImmutableArray.CreateRange( typeNames.Select(typeName => compilationStartAnalysisContext.Compilation.GetTypeByMetadataName(typeName)?.OriginalDefinition).WhereNotNull()); suffixToBaseTypeDictionaryBuilder.Add(suffix, namedTypeSymbolArray); } var suffixToBaseTypeDictionary = suffixToBaseTypeDictionaryBuilder.ToImmutableDictionary(); compilationStartAnalysisContext.RegisterSymbolAction( (SymbolAnalysisContext symbolAnalysisContext) => { var namedTypeSymbol = (INamedTypeSymbol)symbolAnalysisContext.Symbol; if (namedTypeSymbol.GetResultantVisibility()!= SymbolVisibility.Public) { return; } string name = namedTypeSymbol.Name; Compilation compilation = symbolAnalysisContext.Compilation; foreach (string suffix in s_suffixToBaseTypeNamesDictionary.Keys) { if (IsNotChildOfAnyButHasSuffix(namedTypeSymbol, suffixToBaseTypeDictionary[suffix], suffix)) { symbolAnalysisContext.ReportDiagnostic( namedTypeSymbol.CreateDiagnostic(TypeNoAlternateRule, name, suffix)); return; } } foreach (string suffix in s_suffixToAllowedTypesDictionary.Keys) { if (name.HasSuffix(suffix) && !s_suffixToAllowedTypesDictionary[suffix].Contains(name)) { symbolAnalysisContext.ReportDiagnostic( namedTypeSymbol.CreateDiagnostic(TypeNoAlternateRule, name, suffix)); return; } } if (name.HasSuffix(ImplSuffix)) { symbolAnalysisContext.ReportDiagnostic( namedTypeSymbol.CreateDiagnostic(MemberWithAlternateRule, ImplSuffix, name, CoreSuffix)); return; } // FxCop performed the length check for "Ex", but not for any of the other // suffixes, because alone among the suffixes, "Ex" is the only one that // isn't itself a known type or a language keyword. if (name.HasSuffix(ExSuffix) && name.Length > ExSuffix.Length) { symbolAnalysisContext.ReportDiagnostic( namedTypeSymbol.CreateDiagnostic(TypeNewerVersionRule, ExSuffix, name)); return; } if (name.HasSuffix(NewSuffix)) { symbolAnalysisContext.ReportDiagnostic( namedTypeSymbol.CreateDiagnostic(TypeNewerVersionRule, NewSuffix, name)); return; } }, SymbolKind.NamedType); }); // Analyze method names. analysisContext.RegisterSymbolAction( (SymbolAnalysisContext context) => { var memberSymbol = context.Symbol; if (memberSymbol.GetResultantVisibility() != SymbolVisibility.Public) { return; } if (memberSymbol.IsOverride || memberSymbol.IsImplementationOfAnyInterfaceMember()) { return; } // If this is a method, and it's actually the getter or setter of a property, // then don't complain. We'll complain about the property itself. var methodSymbol = memberSymbol as IMethodSymbol; if (methodSymbol != null && methodSymbol.IsPropertyAccessor()) { return; } string name = memberSymbol.Name; if (name.HasSuffix(ExSuffix)) { context.ReportDiagnostic( memberSymbol.CreateDiagnostic(MemberNewerVersionRule, ExSuffix, name)); return; } // We only fire on member suffix "New" if the type already defines // another member minus the suffix, e.g., we only fire on "MemberNew" if // "Member" already exists. For some reason FxCop did not apply the // same logic to the "Ex" suffix, and we follow FxCop's implementation. if (name.HasSuffix(NewSuffix)) { string nameWithoutSuffix = name.WithoutSuffix(NewSuffix); INamedTypeSymbol containingType = memberSymbol.ContainingType; if (MemberNameExistsInHierarchy(nameWithoutSuffix, containingType, memberSymbol.Kind)) { context.ReportDiagnostic( memberSymbol.CreateDiagnostic(MemberNewerVersionRule, NewSuffix, name)); return; } } if (name.HasSuffix(ImplSuffix)) { context.ReportDiagnostic( memberSymbol.CreateDiagnostic(MemberWithAlternateRule, ImplSuffix, name, CoreSuffix)); } }, SymbolKind.Event, SymbolKind.Field, SymbolKind.Method, SymbolKind.Property); } private static bool MemberNameExistsInHierarchy(string memberName, INamedTypeSymbol containingType, SymbolKind kind) { for (INamedTypeSymbol baseType = containingType; baseType != null; baseType = baseType.BaseType) { if (baseType.GetMembers(memberName).Any(member => member.Kind == kind)) { return true; } } return false; } private static bool IsNotChildOfAnyButHasSuffix(INamedTypeSymbol namedTypeSymbol, ImmutableArray<INamedTypeSymbol> parentTypes, string suffix) { if (parentTypes.IsEmpty) { // Bail out if we cannot find any well-known types with the suffix in the compilation. return false; } return namedTypeSymbol.Name.HasSuffix(suffix) && !parentTypes.Any(parentType => namedTypeSymbol.DerivesFromOrImplementsAnyConstructionOf(parentType)); } } }
// Copyright 2011 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; namespace Microsoft.Data.Edm.Internal { /// <summary> /// Provides a dictionary that is thread safe by virtue of being immutable. /// Any update returns a new dictionary (which, for efficiency, may share some of the state of the old one). /// </summary> /// <typeparam name="TKey">Key type of the dictionary.</typeparam> /// <typeparam name="TValue">Value type of the dictionary.</typeparam> internal abstract class VersioningDictionary<TKey, TValue> { protected readonly Func<TKey, TKey, int> CompareFunction; protected VersioningDictionary(Func<TKey, TKey, int> compareFunction) { this.CompareFunction = compareFunction; } public static VersioningDictionary<TKey, TValue> Create(Func<TKey, TKey, int> compareFunction) { return new EmptyVersioningDictionary(compareFunction); } public abstract VersioningDictionary<TKey, TValue> Set(TKey keyToSet, TValue newValue); public abstract VersioningDictionary<TKey, TValue> Remove(TKey keyToRemove); public TValue Get(TKey key) { TValue value; if (this.TryGetValue(key, out value)) { return value; } throw new KeyNotFoundException(key.ToString()); } public abstract bool TryGetValue(TKey key, out TValue value); internal sealed class EmptyVersioningDictionary : VersioningDictionary<TKey, TValue> { public EmptyVersioningDictionary(Func<TKey, TKey, int> compareFunction) : base(compareFunction) { } public override VersioningDictionary<TKey, TValue> Set(TKey keyToSet, TValue newValue) { return new OneKeyDictionary(this.CompareFunction, keyToSet, newValue); } public override VersioningDictionary<TKey, TValue> Remove(TKey keyToRemove) { throw new KeyNotFoundException(keyToRemove.ToString()); } public override bool TryGetValue(TKey key, out TValue value) { value = default(TValue); return false; } } internal sealed class OneKeyDictionary : VersioningDictionary<TKey, TValue> { private readonly TKey key; private readonly TValue value; public OneKeyDictionary(Func<TKey, TKey, int> compareFunction, TKey key, TValue value) : base(compareFunction) { this.key = key; this.value = value; } public override VersioningDictionary<TKey, TValue> Set(TKey keyToSet, TValue newValue) { if (this.CompareFunction(keyToSet, this.key) == 0) { // Replacing the single key produces a new dictionary. return new OneKeyDictionary(this.CompareFunction, keyToSet, newValue); } return new TwoKeyDictionary(this.CompareFunction, this.key, this.value, keyToSet, newValue); } public override VersioningDictionary<TKey, TValue> Remove(TKey keyToRemove) { if (this.CompareFunction(keyToRemove, this.key) == 0) { return new EmptyVersioningDictionary(this.CompareFunction); } throw new KeyNotFoundException(keyToRemove.ToString()); } public override bool TryGetValue(TKey key, out TValue value) { if (this.CompareFunction(key, this.key) == 0) { value = this.value; return true; } value = default(TValue); return false; } } internal sealed class TwoKeyDictionary : VersioningDictionary<TKey, TValue> { private readonly TKey firstKey; private readonly TValue firstValue; private readonly TKey secondKey; private readonly TValue secondValue; public TwoKeyDictionary(Func<TKey, TKey, int> compareFunction, TKey firstKey, TValue firstValue, TKey secondKey, TValue secondValue) : base(compareFunction) { this.firstKey = firstKey; this.firstValue = firstValue; this.secondKey = secondKey; this.secondValue = secondValue; } public override VersioningDictionary<TKey, TValue> Set(TKey keyToSet, TValue newValue) { if (this.CompareFunction(keyToSet, this.firstKey) == 0) { return new TwoKeyDictionary(this.CompareFunction, keyToSet, newValue, this.secondKey, this.secondValue); } if (this.CompareFunction(keyToSet, this.secondKey) == 0) { return new TwoKeyDictionary(this.CompareFunction, this.firstKey, this.firstValue, keyToSet, newValue); } return new TreeDictionary(this.CompareFunction, this.firstKey, this.firstValue, this.secondKey, this.secondValue, keyToSet, newValue); } public override VersioningDictionary<TKey, TValue> Remove(TKey keyToRemove) { if (this.CompareFunction(keyToRemove, this.firstKey) == 0) { return new OneKeyDictionary(this.CompareFunction, this.secondKey, this.secondValue); } if (this.CompareFunction(keyToRemove, this.secondKey) == 0) { return new OneKeyDictionary(this.CompareFunction, this.firstKey, this.firstValue); } throw new KeyNotFoundException(keyToRemove.ToString()); } public override bool TryGetValue(TKey key, out TValue value) { if (this.CompareFunction(key, this.firstKey) == 0) { value = this.firstValue; return true; } if (this.CompareFunction(key, this.secondKey) == 0) { value = this.secondValue; return true; } value = default(TValue); return false; } } internal sealed class TreeDictionary : VersioningDictionary<TKey, TValue> { private const int MaxTreeHeight = 10; private readonly VersioningTree<TKey, TValue> tree; public TreeDictionary(Func<TKey, TKey, int> compareFunction, TKey firstKey, TValue firstValue, TKey secondKey, TValue secondValue, TKey thirdKey, TValue thirdValue) : base(compareFunction) { this.tree = new VersioningTree<TKey, TValue>(firstKey, firstValue, null, null).SetKeyValue(secondKey, secondValue, this.CompareFunction).SetKeyValue(thirdKey, thirdValue, this.CompareFunction); } public TreeDictionary(Func<TKey, TKey, int> compareFunction, VersioningTree<TKey, TValue> tree) : base(compareFunction) { this.tree = tree; } public override VersioningDictionary<TKey, TValue> Set(TKey keyToSet, TValue newValue) { if (this.tree.Height > MaxTreeHeight) { return new HashTreeDictionary(this.CompareFunction, this.tree, keyToSet, newValue); } return new TreeDictionary(this.CompareFunction, this.tree.SetKeyValue(keyToSet, newValue, this.CompareFunction)); } public override VersioningDictionary<TKey, TValue> Remove(TKey keyToRemove) { return new TreeDictionary(this.CompareFunction, this.tree.Remove(keyToRemove, this.CompareFunction)); } public override bool TryGetValue(TKey key, out TValue value) { if (this.tree == null) { value = default(TValue); return false; } return this.tree.TryGetValue(key, this.CompareFunction, out value); } } internal sealed class HashTreeDictionary : VersioningDictionary<TKey, TValue> { private const int HashSize = 17; private readonly VersioningTree<TKey, TValue>[] treeBuckets; public HashTreeDictionary(Func<TKey, TKey, int> compareFunction, VersioningTree<TKey, TValue> tree, TKey key, TValue value) : base(compareFunction) { this.treeBuckets = new VersioningTree<TKey, TValue>[HashSize]; this.SetKeyValues(tree); this.SetKeyValue(key, value); } public HashTreeDictionary(Func<TKey, TKey, int> compareFunction, VersioningTree<TKey, TValue>[] trees, TKey key, TValue value) : base(compareFunction) { this.treeBuckets = (VersioningTree<TKey, TValue>[])trees.Clone(); this.SetKeyValue(key, value); } public HashTreeDictionary(Func<TKey, TKey, int> compareFunction, VersioningTree<TKey, TValue>[] trees, TKey key) : base(compareFunction) { this.treeBuckets = (VersioningTree<TKey, TValue>[])trees.Clone(); this.RemoveKey(key); } public override VersioningDictionary<TKey, TValue> Set(TKey keyToSet, TValue newValue) { return new HashTreeDictionary(this.CompareFunction, this.treeBuckets, keyToSet, newValue); } public override VersioningDictionary<TKey, TValue> Remove(TKey keyToRemove) { return new HashTreeDictionary(this.CompareFunction, this.treeBuckets, keyToRemove); } public override bool TryGetValue(TKey key, out TValue value) { VersioningTree<TKey, TValue> tree = this.treeBuckets[this.GetBucket(key)]; if (tree == null) { value = default(TValue); return false; } else { return tree.TryGetValue(key, this.CompareFunction, out value); } } private void SetKeyValue(TKey keyToSet, TValue newValue) { int hashBucket = this.GetBucket(keyToSet); if (this.treeBuckets[hashBucket] == null) { this.treeBuckets[hashBucket] = new VersioningTree<TKey, TValue>(keyToSet, newValue, null, null); } else { this.treeBuckets[hashBucket] = this.treeBuckets[hashBucket].SetKeyValue(keyToSet, newValue, this.CompareFunction); } } private void SetKeyValues(VersioningTree<TKey, TValue> tree) { if (tree == null) { return; } this.SetKeyValue(tree.Key, tree.Value); this.SetKeyValues(tree.LeftChild); this.SetKeyValues(tree.RightChild); } private void RemoveKey(TKey keyToRemove) { int hashBucket = this.GetBucket(keyToRemove); if (this.treeBuckets[hashBucket] == null) { throw new KeyNotFoundException(keyToRemove.ToString()); } else { this.treeBuckets[hashBucket] = this.treeBuckets[hashBucket].Remove(keyToRemove, this.CompareFunction); } } private int GetBucket(TKey key) { int hash = key.GetHashCode(); if (hash < 0) { hash = -hash; } return hash % HashSize; } } } }
using Bridge.Html5; using Bridge.Test.NUnit; using System; using System.Collections.Generic; namespace Bridge.ClientTest.Collections.Native { [Category(Constants.MODULE_TYPEDARRAYS)] [TestFixture(TestNameFormat = "Int16ArrayTests - {0}")] public class Int16ArrayTests { private void AssertContent(Int16Array actual, int[] expected, string message) { if (actual.Length != expected.Length) { Assert.Fail(message + ": Expected length " + expected.Length + ", actual: " + actual.Length); return; } for (int i = 0; i < expected.Length; i++) { if (actual[i] != expected[i]) { Assert.Fail(message + ": Position " + i + ": expected " + expected[i] + ", actual: " + actual[i]); return; } } Assert.True(true, message); } [Test] public void LengthConstructorWorks() { var arr = new Int16Array(13); Assert.True((object)arr is Int16Array, "is Int16Array"); Assert.AreEqual(13, arr.Length, "Length"); } [Test] public void ConstructorFromIntWorks() { var source = new short[] { 3, 8, 4 }; var arr = new Int16Array(source); Assert.True((object)arr != (object)source, "New object"); Assert.True((object)arr is Int16Array, "is Int16Array"); AssertContent(arr, new[] { 3, 8, 4 }, "content"); } [Test] public void CopyConstructorWorks() { var source = new Int16Array(new short[] { 3, 8, 4 }); var arr = new Int16Array(source); Assert.True(arr != source, "New object"); Assert.True((object)arr is Int16Array, "is Int16Array"); AssertContent(arr, new[] { 3, 8, 4 }, "content"); } [Test] public void ArrayBufferConstructorWorks() { var buf = new ArrayBuffer(80); var arr = new Int16Array(buf); Assert.True((object)arr is Int16Array); Assert.True(arr.Buffer == buf, "buffer"); Assert.AreEqual(40, arr.Length, "length"); } [Test] public void ArrayBufferWithOffsetConstructorWorks() { var buf = new ArrayBuffer(80); var arr = new Int16Array(buf, 16); Assert.True((object)arr is Int16Array); Assert.True(arr.Buffer == buf, "buffer"); Assert.AreEqual(32, arr.Length, "length"); } [Test] public void ArrayBufferWithOffsetAndLengthConstructorWorks() { var buf = new ArrayBuffer(80); var arr = new Int16Array(buf, 16, 12); Assert.True((object)arr is Int16Array); Assert.True(arr.Buffer == buf, "buffer"); Assert.AreEqual(12, arr.Length, "length"); } // Not JS API //[Test] //public void InstanceBytesPerElementWorks() //{ // Assert.AreEqual(new Int16Array(0).BytesPerElement, 2); //} [Test] public void StaticBytesPerElementWorks() { Assert.AreEqual(2, Int16Array.BYTES_PER_ELEMENT); } [Test] public void LengthWorks() { var arr = new Int16Array(13); Assert.AreEqual(13, arr.Length, "Length"); } [Test] public void IndexingWorks() { var arr = new Int16Array(3); arr[1] = 42; AssertContent(arr, new[] { 0, 42, 0 }, "Content"); Assert.AreEqual(42, arr[1], "[1]"); } [Test] public void SetInt16ArrayWorks() { var arr = new Int16Array(4); arr.Set(new Int16Array(new short[] { 3, 6, 7 })); AssertContent(arr, new[] { 3, 6, 7, 0 }, "Content"); } [Test] public void SetInt16ArrayWithOffsetWorks() { var arr = new Int16Array(6); arr.Set(new Int16Array(new short[] { 3, 6, 7 }), 2); AssertContent(arr, new[] { 0, 0, 3, 6, 7, 0 }, "Content"); } [Test] public void SetNormalArrayWorks() { var arr = new Int16Array(4); arr.Set(new short[] { 3, 6, 7 }); AssertContent(arr, new[] { 3, 6, 7, 0 }, "Content"); } [Test] public void SetNormalArrayWithOffsetWorks() { var arr = new Int16Array(6); arr.Set(new short[] { 3, 6, 7 }, 2); AssertContent(arr, new[] { 0, 0, 3, 6, 7, 0 }, "Content"); } [Test] public void SubarrayWithBeginWorks() { var source = new Int16Array(10); var arr = source.SubArray(3); Assert.False(arr == source, "Should be a new array"); Assert.True(arr.Buffer == source.Buffer, "Should be the same buffer"); Assert.AreEqual(6, arr.ByteOffset, "ByteOffset should be correct"); } [Test] public void SubarrayWithBeginAndEndWorks() { var source = new Int16Array(10); var arr = source.SubArray(3, 7); Assert.False(arr == source, "Should be a new array"); Assert.True(arr.Buffer == source.Buffer, "Should be the same buffer"); Assert.AreEqual(6, arr.ByteOffset, "ByteOffset should be correct"); Assert.AreEqual(4, arr.Length, "Length should be correct"); } [Test] public void BufferPropertyWorks() { var buf = new ArrayBuffer(100); var arr = new Int16Array(buf); Assert.True(arr.Buffer == buf, "Should be correct"); } [Test] public void ByteOffsetPropertyWorks() { var buf = new ArrayBuffer(100); var arr = new Int16Array(buf, 32); Assert.AreEqual(32, arr.ByteOffset, "Should be correct"); } [Test] public void ByteLengthPropertyWorks() { var arr = new Int16Array(23); Assert.AreEqual(46, arr.ByteLength, "Should be correct"); } [Test] public void IndexOfWorks() { var arr = new Int16Array(new short[] { 3, 6, 2, 9, 5 }); Assert.AreEqual(3, arr.IndexOf(9), "9"); Assert.AreEqual(-1, arr.IndexOf(1), "1"); } // Not JS API [Test] public void ContainsWorks() { var arr = new Int16Array(new short[] { 3, 6, 2, 9, 5 }); Assert.True(arr.Contains(9), "9"); Assert.False(arr.Contains(1), "1"); } // #SPI [Test] public void ForeachWorks_SPI_1401() { var arr = new Int16Array(new short[] { 3, 6, 2, 9, 5 }); var l = new List<int>(); // #1401 foreach (var i in arr) { l.Add(i); } Assert.AreEqual(l.ToArray(), new[] { 3, 6, 2, 9, 5 }); } // #SPI [Test] public void GetEnumeratorWorks_SPI_1401() { var arr = new Int16Array(new short[] { 3, 6, 2, 9, 5 }); var l = new List<int>(); // #1401 var enm = arr.GetEnumerator(); while (enm.MoveNext()) { l.Add(enm.Current); } Assert.AreEqual(l.ToArray(), new[] { 3, 6, 2, 9, 5 }); } [Test] public void IEnumerableGetEnumeratorWorks() { var arr = (IEnumerable<short>)new Int16Array(new short[] { 3, 6, 2, 9, 5 }); var l = new List<int>(); var enm = arr.GetEnumerator(); while (enm.MoveNext()) { l.Add(enm.Current); } Assert.AreEqual(new[] { 3, 6, 2, 9, 5 }, l.ToArray()); } [Test] public void ICollectionMethodsWork_SPI_1559() { // #1559 var coll = (ICollection<short>)new Int16Array(new short[] { 3, 6, 2, 9, 5 }); Assert.AreEqual(5, coll.Count, "Count"); Assert.True(coll.Contains(6), "Contains(6)"); Assert.False(coll.Contains(1), "Contains(1)"); Assert.Throws<NotSupportedException>(() => coll.Add(2), "Add"); Assert.Throws<NotSupportedException>(() => coll.Clear(), "Clear"); Assert.Throws<NotSupportedException>(() => coll.Remove(2), "Remove"); } [Test] public void IListMethodsWork_SPI_1559() { // #1559 var list = (IList<short>)new Int16Array(new short[] { 3, 6, 2, 9, 5 }); Assert.AreEqual(1, list.IndexOf(6), "IndexOf(6)"); Assert.AreEqual(-1, list.IndexOf(1), "IndexOf(1)"); Assert.AreEqual(9, list[3], "Get item"); list[3] = 4; Assert.AreEqual(4, list[3], "Set item"); Assert.Throws<NotSupportedException>(() => list.Insert(2, 2), "Insert"); Assert.Throws<NotSupportedException>(() => list.RemoveAt(2), "RemoveAt"); } // Not JS API //[Test] //public void IReadOnlyCollectionMethodsWork() //{ // var coll = (IReadOnlyCollection<short>)new Int16Array(new short[] { 3, 6, 2, 9, 5 }); // Assert.AreEqual(coll.Count, 5, "Count"); // Assert.True(coll.Contains(6), "Contains(6)"); // Assert.False(coll.Contains(1), "Contains(1)"); //} // Not JS API //[Test] //public void IReadOnlyListMethodsWork() //{ // var list = (IReadOnlyList<short>)new Int16Array(new short[] { 3, 6, 2, 9, 5 }); // Assert.AreEqual(list[3], 9, "Get item"); //} [Test] public void IListIsReadOnlyWorks() { var list = (IList<float>)new Int16Array(new float[0]); Assert.True(list.IsReadOnly); } [Test] public void ICollectionIsReadOnlyWorks() { var list = (ICollection<float>)new Int16Array(new float[0]); Assert.True(list.IsReadOnly); } [Test] public void ICollectionCopyTo() { ICollection<short> l = new Int16Array(new short[] { 0, 1, 2 }); var a1 = new short[3]; l.CopyTo(a1, 0); Assert.AreEqual(0, a1[0], "1.Element 0"); Assert.AreEqual(1, a1[1], "1.Element 1"); Assert.AreEqual(2, a1[2], "1.Element 2"); var a2 = new short[5]; l.CopyTo(a2, 1); Assert.AreEqual(0, a2[0], "2.Element 0"); Assert.AreEqual(0, a2[1], "2.Element 1"); Assert.AreEqual(1, a2[2], "2.Element 2"); Assert.AreEqual(2, a2[3], "2.Element 3"); Assert.AreEqual(0, a2[4], "2.Element 4"); Assert.Throws<ArgumentNullException>(() => { l.CopyTo(null, 0); }, "3.null"); var a3 = new short[2]; Assert.Throws<ArgumentException>(() => { l.CopyTo(a3, 0); }, "3.Short array"); var a4 = new short[3]; Assert.Throws<ArgumentException>(() => { l.CopyTo(a4, 1); }, "3.Start index 1"); Assert.Throws<ArgumentOutOfRangeException>(() => { l.CopyTo(a4, -1); }, "3.Negative start index"); Assert.Throws<ArgumentException>(() => { l.CopyTo(a4, 3); }, "3.Start index 3"); } } }
// The MIT License (MIT) // // Copyright (c) 2015, Unity Technologies & Google, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using UnityEngine; using UnityEngine.EventSystems; /// This script provides an implemention of Unity's `BaseInputModule` class, so /// that Canvas-based (_uGUI_) UI elements can be selected by looking at them and /// pulling the viewer's trigger or touching the screen. /// This uses the player's gaze and the trigger as a raycast generator. /// /// To use, attach to the scene's **EventSystem** object. Be sure to move it above the /// other modules, such as _TouchInputModule_ and _StandaloneInputModule_, in order /// for the user's gaze to take priority in the event system. /// /// Next, set the **Canvas** object's _Render Mode_ to **World Space**, and set its _Event Camera_ /// to a (mono) camera that is controlled by a GvrHead. If you'd like gaze to work /// with 3D scene objects, add a _PhysicsRaycaster_ to the gazing camera, and add a /// component that implements one of the _Event_ interfaces (_EventTrigger_ will work nicely). /// The objects must have colliders too. /// /// GazeInputModule emits the following events: _Enter_, _Exit_, _Down_, _Up_, _Click_, _Select_, /// _Deselect_, and _UpdateSelected_. Scroll, move, and submit/cancel events are not emitted. [AddComponentMenu("GoogleVR/GazeInputModule")] public class GazeInputModule : BaseInputModule { /// Determines whether gaze input is active in VR Mode only (`true`), or all of the /// time (`false`). Set to false if you plan to use direct screen taps or other /// input when not in VR Mode. [Tooltip("Whether gaze input is active in VR Mode only (true), or all the time (false).")] public bool vrModeOnly = false; /// Time in seconds between the pointer down and up events sent by a trigger. /// Allows time for the UI elements to make their state transitions. [HideInInspector] public float clickTime = 0.1f; // Based on default time for a button to animate to Pressed. /// The pixel through which to cast rays, in viewport coordinates. Generally, the center /// pixel is best, assuming a monoscopic camera is selected as the `Canvas`' event camera. [HideInInspector] public Vector2 hotspot = new Vector2(0.5f, 0.5f); private PointerEventData pointerData; private Vector2 lastHeadPose; /// The IGvrGazePointer which will be responding to gaze events. public static IGvrGazePointer gazePointer; // Active state private bool isActive = false; /// @cond public override bool ShouldActivateModule() { bool activeState = base.ShouldActivateModule(); activeState = activeState && (GvrViewer.Instance.VRModeEnabled || !vrModeOnly); if (activeState != isActive) { isActive = activeState; // Activate gaze pointer if (gazePointer != null) { if (isActive) { gazePointer.OnGazeEnabled(); } } } return activeState; } /// @endcond public override void DeactivateModule() { DisableGazePointer(); base.DeactivateModule(); if (pointerData != null) { HandlePendingClick(); HandlePointerExitAndEnter(pointerData, null); pointerData = null; } eventSystem.SetSelectedGameObject(null, GetBaseEventData()); } public override bool IsPointerOverGameObject(int pointerId) { return pointerData != null && pointerData.pointerEnter != null; } public override void Process() { // Save the previous Game Object GameObject gazeObjectPrevious = GetCurrentGameObject(); CastRayFromGaze(); UpdateCurrentObject(); UpdateReticle(gazeObjectPrevious); // Handle input if (!Input.GetMouseButtonDown(0) && Input.GetMouseButton(0)) { HandleDrag(); } else if (Time.unscaledTime - pointerData.clickTime < clickTime) { // Delay new events until clickTime has passed. } else if (!pointerData.eligibleForClick && (GvrViewer.Instance.Triggered || Input.GetMouseButtonDown(0))) { // New trigger action. HandleTrigger(); } else if (!GvrViewer.Instance.Triggered && !Input.GetMouseButton(0)) { // Check if there is a pending click to handle. HandlePendingClick(); } } /// @endcond private void CastRayFromGaze() { Vector2 headPose = NormalizedCartesianToSpherical(GvrViewer.Instance.HeadPose.Orientation * Vector3.forward); if (pointerData == null) { pointerData = new PointerEventData(eventSystem); lastHeadPose = headPose; } // Cast a ray into the scene pointerData.Reset(); pointerData.position = new Vector2(hotspot.x * Screen.width, hotspot.y * Screen.height); eventSystem.RaycastAll(pointerData, m_RaycastResultCache); pointerData.pointerCurrentRaycast = FindFirstRaycast(m_RaycastResultCache); m_RaycastResultCache.Clear(); pointerData.delta = headPose - lastHeadPose; lastHeadPose = headPose; } private void UpdateCurrentObject() { // Send enter events and update the highlight. var go = pointerData.pointerCurrentRaycast.gameObject; HandlePointerExitAndEnter(pointerData, go); // Update the current selection, or clear if it is no longer the current object. var selected = ExecuteEvents.GetEventHandler<ISelectHandler>(go); if (selected == eventSystem.currentSelectedGameObject) { ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, GetBaseEventData(), ExecuteEvents.updateSelectedHandler); } else { eventSystem.SetSelectedGameObject(null, pointerData); } } void UpdateReticle(GameObject previousGazedObject) { if (gazePointer == null) { return; } Camera camera = pointerData.enterEventCamera; // Get the camera GameObject gazeObject = GetCurrentGameObject(); // Get the gaze target Vector3 intersectionPosition = GetIntersectionPosition(); bool isInteractive = pointerData.pointerPress != null || ExecuteEvents.GetEventHandler<IPointerClickHandler>(gazeObject) != null; if (gazeObject == previousGazedObject) { if (gazeObject != null) { gazePointer.OnGazeStay(camera, gazeObject, intersectionPosition, isInteractive); } } else { if (previousGazedObject != null) { gazePointer.OnGazeExit(camera, previousGazedObject); } if (gazeObject != null) { gazePointer.OnGazeStart(camera, gazeObject, intersectionPosition, isInteractive); } } } private void HandleDrag() { bool moving = pointerData.IsPointerMoving(); if (moving && pointerData.pointerDrag != null && !pointerData.dragging) { ExecuteEvents.Execute(pointerData.pointerDrag, pointerData, ExecuteEvents.beginDragHandler); pointerData.dragging = true; } // Drag notification if (pointerData.dragging && moving && pointerData.pointerDrag != null) { // Before doing drag we should cancel any pointer down state // And clear selection! if (pointerData.pointerPress != pointerData.pointerDrag) { ExecuteEvents.Execute(pointerData.pointerPress, pointerData, ExecuteEvents.pointerUpHandler); pointerData.eligibleForClick = false; pointerData.pointerPress = null; pointerData.rawPointerPress = null; } ExecuteEvents.Execute(pointerData.pointerDrag, pointerData, ExecuteEvents.dragHandler); } } private void HandlePendingClick() { if (!pointerData.eligibleForClick && !pointerData.dragging) { return; } if (gazePointer != null) { Camera camera = pointerData.enterEventCamera; gazePointer.OnGazeTriggerEnd(camera); } var go = pointerData.pointerCurrentRaycast.gameObject; // Send pointer up and click events. ExecuteEvents.Execute(pointerData.pointerPress, pointerData, ExecuteEvents.pointerUpHandler); if (pointerData.eligibleForClick) { ExecuteEvents.Execute(pointerData.pointerPress, pointerData, ExecuteEvents.pointerClickHandler); } else if (pointerData.dragging) { ExecuteEvents.ExecuteHierarchy(go, pointerData, ExecuteEvents.dropHandler); ExecuteEvents.Execute(pointerData.pointerDrag, pointerData, ExecuteEvents.endDragHandler); } // Clear the click state. pointerData.pointerPress = null; pointerData.rawPointerPress = null; pointerData.eligibleForClick = false; pointerData.clickCount = 0; pointerData.clickTime = 0; pointerData.pointerDrag = null; pointerData.dragging = false; } private void HandleTrigger() { var go = pointerData.pointerCurrentRaycast.gameObject; // Send pointer down event. pointerData.pressPosition = pointerData.position; pointerData.pointerPressRaycast = pointerData.pointerCurrentRaycast; pointerData.pointerPress = ExecuteEvents.ExecuteHierarchy(go, pointerData, ExecuteEvents.pointerDownHandler) ?? ExecuteEvents.GetEventHandler<IPointerClickHandler>(go); // Save the drag handler as well pointerData.pointerDrag = ExecuteEvents.GetEventHandler<IDragHandler>(go); if (pointerData.pointerDrag != null) { ExecuteEvents.Execute(pointerData.pointerDrag, pointerData, ExecuteEvents.initializePotentialDrag); } // Save the pending click state. pointerData.rawPointerPress = go; pointerData.eligibleForClick = true; pointerData.delta = Vector2.zero; pointerData.dragging = false; pointerData.useDragThreshold = true; pointerData.clickCount = 1; pointerData.clickTime = Time.unscaledTime; if (gazePointer != null) { gazePointer.OnGazeTriggerStart(pointerData.enterEventCamera); } } private Vector2 NormalizedCartesianToSpherical(Vector3 cartCoords) { cartCoords.Normalize(); if (cartCoords.x == 0) cartCoords.x = Mathf.Epsilon; float outPolar = Mathf.Atan(cartCoords.z / cartCoords.x); if (cartCoords.x < 0) outPolar += Mathf.PI; float outElevation = Mathf.Asin(cartCoords.y); return new Vector2(outPolar, outElevation); } GameObject GetCurrentGameObject() { if (pointerData != null && pointerData.enterEventCamera != null) { return pointerData.pointerCurrentRaycast.gameObject; } return null; } Vector3 GetIntersectionPosition() { // Check for camera Camera cam = pointerData.enterEventCamera; if (cam == null) { return Vector3.zero; } float intersectionDistance = pointerData.pointerCurrentRaycast.distance + cam.nearClipPlane; Vector3 intersectionPosition = cam.transform.position + cam.transform.forward * intersectionDistance; return intersectionPosition; } void DisableGazePointer() { if (gazePointer == null) { return; } GameObject currentGameObject = GetCurrentGameObject(); if (currentGameObject) { Camera camera = pointerData.enterEventCamera; gazePointer.OnGazeExit(camera, currentGameObject); } gazePointer.OnGazeDisabled(); } }
using System; using System.Collections.Generic; using System.Linq; namespace Veggerby.Algorithm.Calculus.Visitors { public class IntegralOperandVisitor : IOperandVisitor<Operand> { private readonly Variable _variable; private readonly IEnumerable<Operand> _stack; private static readonly Variable _constant = Variable.Create("c"); public IntegralOperandVisitor(Variable variable, IEnumerable<Operand> stack = null) { if (stack != null && stack.Count() > 25) // abort when too deep { throw new ArgumentOutOfRangeException(nameof(stack), "Too many iterations"); } _variable = variable; _stack = stack?.ToList() ?? new List<Operand>(); } private Operand GetIntegral(Operand operand) { if (_stack.Contains(operand)) // abort when too deep { throw new ArgumentException("Circular call", nameof(operand)); } var visitor = new IntegralOperandVisitor(_variable, _stack.Concat(new [] { operand })); return operand .Reduce()? .Accept(visitor)? .Reduce(); } private Operand GetDerivative(Operand operand) { var visitor = new DerivativeOperandVisitor(_variable); return operand.Reduce()?.Accept(visitor)?.Reduce(); } private Operand ConstantRule(Operand constant) { return Addition.Create( Multiplication.Create(constant, _variable), _constant ); } private Operand PowerRule(double power) { return Addition.Create( Division.Create( Power.Create(_variable, power + 1), power + 1), _constant); } private Operand IntegrationByParts(Operand left, Operand right) { try { var leftDerivative = GetDerivative(left); var rightIntegral = GetIntegral(right); if (leftDerivative == null || rightIntegral == null) { return null; } var rightOperation = Multiplication.Create(leftDerivative, rightIntegral); var rightPart = GetIntegral(rightOperation); if (rightPart == null) { return null; } return Subtraction.Create( Multiplication.Create(left, rightIntegral), rightPart ); } catch (ArgumentException) { return null; } catch (NotImplementedException) { return null; } catch (NotSupportedException) { return null; } } public Operand Visit(Function operand) { var innerOperand = GetIntegral(operand.Operand); return Function.Create(operand.Identifier.ToUpperInvariant(), innerOperand); } public Operand Visit(FunctionReference operand) => null; public Operand Visit(Variable operand) => operand.Equals(_variable) ? PowerRule(1) : ConstantRule(operand); public Operand Visit(Subtraction operand) { var left = GetIntegral(operand.Left); var right = GetIntegral(operand.Right); return left != null && right != null ? Subtraction.Create(left, right) : null; } public Operand Visit(Division operand) { if (operand.Left.IsConstant() && operand.Right.Equals(_variable)) { return Multiplication.Create( operand.Left, Addition.Create( Logarithm.Create(_variable), _constant ) ); } else { throw new NotSupportedException(); } } public Operand Visit(Factorial operand) => null; public Operand Visit(Cosine operand) { if (operand.Inner.Equals(_variable)) { return Addition.Create( Sine.Create(_variable), _constant ); } else { throw new NotSupportedException(); } } public Operand Visit(Exponential operand) { if (operand.Inner.Equals(_variable)) { return Addition.Create( Exponential.Create(_variable), _constant ); } else { throw new NotSupportedException(); } } public Operand Visit(LogarithmBase operand) => throw new NotImplementedException(); public Operand Visit(Negative operand) { var inner = GetIntegral(operand.Inner); if (inner == null) { return null; } return Negative.Create(inner); } public Operand Visit(Logarithm operand) { if (operand.Inner.Equals(_variable)) { return Addition.Create( Subtraction.Create( Multiplication.Create(_variable, Logarithm.Create(_variable)), _variable), _constant); } else { throw new NotSupportedException(); } } public Operand Visit(Tangent operand) => throw new NotImplementedException(); public Operand Visit(Sine operand) { if (operand.Inner.Equals(_variable)) { return Addition.Create( Negative.Create(Cosine.Create(_variable)), _constant ); } else { throw new NotSupportedException(); } } public Operand Visit(Power operand) { if (operand.Left.Equals(_variable) && operand.Right.IsConstant() && operand.Right != ValueConstant.MinusOne) { return PowerRule(((ValueConstant)operand.Right).Value); } else { throw new NotSupportedException(); } } public Operand Visit(Root operand) { if (operand.Inner.Equals(_variable)) { return PowerRule(1D / operand.Exponent); } else { throw new NotSupportedException(); } } public Operand Visit(Multiplication operand) { var parts = operand .Operands .Select(x => new { Left = Multiplication.Create(operand.Operands.Where(y => !object.ReferenceEquals(x, y))), Right = x }) .Distinct() .ToList(); Operand simplest = null; int complexity = int.MaxValue; foreach (var part in parts) { var result = IntegrationByParts(part.Left, part.Right); if (result == null) { continue; } var c = result.GetComplexity(); if (c < complexity) { complexity = c; simplest = result; } } return simplest; } public Operand Visit(Addition operand) { var operands = operand .Operands .Select(x => GetIntegral(x)) .ToList(); if (operands.Any(x => x == null)) { return null; } return Addition.Create(operands); } public Operand Visit(NamedConstant operand) => ConstantRule(operand); public Operand Visit(ValueConstant operand) => ConstantRule(operand); public Operand Visit(UnspecifiedConstant operand) => ConstantRule(operand); public Operand Visit(Fraction operand) => ConstantRule(operand); public Operand Visit(Minimum operand) => null; public Operand Visit(Maximum operand) => null; } }
using UnityEngine; using System.Collections; using UnityEngine.UI.Windows.Plugins.ABTesting.Net.Api; #if UNITY_EDITOR using UnityEditor; #endif namespace UnityEngine.UI.Windows.Plugins.ABTesting { public class Condition2Values : ConditionBase { public Condition2Values(Type type) : base(type) {} #if UNITY_EDITOR public override void OnContentGUI() { } public void Draw2Values(System.Action<string> onLowDraw, System.Action<string> onUpperDraw) { if (this.HasType(Type.From) == true) onLowDraw(this.lowSign); if (this.HasType(Type.From) == true && this.HasType(Type.To) == true) EditorGUILayout.LabelField(" AND "); if (this.HasType(Type.To) == true) onUpperDraw(this.upperSign); if (this.HasType(Type.Strong) == true && this.HasType(Type.From) == false && this.HasType(Type.To) == false) { onLowDraw("Value:"); } } #endif }; [System.Serializable] public class EnumCondition : ConditionBase { public System.Type enumType; public int value; public EnumCondition(Type type, System.Type enumType, int value) : base(type) { this.enumType = enumType; this.value = value; } public EnumCondition(EnumConditionTO source) : base((Type)source.type) { this.value = source.value; } public EnumConditionTO GetTO() { return new EnumConditionTO(this.type) { value = this.value }; } public void SetType(System.Type type) { this.enumType = type; } public bool Resolve(int value) { var result = true; result = ((int)value == this.value); return result; } #if UNITY_EDITOR public override void OnTypeGUI() { this.type = Type.Strong; } public override void OnContentGUI() { this.value = EditorGUILayout.Popup("Value: ", this.value, System.Enum.GetNames(this.enumType)); } #endif }; [System.Serializable] public class IntCondition : Condition2Values { public int fromValue; public int toValue; public IntCondition(Type type, int from, int to) : base(type) { this.fromValue = from; this.toValue = to; } public IntCondition(IntConditionTO source) : base((Type)source.type) { this.fromValue = source.from; this.toValue = source.to; } public IntConditionTO GetTO() { return new IntConditionTO(this.type) { from = this.fromValue, to = this.toValue }; } public bool Resolve(int value) { var result = true; var hasStrong = this.HasType(Type.Strong); if (result == true && this.HasType(Type.From) == true) { result = (hasStrong == true) ? (value >= this.fromValue) : (value > this.fromValue); } if (result == true && this.HasType(Type.To) == true) { result = (hasStrong == true) ? (value <= this.toValue) : (value < this.toValue); } if (result == true && this.HasType(Type.To) == false && this.HasType(Type.From) == false) { result = (value == this.fromValue); } return result; } #if UNITY_EDITOR public override void OnContentGUI() { this.Draw2Values((name) => { this.fromValue = EditorGUILayout.IntField(name, this.fromValue); }, (name) => { this.toValue = EditorGUILayout.IntField(name, this.toValue); }); } #endif }; [System.Serializable] public class FloatCondition : Condition2Values { public float fromValue; public float toValue; public FloatCondition(Type type, float from, float to) : base(type) { this.fromValue = from; this.toValue = to; } public FloatCondition(FloatConditionTO source) : base((Type)source.type) { this.fromValue = source.from; this.toValue = source.to; } public FloatConditionTO GetTO() { return new FloatConditionTO(this.type) { from = this.fromValue, to = this.toValue }; } public bool Resolve(float value) { var result = true; var hasStrong = this.HasType(Type.Strong); if (result == true && this.HasType(Type.From) == true) { result = (hasStrong == true) ? (value >= this.fromValue) : (value > this.fromValue); } if (result == true && this.HasType(Type.To) == true) { result = (hasStrong == true) ? (value <= this.toValue) : (value < this.toValue); } if (result == true && this.HasType(Type.To) == false && this.HasType(Type.From) == false) { result = (value == this.fromValue); } return result; } #if UNITY_EDITOR public override void OnContentGUI() { this.Draw2Values((name) => { this.fromValue = EditorGUILayout.FloatField(name, this.fromValue); }, (name) => { this.toValue = EditorGUILayout.FloatField(name, this.toValue); }); } #endif }; [System.Serializable] public class LongCondition : Condition2Values { public long fromValue; public long toValue; public LongCondition(Type type, long from, long to) : base(type) { this.fromValue = from; this.toValue = to; } public LongCondition(LongConditionTO source) : base((Type)source.type) { this.fromValue = source.from; this.toValue = source.to; } public LongConditionTO GetTO() { return new LongConditionTO(this.type) { from = this.fromValue, to = this.toValue }; } public bool Resolve(long value) { var result = true; var hasStrong = this.HasType(Type.Strong); if (result == true && this.HasType(Type.From) == true) { result = (hasStrong == true) ? (value >= this.fromValue) : (value > this.fromValue); } if (result == true && this.HasType(Type.To) == true) { result = (hasStrong == true) ? (value <= this.toValue) : (value < this.toValue); } if (result == true && this.HasType(Type.To) == false && this.HasType(Type.From) == false) { result = (value == this.fromValue); } return result; } #if UNITY_EDITOR public override void OnContentGUI() { this.Draw2Values((name) => { this.fromValue = EditorGUILayout.LongField(name, this.fromValue); }, (name) => { this.toValue = EditorGUILayout.LongField(name, this.toValue); }); } #endif }; [System.Serializable] public class DoubleCondition : Condition2Values { public double fromValue; public double toValue; public DoubleCondition(Type type, double from, double to) : base(type) { this.fromValue = from; this.toValue = to; } public DoubleCondition(DoubleConditionTO source) : base((Type)source.type) { this.fromValue = source.from; this.toValue = source.to; } public DoubleConditionTO GetTO() { return new DoubleConditionTO(this.type) { from = this.fromValue, to = this.toValue }; } public bool Resolve(double value) { var result = true; var hasStrong = this.HasType(Type.Strong); if (result == true && this.HasType(Type.From) == true) { result = (hasStrong == true) ? (value >= this.fromValue) : (value > this.fromValue); } if (result == true && this.HasType(Type.To) == true) { result = (hasStrong == true) ? (value <= this.toValue) : (value < this.toValue); } if (result == true && this.HasType(Type.To) == false && this.HasType(Type.From) == false) { result = (value == this.fromValue); } return result; } #if UNITY_EDITOR public override void OnContentGUI() { this.Draw2Values((name) => { this.fromValue = EditorGUILayout.DoubleField(name, this.fromValue); }, (name) => { this.toValue = EditorGUILayout.DoubleField(name, this.toValue); }); } #endif }; [System.Serializable] public abstract class ConditionBase : IBaseCondition { public enum Type : byte { None = 0x0, Strong = 0x1, From = 0x2, To = 0x4, }; public Type type = Type.None; public string lowSign { get { if (this.HasType(Type.Strong) == true) return ">="; return ">"; } } public string upperSign { get { if (this.HasType(Type.Strong) == true) return "<="; return "<"; } } public ConditionBase(Type type) { this.type = type; } protected bool HasType(Type type) { return (this.type & type) != 0; } #if UNITY_EDITOR public virtual void OnTypeGUI() { GUILayout.BeginHorizontal(); { var values = System.Enum.GetValues(typeof(Type)); var names = System.Enum.GetNames(typeof(Type)); for (int i = 0; i < values.Length; ++i) { var value = (Type)values.GetValue(i); if (value == Type.None) continue; var oldCheck = this.HasType(value); var check = GUILayout.Toggle(oldCheck, names[i]); if (oldCheck != check) { if (check == true) { this.type |= value; } else { this.type ^= value; } } } } GUILayout.EndHorizontal(); //this.type = (Type)EditorExtension.DrawBitMaskFieldLayout((int)this.type, this.type.GetType(), new GUIContent("Keys:")); } public abstract void OnContentGUI(); public void OnGUI() { this.OnTypeGUI(); EditorGUIUtility.labelWidth = 50f; GUILayout.BeginVertical(EditorStyles.helpBox); { this.OnContentGUI(); } GUILayout.EndVertical(); EditorGUIUtilityExt.LookLikeControls(); } #endif }; }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Threading; using PSHost = System.Management.Automation.Host.PSHost; using System.Management.Automation.Internal; using System.Management.Automation.Runspaces.Internal; using System.Collections.ObjectModel; using System.Runtime.Serialization; namespace System.Management.Automation.Runspaces { #region Exceptions /// <summary> /// Exception thrown when state of the runspace pool is different from /// expected state of runspace pool. /// </summary> [Serializable] public class InvalidRunspacePoolStateException : SystemException { /// <summary> /// Creates a new instance of InvalidRunspacePoolStateException class. /// </summary> public InvalidRunspacePoolStateException() : base ( StringUtil.Format(RunspacePoolStrings.InvalidRunspacePoolStateGeneral) ) { } /// <summary> /// Creates a new instance of InvalidRunspacePoolStateException class. /// </summary> /// <param name="message"> /// The error message that explains the reason for the exception. /// </param> public InvalidRunspacePoolStateException(string message) : base(message) { } /// <summary> /// Creates a new instance of InvalidRunspacePoolStateException class. /// </summary> /// <param name="message"> /// The error message that explains the reason for the exception. /// </param> /// <param name="innerException"> /// The exception that is the cause of the current exception. /// </param> public InvalidRunspacePoolStateException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// Initializes a new instance of the InvalidRunspacePoolStateException /// with a specified error message and current and expected state. /// </summary> /// <param name="message">The message that describes the error.</param> /// <param name="currentState">Current state of runspace pool.</param> /// <param name="expectedState">Expected state of the runspace pool.</param> internal InvalidRunspacePoolStateException ( string message, RunspacePoolState currentState, RunspacePoolState expectedState ) : base(message) { _expectedState = expectedState; _currentState = currentState; } #region ISerializable Members // No need to implement GetObjectData // if all fields are static or [NonSerialized] /// <summary> /// Initializes a new instance of the InvalidRunspacePoolStateException /// class with serialized data. /// </summary> /// <param name="info"> /// The <see cref="SerializationInfo"/> that holds /// the serialized object data about the exception being thrown. /// </param> /// <param name="context"> /// The <see cref="StreamingContext"/> that contains /// contextual information about the source or destination. /// </param> protected InvalidRunspacePoolStateException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endregion /// <summary> /// Access CurrentState of the runspace pool. /// </summary> /// <remarks> /// This is the state of the runspace pool when exception was thrown. /// </remarks> public RunspacePoolState CurrentState { get { return _currentState; } } /// <summary> /// Expected state of runspace pool by the operation which has thrown /// this exception. /// </summary> public RunspacePoolState ExpectedState { get { return _expectedState; } } /// <summary> /// Converts the current to an InvalidRunspaceStateException. /// </summary> internal InvalidRunspaceStateException ToInvalidRunspaceStateException() { InvalidRunspaceStateException exception = new InvalidRunspaceStateException( RunspaceStrings.InvalidRunspaceStateGeneral, this); exception.CurrentState = RunspacePoolStateToRunspaceState(this.CurrentState); exception.ExpectedState = RunspacePoolStateToRunspaceState(this.ExpectedState); return exception; } /// <summary> /// Converts a RunspacePoolState to a RunspaceState. /// </summary> private static RunspaceState RunspacePoolStateToRunspaceState(RunspacePoolState state) { switch (state) { case RunspacePoolState.BeforeOpen: return RunspaceState.BeforeOpen; case RunspacePoolState.Opening: return RunspaceState.Opening; case RunspacePoolState.Opened: return RunspaceState.Opened; case RunspacePoolState.Closed: return RunspaceState.Closed; case RunspacePoolState.Closing: return RunspaceState.Closing; case RunspacePoolState.Broken: return RunspaceState.Broken; case RunspacePoolState.Disconnecting: return RunspaceState.Disconnecting; case RunspacePoolState.Disconnected: return RunspaceState.Disconnected; case RunspacePoolState.Connecting: return RunspaceState.Connecting; default: Diagnostics.Assert(false, "Unexpected RunspacePoolState"); return 0; } } /// <summary> /// State of the runspace pool when exception was thrown. /// </summary> [NonSerialized] private RunspacePoolState _currentState = 0; /// <summary> /// State of the runspace pool expected in method which throws this exception. /// </summary> [NonSerialized] private RunspacePoolState _expectedState = 0; } #endregion #region State /// <summary> /// Defines various states of a runspace pool. /// </summary> public enum RunspacePoolState { /// <summary> /// Beginning state upon creation. /// </summary> BeforeOpen = 0, /// <summary> /// A RunspacePool is being created. /// </summary> Opening = 1, /// <summary> /// The RunspacePool is created and valid. /// </summary> Opened = 2, /// <summary> /// The RunspacePool is closed. /// </summary> Closed = 3, /// <summary> /// The RunspacePool is being closed. /// </summary> Closing = 4, /// <summary> /// The RunspacePool has been disconnected abnormally. /// </summary> Broken = 5, /// <summary> /// The RunspacePool is being disconnected. /// </summary> Disconnecting = 6, /// <summary> /// The RunspacePool has been disconnected. /// </summary> Disconnected = 7, /// <summary> /// The RunspacePool is being connected. /// </summary> Connecting = 8, } /// <summary> /// Event arguments passed to runspacepool state change handlers /// <see cref="RunspacePool.StateChanged"/> event. /// </summary> public sealed class RunspacePoolStateChangedEventArgs : EventArgs { #region Constructors /// <summary> /// Constructor. /// </summary> /// <param name="state"> /// state to raise the event with. /// </param> internal RunspacePoolStateChangedEventArgs(RunspacePoolState state) { RunspacePoolStateInfo = new RunspacePoolStateInfo(state, null); } /// <summary> /// </summary> /// <param name="stateInfo"></param> internal RunspacePoolStateChangedEventArgs(RunspacePoolStateInfo stateInfo) { RunspacePoolStateInfo = stateInfo; } #endregion #region Public Properties /// <summary> /// Gets the stateinfo of RunspacePool when this event occurred. /// </summary> public RunspacePoolStateInfo RunspacePoolStateInfo { get; } #endregion #region Private Data #endregion } /// <summary> /// Event arguments passed to RunspaceCreated event of RunspacePool. /// </summary> internal sealed class RunspaceCreatedEventArgs : EventArgs { #region Private Data #endregion #region Constructors /// <summary> /// </summary> /// <param name="runspace"></param> internal RunspaceCreatedEventArgs(Runspace runspace) { Runspace = runspace; } #endregion #region Internal Properties internal Runspace Runspace { get; } #endregion } #endregion #region RunspacePool Availability /// <summary> /// Defines runspace pool availability. /// </summary> public enum RunspacePoolAvailability { /// <summary> /// RunspacePool is not in the Opened state. /// </summary> None = 0, /// <summary> /// RunspacePool is Opened and available to accept commands. /// </summary> Available = 1, /// <summary> /// RunspacePool on the server is connected to another /// client and is not available to this client for connection /// or running commands. /// </summary> Busy = 2 } #endregion #region RunspacePool Capabilities /// <summary> /// Defines runspace capabilities. /// </summary> public enum RunspacePoolCapability { /// <summary> /// No additional capabilities beyond a default runspace. /// </summary> Default = 0x0, /// <summary> /// Runspacepool and remoting layer supports disconnect/connect feature. /// </summary> SupportsDisconnect = 0x1 } #endregion #region AsyncResult /// <summary> /// Encapsulated the AsyncResult for pool's Open/Close async operations. /// </summary> internal sealed class RunspacePoolAsyncResult : AsyncResult { #region Private Data #endregion #region Constructor /// <summary> /// Constructor. /// </summary> /// <param name="ownerId"> /// Instance Id of the pool creating this instance /// </param> /// <param name="callback"> /// Callback to call when the async operation completes. /// </param> /// <param name="state"> /// A user supplied state to call the "callback" with. /// </param> /// <param name="isCalledFromOpenAsync"> /// true if AsyncResult monitors Async Open. /// false otherwise /// </param> internal RunspacePoolAsyncResult(Guid ownerId, AsyncCallback callback, object state, bool isCalledFromOpenAsync) : base(ownerId, callback, state) { IsAssociatedWithAsyncOpen = isCalledFromOpenAsync; } #endregion #region Internal Properties /// <summary> /// True if AsyncResult monitors Async Open. /// false otherwise. /// </summary> internal bool IsAssociatedWithAsyncOpen { get; } #endregion } /// <summary> /// Encapsulated the results of a RunspacePool.BeginGetRunspace method. /// </summary> internal sealed class GetRunspaceAsyncResult : AsyncResult { #region Private Data private bool _isActive; #endregion #region Constructor /// <summary> /// Constructor. /// </summary> /// <param name="ownerId"> /// Instance Id of the pool creating this instance /// </param> /// <param name="callback"> /// Callback to call when the async operation completes. /// </param> /// <param name="state"> /// A user supplied state to call the "callback" with. /// </param> internal GetRunspaceAsyncResult(Guid ownerId, AsyncCallback callback, object state) : base(ownerId, callback, state) { _isActive = true; } #endregion #region Internal Methods/Properties /// <summary> /// Gets the runspace that is assigned to the async operation. /// </summary> /// <remarks> /// This can be null if the async Get operation is not completed. /// </remarks> internal Runspace Runspace { get; set; } /// <summary> /// Gets or sets a value indicating whether this operation /// is active or not. /// </summary> internal bool IsActive { get { lock (SyncObject) { return _isActive; } } set { lock (SyncObject) { _isActive = value; } } } /// <summary> /// Marks the async operation as completed and releases /// waiting threads. /// </summary> /// <param name="state"> /// This is not used /// </param> /// <remarks> /// This method is called from a thread pool thread to release /// the async operation. /// </remarks> internal void DoComplete(object state) { SetAsCompleted(null); } #endregion } #endregion #region RunspacePool /// <summary> /// Public interface which supports pooling PowerShell Runspaces. /// </summary> public sealed class RunspacePool : IDisposable { #region Private Data private RunspacePoolInternal _internalPool; private object _syncObject = new object(); private event EventHandler<RunspacePoolStateChangedEventArgs> InternalStateChanged = null; private event EventHandler<PSEventArgs> InternalForwardEvent = null; private event EventHandler<RunspaceCreatedEventArgs> InternalRunspaceCreated = null; #endregion #region Internal Constructor /// <summary> /// Constructor which creates a RunspacePool using the /// supplied <paramref name="configuration"/>, /// <paramref name="minRunspaces"/> and <paramref name="maxRunspaces"/> /// </summary> /// <param name="minRunspaces"> /// The minimum number of Runspaces that can exist in this pool. /// Should be greater than or equal to 1. /// </param> /// <param name="maxRunspaces"> /// The maximum number of Runspaces that can exist in this pool. /// Should be greater than or equal to 1. /// </param> /// <param name="host"> /// The explicit PSHost implementation. /// </param> /// <exception cref="ArgumentNullException"> /// Host is null. /// </exception> /// <exception cref="ArgumentException"> /// Maximum runspaces is less than 1. /// Minimum runspaces is less than 1. /// </exception> internal RunspacePool(int minRunspaces, int maxRunspaces, PSHost host) { // Currently we support only Local Runspace Pool.. // this needs to be changed once remote runspace pool // is implemented _internalPool = new RunspacePoolInternal(minRunspaces, maxRunspaces, host); } /// <summary> /// Constructor which creates a RunspacePool using the /// supplied <paramref name="initialSessionState"/>, /// <paramref name="minRunspaces"/> and <paramref name="maxRunspaces"/> /// </summary> /// <param name="minRunspaces"> /// The minimum number of Runspaces that can exist in this pool. /// Should be greater than or equal to 1. /// </param> /// <param name="maxRunspaces"> /// The maximum number of Runspaces that can exist in this pool. /// Should be greater than or equal to 1. /// </param> /// <param name="initialSessionState"> /// InitialSessionState object to use when creating a new Runspace. /// </param> /// <param name="host"> /// The explicit PSHost implementation. /// </param> /// <exception cref="ArgumentNullException"> /// initialSessionState is null. /// Host is null. /// </exception> /// <exception cref="ArgumentException"> /// Maximum runspaces is less than 1. /// Minimum runspaces is less than 1. /// </exception> internal RunspacePool(int minRunspaces, int maxRunspaces, InitialSessionState initialSessionState, PSHost host) { // Currently we support only Local Runspace Pool.. // this needs to be changed once remote runspace pool // is implemented _internalPool = new RunspacePoolInternal(minRunspaces, maxRunspaces, initialSessionState, host); } /// <summary> /// Construct a runspace pool object. /// </summary> /// <param name="minRunspaces">Min runspaces.</param> /// <param name="maxRunspaces">Max runspaces.</param> /// <param name="typeTable">TypeTable.</param> /// <param name="host">Host.</param> /// <param name="applicationArguments">App arguments.</param> /// <param name="connectionInfo">Connection information.</param> /// <param name="name">Session name.</param> internal RunspacePool( int minRunspaces, int maxRunspaces, TypeTable typeTable, PSHost host, PSPrimitiveDictionary applicationArguments, RunspaceConnectionInfo connectionInfo, string name = null) { _internalPool = new RemoteRunspacePoolInternal( minRunspaces, maxRunspaces, typeTable, host, applicationArguments, connectionInfo, name); IsRemote = true; } /// <summary> /// Creates a runspace pool object in a disconnected state that is /// ready to connect to a remote runspace pool session specified by /// the instanceId parameter. /// </summary> /// <param name="isDisconnected">Indicates whether the shell/runspace pool is disconnected.</param> /// <param name="instanceId">Identifies a remote runspace pool session to connect to.</param> /// <param name="name">Friendly name for runspace pool.</param> /// <param name="connectCommands">Runspace pool running commands information.</param> /// <param name="connectionInfo">Connection information of remote server.</param> /// <param name="host">PSHost object.</param> /// <param name="typeTable">TypeTable used for serialization/deserialization of remote objects.</param> internal RunspacePool( bool isDisconnected, Guid instanceId, string name, ConnectCommandInfo[] connectCommands, RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable) { // Disconnect-Connect semantics are currently only supported in WSMan transport. if (!(connectionInfo is WSManConnectionInfo)) { throw new NotSupportedException(); } _internalPool = new RemoteRunspacePoolInternal(instanceId, name, isDisconnected, connectCommands, connectionInfo, host, typeTable); IsRemote = true; } #endregion #region Public Properties /// <summary> /// Get unique id for this instance of runspace pool. It is primarily used /// for logging purposes. /// </summary> public Guid InstanceId { get { return _internalPool.InstanceId; } } /// <summary> /// Gets a boolean which describes if the runspace pool is disposed. /// </summary> public bool IsDisposed { get { return _internalPool.IsDisposed; } } /// <summary> /// Gets State of the current runspace pool. /// </summary> public RunspacePoolStateInfo RunspacePoolStateInfo { get { return _internalPool.RunspacePoolStateInfo; } } /// <summary> /// Gets the InitialSessionState object that this pool uses /// to create the runspaces. /// </summary> public InitialSessionState InitialSessionState { get { return _internalPool.InitialSessionState; } } /// <summary> /// Connection information for remote RunspacePools, null for local RunspacePools. /// </summary> public RunspaceConnectionInfo ConnectionInfo { get { return _internalPool.ConnectionInfo; } } /// <summary> /// Specifies how often unused runspaces are disposed. /// </summary> public TimeSpan CleanupInterval { get { return _internalPool.CleanupInterval; } set { _internalPool.CleanupInterval = value; } } /// <summary> /// Returns runspace pool availability. /// </summary> public RunspacePoolAvailability RunspacePoolAvailability { get { return _internalPool.RunspacePoolAvailability; } } #endregion #region events /// <summary> /// Event raised when RunspacePoolState changes. /// </summary> public event EventHandler<RunspacePoolStateChangedEventArgs> StateChanged { add { lock (_syncObject) { bool firstEntry = (InternalStateChanged == null); InternalStateChanged += value; if (firstEntry) { // call any event handlers on this object, replacing the // internalPool sender with 'this' since receivers // are expecting a RunspacePool. _internalPool.StateChanged += new EventHandler<RunspacePoolStateChangedEventArgs>(OnStateChanged); } } } remove { lock (_syncObject) { InternalStateChanged -= value; if (InternalStateChanged == null) { _internalPool.StateChanged -= new EventHandler<RunspacePoolStateChangedEventArgs>(OnStateChanged); } } } } /// <summary> /// Handle internal Pool state changed events. /// </summary> /// <param name="source"></param> /// <param name="args"></param> private void OnStateChanged(object source, RunspacePoolStateChangedEventArgs args) { if (ConnectionInfo is NewProcessConnectionInfo) { NewProcessConnectionInfo connectionInfo = ConnectionInfo as NewProcessConnectionInfo; if (connectionInfo.Process != null && (args.RunspacePoolStateInfo.State == RunspacePoolState.Opened || args.RunspacePoolStateInfo.State == RunspacePoolState.Broken)) { connectionInfo.Process.RunspacePool = this; } } // call any event handlers on this, replacing the // internalPool sender with 'this' since receivers // are expecting a RunspacePool InternalStateChanged.SafeInvoke(this, args); } /// <summary> /// Event raised when one of the runspaces in the pool forwards an event to this instance. /// </summary> internal event EventHandler<PSEventArgs> ForwardEvent { add { lock (_syncObject) { bool firstEntry = InternalForwardEvent == null; InternalForwardEvent += value; if (firstEntry) { _internalPool.ForwardEvent += OnInternalPoolForwardEvent; } } } remove { lock (_syncObject) { InternalForwardEvent -= value; if (InternalForwardEvent == null) { _internalPool.ForwardEvent -= OnInternalPoolForwardEvent; } } } } /// <summary> /// Pass thru of the ForwardEvent event from the internal pool. /// </summary> private void OnInternalPoolForwardEvent(object sender, PSEventArgs e) { OnEventForwarded(e); } /// <summary> /// Raises the ForwardEvent event. /// </summary> private void OnEventForwarded(PSEventArgs e) { EventHandler<PSEventArgs> eh = InternalForwardEvent; if (eh != null) { eh(this, e); } } /// <summary> /// Event raised when a new Runspace is created by the pool. /// </summary> internal event EventHandler<RunspaceCreatedEventArgs> RunspaceCreated { add { lock (_syncObject) { bool firstEntry = (InternalRunspaceCreated == null); InternalRunspaceCreated += value; if (firstEntry) { // call any event handlers on this object, replacing the // internalPool sender with 'this' since receivers // are expecting a RunspacePool. _internalPool.RunspaceCreated += OnRunspaceCreated; } } } remove { lock (_syncObject) { InternalRunspaceCreated -= value; if (InternalRunspaceCreated == null) { _internalPool.RunspaceCreated -= OnRunspaceCreated; } } } } /// <summary> /// Handle internal Pool RunspaceCreated events. /// </summary> /// <param name="source"></param> /// <param name="args"></param> private void OnRunspaceCreated(object source, RunspaceCreatedEventArgs args) { // call any event handlers on this, replacing the // internalPool sender with 'this' since receivers // are expecting a RunspacePool InternalRunspaceCreated.SafeInvoke(this, args); } #endregion events #region Public static methods. /// <summary> /// Queries the server for disconnected runspace pools and creates an array of runspace /// pool objects associated with each disconnected runspace pool on the server. Each /// runspace pool object in the returned array is in the Disconnected state and can be /// connected to the server by calling the Connect() method on the runspace pool. /// </summary> /// <param name="connectionInfo">Connection object for the target server.</param> /// <returns>Array of RunspacePool objects each in the Disconnected state.</returns> public static RunspacePool[] GetRunspacePools(RunspaceConnectionInfo connectionInfo) { return GetRunspacePools(connectionInfo, null, null); } /// <summary> /// Queries the server for disconnected runspace pools and creates an array of runspace /// pool objects associated with each disconnected runspace pool on the server. Each /// runspace pool object in the returned array is in the Disconnected state and can be /// connected to the server by calling the Connect() method on the runspace pool. /// </summary> /// <param name="connectionInfo">Connection object for the target server.</param> /// <param name="host">Client host object.</param> /// <returns>Array of RunspacePool objects each in the Disconnected state.</returns> public static RunspacePool[] GetRunspacePools(RunspaceConnectionInfo connectionInfo, PSHost host) { return GetRunspacePools(connectionInfo, host, null); } /// <summary> /// Queries the server for disconnected runspace pools and creates an array of runspace /// pool objects associated with each disconnected runspace pool on the server. Each /// runspace pool object in the returned array is in the Disconnected state and can be /// connected to the server by calling the Connect() method on the runspace pool. /// </summary> /// <param name="connectionInfo">Connection object for the target server.</param> /// <param name="host">Client host object.</param> /// <param name="typeTable">TypeTable object.</param> /// <returns>Array of RunspacePool objects each in the Disconnected state.</returns> public static RunspacePool[] GetRunspacePools(RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable) { return RemoteRunspacePoolInternal.GetRemoteRunspacePools(connectionInfo, host, typeTable); } #endregion #region Public Disconnect-Connect API /// <summary> /// Disconnects the runspace pool synchronously. Runspace pool must be in Opened state. /// </summary> public void Disconnect() { _internalPool.Disconnect(); } /// <summary> /// Disconnects the runspace pool asynchronously. Runspace pool must be in Opened state. /// </summary> /// <param name="callback">An AsyncCallback to call once the BeginClose completes.</param> /// <param name="state">A user supplied state to call the callback with.</param> public IAsyncResult BeginDisconnect(AsyncCallback callback, object state) { return _internalPool.BeginDisconnect(callback, state); } /// <summary> /// Waits for the pending asynchronous BeginDisconnect to complete. /// </summary> /// <param name="asyncResult">Asynchronous call result object.</param> public void EndDisconnect(IAsyncResult asyncResult) { _internalPool.EndDisconnect(asyncResult); } /// <summary> /// Connects the runspace pool synchronously. Runspace pool must be in disconnected state. /// </summary> public void Connect() { _internalPool.Connect(); } /// <summary> /// Connects the runspace pool asynchronously. Runspace pool must be in disconnected state. /// </summary> /// <param name="callback"></param> /// <param name="state"></param> public IAsyncResult BeginConnect(AsyncCallback callback, object state) { return _internalPool.BeginConnect(callback, state); } /// <summary> /// Waits for the pending asynchronous BeginConnect to complete. /// </summary> /// <param name="asyncResult">Asynchronous call result object.</param> public void EndConnect(IAsyncResult asyncResult) { _internalPool.EndConnect(asyncResult); } /// <summary> /// Creates an array of PowerShell objects that are in the Disconnected state for /// all currently disconnected running commands associated with this runspace pool. /// </summary> /// <returns></returns> public Collection<PowerShell> CreateDisconnectedPowerShells() { return _internalPool.CreateDisconnectedPowerShells(this); } ///<summary> /// Returns RunspacePool capabilities. /// </summary> /// <returns>RunspacePoolCapability.</returns> public RunspacePoolCapability GetCapabilities() { return _internalPool.GetCapabilities(); } #endregion #region Public API /// <summary> /// Sets the maximum number of Runspaces that can be active concurrently /// in the pool. All requests above that number remain queued until /// runspaces become available. /// </summary> /// <param name="maxRunspaces"> /// The maximum number of runspaces in the pool. /// </param> /// <returns> /// true if the change is successful; otherwise, false. /// </returns> /// <remarks> /// You cannot set the number of runspaces to a number smaller than /// the minimum runspaces. /// </remarks> public bool SetMaxRunspaces(int maxRunspaces) { return _internalPool.SetMaxRunspaces(maxRunspaces); } /// <summary> /// Retrieves the maximum number of runspaces the pool maintains. /// </summary> /// <returns> /// The maximum number of runspaces in the pool /// </returns> public int GetMaxRunspaces() { return _internalPool.GetMaxRunspaces(); } /// <summary> /// Sets the minimum number of Runspaces that the pool maintains /// in anticipation of new requests. /// </summary> /// <param name="minRunspaces"> /// The minimum number of runspaces in the pool. /// </param> /// <returns> /// true if the change is successful; otherwise, false. /// </returns> /// <remarks> /// You cannot set the number of idle runspaces to a number smaller than /// 1 or greater than maximum number of active runspaces. /// </remarks> public bool SetMinRunspaces(int minRunspaces) { return _internalPool.SetMinRunspaces(minRunspaces); } /// <summary> /// Retrieves the minimum number of runspaces the pool maintains. /// </summary> /// <returns> /// The minimum number of runspaces in the pool /// </returns> public int GetMinRunspaces() { return _internalPool.GetMinRunspaces(); } /// <summary> /// Retrieves the number of runspaces available at the time of calling /// this method. /// </summary> /// <returns> /// The number of available runspace in the pool. /// </returns> public int GetAvailableRunspaces() { return _internalPool.GetAvailableRunspaces(); } /// <summary> /// Opens the runspacepool synchronously. RunspacePool must /// be opened before it can be used. /// </summary> /// <exception cref="InvalidRunspacePoolStateException"> /// RunspacePoolState is not BeforeOpen /// </exception> public void Open() { _internalPool.Open(); } /// <summary> /// Opens the RunspacePool asynchronously. RunspacePool must /// be opened before it can be used. /// To get the exceptions that might have occurred, call /// EndOpen. /// </summary> /// <param name="callback"> /// A AsyncCallback to call once the BeginOpen completes. /// </param> /// <param name="state"> /// A user supplied state to call the <paramref name="callback"/> /// with. /// </param> /// <returns> /// An AsyncResult object to monitor the state of the async /// operation. /// </returns> public IAsyncResult BeginOpen(AsyncCallback callback, object state) { return _internalPool.BeginOpen(callback, state); } /// <summary> /// Waits for the pending asynchronous BeginOpen to complete. /// </summary> /// <exception cref="ArgumentNullException"> /// asyncResult is a null reference. /// </exception> /// <exception cref="ArgumentException"> /// asyncResult object was not created by calling BeginOpen /// on this runspacepool instance. /// </exception> /// <exception cref="InvalidRunspacePoolStateException"> /// RunspacePoolState is not BeforeOpen. /// </exception> /// <remarks> /// TODO: Behavior if EndOpen is called multiple times. /// </remarks> public void EndOpen(IAsyncResult asyncResult) { _internalPool.EndOpen(asyncResult); } /// <summary> /// Closes the RunspacePool and cleans all the internal /// resources. This will close all the runspaces in the /// runspacepool and release all the async operations /// waiting for a runspace. If the pool is already closed /// or broken or closing this will just return. /// </summary> /// <exception cref="InvalidRunspacePoolStateException"> /// Cannot close the RunspacePool because RunspacePool is /// in Closing state. /// </exception> public void Close() { _internalPool.Close(); } /// <summary> /// Closes the RunspacePool asynchronously and cleans all the internal /// resources. This will close all the runspaces in the /// runspacepool and release all the async operations /// waiting for a runspace. If the pool is already closed /// or broken or closing this will just return. /// </summary> /// <param name="callback"> /// A AsyncCallback to call once the BeginClose completes. /// </param> /// <param name="state"> /// A user supplied state to call the <paramref name="callback"/> /// with. /// </param> /// <returns> /// An AsyncResult object to monitor the state of the async /// operation. /// </returns> public IAsyncResult BeginClose(AsyncCallback callback, object state) { return _internalPool.BeginClose(callback, state); } /// <summary> /// Waits for the pending asynchronous BeginClose to complete. /// </summary> /// <exception cref="ArgumentNullException"> /// asyncResult is a null reference. /// </exception> /// <exception cref="ArgumentException"> /// asyncResult object was not created by calling BeginClose /// on this runspacepool instance. /// </exception> public void EndClose(IAsyncResult asyncResult) { _internalPool.EndClose(asyncResult); } /// <summary> /// Dispose the current runspacepool. /// </summary> public void Dispose() { _internalPool.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Private data to be used by applications built on top of PowerShell. /// /// Local runspace pool is created with application private data set to an empty <see cref="PSPrimitiveDictionary"/>. /// /// Remote runspace pool gets its application private data from the server (when creating the remote runspace pool) /// Calling this method on a remote runspace pool will block until the data is received from the server. /// The server will send application private data before reaching <see cref="RunspacePoolState.Opened"/> state. /// /// Runspaces that are part of a <see cref="RunspacePool"/> inherit application private data from the pool. /// </summary> public PSPrimitiveDictionary GetApplicationPrivateData() { return _internalPool.GetApplicationPrivateData(); } #endregion #region Internal API /// <summary> /// This property determines whether a new thread is created for each invocation. /// </summary> /// <remarks> /// Any updates to the value of this property must be done before the RunspacePool is opened /// </remarks> /// <exception cref="InvalidRunspacePoolStateException"> /// An attempt to change this property was made after opening the RunspacePool /// </exception> public PSThreadOptions ThreadOptions { get { return _internalPool.ThreadOptions; } set { if (this.RunspacePoolStateInfo.State != RunspacePoolState.BeforeOpen) { throw new InvalidRunspacePoolStateException(RunspacePoolStrings.ChangePropertyAfterOpen); } _internalPool.ThreadOptions = value; } } #if !CORECLR // No ApartmentState In CoreCLR /// <summary> /// ApartmentState of the thread used to execute commands within this RunspacePool. /// </summary> /// <remarks> /// Any updates to the value of this property must be done before the RunspacePool is opened /// </remarks> /// <exception cref="InvalidRunspacePoolStateException"> /// An attempt to change this property was made after opening the RunspacePool /// </exception> public ApartmentState ApartmentState { get { return _internalPool.ApartmentState; } set { if (this.RunspacePoolStateInfo.State != RunspacePoolState.BeforeOpen) { throw new InvalidRunspacePoolStateException(RunspacePoolStrings.ChangePropertyAfterOpen); } _internalPool.ApartmentState = value; } } #endif /// <summary> /// Gets Runspace asynchronously from the runspace pool. The caller /// will get notified with the runspace using <paramref name="callback"/> /// </summary> /// <param name="callback"> /// A AsyncCallback to call once the runspace is available. /// </param> /// <param name="state"> /// A user supplied state to call the <paramref name="callback"/> /// with. /// </param> /// <returns> /// An IAsyncResult object to track the status of the Async operation. /// </returns> internal IAsyncResult BeginGetRunspace( AsyncCallback callback, object state) { return _internalPool.BeginGetRunspace(callback, state); } /// <summary> /// Cancels the pending asynchronous BeginGetRunspace operation. /// </summary> /// <param name="asyncResult"> /// </param> internal void CancelGetRunspace(IAsyncResult asyncResult) { _internalPool.CancelGetRunspace(asyncResult); } /// <summary> /// Waits for the pending asynchronous BeginGetRunspace to complete. /// </summary> /// <param name="asyncResult"> /// </param> /// <exception cref="ArgumentNullException"> /// asyncResult is a null reference. /// </exception> /// <exception cref="ArgumentException"> /// asyncResult object was not created by calling BeginGetRunspace /// on this runspacepool instance. /// </exception> /// <exception cref="InvalidRunspacePoolStateException"> /// RunspacePoolState is not BeforeOpen. /// </exception> internal Runspace EndGetRunspace(IAsyncResult asyncResult) { return _internalPool.EndGetRunspace(asyncResult); } /// <summary> /// Releases a Runspace to the pool. If pool is closed, this /// will be a no-op. /// </summary> /// <param name="runspace"> /// Runspace to release to the pool. /// </param> /// <exception cref="ArgumentException"> /// <paramref name="runspace"/> is null. /// </exception> /// <exception cref="InvalidOperationException"> /// Cannot release the runspace to this pool as the runspace /// doesn't belong to this pool. /// </exception> /// <exception cref="InvalidRunspaceStateException"> /// Only opened runspaces can be released back to the pool. /// </exception> internal void ReleaseRunspace(Runspace runspace) { _internalPool.ReleaseRunspace(runspace); } /// <summary> /// Indicates whether the RunspacePool is a remote one. /// </summary> internal bool IsRemote { get; } = false; /// <summary> /// RemoteRunspacePoolInternal associated with this /// runspace pool. /// </summary> internal RemoteRunspacePoolInternal RemoteRunspacePoolInternal { get { if (_internalPool is RemoteRunspacePoolInternal) { return (RemoteRunspacePoolInternal)_internalPool; } else { return null; } } } internal void AssertPoolIsOpen() { _internalPool.AssertPoolIsOpen(); } #endregion } #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * 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 InsertVector128UInt321() { var test = new ImmBinaryOpTest__InsertVector128UInt321(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } 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 ImmBinaryOpTest__InsertVector128UInt321 { private struct TestStruct { public Vector256<UInt32> _fld1; public Vector128<UInt32> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__InsertVector128UInt321 testClass) { var result = Avx.InsertVector128(_fld1, _fld2, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32); private static UInt32[] _data1 = new UInt32[Op1ElementCount]; private static UInt32[] _data2 = new UInt32[Op2ElementCount]; private static Vector256<UInt32> _clsVar1; private static Vector128<UInt32> _clsVar2; private Vector256<UInt32> _fld1; private Vector128<UInt32> _fld2; private SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32> _dataTable; static ImmBinaryOpTest__InsertVector128UInt321() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _clsVar2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); } public ImmBinaryOpTest__InsertVector128UInt321() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld1), ref Unsafe.As<UInt32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt32>, byte>(ref _fld2), ref Unsafe.As<UInt32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt32(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt32(); } _dataTable = new SimpleBinaryOpTest__DataTable<UInt32, UInt32, UInt32>(_data1, _data2, new UInt32[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx.InsertVector128( Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx.InsertVector128( Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx.InsertVector128( Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx).GetMethod(nameof(Avx.InsertVector128), new Type[] { typeof(Vector256<UInt32>), typeof(Vector128<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx).GetMethod(nameof(Avx.InsertVector128), new Type[] { typeof(Vector256<UInt32>), typeof(Vector128<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx).GetMethod(nameof(Avx.InsertVector128), new Type[] { typeof(Vector256<UInt32>), typeof(Vector128<UInt32>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx.InsertVector128( _clsVar1, _clsVar2, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<UInt32>>(_dataTable.inArray2Ptr); var result = Avx.InsertVector128(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Avx.LoadVector256((UInt32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector128((UInt32*)(_dataTable.inArray2Ptr)); var result = Avx.InsertVector128(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector128((UInt32*)(_dataTable.inArray2Ptr)); var result = Avx.InsertVector128(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__InsertVector128UInt321(); var result = Avx.InsertVector128(test._fld1, test._fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx.InsertVector128(_fld1, _fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx.InsertVector128(test._fld1, test._fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<UInt32> left, Vector128<UInt32> right, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { UInt32[] inArray1 = new UInt32[Op1ElementCount]; UInt32[] inArray2 = new UInt32[Op2ElementCount]; UInt32[] outArray = new UInt32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<UInt32>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt32>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt32[] left, UInt32[] right, UInt32[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != left[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (i < 4 ? left[i] : right[i-4])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.InsertVector128)}<UInt32>(Vector256<UInt32>.1, Vector128<UInt32>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
// Copyright (c) 2011-2018 SIL International // This software is licensed under the MIT license (http://opensource.org/licenses/MIT) using System; using System.IO; using System.Reflection; using System.Text; using Autofac; using Chorus.Utilities; using IniParser.Parser; using LfMerge.Core.Actions.Infrastructure; using LfMerge.Core.LanguageForge.Infrastructure; using LfMerge.Core.Logging; using LfMerge.Core.MongoConnector; using LfMerge.Core.Settings; using NUnit.Framework; using SIL.IO; using SIL.LCModel.Core.WritingSystems; using SIL.LCModel.Utils; using SIL.TestUtilities; using SIL.WritingSystems; using SIL.WritingSystems.Migration; using ReflectionHelper = SIL.Reflection.ReflectionHelper; namespace LfMerge.Core.Tests { public class TestEnvironment : IDisposable { private readonly TemporaryFolder _languageForgeServerFolder; private bool _resetLfProjectsDuringCleanup; private bool _releaseSingletons; public LfMergeSettings Settings; private MongoConnectionDouble _mongoConnection; public ILogger Logger { get { return MainClass.Logger; }} static TestEnvironment() { // Need to call MongoConnectionDouble.Initialize() exactly once, before any tests are run -- so do it here MongoConnectionDouble.Initialize(); } public TestEnvironment(bool registerSettingsModelDouble = true, bool registerProcessingStateDouble = true, bool resetLfProjectsDuringCleanup = true, TemporaryFolder languageForgeServerFolder = null, bool registerLfProxyMock = true) { _resetLfProjectsDuringCleanup = resetLfProjectsDuringCleanup; _languageForgeServerFolder = languageForgeServerFolder ?? new TemporaryFolder(TestName + Path.GetRandomFileName()); Environment.SetEnvironmentVariable("FW_CommonAppData", _languageForgeServerFolder.Path); MainClass.Container = RegisterTypes(registerSettingsModelDouble, registerProcessingStateDouble, _languageForgeServerFolder.Path, registerLfProxyMock).Build(); Settings = MainClass.Container.Resolve<LfMergeSettings>(); MainClass.Logger = MainClass.Container.Resolve<ILogger>(); Directory.CreateDirectory(Settings.LcmDirectorySettings.ProjectsDirectory); Directory.CreateDirectory(Settings.LcmDirectorySettings.TemplateDirectory); Directory.CreateDirectory(Settings.StateDirectory); _mongoConnection = MainClass.Container.Resolve<IMongoConnection>() as MongoConnectionDouble; // only call SingletonsContainer.Release() at the end if we actually create the // singleton _releaseSingletons = !SingletonsContainer.Contains<CoreGlobalWritingSystemRepository>(); } private string TestName { get { var testName = TestContext.CurrentContext.Test.Name; var firstInvalidChar = testName.IndexOfAny(Path.GetInvalidPathChars()); if (firstInvalidChar >= 0) testName = testName.Substring(0, firstInvalidChar); return testName; } } private ContainerBuilder RegisterTypes(bool registerSettingsModel, bool registerProcessingStateDouble, string temporaryFolder, bool registerLfProxyMock) { ContainerBuilder containerBuilder = MainClass.RegisterTypes(); containerBuilder.RegisterType<LfMergeSettingsDouble>() .WithParameter(new TypedParameter(typeof(string), temporaryFolder)).SingleInstance() .As<LfMergeSettings>(); containerBuilder.RegisterType<TestLogger>().SingleInstance().As<ILogger>() .WithParameter(new TypedParameter(typeof(string), TestName)); containerBuilder.RegisterType<MongoConnectionDouble>().As<IMongoConnection>().SingleInstance(); if (registerLfProxyMock) containerBuilder.RegisterType<LanguageForgeProxyMock>().As<ILanguageForgeProxy>(); if (registerSettingsModel) { containerBuilder.RegisterType<ChorusHelperDouble>().As<ChorusHelper>().SingleInstance(); containerBuilder.RegisterType<MongoProjectRecordFactoryDouble>().As<MongoProjectRecordFactory>(); } var ldProj = new LanguageDepotProjectDouble(); containerBuilder.RegisterInstance(ldProj) .As<ILanguageDepotProject>().AsSelf().SingleInstance(); if (registerProcessingStateDouble) { containerBuilder.RegisterType<ProcessingStateFactoryDouble>() .As<IProcessingStateDeserialize>().AsSelf().SingleInstance(); } return containerBuilder; } public void Dispose() { _mongoConnection?.Reset(); MainClass.Container?.Dispose(); MainClass.Container = null; if (_resetLfProjectsDuringCleanup) LanguageForgeProjectAccessor.Reset(); _languageForgeServerFolder?.Dispose(); Settings = null; if (_releaseSingletons) SingletonsContainer.Release(); Environment.SetEnvironmentVariable("FW_CommonAppData", null); } public string LanguageForgeFolder { // get { return Path.Combine(_languageForgeServerFolder.Path, "webwork"); } // Should get this from Settings object, but unfortunately we have to resolve this // *before* the Settings object is available. get { return LangForgeDirFinder.LcmDirectorySettings.ProjectsDirectory; } } public LfMergeSettings LangForgeDirFinder { get { return Settings; } } public string ProjectPath(string projectCode) { return Path.Combine(LanguageForgeFolder, projectCode); } public void CreateProjectUpdateFolder(string projectCode) { Directory.CreateDirectory(ProjectPath(projectCode)); } public static void CopyFwProjectTo(string projectCode, string destDir) { string dataDir = Path.Combine(FindGitRepoRoot(), "data"); DirectoryHelper.Copy(Path.Combine(dataDir, projectCode), Path.Combine(destDir, projectCode)); // Adjust hgrc file var hgrc = Path.Combine(destDir, projectCode, ".hg/hgrc"); if (File.Exists(hgrc)) { var parser = new IniDataParser(); var iniData = parser.Parse(File.ReadAllText(hgrc)); iniData["ui"]["username"] = Environment.UserName; var outputDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); iniData["merge-tools"]["chorusmerge.executable"] = Path.Combine(outputDirectory, "chorusmerge"); iniData["extensions"]["fixutf8"] = Path.Combine(FindGitRepoRoot(), "MercurialExtensions/fixutf8/fixutf8.py"); var contents = iniData.ToString(); File.WriteAllText(hgrc, contents); } Console.WriteLine("Copied {0} to {1}", projectCode, destDir); } public static string FindGitRepoRoot(string startDir = null) { if (String.IsNullOrEmpty(startDir)) startDir = ExecutionEnvironment.DirectoryOfExecutingAssembly; while (!Directory.Exists(Path.Combine(startDir, ".git"))) { var di = new DirectoryInfo(startDir); if (di.Parent == null) // We've reached the root directory { // Last-ditch effort: assume we're in output/Debug, even though we never found .git return Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), "..", "..")); } startDir = Path.Combine(startDir, ".."); } return Path.GetFullPath(startDir); } public static void ChangeFileEncoding(string fileName, Encoding inEncoding, Encoding outEncoding) { if (!File.Exists(fileName)) return; string s = null; using (StreamReader r = new StreamReader(fileName, inEncoding)) { s = r.ReadToEnd(); } if (s != null) { using (StreamWriter w = new StreamWriter(fileName, false, outEncoding)) { w.Write(s); } } } public static void OverwriteBytesInFile(string fileName, byte[] bytes, int offset) { if (!File.Exists(fileName)) return; using (FileStream f = new FileStream(fileName, FileMode.OpenOrCreate)) { f.Seek(offset, SeekOrigin.Begin); f.Write(bytes, 0, bytes.Length); } } public static void WriteTextFile(string fileName, string content, bool append = false, Encoding encoding = null) { if (encoding == null) { encoding = new UTF8Encoding(false); } using (var writer = new StreamWriter(fileName, append, encoding)) { writer.Write(content); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.Hashing.Algorithms.Tests { public abstract class HashAlgorithmTest { protected abstract HashAlgorithm Create(); protected void Verify(string input, string output) { Verify(ByteUtils.AsciiBytes(input), output); } private void VerifyComputeHashStream(Stream input, string output) { byte[] expected = ByteUtils.HexToByteArray(output); byte[] actual; using (HashAlgorithm hash = Create()) { Assert.True(hash.HashSize > 0); actual = hash.ComputeHash(input); } Assert.Equal(expected, actual); } private void VerifyICryptoTransformStream(Stream input, string output) { byte[] expected = ByteUtils.HexToByteArray(output); byte[] actual; using (HashAlgorithm hash = Create()) using (CryptoStream cryptoStream = new CryptoStream(input, hash, CryptoStreamMode.Read)) { byte[] buffer = new byte[1024]; // A different default than HashAlgorithm which uses 4K int bytesRead; while ((bytesRead = cryptoStream.Read(buffer, 0, buffer.Length)) > 0) { // CryptoStream will build up the hash } actual = hash.Hash; } Assert.Equal(expected, actual); } protected void VerifyMultiBlock(string block1, string block2, string expectedHash, string emptyHash) { byte[] block1_bytes = ByteUtils.AsciiBytes(block1); byte[] block2_bytes = ByteUtils.AsciiBytes(block2); byte[] expected_bytes = ByteUtils.HexToByteArray(expectedHash); byte[] emptyHash_bytes = ByteUtils.HexToByteArray(emptyHash); VerifyTransformBlockOutput(block1_bytes, block2_bytes); VerifyTransformBlockHash(block1_bytes, block2_bytes, expected_bytes, emptyHash_bytes); VerifyTransformBlockComputeHashInteraction(block1_bytes, block2_bytes, expected_bytes, emptyHash_bytes); } private void VerifyTransformBlockOutput(byte[] block1, byte[] block2) { using (HashAlgorithm hash = Create()) { byte[] actualBlock1 = new byte[block1.Length]; int byteCount = hash.TransformBlock(block1, 0, block1.Length, actualBlock1, 0); Assert.Equal(block1.Length, byteCount); Assert.Equal(block1, actualBlock1); byte[] actualBlock2 = hash.TransformFinalBlock(block2, 0, block2.Length); Assert.Equal(block2, actualBlock2); } } private void VerifyTransformBlockHash(byte[] block1, byte[] block2, byte[] expected, byte[] expectedEmpty) { using (HashAlgorithm hash = Create()) { // Verify Empty Hash hash.TransformBlock(Array.Empty<byte>(), 0, 0, null, 0); hash.TransformFinalBlock(Array.Empty<byte>(), 0, 0); Assert.Equal(hash.Hash, expectedEmpty); hash.TransformFinalBlock(Array.Empty<byte>(), 0, 0); Assert.Equal(hash.Hash, expectedEmpty); // Verify Hash hash.TransformBlock(block1, 0, block1.Length, null, 0); hash.TransformFinalBlock(block2, 0, block2.Length); Assert.Equal(expected, hash.Hash); Assert.Equal(expected, hash.Hash); // .Hash doesn't clear hash // Verify bad State hash.TransformBlock(block1, 0, block1.Length, null, 0); // Can't access hash until TransformFinalBlock is called Assert.Throws<CryptographicUnexpectedOperationException>(() => hash.Hash); hash.TransformFinalBlock(block2, 0, block2.Length); Assert.Equal(expected, hash.Hash); // Verify clean State hash.TransformFinalBlock(Array.Empty<byte>(), 0, 0); Assert.Equal(hash.Hash, expectedEmpty); } } private void VerifyTransformBlockComputeHashInteraction(byte[] block1, byte[] block2, byte[] expected, byte[] expectedEmpty) { using (HashAlgorithm hash = Create()) { // TransformBlock + ComputeHash hash.TransformBlock(block1, 0, block1.Length, null, 0); byte[] actual = hash.ComputeHash(block2, 0, block2.Length); Assert.Equal(expected, actual); // ComputeHash does not reset State variable Assert.Throws<CryptographicUnexpectedOperationException>(() => hash.Hash); hash.TransformFinalBlock(Array.Empty<byte>(), 0, 0); Assert.Equal(expectedEmpty, hash.Hash); actual = hash.ComputeHash(Array.Empty<byte>(), 0, 0); Assert.Equal(expectedEmpty, actual); // TransformBlock + TransformBlock + ComputeHash(empty) hash.TransformBlock(block1, 0, block1.Length, null, 0); hash.TransformBlock(block2, 0, block2.Length, null, 0); actual = hash.ComputeHash(Array.Empty<byte>(), 0, 0); Assert.Equal(expected, actual); } } [Fact] public void VerifyObjectDisposedException() { HashAlgorithm hash = Create(); hash.Dispose(); Assert.Throws<ObjectDisposedException>(() => hash.Hash); Assert.Throws<ObjectDisposedException>(() => hash.ComputeHash(Array.Empty<byte>())); Assert.Throws<ObjectDisposedException>(() => hash.ComputeHash(Array.Empty<byte>(), 0, 0)); Assert.Throws<ObjectDisposedException>(() => hash.ComputeHash((Stream)null)); Assert.Throws<ObjectDisposedException>(() => hash.TransformBlock(Array.Empty<byte>(), 0, 0, null, 0)); Assert.Throws<ObjectDisposedException>(() => hash.TransformFinalBlock(Array.Empty<byte>(), 0, 0)); } [Fact] public void VerifyHashNotYetFinalized() { using (HashAlgorithm hash = Create()) { hash.TransformBlock(Array.Empty<byte>(), 0, 0, null, 0); Assert.Throws<CryptographicUnexpectedOperationException>(() => hash.Hash); } } [Fact] public void InvalidInput_ComputeHash() { using (HashAlgorithm hash = Create()) { Assert.Throws<ArgumentNullException>("buffer", () => hash.ComputeHash((byte[])null)); Assert.Throws<ArgumentNullException>("buffer", () => hash.ComputeHash(null, 0, 0)); } } [Fact] public void InvalidInput_TransformBlock() { using (HashAlgorithm hash = Create()) { Assert.Throws<ArgumentNullException>("inputBuffer", () => hash.TransformBlock(null, 0, 0, null, 0)); Assert.Throws<ArgumentOutOfRangeException>("inputOffset", () => hash.TransformBlock(Array.Empty<byte>(), -1, 0, null, 0)); Assert.Throws<ArgumentException>(null, () => hash.TransformBlock(Array.Empty<byte>(), 0, 1, null, 0)); Assert.Throws<ArgumentException>(null, () => hash.TransformBlock(Array.Empty<byte>(), 1, 0, null, 0)); } } [Fact] public void InvalidInput_TransformFinalBlock() { using (HashAlgorithm hash = Create()) { Assert.Throws<ArgumentNullException>("inputBuffer", () => hash.TransformFinalBlock(null, 0, 0)); Assert.Throws<ArgumentOutOfRangeException>("inputOffset", () => hash.TransformFinalBlock(Array.Empty<byte>(), -1, 0)); Assert.Throws<ArgumentException>(null, () => hash.TransformFinalBlock(Array.Empty<byte>(), 1, 0)); Assert.Throws<ArgumentException>(null, () => hash.TransformFinalBlock(Array.Empty<byte>(), 0, -1)); Assert.Throws<ArgumentException>(null, () => hash.TransformFinalBlock(Array.Empty<byte>(), 0, 1)); } } protected void Verify(byte[] input, string output) { byte[] expected = ByteUtils.HexToByteArray(output); byte[] actual; using (HashAlgorithm hash = Create()) { Assert.True(hash.HashSize > 0); actual = hash.ComputeHash(input, 0, input.Length); Assert.Equal(expected, actual); actual = hash.Hash; Assert.Equal(expected, actual); } } protected void VerifyRepeating(string input, int repeatCount, string output) { using (Stream stream = new DataRepeatingStream(input, repeatCount)) { VerifyComputeHashStream(stream, output); } using (Stream stream = new DataRepeatingStream(input, repeatCount)) { VerifyICryptoTransformStream(stream, output); } } [Fact] public void InvalidInput_Null() { using (HashAlgorithm hash = Create()) { Assert.Throws<ArgumentNullException>("buffer", () => hash.ComputeHash((byte[])null)); Assert.Throws<ArgumentNullException>("buffer", () => hash.ComputeHash(null, 0, 0)); Assert.Throws<NullReferenceException>(() => hash.ComputeHash((Stream)null)); } } [Fact] public void InvalidInput_NegativeOffset() { using (HashAlgorithm hash = Create()) { Assert.Throws<ArgumentOutOfRangeException>("offset", () => hash.ComputeHash(Array.Empty<byte>(), -1, 0)); } } [Fact] public void InvalidInput_NegativeCount() { using (HashAlgorithm hash = Create()) { Assert.Throws<ArgumentException>(null, () => hash.ComputeHash(Array.Empty<byte>(), 0, -1)); } } [Fact] public void InvalidInput_TooBigOffset() { using (HashAlgorithm hash = Create()) { Assert.Throws<ArgumentException>(null, () => hash.ComputeHash(Array.Empty<byte>(), 1, 0)); } } [Fact] public void InvalidInput_TooBigCount() { byte[] nonEmpty = new byte[53]; using (HashAlgorithm hash = Create()) { Assert.Throws<ArgumentException>(null, () => hash.ComputeHash(nonEmpty, 0, nonEmpty.Length + 1)); Assert.Throws<ArgumentException>(null, () => hash.ComputeHash(nonEmpty, 1, nonEmpty.Length)); Assert.Throws<ArgumentException>(null, () => hash.ComputeHash(nonEmpty, 2, nonEmpty.Length - 1)); Assert.Throws<ArgumentException>(null, () => hash.ComputeHash(Array.Empty<byte>(), 0, 1)); } } [Fact] public void BoundaryCondition_Count0() { byte[] nonEmpty = new byte[53]; using (HashAlgorithm 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 (HashAlgorithm 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); } } protected class DataRepeatingStream : Stream { private int _remaining; private byte[] _data; public DataRepeatingStream(string data, int repeatCount) { _remaining = repeatCount; _data = ByteUtils.AsciiBytes(data); } public override int Read(byte[] buffer, int offset, int count) { if (!CanRead) { throw new NotSupportedException(); } if (_remaining == 0) { return 0; } if (count < _data.Length) { throw new InvalidOperationException(); } int multiple = count / _data.Length; if (multiple > _remaining) { multiple = _remaining; } int localOffset = offset; for (int i = 0; i < multiple; i++) { Buffer.BlockCopy(_data, 0, buffer, localOffset, _data.Length); localOffset += _data.Length; } _remaining -= multiple; return _data.Length * multiple; } protected override void Dispose(bool disposing) { if (disposing) { _data = null; } } public override void Flush() { } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override bool CanRead { get { return _data != null; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return false; } } public override long Length { get { throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } } } }
namespace BooCompiler.Tests { using NUnit.Framework; [TestFixture] public class CallablesIntegrationTestFixture : AbstractCompilerTestCase { [Test] public void byref_1() { RunCompilerTestCase(@"byref-1.boo"); } [Category("FailsOnMono")][Test] public void byref_10() { RunCompilerTestCase(@"byref-10.boo"); } [Test] public void byref_11() { RunCompilerTestCase(@"byref-11.boo"); } [Test] public void byref_12() { RunCompilerTestCase(@"byref-12.boo"); } [Test] public void byref_13() { RunCompilerTestCase(@"byref-13.boo"); } [Test] public void byref_14() { RunCompilerTestCase(@"byref-14.boo"); } [Test] public void byref_2() { RunCompilerTestCase(@"byref-2.boo"); } [Test] public void byref_3() { RunCompilerTestCase(@"byref-3.boo"); } [Test] public void byref_4() { RunCompilerTestCase(@"byref-4.boo"); } [Test] public void byref_5() { RunCompilerTestCase(@"byref-5.boo"); } [Test] public void byref_6() { RunCompilerTestCase(@"byref-6.boo"); } [Test] public void byref_7() { RunCompilerTestCase(@"byref-7.boo"); } [Test] public void byref_8() { RunCompilerTestCase(@"byref-8.boo"); } [Test] public void byref_9() { RunCompilerTestCase(@"byref-9.boo"); } [Test] public void callables_1() { RunCompilerTestCase(@"callables-1.boo"); } [Test] public void callables_10() { RunCompilerTestCase(@"callables-10.boo"); } [Test] public void callables_11() { RunCompilerTestCase(@"callables-11.boo"); } [Test] public void callables_12() { RunCompilerTestCase(@"callables-12.boo"); } [Test] public void callables_13() { RunCompilerTestCase(@"callables-13.boo"); } [Test] public void callables_14() { RunCompilerTestCase(@"callables-14.boo"); } [Test] public void callables_15() { RunCompilerTestCase(@"callables-15.boo"); } [Test] public void callables_16() { RunCompilerTestCase(@"callables-16.boo"); } [Test] public void callables_17() { RunCompilerTestCase(@"callables-17.boo"); } [Test] public void callables_18() { RunCompilerTestCase(@"callables-18.boo"); } [Test] public void callables_19() { RunCompilerTestCase(@"callables-19.boo"); } [Test] public void callables_2() { RunCompilerTestCase(@"callables-2.boo"); } [Test] public void callables_20() { RunCompilerTestCase(@"callables-20.boo"); } [Test] public void callables_21() { RunCompilerTestCase(@"callables-21.boo"); } [Test] public void callables_22() { RunCompilerTestCase(@"callables-22.boo"); } [Test] public void callables_23() { RunCompilerTestCase(@"callables-23.boo"); } [Test] public void callables_24() { RunCompilerTestCase(@"callables-24.boo"); } [Test] public void callables_25() { RunCompilerTestCase(@"callables-25.boo"); } [Test] public void callables_26() { RunCompilerTestCase(@"callables-26.boo"); } [Test] public void callables_27() { RunCompilerTestCase(@"callables-27.boo"); } [Test] public void callables_28() { RunCompilerTestCase(@"callables-28.boo"); } [Test] public void callables_29() { RunCompilerTestCase(@"callables-29.boo"); } [Test] public void callables_3() { RunCompilerTestCase(@"callables-3.boo"); } [Test] public void callables_30() { RunCompilerTestCase(@"callables-30.boo"); } [Test] public void callables_31() { RunCompilerTestCase(@"callables-31.boo"); } [Test] public void callables_32() { RunCompilerTestCase(@"callables-32.boo"); } [Test] public void callables_33() { RunCompilerTestCase(@"callables-33.boo"); } [Test] public void callables_34() { RunCompilerTestCase(@"callables-34.boo"); } [Test] public void callables_35() { RunCompilerTestCase(@"callables-35.boo"); } [Test] public void callables_36() { RunCompilerTestCase(@"callables-36.boo"); } [Test] public void callables_37() { RunCompilerTestCase(@"callables-37.boo"); } [Test] public void callables_38() { RunCompilerTestCase(@"callables-38.boo"); } [Test] public void callables_39() { RunCompilerTestCase(@"callables-39.boo"); } [Test] public void callables_4() { RunCompilerTestCase(@"callables-4.boo"); } [Test] public void callables_40() { RunCompilerTestCase(@"callables-40.boo"); } [Test] public void callables_41() { RunCompilerTestCase(@"callables-41.boo"); } [Test] public void callables_42() { RunCompilerTestCase(@"callables-42.boo"); } [Test] public void callables_43() { RunCompilerTestCase(@"callables-43.boo"); } [Test] public void callables_44() { RunCompilerTestCase(@"callables-44.boo"); } [Test] public void callables_45() { RunCompilerTestCase(@"callables-45.boo"); } [Test] public void callables_46() { RunCompilerTestCase(@"callables-46.boo"); } [Test] public void callables_47() { RunCompilerTestCase(@"callables-47.boo"); } [Test] public void callables_48() { RunCompilerTestCase(@"callables-48.boo"); } [Test] public void callables_49() { RunCompilerTestCase(@"callables-49.boo"); } [Test] public void callables_5() { RunCompilerTestCase(@"callables-5.boo"); } [Test] public void callables_50() { RunCompilerTestCase(@"callables-50.boo"); } [Test] public void callables_6() { RunCompilerTestCase(@"callables-6.boo"); } [Test] public void callables_7() { RunCompilerTestCase(@"callables-7.boo"); } [Test] public void callables_8() { RunCompilerTestCase(@"callables-8.boo"); } [Test] public void callables_9() { RunCompilerTestCase(@"callables-9.boo"); } [Test] public void callables_as_ternary_operands() { RunCompilerTestCase(@"callables-as-ternary-operands.boo"); } [Test] public void callables_as_ternay_operands_invocation() { RunCompilerTestCase(@"callables-as-ternay-operands-invocation.boo"); } [Test] public void delegates_1() { RunCompilerTestCase(@"delegates-1.boo"); } [Test] public void delegates_10() { RunCompilerTestCase(@"delegates-10.boo"); } [Test] public void delegates_11() { RunCompilerTestCase(@"delegates-11.boo"); } [Test] public void delegates_12() { RunCompilerTestCase(@"delegates-12.boo"); } [Test] public void delegates_13() { RunCompilerTestCase(@"delegates-13.boo"); } [Test] public void delegates_14() { RunCompilerTestCase(@"delegates-14.boo"); } [Test] public void delegates_15() { RunCompilerTestCase(@"delegates-15.boo"); } [Test] public void delegates_16() { RunCompilerTestCase(@"delegates-16.boo"); } [Test] public void delegates_17() { RunCompilerTestCase(@"delegates-17.boo"); } [Test] public void delegates_18() { RunCompilerTestCase(@"delegates-18.boo"); } [Test] public void delegates_2() { RunCompilerTestCase(@"delegates-2.boo"); } [Test] public void delegates_3() { RunCompilerTestCase(@"delegates-3.boo"); } [Test] public void delegates_4() { RunCompilerTestCase(@"delegates-4.boo"); } [Test] public void delegates_5() { RunCompilerTestCase(@"delegates-5.boo"); } [Test] public void delegates_6() { RunCompilerTestCase(@"delegates-6.boo"); } [Test] public void delegates_7() { RunCompilerTestCase(@"delegates-7.boo"); } [Test] public void delegates_8() { RunCompilerTestCase(@"delegates-8.boo"); } [Test] public void delegates_9() { RunCompilerTestCase(@"delegates-9.boo"); } [Test] public void generic_dict_of_anonymous_callable() { RunCompilerTestCase(@"generic-dict-of-anonymous-callable.boo"); } [Test] public void method_as_macro_1() { RunCompilerTestCase(@"method-as-macro-1.boo"); } [Test] public void method_as_macro_2() { RunCompilerTestCase(@"method-as-macro-2.boo"); } [Test] public void method_as_macro_3() { RunCompilerTestCase(@"method-as-macro-3.boo"); } [Test] public void method_invocations_1() { RunCompilerTestCase(@"method-invocations-1.boo"); } [Test] public void out_1() { RunCompilerTestCase(@"out-1.boo"); } [Test] public void out_2() { RunCompilerTestCase(@"out-2.boo"); } [Test] public void out_3() { RunCompilerTestCase(@"out-3.boo"); } [Test] public void overload_resolution_1() { RunCompilerTestCase(@"overload-resolution-1.boo"); } [Test] public void overload_resolution_2() { RunCompilerTestCase(@"overload-resolution-2.boo"); } [Test] public void params_1() { RunCompilerTestCase(@"params-1.boo"); } [Test] public void params_2() { RunCompilerTestCase(@"params-2.boo"); } [Test] public void params_3() { RunCompilerTestCase(@"params-3.boo"); } [Test] public void params_4() { RunCompilerTestCase(@"params-4.boo"); } [Test] public void params_5() { RunCompilerTestCase(@"params-5.boo"); } [Test] public void params_6() { RunCompilerTestCase(@"params-6.boo"); } [Test] public void params_7() { RunCompilerTestCase(@"params-7.boo"); } [Test] public void params_8() { RunCompilerTestCase(@"params-8.boo"); } override protected string GetRelativeTestCasesPath() { return "integration/callables"; } } }
using System; using System.Collections.Generic; using System.Linq; using GitVersion.Extensions; using GitVersion.Model.Configuration; using GitVersion.VersionCalculation; using JetBrains.Annotations; namespace GitVersion.Configuration { public class ConfigurationBuilder { private const int DefaultTagPreReleaseWeight = 60000; private readonly List<Config> _overrides = new(); public ConfigurationBuilder Add([NotNull] Config config) { if (config == null) throw new ArgumentNullException(nameof(config)); _overrides.Add(config); return this; } [NotNull] public Config Build() { var config = CreateDefaultConfiguration(); foreach (var overrideConfig in _overrides) { ApplyOverrides(config, overrideConfig); } FinalizeConfiguration(config); ValidateConfiguration(config); return config; } private static void ApplyOverrides([NotNull] Config targetConfig, [NotNull] Config overrideConfig) { targetConfig.AssemblyVersioningScheme = overrideConfig.AssemblyVersioningScheme ?? targetConfig.AssemblyVersioningScheme; targetConfig.AssemblyFileVersioningScheme = overrideConfig.AssemblyFileVersioningScheme ?? targetConfig.AssemblyFileVersioningScheme; targetConfig.AssemblyInformationalFormat = overrideConfig.AssemblyInformationalFormat ?? targetConfig.AssemblyInformationalFormat; targetConfig.AssemblyVersioningFormat = overrideConfig.AssemblyVersioningFormat ?? targetConfig.AssemblyVersioningFormat; targetConfig.AssemblyFileVersioningFormat = overrideConfig.AssemblyFileVersioningFormat ?? targetConfig.AssemblyFileVersioningFormat; targetConfig.VersioningMode = overrideConfig.VersioningMode ?? targetConfig.VersioningMode; targetConfig.TagPrefix = overrideConfig.TagPrefix ?? targetConfig.TagPrefix; targetConfig.ContinuousDeploymentFallbackTag = overrideConfig.ContinuousDeploymentFallbackTag ?? targetConfig.ContinuousDeploymentFallbackTag; targetConfig.NextVersion = overrideConfig.NextVersion ?? targetConfig.NextVersion; targetConfig.MajorVersionBumpMessage = overrideConfig.MajorVersionBumpMessage ?? targetConfig.MajorVersionBumpMessage; targetConfig.MinorVersionBumpMessage = overrideConfig.MinorVersionBumpMessage ?? targetConfig.MinorVersionBumpMessage; targetConfig.PatchVersionBumpMessage = overrideConfig.PatchVersionBumpMessage ?? targetConfig.PatchVersionBumpMessage; targetConfig.NoBumpMessage = overrideConfig.NoBumpMessage ?? targetConfig.NoBumpMessage; targetConfig.LegacySemVerPadding = overrideConfig.LegacySemVerPadding ?? targetConfig.LegacySemVerPadding; targetConfig.BuildMetaDataPadding = overrideConfig.BuildMetaDataPadding ?? targetConfig.BuildMetaDataPadding; targetConfig.CommitsSinceVersionSourcePadding = overrideConfig.CommitsSinceVersionSourcePadding ?? targetConfig.CommitsSinceVersionSourcePadding; targetConfig.TagPreReleaseWeight = overrideConfig.TagPreReleaseWeight ?? targetConfig.TagPreReleaseWeight; targetConfig.CommitMessageIncrementing = overrideConfig.CommitMessageIncrementing ?? targetConfig.CommitMessageIncrementing; targetConfig.Increment = overrideConfig.Increment ?? targetConfig.Increment; targetConfig.CommitDateFormat = overrideConfig.CommitDateFormat ?? targetConfig.CommitDateFormat; targetConfig.MergeMessageFormats = overrideConfig.MergeMessageFormats.Any() ? overrideConfig.MergeMessageFormats : targetConfig.MergeMessageFormats; targetConfig.UpdateBuildNumber = overrideConfig.UpdateBuildNumber ?? targetConfig.UpdateBuildNumber; if (overrideConfig.Ignore != null && !overrideConfig.Ignore.IsEmpty) { targetConfig.Ignore = overrideConfig.Ignore; } ApplyBranchOverrides(targetConfig, overrideConfig); } private static void ApplyBranchOverrides(Config targetConfig, Config overrideConfig) { if (overrideConfig.Branches != null && overrideConfig.Branches.Count > 0) { // We can't just add new configs to the targetConfig.Branches, and have to create a new dictionary. // The reason is that GitVersion 5.3.x (and earlier) merges default configs into overrides. The new approach is opposite: we merge overrides into default config. // The important difference of these approaches is the order of branches in a dictionary (we should not rely on Dictionary's implementation details, but we already did that): // Old approach: { new-branch-1, new-branch-2, default-branch-1, default-branch-2, ... } // New approach: { default-branch-1, default-branch-2, ..., new-branch-1, new-branch-2 } // In case when several branch configurations match the current branch (by regex), we choose the first one. // So we have to add new branches to the beginning of a dictionary to preserve 5.3.x behavior. var newBranches = new Dictionary<string, BranchConfig>(); var targetConfigBranches = targetConfig.Branches; foreach (var (name, branchConfig) in overrideConfig.Branches) { // for compatibility reason we check if it's master, we rename it to main var branchName = name == Config.MasterBranchKey ? Config.MainBranchKey : name; if (!targetConfigBranches.TryGetValue(branchName, out var target)) { target = BranchConfig.CreateDefaultBranchConfig(branchName); } branchConfig.MergeTo(target); if (target.SourceBranches != null && target.SourceBranches.Contains(Config.MasterBranchKey)) { target.SourceBranches.Remove(Config.MasterBranchKey); target.SourceBranches.Add(Config.MainBranchKey); } newBranches[branchName] = target; } foreach (var (name, branchConfig) in targetConfigBranches) { if (!newBranches.ContainsKey(name)) { newBranches[name] = branchConfig; } } targetConfig.Branches = newBranches; } } private static void FinalizeConfiguration(Config config) { config.Ignore ??= new IgnoreConfig(); foreach (var (name, branchConfig) in config.Branches) { FinalizeBranchConfiguration(config, name, branchConfig); } } private static void FinalizeBranchConfiguration(Config config, string name, BranchConfig branchConfig) { branchConfig.Name = name; branchConfig.Increment ??= config.Increment ?? IncrementStrategy.Inherit; if (branchConfig.VersioningMode == null) { if (name == Config.DevelopBranchKey) { branchConfig.VersioningMode = config.VersioningMode == VersioningMode.Mainline ? VersioningMode.Mainline : VersioningMode.ContinuousDeployment; } else { branchConfig.VersioningMode = config.VersioningMode; } } if (branchConfig.IsSourceBranchFor != null) { foreach (var targetBranchName in branchConfig.IsSourceBranchFor) { var targetBranchConfig = config.Branches[targetBranchName]; targetBranchConfig.SourceBranches ??= new HashSet<string>(); targetBranchConfig.SourceBranches.Add(name); } } } private static void ValidateConfiguration(Config config) { foreach (var (name, branchConfig) in config.Branches) { var regex = branchConfig.Regex; var helpUrl = $"{System.Environment.NewLine}See https://gitversion.net/docs/reference/configuration for more info"; if (regex == null) { throw new ConfigurationException($"Branch configuration '{name}' is missing required configuration 'regex'{helpUrl}"); } var sourceBranches = branchConfig.SourceBranches; if (sourceBranches == null) { throw new ConfigurationException($"Branch configuration '{name}' is missing required configuration 'source-branches'{helpUrl}"); } var missingSourceBranches = sourceBranches.Where(sb => !config.Branches.ContainsKey(sb)).ToArray(); if (missingSourceBranches.Any()) throw new ConfigurationException($"Branch configuration '{name}' defines these 'source-branches' that are not configured: '[{string.Join(",", missingSourceBranches)}]'{helpUrl}"); } } private static Config CreateDefaultConfiguration() { var config = new Config { AssemblyVersioningScheme = AssemblyVersioningScheme.MajorMinorPatch, AssemblyFileVersioningScheme = AssemblyFileVersioningScheme.MajorMinorPatch, TagPrefix = Config.DefaultTagPrefix, VersioningMode = VersioningMode.ContinuousDelivery, ContinuousDeploymentFallbackTag = "ci", MajorVersionBumpMessage = IncrementStrategyFinder.DefaultMajorPattern, MinorVersionBumpMessage = IncrementStrategyFinder.DefaultMinorPattern, PatchVersionBumpMessage = IncrementStrategyFinder.DefaultPatchPattern, NoBumpMessage = IncrementStrategyFinder.DefaultNoBumpPattern, CommitMessageIncrementing = CommitMessageIncrementMode.Enabled, LegacySemVerPadding = 4, BuildMetaDataPadding = 4, CommitsSinceVersionSourcePadding = 4, CommitDateFormat = "yyyy-MM-dd", UpdateBuildNumber = true, TagPreReleaseWeight = DefaultTagPreReleaseWeight }; AddBranchConfig(Config.DevelopBranchKey, new BranchConfig { Regex = Config.DevelopBranchRegex, SourceBranches = new HashSet<string>(), Tag = "alpha", Increment = IncrementStrategy.Minor, TrackMergeTarget = true, TracksReleaseBranches = true, PreReleaseWeight = 0, }); AddBranchConfig(Config.MainBranchKey, new BranchConfig { Regex = Config.MainBranchRegex, SourceBranches = new HashSet<string> { Config.DevelopBranchKey, Config.ReleaseBranchKey }, Tag = string.Empty, PreventIncrementOfMergedBranchVersion = true, Increment = IncrementStrategy.Patch, IsMainline = true, PreReleaseWeight = 55000, }); AddBranchConfig(Config.ReleaseBranchKey, new BranchConfig { Regex = Config.ReleaseBranchRegex, SourceBranches = new HashSet<string> { Config.DevelopBranchKey, Config.MainBranchKey, Config.SupportBranchKey, Config.ReleaseBranchKey }, Tag = "beta", PreventIncrementOfMergedBranchVersion = true, Increment = IncrementStrategy.None, IsReleaseBranch = true, PreReleaseWeight = 30000, }); AddBranchConfig(Config.FeatureBranchKey, new BranchConfig { Regex = Config.FeatureBranchRegex, SourceBranches = new HashSet<string> { Config.DevelopBranchKey, Config.MainBranchKey, Config.ReleaseBranchKey, Config.FeatureBranchKey, Config.SupportBranchKey, Config.HotfixBranchKey }, Increment = IncrementStrategy.Inherit, PreReleaseWeight = 30000, }); AddBranchConfig(Config.PullRequestBranchKey, new BranchConfig { Regex = Config.PullRequestRegex, SourceBranches = new HashSet<string> { Config.DevelopBranchKey, Config.MainBranchKey, Config.ReleaseBranchKey, Config.FeatureBranchKey, Config.SupportBranchKey, Config.HotfixBranchKey }, Tag = "PullRequest", TagNumberPattern = @"[/-](?<number>\d+)", Increment = IncrementStrategy.Inherit, PreReleaseWeight = 30000, }); AddBranchConfig(Config.HotfixBranchKey, new BranchConfig { Regex = Config.HotfixBranchRegex, SourceBranches = new HashSet<string> { Config.DevelopBranchKey, Config.MainBranchKey, Config.SupportBranchKey }, Tag = "beta", Increment = IncrementStrategy.Patch, PreReleaseWeight = 30000, }); AddBranchConfig(Config.SupportBranchKey, new BranchConfig { Regex = Config.SupportBranchRegex, SourceBranches = new HashSet<string> { Config.MainBranchKey }, Tag = string.Empty, PreventIncrementOfMergedBranchVersion = true, Increment = IncrementStrategy.Patch, IsMainline = true, PreReleaseWeight = 55000, }); return config; void AddBranchConfig(string name, BranchConfig overrides) { config.Branches[name] = BranchConfig.CreateDefaultBranchConfig(name).Apply(overrides); } } } }
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using SessionMMiniJSON; /*! * SessionM Android Native Implementation. */ #if UNITY_ANDROID public class ISessionM_Android : ISessionM { private SessionM sessionMGameObject; private ISessionMCallback callback; private SessionMEventListener listener; private static AndroidJavaObject androidInstance; private AndroidJavaClass sessionMObject = new AndroidJavaClass("com.sessionm.unity.SessionMPlugin"); private Boolean isPresented = false; public ISessionM_Android(SessionM sessionMParent) { sessionMGameObject = sessionMParent; initAndroidInstance(); CreateListenerObject(); SetShouldAutoUpdateAchievementsList(SessionM.shouldAutoUpdateAchievementsList); SetMessagesEnabled(SessionM.shouldEnableMessages); SetLogLevel(sessionMParent.logLevel); if (SessionM.serviceRegion == ServiceRegion.Custom) { SetServerType(SessionM.serverURL); } else { SetServiceRegion(SessionM.serviceRegion); } if (SessionM.shouldAutoStartSession && sessionMGameObject.androidAppId != null) { StartSession(sessionMGameObject.androidAppId); } } private void CreateListenerObject() { listener = sessionMGameObject.gameObject.AddComponent<SessionMEventListener>(); sessionMObject.CallStatic("setCallbackGameObjectName", sessionMGameObject.gameObject.name); listener.SetNativeParent(this); if(callback != null) { listener.SetCallback(callback); } } public void StartSession(string appId) { using (AndroidJavaObject activityObject = GetCurrentActivity()) { if(appId != null) { androidInstance.Call("startSession", activityObject, appId); } else if(sessionMGameObject.androidAppId != null) { androidInstance.Call("startSession", activityObject, sessionMGameObject.androidAppId); } } } public SessionState GetSessionState() { SessionState state = SessionState.Stopped; using (AndroidJavaObject stateObject = androidInstance.Call<AndroidJavaObject>("getSessionState")) { string stateName = stateObject.Call<string>("name"); if(stateName.Equals("STOPPED")) { state = SessionState.Stopped; } else if(stateName.Equals("STARTED_ONLINE")) { state = SessionState.StartedOnline; } else if(stateName.Equals("STARTED_OFFLINE")) { state = SessionState.StartedOffline; } } return state; } public string GetUser() { return sessionMObject.CallStatic<string>("getUser"); } public bool LogInUserWithEmail(string email, string password) { return sessionMObject.CallStatic<bool>("logInUserWithEmail", email, password); } public void LogOutUser() { sessionMObject.CallStatic("logOutUser"); } public bool SignUpUser(string email, string password, string birthYear, string gender, string zipCode) { return sessionMObject.CallStatic<bool>("signUpUser", email, password, birthYear, gender, zipCode); } public void SetUserOptOutStatus(bool status) { sessionMObject.CallStatic("setUserOptOutStatus", status); } public void SetShouldAutoUpdateAchievementsList(bool shouldAutoUpdate) { sessionMObject.CallStatic("setShouldAutoUpdateAchievementsList", shouldAutoUpdate); } public void SetSessionAutoStartEnabled(bool autoStart) { sessionMObject.CallStatic("setSessionAutoStartEnabled", autoStart); } public bool IsSessionAutoStartEnabled() { return sessionMObject.CallStatic<bool>("isSessionAutoStartEnabled"); } public void UpdateAchievementsList() { sessionMObject.CallStatic("updateAchievementsList"); } public int GetUnclaimedAchievementCount() { return sessionMObject.CallStatic<int>("getUnclaimedAchievementCount"); } public string GetUnclaimedAchievementData() { return sessionMObject.CallStatic<string>("getUnclaimedAchievementJSON"); } public void LogAction(string action) { androidInstance.Call("logAction", action); } public void LogAction(string action, int count) { androidInstance.Call("logAction", action, count); } public void LogAction(string action, int count, Dictionary<string, object> payloads) { string payloadsJSON = Json.Serialize(payloads); using (AndroidJavaObject activityObject = GetCurrentActivity()) { activityObject.Call("logAction", action, count, payloadsJSON); } } public bool PresentActivity(ActivityType type) { using (AndroidJavaObject activityType = GetAndroidActivityTypeObject(type)) { isPresented = androidInstance.Call<bool>("presentActivity", activityType); } return isPresented; } public void DismissActivity() { if (isPresented) { androidInstance.Call ("dismissActivity"); isPresented = false; } } public bool IsActivityPresented() { bool presented = false; presented = androidInstance.Call<bool>("isActivityPresented"); return presented; } public bool IsActivityAvailable(ActivityType type) { bool available = false; using (AndroidJavaObject activityType = GetAndroidActivityTypeObject(type)) { available = sessionMObject.CallStatic<bool>("isActivityAvailable", activityType); } return available; } public void SetLogLevel(LogLevel level) { // use logcat on Android } public LogLevel GetLogLevel() { return LogLevel.Off; } public string GetSDKVersion() { return androidInstance.Call<string>("getSDKVersion"); } public string GetRewards() { return sessionMObject.CallStatic<string>("getRewardsJSON"); } public string GetMessagesList() { return sessionMObject.CallStatic<string>("getMessagesList"); } public void SetMessagesEnabled(bool enabled) { sessionMObject.CallStatic("setMessagesEnabled", enabled); } public void SetMetaData(string data, string key) { androidInstance.Call("setMetaData", key, data); } public bool AuthenticateWithToken(string provider, string token) { return androidInstance.Call<bool>("authenticateWithToken", provider, token); } public void SetServiceRegion(ServiceRegion serviceRegion) { //Always 0 for now sessionMObject.CallStatic("setServiceRegion", 0); } public void SetServerType(string url) { sessionMObject.CallStatic("setServerType", url); } public void SetAppKey(string appKey) { sessionMObject.CallStatic("setAppKey", appKey); } public void NotifyPresented() { isPresented = sessionMObject.CallStatic<bool>("notifyCustomAchievementPresented"); } public void NotifyDismissed() { if (isPresented) { sessionMObject.CallStatic("notifyCustomAchievementCancelled"); } } public void NotifyClaimed() { if (isPresented) { sessionMObject.CallStatic("notifyCustomAchievementClaimed"); isPresented = false; } } public void PresentTierList() { sessionMObject.CallStatic("presentTierList"); } public string GetTiers() { return sessionMObject.CallStatic<string>("getTiers"); } public double GetApplicationMultiplier() { return sessionMObject.CallStatic<double>("getApplicationMultiplier"); } public void UpdateOffers() { sessionMObject.CallStatic("fetchOffers"); } public string GetOffers() { return sessionMObject.CallStatic<string>("getOffers"); } public void FetchContent(string contentID, bool isExternalID) { sessionMObject.CallStatic("fetchContent", contentID, isExternalID); } public void SetCallback(ISessionMCallback callback) { this.callback = callback; listener.SetCallback(callback); } public ISessionMCallback GetCallback() { return this.callback; } // MonoBehavior public AndroidJavaObject GetCurrentActivity() { using (AndroidJavaClass playerClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) { return playerClass.GetStatic<AndroidJavaObject>("currentActivity"); } } private AndroidJavaObject GetAndroidActivityTypeObject(ActivityType type) { if(Application.platform != RuntimePlatform.Android) { return null; } using (AndroidJavaClass typeClass = new AndroidJavaClass("com.sessionm.api.SessionM$ActivityType")) { string typeString = null; if(type == ActivityType.Achievement) { typeString = "ACHIEVEMENT"; } else if(type == ActivityType.Portal) { typeString = "PORTAL"; } AndroidJavaObject activityType = typeClass.CallStatic<AndroidJavaObject>("valueOf", typeString); return activityType; } } protected static void initAndroidInstance() { using (AndroidJavaClass sessionMClass = new AndroidJavaClass("com.sessionm.api.SessionM")) { androidInstance = sessionMClass.CallStatic<AndroidJavaObject>("getInstance"); } } } #endif
//#define DEBUG //#define DEBUG2 using System; using System.Collections.Generic; namespace ICSimulator { public class Controller_Global_round_robin : Controller_ClassicBLESS { public bool[] m_isThrottled = new bool[Config.N]; //This represent the round-robin turns public int[] throttleTable = new int[Config.N]; public bool isThrottling; //This tell which group are allowed to run in a certain epoch public int currentAllow = 1; //Packet Pools IPrioPktPool[] m_injPools = new IPrioPktPool[Config.N]; //thresholdTrigger will return true if the evaluation of the throttled related metric //exceed the threshold. This threshold can be made dynamic public virtual bool thresholdTrigger() { #if DEBUG2 Console.WriteLine("throttle OFF!"); #endif Simulator.stats.total_th_off.Add(1); double avg = 0.0; for (int i = 0; i < Config.N; i++) avg = avg + MPKI[i]; avg = avg/Config.N; #if DEBUG Console.WriteLine("NOT THROTTLING->Estimating MPKI, max_thresh {1}: avg MPKI {0}",avg,Config.MPKI_max_thresh); #endif //greater than the max threshold return avg > Config.MPKI_max_thresh; } public Controller_Global_round_robin() { isThrottling = false; for (int i = 0; i < Config.N; i++) { MPKI[i]=0.0; prev_MPKI[i]=0.0; num_ins_last_epoch[i]=0; m_isThrottled[i]=false; L1misses[i]=0; } } //Default controller uses one single queue. However, we are trying //completely shut off injection of control packets only. Therefore //we need to use separate queues for each control, data, & writeback. public override IPrioPktPool newPrioPktPool(int node) { return MultiQThrottlePktPool.construct(); } //configure the packet pool for each node. Makes it aware of //the node position. public override void setInjPool(int node, IPrioPktPool pool) { m_injPools[node] = pool; pool.setNodeId(node); } public override void resetStat() { for (int i = 0; i < Config.N; i++) { //prev_MPKI=MPKI[i]; //MPKI[i]=0.0; num_ins_last_epoch[i] = (ulong)Simulator.stats.insns_persrc[i].Count; L1misses[i]=0; } } //On or off public virtual void setThrottleRate(int node, bool cond) { m_isThrottled[node] = cond; } // true to allow injection, false to block (throttle) // RouterFlit uses this function to determine whether it can inject or not public override bool tryInject(int node) { if(m_isThrottled[node]&&Simulator.rand.NextDouble()<Config.RR_throttle_rate) { Simulator.stats.throttled_counts_persrc[node].Add(); return false; } else { Simulator.stats.not_throttled_counts_persrc[node].Add(); return true; } } public virtual void doThrottling() { for(int i=0;i<Config.N;i++) { if((throttleTable[i]==currentAllow)||(throttleTable[i]==0)) setThrottleRate(i,false); else setThrottleRate(i, true); } currentAllow++; //interval based if(currentAllow > Config.num_epoch) currentAllow=1; } public override void doStep() { // for (int i = 0; i < Config.N; i++) // { // this is not needed. Can be uncommented if we want to consider the starvation // avg_MPKI[i].accumulate(m_starved[i]); // avg_qlen[i].accumulate(m_injPools[i].Count); // m_starved[i] = false; // } //throttle stats for(int i=0;i<Config.N;i++) { if(throttleTable[i]!=0 && throttleTable[i]!=currentAllow && isThrottling) Simulator.stats.throttle_time_bysrc[i].Add(); } if (Simulator.CurrentRound > (ulong)Config.warmup_cyc && (Simulator.CurrentRound % (ulong)Config.throttle_sampling_period) == 0) { setThrottling(); resetStat(); } if (isThrottling && Simulator.CurrentRound > (ulong)Config.warmup_cyc && (Simulator.CurrentRound % (ulong)Config.interval_length) == 0) { doThrottling(); } } /** *** SetThrottleTable will specify which group the workload belongs to, this will be used *** when we are throttling the network. The current setting is it will rank the node base on *** the injection (MPKI is actually the injection) and try to weight out among the workloads *** TODO: location-aware binning mechanism, congestion-aware binning mechanism ***/ /** * @brief Random cluster assignment **/ public virtual void setThrottleTable() { //if the node is throttled, randomly assign a cluster group to it. for(int i = 0; i < Config.N; i++) { if(m_isThrottled[i]) { int randseed=Simulator.rand.Next(1,Config.num_epoch+1); if(randseed==0 || randseed>Config.num_epoch) throw new Exception("rand seed errors: out of range!"); throttleTable[i] = randseed; } } #if DEBUG2 Console.WriteLine("\nThrottle Table:"); for(int i = 0; i < Config.N; i++) { Console.Write("(id:{0},th? {1},cluster:{2}) ",i,m_isThrottled[i],throttleTable[i]); } #endif } public virtual void recordStats() { double mpki_sum=0; double mpki=0; for(int i=0;i<Config.N;i++) { mpki=MPKI[i]; mpki_sum+=mpki; Simulator.stats.mpki_bysrc[i].Add(mpki); } Simulator.stats.total_sum_mpki.Add(mpki_sum); } public virtual void setThrottling() { #if DEBUG Console.Write("\n:: cycle {0} ::", Simulator.CurrentRound); #endif //get the MPKI value for (int i = 0; i < Config.N; i++) { prev_MPKI[i]=MPKI[i]; if(num_ins_last_epoch[i]==0) MPKI[i]=((double)(L1misses[i]*1000))/(Simulator.stats.insns_persrc[i].Count); else { if(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]>0) MPKI[i]=((double)(L1misses[i]*1000))/(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]); else if(Simulator.stats.insns_persrc[i].Count-num_ins_last_epoch[i]==0) MPKI[i]=0; else throw new Exception("MPKI error!"); } #if DEBUG if(MPKI[i]>1000) { Console.WriteLine("node:{2} MPKI:{0} warmup cycles:{1}",MPKI[i],Config.warmup_cyc,i); Console.WriteLine("insns:{0} insns_last_epoch:{1} l1misses:{2}",Simulator.stats.insns_persrc[i].Count,num_ins_last_epoch[i],L1misses[i]); throw new Exception("abnormally high mpki"); } #endif } recordStats(); if(isThrottling) { #if DEBUG2 Console.WriteLine("throttle on!"); #endif //see if we can un-throttle the netowork double avg = 0.0; //check if we can go back to FFA for (int i = 0; i < Config.N; i++) { #if DEBUG Console.Write("[{1}] {0} |",(int)MPKI[i],i); #endif avg = avg + MPKI[i]; } avg = avg/Config.N; #if DEBUG Console.WriteLine("THROTTLING->Estimating MPKI, min_thresh {1}: avg MPKI {0}",avg,Config.MPKI_min_thresh); #endif if(avg < Config.MPKI_min_thresh) { #if DEBUG Console.WriteLine("\n****OFF****Transition from Throttle mode to FFA! with avg MPKI {0}\n",avg); #endif isThrottling = false; //un-throttle the network for(int i=0;i<Config.N;i++) setThrottleRate(i,false); } } else { if (thresholdTrigger()) // an abstract fn() that trigger whether to start throttling or not { #if DEBUG Console.Write("Throttle mode turned on: cycle {0} (", Simulator.CurrentRound); #endif //determine if the node is congested int total_high = 0; for (int i = 0; i < Config.N; i++) { //Also uses previous sampled MPKI as a metric to avoid throttling low network //intensive apps if (MPKI[i] > Config.MPKI_high_node /*&& prev_MPKI[i] > Config.MPKI_high_node*/) { total_high++; //throttleTable[i] = Simulator.rand.Next(Config.num_epoch); setThrottleRate(i, true); #if DEBUG Console.Write("#ON#:Node {0} with MPKI {1} ",i,MPKI[i]); #endif } else { throttleTable[i]=0; setThrottleRate(i, false); #if DEBUG Console.Write("@OFF@:Node {0} with MPKI {1} prev_MPKI {2} ",i,MPKI[i],prev_MPKI[i]); #endif } } setThrottleTable(); #if DEBUG Console.WriteLine(")"); #endif isThrottling = true; currentAllow = 1; } } } protected enum NodeState { Low = 0, HighGolden = 1, HighOther = 2, AlwaysThrottled = 3 } protected NodeState[] m_nodeStates = new NodeState[Config.N]; public override int rankFlits(Flit f1, Flit f2) { if (Config.cluster_prios) { if (f1.packet.requesterID != -1 && f2.packet.requesterID != -1) { if ((int)m_nodeStates[f1.packet.requesterID] < (int)m_nodeStates[f2.packet.requesterID]) return -1; if ((int)m_nodeStates[f1.packet.requesterID] > (int)m_nodeStates[f2.packet.requesterID]) return 1; } } return Router_Flit_OldestFirst._rank(f1, f2); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using System.Threading; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Audio; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Framework.Input.Events; using osu.Framework.Input.States; using osu.Framework.Platform; using osu.Framework.Screens; using osu.Game.Beatmaps; using osu.Game.Configuration; using osu.Game.Graphics; using osu.Game.Graphics.Containers; using osu.Game.Graphics.Sprites; using osu.Game.Rulesets; using osu.Game.Rulesets.Osu.Mods; using osu.Game.Scoring; using osu.Game.Screens; using osu.Game.Screens.Backgrounds; using osu.Game.Screens.Play; using osu.Game.Screens.Play.PlayerSettings; using osu.Game.Screens.Ranking; using osu.Game.Screens.Select; using osu.Game.Tests.Beatmaps; using osu.Game.Tests.Resources; using osu.Game.Users; using osuTK; using osuTK.Graphics; namespace osu.Game.Tests.Visual.Background { [TestFixture] public class TestSceneUserDimBackgrounds : OsuManualInputManagerTestScene { private DummySongSelect songSelect; private TestPlayerLoader playerLoader; private LoadBlockingTestPlayer player; private BeatmapManager manager; private RulesetStore rulesets; [BackgroundDependencyLoader] private void load(GameHost host, AudioManager audio) { Dependencies.Cache(rulesets = new RulesetStore(ContextFactory)); Dependencies.Cache(manager = new BeatmapManager(LocalStorage, ContextFactory, rulesets, null, audio, Resources, host, Beatmap.Default)); Dependencies.Cache(new OsuConfigManager(LocalStorage)); manager.Import(TestResources.GetQuickTestBeatmapForImport()).Wait(); Beatmap.SetDefault(); } [SetUp] public virtual void SetUp() => Schedule(() => { var stack = new OsuScreenStack { RelativeSizeAxes = Axes.Both }; Child = stack; stack.Push(songSelect = new DummySongSelect()); }); /// <summary> /// User settings should always be ignored on song select screen. /// </summary> [Test] public void TestUserSettingsIgnoredOnSongSelect() { setupUserSettings(); AddUntilStep("Screen is undimmed", () => songSelect.IsBackgroundUndimmed()); AddUntilStep("Screen using background blur", () => songSelect.IsBackgroundBlur()); performFullSetup(); AddStep("Exit to song select", () => player.Exit()); AddUntilStep("Screen is undimmed", () => songSelect.IsBackgroundUndimmed()); AddUntilStep("Screen using background blur", () => songSelect.IsBackgroundBlur()); } /// <summary> /// Check if <see cref="PlayerLoader"/> properly triggers the visual settings preview when a user hovers over the visual settings panel. /// </summary> [Test] public void TestPlayerLoaderSettingsHover() { setupUserSettings(); AddStep("Start player loader", () => songSelect.Push(playerLoader = new TestPlayerLoader(player = new LoadBlockingTestPlayer { BlockLoad = true }))); AddUntilStep("Wait for Player Loader to load", () => playerLoader?.IsLoaded ?? false); AddAssert("Background retained from song select", () => songSelect.IsBackgroundCurrent()); AddStep("Trigger background preview", () => { InputManager.MoveMouseTo(playerLoader.ScreenPos); InputManager.MoveMouseTo(playerLoader.VisualSettingsPos); }); AddUntilStep("Screen is dimmed and blur applied", () => songSelect.IsBackgroundDimmed() && songSelect.IsUserBlurApplied()); AddStep("Stop background preview", () => InputManager.MoveMouseTo(playerLoader.ScreenPos)); AddUntilStep("Screen is undimmed and user blur removed", () => songSelect.IsBackgroundUndimmed() && songSelect.CheckBackgroundBlur(playerLoader.ExpectedBackgroundBlur)); } /// <summary> /// In the case of a user triggering the dim preview the instant player gets loaded, then moving the cursor off of the visual settings: /// The OnHover of PlayerLoader will trigger, which could potentially cause visual settings to be unapplied unless checked for in PlayerLoader. /// We need to check that in this scenario, the dim and blur is still properly applied after entering player. /// </summary> [Test] public void TestPlayerLoaderTransition() { performFullSetup(); AddStep("Trigger hover event", () => playerLoader.TriggerOnHover()); AddAssert("Background retained from song select", () => songSelect.IsBackgroundCurrent()); AddUntilStep("Screen is dimmed and blur applied", () => songSelect.IsBackgroundDimmed() && songSelect.IsUserBlurApplied()); } /// <summary> /// Make sure the background is fully invisible (Alpha == 0) when the background should be disabled by the storyboard. /// </summary> [Test] public void TestStoryboardBackgroundVisibility() { performFullSetup(); AddAssert("Background retained from song select", () => songSelect.IsBackgroundCurrent()); createFakeStoryboard(); AddStep("Enable Storyboard", () => { player.ReplacesBackground.Value = true; player.StoryboardEnabled.Value = true; }); AddUntilStep("Background is invisible, storyboard is visible", () => songSelect.IsBackgroundInvisible() && player.IsStoryboardVisible); AddStep("Disable Storyboard", () => { player.ReplacesBackground.Value = false; player.StoryboardEnabled.Value = false; }); AddUntilStep("Background is visible, storyboard is invisible", () => songSelect.IsBackgroundVisible() && !player.IsStoryboardVisible); } /// <summary> /// When exiting player, the screen that it suspends/exits to needs to have a fully visible (Alpha == 1) background. /// </summary> [Test] public void TestStoryboardTransition() { performFullSetup(); createFakeStoryboard(); AddStep("Exit to song select", () => player.Exit()); AddUntilStep("Background is visible", () => songSelect.IsBackgroundVisible()); } /// <summary> /// Ensure <see cref="UserDimContainer"/> is properly accepting user-defined visual changes for a background. /// </summary> [Test] public void TestDisableUserDimBackground() { performFullSetup(); AddUntilStep("Screen is dimmed and blur applied", () => songSelect.IsBackgroundDimmed() && songSelect.IsUserBlurApplied()); AddStep("Disable user dim", () => songSelect.IgnoreUserSettings.Value = true); AddUntilStep("Screen is undimmed and user blur removed", () => songSelect.IsBackgroundUndimmed() && songSelect.IsUserBlurDisabled()); AddStep("Enable user dim", () => songSelect.IgnoreUserSettings.Value = false); AddUntilStep("Screen is dimmed and blur applied", () => songSelect.IsBackgroundDimmed() && songSelect.IsUserBlurApplied()); } /// <summary> /// Ensure <see cref="UserDimContainer"/> is properly accepting user-defined visual changes for a storyboard. /// </summary> [Test] public void TestDisableUserDimStoryboard() { performFullSetup(); createFakeStoryboard(); AddStep("Enable Storyboard", () => { player.ReplacesBackground.Value = true; player.StoryboardEnabled.Value = true; }); AddStep("Enable user dim", () => player.DimmableStoryboard.IgnoreUserSettings.Value = false); AddStep("Set dim level to 1", () => songSelect.DimLevel.Value = 1f); AddUntilStep("Storyboard is invisible", () => !player.IsStoryboardVisible); AddStep("Disable user dim", () => player.DimmableStoryboard.IgnoreUserSettings.Value = true); AddUntilStep("Storyboard is visible", () => player.IsStoryboardVisible); } [Test] public void TestStoryboardIgnoreUserSettings() { performFullSetup(); createFakeStoryboard(); AddStep("Enable replacing background", () => player.ReplacesBackground.Value = true); AddUntilStep("Storyboard is invisible", () => !player.IsStoryboardVisible); AddUntilStep("Background is visible", () => songSelect.IsBackgroundVisible()); AddStep("Ignore user settings", () => { player.ApplyToBackground(b => b.IgnoreUserSettings.Value = true); player.DimmableStoryboard.IgnoreUserSettings.Value = true; }); AddUntilStep("Storyboard is visible", () => player.IsStoryboardVisible); AddUntilStep("Background is invisible", () => songSelect.IsBackgroundInvisible()); AddStep("Disable background replacement", () => player.ReplacesBackground.Value = false); AddUntilStep("Storyboard is visible", () => player.IsStoryboardVisible); AddUntilStep("Background is visible", () => songSelect.IsBackgroundVisible()); } /// <summary> /// Check if the visual settings container retains dim and blur when pausing /// </summary> [Test] public void TestPause() { performFullSetup(true); AddStep("Pause", () => player.Pause()); AddUntilStep("Screen is dimmed and blur applied", () => songSelect.IsBackgroundDimmed() && songSelect.IsUserBlurApplied()); AddStep("Unpause", () => player.Resume()); AddUntilStep("Screen is dimmed and blur applied", () => songSelect.IsBackgroundDimmed() && songSelect.IsUserBlurApplied()); } /// <summary> /// Check if the visual settings container removes user dim when suspending <see cref="Player"/> for <see cref="ResultsScreen"/> /// </summary> [Test] public void TestTransition() { performFullSetup(); FadeAccessibleResults results = null; AddStep("Transition to Results", () => player.Push(results = new FadeAccessibleResults(new ScoreInfo { User = new User { Username = "osu!" }, Beatmap = new TestBeatmap(Ruleset.Value).BeatmapInfo, Ruleset = Ruleset.Value, }))); AddUntilStep("Wait for results is current", () => results.IsCurrentScreen()); AddUntilStep("Screen is undimmed, original background retained", () => songSelect.IsBackgroundUndimmed() && songSelect.IsBackgroundCurrent() && songSelect.CheckBackgroundBlur(results.ExpectedBackgroundBlur)); } /// <summary> /// Check if hovering on the visual settings dialogue after resuming from player still previews the background dim. /// </summary> [Test] public void TestResumeFromPlayer() { performFullSetup(); AddStep("Move mouse to Visual Settings", () => InputManager.MoveMouseTo(playerLoader.VisualSettingsPos)); AddStep("Resume PlayerLoader", () => player.Restart()); AddUntilStep("Screen is dimmed and blur applied", () => songSelect.IsBackgroundDimmed() && songSelect.IsUserBlurApplied()); AddStep("Move mouse to center of screen", () => InputManager.MoveMouseTo(playerLoader.ScreenPos)); AddUntilStep("Screen is undimmed and user blur removed", () => songSelect.IsBackgroundUndimmed() && songSelect.CheckBackgroundBlur(playerLoader.ExpectedBackgroundBlur)); } private void createFakeStoryboard() => AddStep("Create storyboard", () => { player.StoryboardEnabled.Value = false; player.ReplacesBackground.Value = false; player.DimmableStoryboard.Add(new OsuSpriteText { Size = new Vector2(500, 50), Alpha = 1, Colour = Color4.White, Anchor = Anchor.Centre, Origin = Anchor.Centre, Text = "THIS IS A STORYBOARD", Font = new FontUsage(size: 50) }); }); private void performFullSetup(bool allowPause = false) { setupUserSettings(); AddStep("Start player loader", () => songSelect.Push(playerLoader = new TestPlayerLoader(player = new LoadBlockingTestPlayer(allowPause)))); AddUntilStep("Wait for Player Loader to load", () => playerLoader.IsLoaded); AddStep("Move mouse to center of screen", () => InputManager.MoveMouseTo(playerLoader.ScreenPos)); AddUntilStep("Wait for player to load", () => player.IsLoaded); } private void setupUserSettings() { AddUntilStep("Song select is current", () => songSelect.IsCurrentScreen()); AddUntilStep("Song select has selection", () => songSelect.Carousel?.SelectedBeatmap != null); AddStep("Set default user settings", () => { SelectedMods.Value = SelectedMods.Value.Concat(new[] { new OsuModNoFail() }).ToArray(); songSelect.DimLevel.Value = 0.7f; songSelect.BlurLevel.Value = 0.4f; }); } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); rulesets?.Dispose(); } private class DummySongSelect : PlaySongSelect { private FadeAccessibleBackground background; protected override BackgroundScreen CreateBackground() { background = new FadeAccessibleBackground(Beatmap.Value); IgnoreUserSettings.BindTo(background.IgnoreUserSettings); return background; } public readonly Bindable<bool> IgnoreUserSettings = new Bindable<bool>(); public readonly Bindable<double> DimLevel = new BindableDouble(); public readonly Bindable<double> BlurLevel = new BindableDouble(); public new BeatmapCarousel Carousel => base.Carousel; [BackgroundDependencyLoader] private void load(OsuConfigManager config) { config.BindWith(OsuSetting.DimLevel, DimLevel); config.BindWith(OsuSetting.BlurLevel, BlurLevel); } public bool IsBackgroundDimmed() => background.CurrentColour == OsuColour.Gray(1f - background.CurrentDim); public bool IsBackgroundUndimmed() => background.CurrentColour == Color4.White; public bool IsUserBlurApplied() => background.CurrentBlur == new Vector2((float)BlurLevel.Value * BackgroundScreenBeatmap.USER_BLUR_FACTOR); public bool IsUserBlurDisabled() => background.CurrentBlur == new Vector2(0); public bool IsBackgroundInvisible() => background.CurrentAlpha == 0; public bool IsBackgroundVisible() => background.CurrentAlpha == 1; public bool IsBackgroundBlur() => background.CurrentBlur == new Vector2(BACKGROUND_BLUR); public bool CheckBackgroundBlur(Vector2 expected) => background.CurrentBlur == expected; /// <summary> /// Make sure every time a screen gets pushed, the background doesn't get replaced /// </summary> /// <returns>Whether or not the original background (The one created in DummySongSelect) is still the current background</returns> public bool IsBackgroundCurrent() => background?.IsCurrentScreen() == true; } private class FadeAccessibleResults : ResultsScreen { public FadeAccessibleResults(ScoreInfo score) : base(score, true) { } protected override BackgroundScreen CreateBackground() => new FadeAccessibleBackground(Beatmap.Value); public Vector2 ExpectedBackgroundBlur => new Vector2(BACKGROUND_BLUR); } private class LoadBlockingTestPlayer : TestPlayer { protected override BackgroundScreen CreateBackground() => new FadeAccessibleBackground(Beatmap.Value); public override void OnEntering(IScreen last) { base.OnEntering(last); ApplyToBackground(b => ReplacesBackground.BindTo(b.StoryboardReplacesBackground)); } public new DimmableStoryboard DimmableStoryboard => base.DimmableStoryboard; // Whether or not the player should be allowed to load. public bool BlockLoad; public Bindable<bool> StoryboardEnabled; public readonly Bindable<bool> ReplacesBackground = new Bindable<bool>(); public readonly Bindable<bool> IsPaused = new Bindable<bool>(); public LoadBlockingTestPlayer(bool allowPause = true) : base(allowPause) { } public bool IsStoryboardVisible => DimmableStoryboard.ContentDisplayed; [BackgroundDependencyLoader] private void load(OsuConfigManager config, CancellationToken token) { while (BlockLoad && !token.IsCancellationRequested) Thread.Sleep(1); StoryboardEnabled = config.GetBindable<bool>(OsuSetting.ShowStoryboard); DrawableRuleset.IsPaused.BindTo(IsPaused); } } private class TestPlayerLoader : PlayerLoader { private FadeAccessibleBackground background; public VisualSettings VisualSettingsPos => VisualSettings; public BackgroundScreen ScreenPos => background; public TestPlayerLoader(Player player) : base(() => player) { } public void TriggerOnHover() => OnHover(new HoverEvent(new InputState())); public Vector2 ExpectedBackgroundBlur => new Vector2(BACKGROUND_BLUR); protected override BackgroundScreen CreateBackground() => background = new FadeAccessibleBackground(Beatmap.Value); } private class FadeAccessibleBackground : BackgroundScreenBeatmap { protected override DimmableBackground CreateFadeContainer() => dimmable = new TestDimmableBackground { RelativeSizeAxes = Axes.Both }; public Color4 CurrentColour => dimmable.CurrentColour; public float CurrentAlpha => dimmable.CurrentAlpha; public float CurrentDim => dimmable.DimLevel; public Vector2 CurrentBlur => Background.BlurSigma; private TestDimmableBackground dimmable; public FadeAccessibleBackground(WorkingBeatmap beatmap) : base(beatmap) { } } private class TestDimmableBackground : BackgroundScreenBeatmap.DimmableBackground { public Color4 CurrentColour => Content.Colour; public float CurrentAlpha => Content.Alpha; public new float DimLevel => base.DimLevel; } } }
/* * 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. */ /* Revised Aug, Sept 2009 by Kitto Flora. ODEDynamics.cs replaces * ODEVehicleSettings.cs. It and ODEPrim.cs are re-organised: * ODEPrim.cs contains methods dealing with Prim editing, Prim * characteristics and Kinetic motion. * ODEDynamics.cs contains methods dealing with Prim Physical motion * (dynamics) and the associated settings. Old Linear and angular * motors for dynamic motion have been replace with MoveLinear() * and MoveAngular(); 'Physical' is used only to switch ODE dynamic * simualtion on/off; VEHICAL_TYPE_NONE/VEHICAL_TYPE_<other> is to * switch between 'VEHICLE' parameter use and general dynamics * settings use. */ // Extensive change Ubit 2012 using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.InteropServices; using log4net; using OpenMetaverse; using OdeAPI; using OpenSim.Framework; using OpenSim.Region.PhysicsModules.SharedBase; namespace OpenSim.Region.PhysicsModule.ubOde { public class ODEDynamics { public Vehicle Type { get { return m_type; } } private OdePrim rootPrim; private ODEScene _pParentScene; // Vehicle properties // WARNING this are working copies for internel use // their values may not be the corresponding parameter private Quaternion m_referenceFrame = Quaternion.Identity; // Axis modifier private Quaternion m_RollreferenceFrame = Quaternion.Identity; // what hell is this ? private Vehicle m_type = Vehicle.TYPE_NONE; // If a 'VEHICLE', and what kind private VehicleFlag m_flags = (VehicleFlag) 0; // Boolean settings: // HOVER_TERRAIN_ONLY // HOVER_GLOBAL_HEIGHT // NO_DEFLECTION_UP // HOVER_WATER_ONLY // HOVER_UP_ONLY // LIMIT_MOTOR_UP // LIMIT_ROLL_ONLY private Vector3 m_BlockingEndPoint = Vector3.Zero; // not sl // Linear properties private Vector3 m_linearMotorDirection = Vector3.Zero; // velocity requested by LSL, decayed by time private Vector3 m_linearFrictionTimescale = new Vector3(1000, 1000, 1000); private float m_linearMotorDecayTimescale = 120; private float m_linearMotorTimescale = 1000; private Vector3 m_linearMotorOffset = Vector3.Zero; //Angular properties private Vector3 m_angularMotorDirection = Vector3.Zero; // angular velocity requested by LSL motor private float m_angularMotorTimescale = 1000; // motor angular velocity ramp up rate private float m_angularMotorDecayTimescale = 120; // motor angular velocity decay rate private Vector3 m_angularFrictionTimescale = new Vector3(1000, 1000, 1000); // body angular velocity decay rate //Deflection properties private float m_angularDeflectionEfficiency = 0; private float m_angularDeflectionTimescale = 1000; private float m_linearDeflectionEfficiency = 0; private float m_linearDeflectionTimescale = 1000; //Banking properties private float m_bankingEfficiency = 0; private float m_bankingMix = 0; private float m_bankingTimescale = 1000; //Hover and Buoyancy properties private float m_VhoverHeight = 0f; private float m_VhoverEfficiency = 0f; private float m_VhoverTimescale = 1000f; private float m_VehicleBuoyancy = 0f; //KF: m_VehicleBuoyancy is set by VEHICLE_BUOYANCY for a vehicle. // Modifies gravity. Slider between -1 (double-gravity) and 1 (full anti-gravity) // KF: So far I have found no good method to combine a script-requested .Z velocity and gravity. // Therefore only m_VehicleBuoyancy=1 (0g) will use the script-requested .Z velocity. //Attractor properties private float m_verticalAttractionEfficiency = 1.0f; // damped private float m_verticalAttractionTimescale = 1000f; // Timescale > 300 means no vert attractor. // auxiliar private float m_lmEfect = 0f; // current linear motor eficiency private float m_lmDecay = 0f; // current linear decay private float m_amEfect = 0; // current angular motor eficiency private float m_amDecay = 0f; // current linear decay private float m_ffactor = 1.0f; private float m_timestep = 0.02f; private float m_invtimestep = 50; float m_ampwr; float m_amdampX; float m_amdampY; float m_amdampZ; float m_gravmod; public float FrictionFactor { get { return m_ffactor; } } public float GravMod { set { m_gravmod = value; } } public ODEDynamics(OdePrim rootp) { rootPrim = rootp; _pParentScene = rootPrim._parent_scene; m_timestep = _pParentScene.ODE_STEPSIZE; m_invtimestep = 1.0f / m_timestep; m_gravmod = rootPrim.GravModifier; } public void DoSetVehicle(VehicleData vd) { m_type = vd.m_type; m_flags = vd.m_flags; // Linear properties m_linearMotorDirection = vd.m_linearMotorDirection; m_linearFrictionTimescale = vd.m_linearFrictionTimescale; if (m_linearFrictionTimescale.X < m_timestep) m_linearFrictionTimescale.X = m_timestep; if (m_linearFrictionTimescale.Y < m_timestep) m_linearFrictionTimescale.Y = m_timestep; if (m_linearFrictionTimescale.Z < m_timestep) m_linearFrictionTimescale.Z = m_timestep; m_linearMotorDecayTimescale = vd.m_linearMotorDecayTimescale; if (m_linearMotorDecayTimescale < m_timestep) m_linearMotorDecayTimescale = m_timestep; m_linearMotorDecayTimescale += 0.2f; m_linearMotorDecayTimescale *= m_invtimestep; m_linearMotorTimescale = vd.m_linearMotorTimescale; if (m_linearMotorTimescale < m_timestep) m_linearMotorTimescale = m_timestep; m_linearMotorOffset = vd.m_linearMotorOffset; //Angular properties m_angularMotorDirection = vd.m_angularMotorDirection; m_angularMotorTimescale = vd.m_angularMotorTimescale; if (m_angularMotorTimescale < m_timestep) m_angularMotorTimescale = m_timestep; m_angularMotorDecayTimescale = vd.m_angularMotorDecayTimescale; if (m_angularMotorDecayTimescale < m_timestep) m_angularMotorDecayTimescale = m_timestep; m_angularMotorDecayTimescale *= m_invtimestep; m_angularFrictionTimescale = vd.m_angularFrictionTimescale; if (m_angularFrictionTimescale.X < m_timestep) m_angularFrictionTimescale.X = m_timestep; if (m_angularFrictionTimescale.Y < m_timestep) m_angularFrictionTimescale.Y = m_timestep; if (m_angularFrictionTimescale.Z < m_timestep) m_angularFrictionTimescale.Z = m_timestep; //Deflection properties m_angularDeflectionEfficiency = vd.m_angularDeflectionEfficiency; m_angularDeflectionTimescale = vd.m_angularDeflectionTimescale; if (m_angularDeflectionTimescale < m_timestep) m_angularDeflectionTimescale = m_timestep; m_linearDeflectionEfficiency = vd.m_linearDeflectionEfficiency; m_linearDeflectionTimescale = vd.m_linearDeflectionTimescale; if (m_linearDeflectionTimescale < m_timestep) m_linearDeflectionTimescale = m_timestep; //Banking properties m_bankingEfficiency = vd.m_bankingEfficiency; m_bankingMix = vd.m_bankingMix; m_bankingTimescale = vd.m_bankingTimescale; if (m_bankingTimescale < m_timestep) m_bankingTimescale = m_timestep; //Hover and Buoyancy properties m_VhoverHeight = vd.m_VhoverHeight; m_VhoverEfficiency = vd.m_VhoverEfficiency; m_VhoverTimescale = vd.m_VhoverTimescale; if (m_VhoverTimescale < m_timestep) m_VhoverTimescale = m_timestep; m_VehicleBuoyancy = vd.m_VehicleBuoyancy; //Attractor properties m_verticalAttractionEfficiency = vd.m_verticalAttractionEfficiency; m_verticalAttractionTimescale = vd.m_verticalAttractionTimescale; if (m_verticalAttractionTimescale < m_timestep) m_verticalAttractionTimescale = m_timestep; // Axis m_referenceFrame = vd.m_referenceFrame; m_lmEfect = 0; m_lmDecay = (1.0f - 1.0f / m_linearMotorDecayTimescale); m_amEfect = 0; m_ffactor = 1.0f; } internal void ProcessFloatVehicleParam(Vehicle pParam, float pValue) { float len; switch (pParam) { case Vehicle.ANGULAR_DEFLECTION_EFFICIENCY: if (pValue < 0f) pValue = 0f; if (pValue > 1f) pValue = 1f; m_angularDeflectionEfficiency = pValue; break; case Vehicle.ANGULAR_DEFLECTION_TIMESCALE: if (pValue < m_timestep) pValue = m_timestep; m_angularDeflectionTimescale = pValue; break; case Vehicle.ANGULAR_MOTOR_DECAY_TIMESCALE: if (pValue < m_timestep) pValue = m_timestep; else if (pValue > 120) pValue = 120; m_angularMotorDecayTimescale = pValue * m_invtimestep; m_amDecay = 1.0f - 1.0f / m_angularMotorDecayTimescale; break; case Vehicle.ANGULAR_MOTOR_TIMESCALE: if (pValue < m_timestep) pValue = m_timestep; m_angularMotorTimescale = pValue; break; case Vehicle.BANKING_EFFICIENCY: if (pValue < -1f) pValue = -1f; if (pValue > 1f) pValue = 1f; m_bankingEfficiency = pValue; break; case Vehicle.BANKING_MIX: if (pValue < 0f) pValue = 0f; if (pValue > 1f) pValue = 1f; m_bankingMix = pValue; break; case Vehicle.BANKING_TIMESCALE: if (pValue < m_timestep) pValue = m_timestep; m_bankingTimescale = pValue; break; case Vehicle.BUOYANCY: if (pValue < -1f) pValue = -1f; if (pValue > 1f) pValue = 1f; m_VehicleBuoyancy = pValue; break; case Vehicle.HOVER_EFFICIENCY: if (pValue < 0f) pValue = 0f; if (pValue > 1f) pValue = 1f; m_VhoverEfficiency = pValue; break; case Vehicle.HOVER_HEIGHT: m_VhoverHeight = pValue; break; case Vehicle.HOVER_TIMESCALE: if (pValue < m_timestep) pValue = m_timestep; m_VhoverTimescale = pValue; break; case Vehicle.LINEAR_DEFLECTION_EFFICIENCY: if (pValue < 0f) pValue = 0f; if (pValue > 1f) pValue = 1f; m_linearDeflectionEfficiency = pValue; break; case Vehicle.LINEAR_DEFLECTION_TIMESCALE: if (pValue < m_timestep) pValue = m_timestep; m_linearDeflectionTimescale = pValue; break; case Vehicle.LINEAR_MOTOR_DECAY_TIMESCALE: if (pValue < m_timestep) pValue = m_timestep; else if (pValue > 120) pValue = 120; m_linearMotorDecayTimescale = (0.2f +pValue) * m_invtimestep; m_lmDecay = (1.0f - 1.0f / m_linearMotorDecayTimescale); break; case Vehicle.LINEAR_MOTOR_TIMESCALE: if (pValue < m_timestep) pValue = m_timestep; m_linearMotorTimescale = pValue; break; case Vehicle.VERTICAL_ATTRACTION_EFFICIENCY: if (pValue < 0f) pValue = 0f; if (pValue > 1f) pValue = 1f; m_verticalAttractionEfficiency = pValue; break; case Vehicle.VERTICAL_ATTRACTION_TIMESCALE: if (pValue < m_timestep) pValue = m_timestep; m_verticalAttractionTimescale = pValue; break; // These are vector properties but the engine lets you use a single float value to // set all of the components to the same value case Vehicle.ANGULAR_FRICTION_TIMESCALE: if (pValue < m_timestep) pValue = m_timestep; m_angularFrictionTimescale = new Vector3(pValue, pValue, pValue); break; case Vehicle.ANGULAR_MOTOR_DIRECTION: m_angularMotorDirection = new Vector3(pValue, pValue, pValue); len = m_angularMotorDirection.Length(); if (len > 12.566f) m_angularMotorDirection *= (12.566f / len); m_amEfect = 1.0f ; // turn it on m_amDecay = 1.0f - 1.0f / m_angularMotorDecayTimescale; if (rootPrim.Body != IntPtr.Zero && !d.BodyIsEnabled(rootPrim.Body) && !rootPrim.m_isSelected && !rootPrim.m_disabled) d.BodyEnable(rootPrim.Body); break; case Vehicle.LINEAR_FRICTION_TIMESCALE: if (pValue < m_timestep) pValue = m_timestep; m_linearFrictionTimescale = new Vector3(pValue, pValue, pValue); break; case Vehicle.LINEAR_MOTOR_DIRECTION: m_linearMotorDirection = new Vector3(pValue, pValue, pValue); len = m_linearMotorDirection.Length(); if (len > 100.0f) m_linearMotorDirection *= (100.0f / len); m_lmDecay = 1.0f - 1.0f / m_linearMotorDecayTimescale; m_lmEfect = 1.0f; // turn it on m_ffactor = 0.0f; if (rootPrim.Body != IntPtr.Zero && !d.BodyIsEnabled(rootPrim.Body) && !rootPrim.m_isSelected && !rootPrim.m_disabled) d.BodyEnable(rootPrim.Body); break; case Vehicle.LINEAR_MOTOR_OFFSET: m_linearMotorOffset = new Vector3(pValue, pValue, pValue); len = m_linearMotorOffset.Length(); if (len > 100.0f) m_linearMotorOffset *= (100.0f / len); break; } }//end ProcessFloatVehicleParam internal void ProcessVectorVehicleParam(Vehicle pParam, Vector3 pValue) { float len; switch (pParam) { case Vehicle.ANGULAR_FRICTION_TIMESCALE: if (pValue.X < m_timestep) pValue.X = m_timestep; if (pValue.Y < m_timestep) pValue.Y = m_timestep; if (pValue.Z < m_timestep) pValue.Z = m_timestep; m_angularFrictionTimescale = new Vector3(pValue.X, pValue.Y, pValue.Z); break; case Vehicle.ANGULAR_MOTOR_DIRECTION: m_angularMotorDirection = new Vector3(pValue.X, pValue.Y, pValue.Z); // Limit requested angular speed to 2 rps= 4 pi rads/sec len = m_angularMotorDirection.Length(); if (len > 12.566f) m_angularMotorDirection *= (12.566f / len); m_amEfect = 1.0f; // turn it on m_amDecay = 1.0f - 1.0f / m_angularMotorDecayTimescale; if (rootPrim.Body != IntPtr.Zero && !d.BodyIsEnabled(rootPrim.Body) && !rootPrim.m_isSelected && !rootPrim.m_disabled) d.BodyEnable(rootPrim.Body); break; case Vehicle.LINEAR_FRICTION_TIMESCALE: if (pValue.X < m_timestep) pValue.X = m_timestep; if (pValue.Y < m_timestep) pValue.Y = m_timestep; if (pValue.Z < m_timestep) pValue.Z = m_timestep; m_linearFrictionTimescale = new Vector3(pValue.X, pValue.Y, pValue.Z); break; case Vehicle.LINEAR_MOTOR_DIRECTION: m_linearMotorDirection = new Vector3(pValue.X, pValue.Y, pValue.Z); len = m_linearMotorDirection.Length(); if (len > 100.0f) m_linearMotorDirection *= (100.0f / len); m_lmEfect = 1.0f; // turn it on m_lmDecay = 1.0f - 1.0f / m_linearMotorDecayTimescale; m_ffactor = 0.0f; if (rootPrim.Body != IntPtr.Zero && !d.BodyIsEnabled(rootPrim.Body) && !rootPrim.m_isSelected && !rootPrim.m_disabled) d.BodyEnable(rootPrim.Body); break; case Vehicle.LINEAR_MOTOR_OFFSET: m_linearMotorOffset = new Vector3(pValue.X, pValue.Y, pValue.Z); len = m_linearMotorOffset.Length(); if (len > 100.0f) m_linearMotorOffset *= (100.0f / len); break; case Vehicle.BLOCK_EXIT: m_BlockingEndPoint = new Vector3(pValue.X, pValue.Y, pValue.Z); break; } }//end ProcessVectorVehicleParam internal void ProcessRotationVehicleParam(Vehicle pParam, Quaternion pValue) { switch (pParam) { case Vehicle.REFERENCE_FRAME: // m_referenceFrame = Quaternion.Inverse(pValue); m_referenceFrame = pValue; break; case Vehicle.ROLL_FRAME: m_RollreferenceFrame = pValue; break; } }//end ProcessRotationVehicleParam internal void ProcessVehicleFlags(int pParam, bool remove) { if (remove) { m_flags &= ~((VehicleFlag)pParam); } else { m_flags |= (VehicleFlag)pParam; } }//end ProcessVehicleFlags internal void ProcessTypeChange(Vehicle pType) { m_lmEfect = 0; m_amEfect = 0; m_ffactor = 1f; m_linearMotorDirection = Vector3.Zero; m_angularMotorDirection = Vector3.Zero; m_BlockingEndPoint = Vector3.Zero; m_RollreferenceFrame = Quaternion.Identity; m_linearMotorOffset = Vector3.Zero; m_referenceFrame = Quaternion.Identity; // Set Defaults For Type m_type = pType; switch (pType) { case Vehicle.TYPE_NONE: m_linearFrictionTimescale = new Vector3(1000, 1000, 1000); m_angularFrictionTimescale = new Vector3(1000, 1000, 1000); m_linearMotorTimescale = 1000; m_linearMotorDecayTimescale = 120 * m_invtimestep; m_angularMotorTimescale = 1000; m_angularMotorDecayTimescale = 1000 * m_invtimestep; m_VhoverHeight = 0; m_VhoverEfficiency = 1; m_VhoverTimescale = 1000; m_VehicleBuoyancy = 0; m_linearDeflectionEfficiency = 0; m_linearDeflectionTimescale = 1000; m_angularDeflectionEfficiency = 0; m_angularDeflectionTimescale = 1000; m_bankingEfficiency = 0; m_bankingMix = 1; m_bankingTimescale = 1000; m_verticalAttractionEfficiency = 0; m_verticalAttractionTimescale = 1000; m_flags = (VehicleFlag)0; break; case Vehicle.TYPE_SLED: m_linearFrictionTimescale = new Vector3(30, 1, 1000); m_angularFrictionTimescale = new Vector3(1000, 1000, 1000); m_linearMotorTimescale = 1000; m_linearMotorDecayTimescale = 120 * m_invtimestep; m_angularMotorTimescale = 1000; m_angularMotorDecayTimescale = 120 * m_invtimestep; m_VhoverHeight = 0; m_VhoverEfficiency = 1; m_VhoverTimescale = 10; m_VehicleBuoyancy = 0; m_linearDeflectionEfficiency = 1; m_linearDeflectionTimescale = 1; m_angularDeflectionEfficiency = 0; m_angularDeflectionTimescale = 10; m_verticalAttractionEfficiency = 1; m_verticalAttractionTimescale = 1000; m_bankingEfficiency = 0; m_bankingMix = 1; m_bankingTimescale = 10; m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT | VehicleFlag.HOVER_UP_ONLY); m_flags |= (VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_ROLL_ONLY | VehicleFlag.LIMIT_MOTOR_UP); break; case Vehicle.TYPE_CAR: m_linearFrictionTimescale = new Vector3(100, 2, 1000); m_angularFrictionTimescale = new Vector3(1000, 1000, 1000); m_linearMotorTimescale = 1; m_linearMotorDecayTimescale = 60 * m_invtimestep; m_angularMotorTimescale = 1; m_angularMotorDecayTimescale = 0.8f * m_invtimestep; m_VhoverHeight = 0; m_VhoverEfficiency = 0; m_VhoverTimescale = 1000; m_VehicleBuoyancy = 0; m_linearDeflectionEfficiency = 1; m_linearDeflectionTimescale = 2; m_angularDeflectionEfficiency = 0; m_angularDeflectionTimescale = 10; m_verticalAttractionEfficiency = 1f; m_verticalAttractionTimescale = 10f; m_bankingEfficiency = -0.2f; m_bankingMix = 1; m_bankingTimescale = 1; m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT); m_flags |= (VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_ROLL_ONLY | VehicleFlag.LIMIT_MOTOR_UP | VehicleFlag.HOVER_UP_ONLY); break; case Vehicle.TYPE_BOAT: m_linearFrictionTimescale = new Vector3(10, 3, 2); m_angularFrictionTimescale = new Vector3(10, 10, 10); m_linearMotorTimescale = 5; m_linearMotorDecayTimescale = 60 * m_invtimestep; m_angularMotorTimescale = 4; m_angularMotorDecayTimescale = 4 * m_invtimestep; m_VhoverHeight = 0; m_VhoverEfficiency = 0.5f; m_VhoverTimescale = 2; m_VehicleBuoyancy = 1; m_linearDeflectionEfficiency = 0.5f; m_linearDeflectionTimescale = 3; m_angularDeflectionEfficiency = 0.5f; m_angularDeflectionTimescale = 5; m_verticalAttractionEfficiency = 0.5f; m_verticalAttractionTimescale = 5f; m_bankingEfficiency = -0.3f; m_bankingMix = 0.8f; m_bankingTimescale = 1; m_flags &= ~(VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT | VehicleFlag.HOVER_UP_ONLY); // | // VehicleFlag.LIMIT_ROLL_ONLY); m_flags |= (VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_MOTOR_UP | VehicleFlag.HOVER_UP_ONLY | // new sl VehicleFlag.HOVER_WATER_ONLY); break; case Vehicle.TYPE_AIRPLANE: m_linearFrictionTimescale = new Vector3(200, 10, 5); m_angularFrictionTimescale = new Vector3(20, 20, 20); m_linearMotorTimescale = 2; m_linearMotorDecayTimescale = 60 * m_invtimestep; m_angularMotorTimescale = 4; m_angularMotorDecayTimescale = 8 * m_invtimestep; m_VhoverHeight = 0; m_VhoverEfficiency = 0.5f; m_VhoverTimescale = 1000; m_VehicleBuoyancy = 0; m_linearDeflectionEfficiency = 0.5f; m_linearDeflectionTimescale = 0.5f; m_angularDeflectionEfficiency = 1; m_angularDeflectionTimescale = 2; m_verticalAttractionEfficiency = 0.9f; m_verticalAttractionTimescale = 2f; m_bankingEfficiency = 1; m_bankingMix = 0.7f; m_bankingTimescale = 2; m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_GLOBAL_HEIGHT | VehicleFlag.HOVER_UP_ONLY | VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_MOTOR_UP); m_flags |= (VehicleFlag.LIMIT_ROLL_ONLY); break; case Vehicle.TYPE_BALLOON: m_linearFrictionTimescale = new Vector3(5, 5, 5); m_angularFrictionTimescale = new Vector3(10, 10, 10); m_linearMotorTimescale = 5; m_linearMotorDecayTimescale = 60 * m_invtimestep; m_angularMotorTimescale = 6; m_angularMotorDecayTimescale = 10 * m_invtimestep; m_VhoverHeight = 5; m_VhoverEfficiency = 0.8f; m_VhoverTimescale = 10; m_VehicleBuoyancy = 1; m_linearDeflectionEfficiency = 0; m_linearDeflectionTimescale = 5 * m_invtimestep; m_angularDeflectionEfficiency = 0; m_angularDeflectionTimescale = 5; m_verticalAttractionEfficiency = 1f; m_verticalAttractionTimescale = 1000f; m_bankingEfficiency = 0; m_bankingMix = 0.7f; m_bankingTimescale = 5; m_flags &= ~(VehicleFlag.HOVER_WATER_ONLY | VehicleFlag.HOVER_TERRAIN_ONLY | VehicleFlag.HOVER_UP_ONLY | VehicleFlag.NO_DEFLECTION_UP | VehicleFlag.LIMIT_MOTOR_UP | //); VehicleFlag.LIMIT_ROLL_ONLY | // new sl VehicleFlag.HOVER_GLOBAL_HEIGHT); // new sl // m_flags |= (VehicleFlag.LIMIT_ROLL_ONLY | // VehicleFlag.HOVER_GLOBAL_HEIGHT); break; } // disable mouse steering m_flags &= ~(VehicleFlag.MOUSELOOK_STEER | VehicleFlag.MOUSELOOK_BANK | VehicleFlag.CAMERA_DECOUPLED); m_lmDecay = (1.0f - 1.0f / m_linearMotorDecayTimescale); m_amDecay = 1.0f - 1.0f / m_angularMotorDecayTimescale; }//end SetDefaultsForType internal void Stop() { m_lmEfect = 0; m_lmDecay = 0f; m_amEfect = 0; m_amDecay = 0; m_ffactor = 1f; } public static Vector3 Xrot(Quaternion rot) { Vector3 vec; rot.Normalize(); // just in case vec.X = 2 * (rot.X * rot.X + rot.W * rot.W) - 1; vec.Y = 2 * (rot.X * rot.Y + rot.Z * rot.W); vec.Z = 2 * (rot.X * rot.Z - rot.Y * rot.W); return vec; } public static Vector3 Zrot(Quaternion rot) { Vector3 vec; rot.Normalize(); // just in case vec.X = 2 * (rot.X * rot.Z + rot.Y * rot.W); vec.Y = 2 * (rot.Y * rot.Z - rot.X * rot.W); vec.Z = 2 * (rot.Z * rot.Z + rot.W * rot.W) - 1; return vec; } private const float pi = (float)Math.PI; private const float halfpi = 0.5f * (float)Math.PI; private const float twopi = 2.0f * pi; public static Vector3 ubRot2Euler(Quaternion rot) { // returns roll in X // pitch in Y // yaw in Z Vector3 vec; // assuming rot is normalised // rot.Normalize(); float zX = rot.X * rot.Z + rot.Y * rot.W; if (zX < -0.49999f) { vec.X = 0; vec.Y = -halfpi; vec.Z = (float)(-2d * Math.Atan(rot.X / rot.W)); } else if (zX > 0.49999f) { vec.X = 0; vec.Y = halfpi; vec.Z = (float)(2d * Math.Atan(rot.X / rot.W)); } else { vec.Y = (float)Math.Asin(2 * zX); float sqw = rot.W * rot.W; float minuszY = rot.X * rot.W - rot.Y * rot.Z; float zZ = rot.Z * rot.Z + sqw - 0.5f; vec.X = (float)Math.Atan2(minuszY, zZ); float yX = rot.Z * rot.W - rot.X * rot.Y; //( have negative ?) float yY = rot.X * rot.X + sqw - 0.5f; vec.Z = (float)Math.Atan2(yX, yY); } return vec; } public static void GetRollPitch(Quaternion rot, out float roll, out float pitch) { // assuming rot is normalised // rot.Normalize(); float zX = rot.X * rot.Z + rot.Y * rot.W; if (zX < -0.49999f) { roll = 0; pitch = -halfpi; } else if (zX > 0.49999f) { roll = 0; pitch = halfpi; } else { pitch = (float)Math.Asin(2 * zX); float minuszY = rot.X * rot.W - rot.Y * rot.Z; float zZ = rot.Z * rot.Z + rot.W * rot.W - 0.5f; roll = (float)Math.Atan2(minuszY, zZ); } return ; } internal void Step() { IntPtr Body = rootPrim.Body; d.Mass dmass; d.BodyGetMass(Body, out dmass); d.Quaternion rot = d.BodyGetQuaternion(Body); Quaternion objrotq = new Quaternion(rot.X, rot.Y, rot.Z, rot.W); // rotq = rotation of object Quaternion rotq = objrotq; // rotq = rotation of object rotq *= m_referenceFrame; // rotq is now rotation in vehicle reference frame Quaternion irotq = Quaternion.Inverse(rotq); d.Vector3 dvtmp; Vector3 tmpV; Vector3 curVel; // velocity in world Vector3 curAngVel; // angular velocity in world Vector3 force = Vector3.Zero; // actually linear aceleration until mult by mass in world frame Vector3 torque = Vector3.Zero;// actually angular aceleration until mult by Inertia in vehicle frame d.Vector3 dtorque = new d.Vector3(); dvtmp = d.BodyGetLinearVel(Body); curVel.X = dvtmp.X; curVel.Y = dvtmp.Y; curVel.Z = dvtmp.Z; Vector3 curLocalVel = curVel * irotq; // current velocity in local dvtmp = d.BodyGetAngularVel(Body); curAngVel.X = dvtmp.X; curAngVel.Y = dvtmp.Y; curAngVel.Z = dvtmp.Z; Vector3 curLocalAngVel = curAngVel * irotq; // current angular velocity in local float ldampZ = 0; bool mousemode = false; bool mousemodebank = false; float bankingEfficiency; float verticalAttractionTimescale = m_verticalAttractionTimescale; if((m_flags & (VehicleFlag.MOUSELOOK_STEER | VehicleFlag.MOUSELOOK_BANK)) != 0 ) { mousemode = true; mousemodebank = (m_flags & VehicleFlag.MOUSELOOK_BANK) != 0; if(mousemodebank) { bankingEfficiency = m_bankingEfficiency; if(verticalAttractionTimescale < 149.9) verticalAttractionTimescale *= 2.0f; // reduce current instability } else bankingEfficiency = 0; } else bankingEfficiency = m_bankingEfficiency; // linear motor if (m_lmEfect > 0.01 && m_linearMotorTimescale < 1000) { tmpV = m_linearMotorDirection - curLocalVel; // velocity error tmpV *= m_lmEfect / m_linearMotorTimescale; // error to correct in this timestep tmpV *= rotq; // to world if ((m_flags & VehicleFlag.LIMIT_MOTOR_UP) != 0) tmpV.Z = 0; if (m_linearMotorOffset.X != 0 || m_linearMotorOffset.Y != 0 || m_linearMotorOffset.Z != 0) { // have offset, do it now tmpV *= dmass.mass; d.BodyAddForceAtRelPos(Body, tmpV.X, tmpV.Y, tmpV.Z, m_linearMotorOffset.X, m_linearMotorOffset.Y, m_linearMotorOffset.Z); } else { force.X += tmpV.X; force.Y += tmpV.Y; force.Z += tmpV.Z; } m_lmEfect *= m_lmDecay; // m_ffactor = 0.01f + 1e-4f * curVel.LengthSquared(); m_ffactor = 0.0f; } else { m_lmEfect = 0; m_ffactor = 1f; } // hover if (m_VhoverTimescale < 300 && rootPrim.prim_geom != IntPtr.Zero) { // d.Vector3 pos = d.BodyGetPosition(Body); d.Vector3 pos = d.GeomGetPosition(rootPrim.prim_geom); pos.Z -= 0.21f; // minor offset that seems to be always there in sl float t = _pParentScene.GetTerrainHeightAtXY(pos.X, pos.Y); float perr; // default to global but don't go underground perr = m_VhoverHeight - pos.Z; if ((m_flags & VehicleFlag.HOVER_GLOBAL_HEIGHT) == 0) { if ((m_flags & VehicleFlag.HOVER_WATER_ONLY) != 0) { perr += _pParentScene.GetWaterLevel(); } else if ((m_flags & VehicleFlag.HOVER_TERRAIN_ONLY) != 0) { perr += t; } else { float w = _pParentScene.GetWaterLevel(); if (t > w) perr += t; else perr += w; } } else if (t > m_VhoverHeight) perr = t - pos.Z; ; if ((m_flags & VehicleFlag.HOVER_UP_ONLY) == 0 || perr > -0.1) { ldampZ = m_VhoverEfficiency * m_invtimestep; perr *= (1.0f + ldampZ) / m_VhoverTimescale; // force.Z += perr - curVel.Z * tmp; force.Z += perr; ldampZ *= -curVel.Z; force.Z += _pParentScene.gravityz * m_gravmod * (1f - m_VehicleBuoyancy); } else // no buoyancy force.Z += _pParentScene.gravityz; } else { // default gravity and Buoyancy force.Z += _pParentScene.gravityz * m_gravmod * (1f - m_VehicleBuoyancy); } // linear deflection if (m_linearDeflectionEfficiency > 0) { float len = curVel.Length(); if (len > 0.01) // if moving { Vector3 atAxis; atAxis = Xrot(rotq); // where are we pointing to atAxis *= len; // make it same size as world velocity vector tmpV = -atAxis; // oposite direction atAxis -= curVel; // error to one direction len = atAxis.LengthSquared(); tmpV -= curVel; // error to oposite float lens = tmpV.LengthSquared(); if (len > 0.01 || lens > 0.01) // do nothing if close enougth { if (len < lens) tmpV = atAxis; tmpV *= (m_linearDeflectionEfficiency / m_linearDeflectionTimescale); // error to correct in this timestep force.X += tmpV.X; force.Y += tmpV.Y; if ((m_flags & VehicleFlag.NO_DEFLECTION_UP) == 0) force.Z += tmpV.Z; } } } // linear friction/damping if (curLocalVel.X != 0 || curLocalVel.Y != 0 || curLocalVel.Z != 0) { tmpV.X = -curLocalVel.X / m_linearFrictionTimescale.X; tmpV.Y = -curLocalVel.Y / m_linearFrictionTimescale.Y; tmpV.Z = -curLocalVel.Z / m_linearFrictionTimescale.Z; tmpV *= rotq; // to world if(ldampZ != 0 && Math.Abs(ldampZ) > Math.Abs(tmpV.Z)) tmpV.Z = ldampZ; force.X += tmpV.X; force.Y += tmpV.Y; force.Z += tmpV.Z; } // vertical atractor if (verticalAttractionTimescale < 300) { float roll; float pitch; float ftmp = m_invtimestep / verticalAttractionTimescale / verticalAttractionTimescale; float ftmp2; ftmp2 = 0.5f * m_verticalAttractionEfficiency * m_invtimestep; m_amdampX = ftmp2; m_ampwr = 1.0f - 0.8f * m_verticalAttractionEfficiency; GetRollPitch(irotq, out roll, out pitch); if (roll > halfpi) roll = pi - roll; else if (roll < -halfpi) roll = -pi - roll; float effroll = pitch / halfpi; effroll *= effroll; effroll = 1 - effroll; effroll *= roll; torque.X += effroll * ftmp; if ((m_flags & VehicleFlag.LIMIT_ROLL_ONLY) == 0) { float effpitch = roll / halfpi; effpitch *= effpitch; effpitch = 1 - effpitch; effpitch *= pitch; torque.Y += effpitch * ftmp; } if (bankingEfficiency != 0 && Math.Abs(effroll) > 0.01) { float broll = effroll; /* if (broll > halfpi) broll = pi - broll; else if (broll < -halfpi) broll = -pi - broll; */ broll *= m_bankingEfficiency; if (m_bankingMix != 0) { float vfact = Math.Abs(curLocalVel.X) / 10.0f; if (vfact > 1.0f) vfact = 1.0f; if (curLocalVel.X >= 0) broll *= (1 + (vfact - 1) * m_bankingMix); else broll *= -(1 + (vfact - 1) * m_bankingMix); } // make z rot be in world Z not local as seems to be in sl broll = broll / m_bankingTimescale; tmpV = Zrot(irotq); tmpV *= broll; torque.X += tmpV.X; torque.Y += tmpV.Y; torque.Z += tmpV.Z; m_amdampZ = Math.Abs(m_bankingEfficiency) / m_bankingTimescale; m_amdampY = m_amdampZ; } else { m_amdampZ = 1 / m_angularFrictionTimescale.Z; m_amdampY = m_amdampX; } } else { m_ampwr = 1.0f; m_amdampX = 1 / m_angularFrictionTimescale.X; m_amdampY = 1 / m_angularFrictionTimescale.Y; m_amdampZ = 1 / m_angularFrictionTimescale.Z; } if(mousemode) { CameraData cam = rootPrim.TryGetCameraData(); if(cam.Valid && cam.MouseLook) { Vector3 dirv = cam.CameraAtAxis * irotq; float invamts = 1.0f/m_angularMotorTimescale; float tmp; // get out of x == 0 plane if(Math.Abs(dirv.X) < 0.001f) dirv.X = 0.001f; if (Math.Abs(dirv.Z) > 0.01) { tmp = -(float)Math.Atan2(dirv.Z, dirv.X) * m_angularMotorDirection.Y; if(tmp < -4f) tmp = -4f; else if(tmp > 4f) tmp = 4f; torque.Y += (tmp - curLocalAngVel.Y) * invamts; torque.Y -= curLocalAngVel.Y * m_amdampY; } else torque.Y -= curLocalAngVel.Y * m_invtimestep; if (Math.Abs(dirv.Y) > 0.01) { if(mousemodebank) { tmp = -(float)Math.Atan2(dirv.Y, dirv.X) * m_angularMotorDirection.X; if(tmp < -4f) tmp = -4f; else if(tmp > 4f) tmp = 4f; torque.X += (tmp - curLocalAngVel.X) * invamts; } else { tmp = (float)Math.Atan2(dirv.Y, dirv.X) * m_angularMotorDirection.Z; tmp *= invamts; if(tmp < -4f) tmp = -4f; else if(tmp > 4f) tmp = 4f; torque.Z += (tmp - curLocalAngVel.Z) * invamts; } torque.X -= curLocalAngVel.X * m_amdampX; torque.Z -= curLocalAngVel.Z * m_amdampZ; } else { if(mousemodebank) torque.X -= curLocalAngVel.X * m_invtimestep; else torque.Z -= curLocalAngVel.Z * m_invtimestep; } } else { if (curLocalAngVel.X != 0 || curLocalAngVel.Y != 0 || curLocalAngVel.Z != 0) { torque.X -= curLocalAngVel.X * 10f; torque.Y -= curLocalAngVel.Y * 10f; torque.Z -= curLocalAngVel.Z * 10f; } } } else { // angular motor if (m_amEfect > 0.01 && m_angularMotorTimescale < 1000) { tmpV = m_angularMotorDirection - curLocalAngVel; // velocity error tmpV *= m_amEfect / m_angularMotorTimescale; // error to correct in this timestep torque.X += tmpV.X * m_ampwr; torque.Y += tmpV.Y * m_ampwr; torque.Z += tmpV.Z; m_amEfect *= m_amDecay; } else m_amEfect = 0; // angular deflection if (m_angularDeflectionEfficiency > 0) { Vector3 dirv; if (curLocalVel.X > 0.01f) dirv = curLocalVel; else if (curLocalVel.X < -0.01f) // use oposite dirv = -curLocalVel; else { // make it fall into small positive x case dirv.X = 0.01f; dirv.Y = curLocalVel.Y; dirv.Z = curLocalVel.Z; } float ftmp = m_angularDeflectionEfficiency / m_angularDeflectionTimescale; if (Math.Abs(dirv.Z) > 0.01) { torque.Y += - (float)Math.Atan2(dirv.Z, dirv.X) * ftmp; } if (Math.Abs(dirv.Y) > 0.01) { torque.Z += (float)Math.Atan2(dirv.Y, dirv.X) * ftmp; } } if (curLocalAngVel.X != 0 || curLocalAngVel.Y != 0 || curLocalAngVel.Z != 0) { torque.X -= curLocalAngVel.X * m_amdampX; torque.Y -= curLocalAngVel.Y * m_amdampY; torque.Z -= curLocalAngVel.Z * m_amdampZ; } } force *= dmass.mass; force += rootPrim.m_force; force += rootPrim.m_forceacc; rootPrim.m_forceacc = Vector3.Zero; if (force.X != 0 || force.Y != 0 || force.Z != 0) { d.BodyAddForce(Body, force.X, force.Y, force.Z); } if (torque.X != 0 || torque.Y != 0 || torque.Z != 0) { torque *= m_referenceFrame; // to object frame dtorque.X = torque.X ; dtorque.Y = torque.Y; dtorque.Z = torque.Z; d.MultiplyM3V3(out dvtmp, ref dmass.I, ref dtorque); d.BodyAddRelTorque(Body, dvtmp.X, dvtmp.Y, dvtmp.Z); // add torque in object frame } torque = rootPrim.m_torque; torque += rootPrim.m_angularForceacc; rootPrim.m_angularForceacc = Vector3.Zero; if (torque.X != 0 || torque.Y != 0 || torque.Z != 0) d.BodyAddTorque(Body,torque.X, torque.Y, torque.Z); } } }
// 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 gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.StorageTransfer.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedStorageTransferServiceClientTest { [xunit::FactAttribute] public void GetGoogleServiceAccountRequestObject() { moq::Mock<StorageTransferService.StorageTransferServiceClient> mockGrpcClient = new moq::Mock<StorageTransferService.StorageTransferServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGoogleServiceAccountRequest request = new GetGoogleServiceAccountRequest { ProjectId = "project_id43ad98b0", }; GoogleServiceAccount expectedResponse = new GoogleServiceAccount { AccountEmail = "account_email01cc68b0", SubjectId = "subject_idd1a1abff", }; mockGrpcClient.Setup(x => x.GetGoogleServiceAccount(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); StorageTransferServiceClient client = new StorageTransferServiceClientImpl(mockGrpcClient.Object, null); GoogleServiceAccount response = client.GetGoogleServiceAccount(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetGoogleServiceAccountRequestObjectAsync() { moq::Mock<StorageTransferService.StorageTransferServiceClient> mockGrpcClient = new moq::Mock<StorageTransferService.StorageTransferServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGoogleServiceAccountRequest request = new GetGoogleServiceAccountRequest { ProjectId = "project_id43ad98b0", }; GoogleServiceAccount expectedResponse = new GoogleServiceAccount { AccountEmail = "account_email01cc68b0", SubjectId = "subject_idd1a1abff", }; mockGrpcClient.Setup(x => x.GetGoogleServiceAccountAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GoogleServiceAccount>(stt::Task.FromResult(expectedResponse), null, null, null, null)); StorageTransferServiceClient client = new StorageTransferServiceClientImpl(mockGrpcClient.Object, null); GoogleServiceAccount responseCallSettings = await client.GetGoogleServiceAccountAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); GoogleServiceAccount responseCancellationToken = await client.GetGoogleServiceAccountAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateTransferJobRequestObject() { moq::Mock<StorageTransferService.StorageTransferServiceClient> mockGrpcClient = new moq::Mock<StorageTransferService.StorageTransferServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateTransferJobRequest request = new CreateTransferJobRequest { TransferJob = new TransferJob(), }; TransferJob expectedResponse = new TransferJob { Name = "name1c9368b0", Description = "description2cf9da67", ProjectId = "project_id43ad98b0", TransferSpec = new TransferSpec(), Schedule = new Schedule(), Status = TransferJob.Types.Status.Disabled, CreationTime = new wkt::Timestamp(), LastModificationTime = new wkt::Timestamp(), DeletionTime = new wkt::Timestamp(), NotificationConfig = new NotificationConfig(), LatestOperationName = "latest_operation_namef5a455e9", }; mockGrpcClient.Setup(x => x.CreateTransferJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); StorageTransferServiceClient client = new StorageTransferServiceClientImpl(mockGrpcClient.Object, null); TransferJob response = client.CreateTransferJob(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateTransferJobRequestObjectAsync() { moq::Mock<StorageTransferService.StorageTransferServiceClient> mockGrpcClient = new moq::Mock<StorageTransferService.StorageTransferServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CreateTransferJobRequest request = new CreateTransferJobRequest { TransferJob = new TransferJob(), }; TransferJob expectedResponse = new TransferJob { Name = "name1c9368b0", Description = "description2cf9da67", ProjectId = "project_id43ad98b0", TransferSpec = new TransferSpec(), Schedule = new Schedule(), Status = TransferJob.Types.Status.Disabled, CreationTime = new wkt::Timestamp(), LastModificationTime = new wkt::Timestamp(), DeletionTime = new wkt::Timestamp(), NotificationConfig = new NotificationConfig(), LatestOperationName = "latest_operation_namef5a455e9", }; mockGrpcClient.Setup(x => x.CreateTransferJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TransferJob>(stt::Task.FromResult(expectedResponse), null, null, null, null)); StorageTransferServiceClient client = new StorageTransferServiceClientImpl(mockGrpcClient.Object, null); TransferJob responseCallSettings = await client.CreateTransferJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TransferJob responseCancellationToken = await client.CreateTransferJobAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateTransferJobRequestObject() { moq::Mock<StorageTransferService.StorageTransferServiceClient> mockGrpcClient = new moq::Mock<StorageTransferService.StorageTransferServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateTransferJobRequest request = new UpdateTransferJobRequest { JobName = "job_namedc176648", ProjectId = "project_id43ad98b0", TransferJob = new TransferJob(), UpdateTransferJobFieldMask = new wkt::FieldMask(), }; TransferJob expectedResponse = new TransferJob { Name = "name1c9368b0", Description = "description2cf9da67", ProjectId = "project_id43ad98b0", TransferSpec = new TransferSpec(), Schedule = new Schedule(), Status = TransferJob.Types.Status.Disabled, CreationTime = new wkt::Timestamp(), LastModificationTime = new wkt::Timestamp(), DeletionTime = new wkt::Timestamp(), NotificationConfig = new NotificationConfig(), LatestOperationName = "latest_operation_namef5a455e9", }; mockGrpcClient.Setup(x => x.UpdateTransferJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); StorageTransferServiceClient client = new StorageTransferServiceClientImpl(mockGrpcClient.Object, null); TransferJob response = client.UpdateTransferJob(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateTransferJobRequestObjectAsync() { moq::Mock<StorageTransferService.StorageTransferServiceClient> mockGrpcClient = new moq::Mock<StorageTransferService.StorageTransferServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); UpdateTransferJobRequest request = new UpdateTransferJobRequest { JobName = "job_namedc176648", ProjectId = "project_id43ad98b0", TransferJob = new TransferJob(), UpdateTransferJobFieldMask = new wkt::FieldMask(), }; TransferJob expectedResponse = new TransferJob { Name = "name1c9368b0", Description = "description2cf9da67", ProjectId = "project_id43ad98b0", TransferSpec = new TransferSpec(), Schedule = new Schedule(), Status = TransferJob.Types.Status.Disabled, CreationTime = new wkt::Timestamp(), LastModificationTime = new wkt::Timestamp(), DeletionTime = new wkt::Timestamp(), NotificationConfig = new NotificationConfig(), LatestOperationName = "latest_operation_namef5a455e9", }; mockGrpcClient.Setup(x => x.UpdateTransferJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TransferJob>(stt::Task.FromResult(expectedResponse), null, null, null, null)); StorageTransferServiceClient client = new StorageTransferServiceClientImpl(mockGrpcClient.Object, null); TransferJob responseCallSettings = await client.UpdateTransferJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TransferJob responseCancellationToken = await client.UpdateTransferJobAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTransferJobRequestObject() { moq::Mock<StorageTransferService.StorageTransferServiceClient> mockGrpcClient = new moq::Mock<StorageTransferService.StorageTransferServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTransferJobRequest request = new GetTransferJobRequest { JobName = "job_namedc176648", ProjectId = "project_id43ad98b0", }; TransferJob expectedResponse = new TransferJob { Name = "name1c9368b0", Description = "description2cf9da67", ProjectId = "project_id43ad98b0", TransferSpec = new TransferSpec(), Schedule = new Schedule(), Status = TransferJob.Types.Status.Disabled, CreationTime = new wkt::Timestamp(), LastModificationTime = new wkt::Timestamp(), DeletionTime = new wkt::Timestamp(), NotificationConfig = new NotificationConfig(), LatestOperationName = "latest_operation_namef5a455e9", }; mockGrpcClient.Setup(x => x.GetTransferJob(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); StorageTransferServiceClient client = new StorageTransferServiceClientImpl(mockGrpcClient.Object, null); TransferJob response = client.GetTransferJob(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTransferJobRequestObjectAsync() { moq::Mock<StorageTransferService.StorageTransferServiceClient> mockGrpcClient = new moq::Mock<StorageTransferService.StorageTransferServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetTransferJobRequest request = new GetTransferJobRequest { JobName = "job_namedc176648", ProjectId = "project_id43ad98b0", }; TransferJob expectedResponse = new TransferJob { Name = "name1c9368b0", Description = "description2cf9da67", ProjectId = "project_id43ad98b0", TransferSpec = new TransferSpec(), Schedule = new Schedule(), Status = TransferJob.Types.Status.Disabled, CreationTime = new wkt::Timestamp(), LastModificationTime = new wkt::Timestamp(), DeletionTime = new wkt::Timestamp(), NotificationConfig = new NotificationConfig(), LatestOperationName = "latest_operation_namef5a455e9", }; mockGrpcClient.Setup(x => x.GetTransferJobAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TransferJob>(stt::Task.FromResult(expectedResponse), null, null, null, null)); StorageTransferServiceClient client = new StorageTransferServiceClientImpl(mockGrpcClient.Object, null); TransferJob responseCallSettings = await client.GetTransferJobAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TransferJob responseCancellationToken = await client.GetTransferJobAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void PauseTransferOperationRequestObject() { moq::Mock<StorageTransferService.StorageTransferServiceClient> mockGrpcClient = new moq::Mock<StorageTransferService.StorageTransferServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); PauseTransferOperationRequest request = new PauseTransferOperationRequest { Name = "name1c9368b0", }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.PauseTransferOperation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); StorageTransferServiceClient client = new StorageTransferServiceClientImpl(mockGrpcClient.Object, null); client.PauseTransferOperation(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task PauseTransferOperationRequestObjectAsync() { moq::Mock<StorageTransferService.StorageTransferServiceClient> mockGrpcClient = new moq::Mock<StorageTransferService.StorageTransferServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); PauseTransferOperationRequest request = new PauseTransferOperationRequest { Name = "name1c9368b0", }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.PauseTransferOperationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); StorageTransferServiceClient client = new StorageTransferServiceClientImpl(mockGrpcClient.Object, null); await client.PauseTransferOperationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.PauseTransferOperationAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void ResumeTransferOperationRequestObject() { moq::Mock<StorageTransferService.StorageTransferServiceClient> mockGrpcClient = new moq::Mock<StorageTransferService.StorageTransferServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ResumeTransferOperationRequest request = new ResumeTransferOperationRequest { Name = "name1c9368b0", }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.ResumeTransferOperation(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); StorageTransferServiceClient client = new StorageTransferServiceClientImpl(mockGrpcClient.Object, null); client.ResumeTransferOperation(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task ResumeTransferOperationRequestObjectAsync() { moq::Mock<StorageTransferService.StorageTransferServiceClient> mockGrpcClient = new moq::Mock<StorageTransferService.StorageTransferServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); ResumeTransferOperationRequest request = new ResumeTransferOperationRequest { Name = "name1c9368b0", }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.ResumeTransferOperationAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); StorageTransferServiceClient client = new StorageTransferServiceClientImpl(mockGrpcClient.Object, null); await client.ResumeTransferOperationAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.ResumeTransferOperationAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } } }
#region Copyright (c) 2004 Ian Davis and James Carlyle /*------------------------------------------------------------------------------ COPYRIGHT AND PERMISSION NOTICE Copyright (c) 2004 Ian Davis and James Carlyle 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 SemPlan.Spiral.Tests.DriveParser { using Drive.Rdf; using NUnit.Framework; using SemPlan.Spiral.DriveParser; using SemPlan.Spiral.Tests.Core; using System; using System.IO; /// <summary> /// Programmer tests for DriveParser class /// </summary> /// <remarks> /// $Id: DriveParserTest.cs,v 1.2 2005/05/26 14:24:30 ian Exp $ ///</remarks> [TestFixture] public class DriveParserTest { [Test] public void parserUsesResourceFactoryToCreatePredicate() { StringReader reader = new StringReader("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><rdf:Description rdf:about=\"http://example.org/node\"><rdf:type rdf:resource=\"http://example.org/type\"/></rdf:Description></rdf:RDF>"); ResourceFactoryStore resourceFactory = new ResourceFactoryStore(); DriveParser parser = new DriveParser(resourceFactory, new StatementFactoryStub() ); parser.Parse( reader, ""); Assert.IsTrue( resourceFactory.WasMakeUriRefCalledWith( "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" ) ); } [Test] public void parserUsesResourceFactoryToCreateUriRefSubject() { StringReader reader = new StringReader("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><rdf:Description rdf:about=\"http://example.org/node\"><rdf:type rdf:resource=\"http://example.org/type\"/></rdf:Description></rdf:RDF>"); ResourceFactoryStore resourceFactory = new ResourceFactoryStore(); DriveParser parser = new DriveParser(resourceFactory, new StatementFactoryStub() ); parser.Parse( reader, ""); Assert.IsTrue( resourceFactory.WasMakeUriRefCalledWith( "http://example.org/node" ) ); } [Test] public void parserUsesResourceFactoryToCreateUriRefObject() { StringReader reader = new StringReader("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><rdf:Description rdf:about=\"http://example.org/node\"><rdf:type rdf:resource=\"http://example.org/type\"/></rdf:Description></rdf:RDF>"); ResourceFactoryStore resourceFactory = new ResourceFactoryStore(); DriveParser parser = new DriveParser(resourceFactory, new StatementFactoryStub() ); parser.Parse( reader, ""); Assert.IsTrue( resourceFactory.WasMakeUriRefCalledWith( "http://example.org/type" ) ); } [Test] public void parserUsesResourceFactoryToCreateBlankSubject() { StringReader reader = new StringReader("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><rdf:Description><rdf:type rdf:resource=\"http://example.org/type\"/></rdf:Description></rdf:RDF>"); ResourceFactoryStore resourceFactory = new ResourceFactoryStore(); DriveParser parser = new DriveParser(resourceFactory, new StatementFactoryStub() ); parser.Parse( reader, ""); Assert.IsTrue( resourceFactory.WasMakeBlankNodeCalledWith( "drive10000" ) ); } [Test] public void parserUsesResourceFactoryToCreateBlankObject() { StringReader reader = new StringReader("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><rdf:Description rdf:about=\"http://example.org/node\"><rdf:type><rdf:Description /></rdf:type></rdf:Description></rdf:RDF>"); ResourceFactoryStore resourceFactory = new ResourceFactoryStore(); DriveParser parser = new DriveParser(resourceFactory, new StatementFactoryStub() ); parser.Parse( reader, ""); Assert.IsTrue( resourceFactory.WasMakeBlankNodeCalledWith( "drive10000" ) ); } [Test] public void parserUsesResourceFactoryToCreatePlainLiteralWithNoLanguageObject() { StringReader reader = new StringReader("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><rdf:Description rdf:about=\"http://example.org/node\"><rdf:type>foo</rdf:type></rdf:Description></rdf:RDF>"); ResourceFactoryStore resourceFactory = new ResourceFactoryStore(); DriveParser parser = new DriveParser(resourceFactory, new StatementFactoryStub() ); parser.Parse( reader, ""); Assert.IsTrue( resourceFactory.WasMakePlainLiteralCalledWith( "foo" ) ); } [Test] public void parserUsesResourceFactoryToCreatePlainLiteralWithLanguageObject() { StringReader reader = new StringReader("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><rdf:Description rdf:about=\"http://example.org/node\"><rdf:type xml:lang=\"pt\">foo</rdf:type></rdf:Description></rdf:RDF>"); ResourceFactoryStore resourceFactory = new ResourceFactoryStore(); DriveParser parser = new DriveParser(resourceFactory, new StatementFactoryStub() ); parser.Parse( reader, ""); Assert.IsTrue( resourceFactory.WasMakePlainLiteralCalledWith( "foo", "pt" ) ); } [Test] public void parserUsesResourceFactoryToCreateTypedLiteralObject() { StringReader reader = new StringReader("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><rdf:Description rdf:about=\"http://example.org/node\"><rdf:type rdf:datatype=\"http://example.com/type\">foo</rdf:type></rdf:Description></rdf:RDF>"); ResourceFactoryStore resourceFactory = new ResourceFactoryStore(); DriveParser parser = new DriveParser(resourceFactory, new StatementFactoryStub() ); parser.Parse( reader, ""); Assert.IsTrue( resourceFactory.WasMakeTypedLiteralCalledWith( "foo", "http://example.com/type" ) ); } [Test] public void parserUsesStatementFactoryToCreateUUUStatement() { StringReader reader = new StringReader("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><rdf:Description rdf:about=\"http://example.org/node\"><rdf:type rdf:resource=\"http://example.org/type\"/></rdf:Description></rdf:RDF>"); StatementFactoryCounter statementFactory = new StatementFactoryCounter(); DriveParser parser = new DriveParser(new ResourceFactoryStub(), statementFactory ); parser.Parse( reader, ""); Assert.AreEqual( 1, statementFactory.MakeStatementUUUCalled ); } [Test] public void parserUsesStatementFactoryToCreateBUUStatement() { StringReader reader = new StringReader("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><rdf:Description><rdf:type rdf:resource=\"http://example.org/type\"/></rdf:Description></rdf:RDF>"); StatementFactoryCounter statementFactory = new StatementFactoryCounter(); DriveParser parser = new DriveParser(new ResourceFactoryStub(), statementFactory ); parser.Parse( reader, ""); Assert.AreEqual( 1, statementFactory.MakeStatementBUUCalled ); } [Test] public void parserUsesStatementFactoryToCreateUUBStatement() { StringReader reader = new StringReader("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><rdf:Description rdf:about=\"http://example.org/node\"><rdf:type><rdf:Description/></rdf:type></rdf:Description></rdf:RDF>"); StatementFactoryCounter statementFactory = new StatementFactoryCounter(); DriveParser parser = new DriveParser(new ResourceFactoryStub(), statementFactory ); parser.Parse( reader, ""); Assert.AreEqual( 1, statementFactory.MakeStatementUUBCalled ); } [Test] public void parserUsesStatementFactoryToCreateBUBStatement() { StringReader reader = new StringReader("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><rdf:Description><rdf:type><rdf:Description/></rdf:type></rdf:Description></rdf:RDF>"); StatementFactoryCounter statementFactory = new StatementFactoryCounter(); DriveParser parser = new DriveParser(new ResourceFactoryStub(), statementFactory ); parser.Parse( reader, ""); Assert.AreEqual( 1, statementFactory.MakeStatementBUBCalled ); } [Test] public void parserUsesStatementFactoryToCreateUUPStatement() { StringReader reader = new StringReader("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><rdf:Description rdf:about=\"http://example.org/node\"><rdf:type>foo</rdf:type></rdf:Description></rdf:RDF>"); StatementFactoryCounter statementFactory = new StatementFactoryCounter(); DriveParser parser = new DriveParser(new ResourceFactoryStub(), statementFactory ); parser.Parse( reader, ""); Assert.AreEqual( 1, statementFactory.MakeStatementUUPCalled ); } [Test] public void parserUsesStatementFactoryToCreateBUPStatement() { StringReader reader = new StringReader("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><rdf:Description><rdf:type>foo</rdf:type></rdf:Description></rdf:RDF>"); StatementFactoryCounter statementFactory = new StatementFactoryCounter(); DriveParser parser = new DriveParser(new ResourceFactoryStub(), statementFactory ); parser.Parse( reader, ""); Assert.AreEqual( 1, statementFactory.MakeStatementBUPCalled ); } [Test] public void parserUsesStatementFactoryToCreateUUTStatement() { StringReader reader = new StringReader("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><rdf:Description rdf:about=\"http://example.org/node\"><rdf:type rdf:datatype=\"http://example.com/type\">foo</rdf:type></rdf:Description></rdf:RDF>"); StatementFactoryCounter statementFactory = new StatementFactoryCounter(); DriveParser parser = new DriveParser(new ResourceFactoryStub(), statementFactory ); parser.Parse( reader, ""); Assert.AreEqual( 1, statementFactory.MakeStatementUUTCalled ); } [Test] public void parserUsesStatementFactoryToCreateBUTStatement() { StringReader reader = new StringReader("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><rdf:Description><rdf:type rdf:datatype=\"http://example.com/type\">foo</rdf:type></rdf:Description></rdf:RDF>"); StatementFactoryCounter statementFactory = new StatementFactoryCounter(); DriveParser parser = new DriveParser(new ResourceFactoryStub(), statementFactory ); parser.Parse( reader, ""); Assert.AreEqual( 1, statementFactory.MakeStatementBUTCalled ); } [Test] public void parserPassesResourceFactoryObjectsToStatementFactory() { StringReader reader = new StringReader("<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"><rdf:Description rdf:about=\"http://example.org/node\"><rdf:type rdf:resource=\"http://example.org/type\"/></rdf:Description></rdf:RDF>"); StatementFactoryStore statementFactory = new StatementFactoryStore(); ResourceFactoryResponder resourceFactory = new ResourceFactoryResponder(); DriveParser parser = new DriveParser(resourceFactory, statementFactory ); parser.Parse( reader, ""); Assert.IsTrue( statementFactory.WasMakeStatementCalledWith( resourceFactory.itsUriRefResponse, resourceFactory.itsUriRefResponse, resourceFactory.itsUriRefResponse) ); } [Test] public void parserUsesSuppliedDereferencerToGetRepresentationsOfUris() { DriveParser parser = new DriveParser(new ResourceFactoryStub(), new StatementFactoryStub() ); DereferencerStore dereferencer = new DereferencerStore(); parser.SetDereferencer(dereferencer); parser.Parse(new Uri("http://example.com/"), ""); Assert.IsTrue( dereferencer.WasDereferenceCalledWith( new Uri("http://example.com/") ) ); } [Test] public void parserUsesSuppliedDereferencerToGetRepresentationsOfStringUris() { DriveParser parser = new DriveParser(new ResourceFactoryStub(), new StatementFactoryStub() ); DereferencerStore dereferencer = new DereferencerStore(); parser.SetDereferencer(dereferencer); parser.Parse( "http://example.com/", ""); Assert.IsTrue( dereferencer.WasDereferenceCalledWith( "http://example.com/" ) ); } } }
using System; using UnityEngine; using UnityEngine.Rendering; namespace UnityStandardAssets.CinematicEffects { [ExecuteInEditMode] #if UNITY_5_4_OR_NEWER [ImageEffectAllowedInSceneView] #endif [RequireComponent(typeof(Camera))] [AddComponentMenu("Image Effects/Cinematic/Screen Space Reflections")] public class ScreenSpaceReflection : MonoBehaviour { public enum SSRResolution { High = 0, Low = 2 } public enum SSRReflectionBlendType { PhysicallyBased, Additive } [Serializable] public struct SSRSettings { [AttributeUsage(AttributeTargets.Field)] public class LayoutAttribute : PropertyAttribute { } [Layout] public ReflectionSettings reflectionSettings; [Layout] public IntensitySettings intensitySettings; [Layout] public ScreenEdgeMask screenEdgeMask; private static readonly SSRSettings s_Default = new SSRSettings { reflectionSettings = new ReflectionSettings { blendType = SSRReflectionBlendType.PhysicallyBased, reflectionQuality = SSRResolution.High, maxDistance = 100.0f, iterationCount = 256, stepSize = 3, widthModifier = 0.5f, reflectionBlur = 1.0f, reflectBackfaces = true }, intensitySettings = new IntensitySettings { reflectionMultiplier = 1.0f, fadeDistance = 100.0f, fresnelFade = 1.0f, fresnelFadePower = 1.0f, }, screenEdgeMask = new ScreenEdgeMask { intensity = 0.03f } }; public static SSRSettings defaultSettings { get { return s_Default; } } } [Serializable] public struct IntensitySettings { [Tooltip("Nonphysical multiplier for the SSR reflections. 1.0 is physically based.")] [Range(0.0f, 2.0f)] public float reflectionMultiplier; [Tooltip("How far away from the maxDistance to begin fading SSR.")] [Range(0.0f, 1000.0f)] public float fadeDistance; [Tooltip("Amplify Fresnel fade out. Increase if floor reflections look good close to the surface and bad farther 'under' the floor.")] [Range(0.0f, 1.0f)] public float fresnelFade; [Tooltip("Higher values correspond to a faster Fresnel fade as the reflection changes from the grazing angle.")] [Range(0.1f, 10.0f)] public float fresnelFadePower; } [Serializable] public struct ReflectionSettings { // When enabled, we just add our reflections on top of the existing ones. This is physically incorrect, but several // popular demos and games have taken this approach, and it does hide some artifacts. [Tooltip("How the reflections are blended into the render.")] public SSRReflectionBlendType blendType; [Tooltip("Half resolution SSRR is much faster, but less accurate.")] public SSRResolution reflectionQuality; [Tooltip("Maximum reflection distance in world units.")] [Range(0.1f, 300.0f)] public float maxDistance; /// REFLECTIONS [Tooltip("Max raytracing length.")] [Range(16, 1024)] public int iterationCount; [Tooltip("Log base 2 of ray tracing coarse step size. Higher traces farther, lower gives better quality silhouettes.")] [Range(1, 16)] public int stepSize; [Tooltip("Typical thickness of columns, walls, furniture, and other objects that reflection rays might pass behind.")] [Range(0.01f, 10.0f)] public float widthModifier; [Tooltip("Blurriness of reflections.")] [Range(0.1f, 8.0f)] public float reflectionBlur; [Tooltip("Enable for a performance gain in scenes where most glossy objects are horizontal, like floors, water, and tables. Leave on for scenes with glossy vertical objects.")] public bool reflectBackfaces; } [Serializable] public struct ScreenEdgeMask { [Tooltip("Higher = fade out SSRR near the edge of the screen so that reflections don't pop under camera motion.")] [Range(0.0f, 1.0f)] public float intensity; } [SerializeField] public SSRSettings settings = SSRSettings.defaultSettings; ///////////// Unexposed Variables ////////////////// [Tooltip("Enable to limit the effect a few bright pixels can have on rougher surfaces")] private bool highlightSuppression = false; [Tooltip("Enable to allow rays to pass behind objects. This can lead to more screen-space reflections, but the reflections are more likely to be wrong.")] private bool traceBehindObjects = true; [Tooltip("Enable to force more surfaces to use reflection probes if you see streaks on the sides of objects or bad reflections of their backs.")] private bool treatBackfaceHitAsMiss = false; [Tooltip("Drastically improves reflection reconstruction quality at the expense of some performance.")] private bool bilateralUpsample = true; ///////////// Unexposed Variables ////////////////// [SerializeField] private Shader m_Shader; public Shader shader { get { if (m_Shader == null) m_Shader = Shader.Find("Hidden/ScreenSpaceReflection"); return m_Shader; } } private Material m_Material; public Material material { get { if (m_Material == null) m_Material = ImageEffectHelper.CheckShaderAndCreateMaterial(shader); return m_Material; } } private Camera m_Camera; public Camera camera_ { get { if (m_Camera == null) m_Camera = GetComponent<Camera>(); return m_Camera; } } private CommandBuffer m_CommandBuffer; private static int kNormalAndRoughnessTexture; private static int kHitPointTexture; private static int[] kReflectionTextures; private static int kFilteredReflections; private static int kBlurTexture; private static int kFinalReflectionTexture; private static int kTempTexture; // Shader pass indices used by the effect private enum PassIndex { RayTraceStep = 0, CompositeFinal = 1, Blur = 2, CompositeSSR = 3, MinMipGeneration = 4, HitPointToReflections = 5, BilateralKeyPack = 6, BlitDepthAsCSZ = 7, PoissonBlur = 8, } private void OnEnable() { if (!ImageEffectHelper.IsSupported(shader, false, true, this)) { enabled = false; return; } camera_.depthTextureMode |= DepthTextureMode.Depth; kReflectionTextures = new int[5]; kNormalAndRoughnessTexture = Shader.PropertyToID("_NormalAndRoughnessTexture"); kHitPointTexture = Shader.PropertyToID("_HitPointTexture"); kReflectionTextures[0] = Shader.PropertyToID("_ReflectionTexture0"); kReflectionTextures[1] = Shader.PropertyToID("_ReflectionTexture1"); kReflectionTextures[2] = Shader.PropertyToID("_ReflectionTexture2"); kReflectionTextures[3] = Shader.PropertyToID("_ReflectionTexture3"); kReflectionTextures[4] = Shader.PropertyToID("_ReflectionTexture4"); kBlurTexture = Shader.PropertyToID("_BlurTexture"); kFilteredReflections = Shader.PropertyToID("_FilteredReflections"); kFinalReflectionTexture = Shader.PropertyToID("_FinalReflectionTexture"); kTempTexture = Shader.PropertyToID("_TempTexture"); } void OnDisable() { if (m_Material) DestroyImmediate(m_Material); m_Material = null; if (camera_ != null) { if (m_CommandBuffer != null) { camera_.RemoveCommandBuffer(CameraEvent.AfterFinalPass, m_CommandBuffer); } m_CommandBuffer = null; } } #if UNITY_EDITOR void OnValidate() { if (camera_ != null) { if (m_CommandBuffer != null) { camera_.RemoveCommandBuffer(CameraEvent.AfterFinalPass, m_CommandBuffer); } m_CommandBuffer = null; } } #endif // [ImageEffectOpaque] public void OnPreRender() { if (material == null) { return; } else if (Camera.current.actualRenderingPath != RenderingPath.DeferredShading) { return; } int downsampleAmount = (settings.reflectionSettings.reflectionQuality == SSRResolution.High) ? 1 : 2; var rtW = camera_.pixelWidth / downsampleAmount; var rtH = camera_.pixelHeight / downsampleAmount; float sWidth = camera_.pixelWidth; float sHeight = camera_.pixelHeight; float sx = sWidth / 2.0f; float sy = sHeight / 2.0f; const int maxMip = 5; RenderTextureFormat intermediateFormat = camera_.hdr ? RenderTextureFormat.ARGBHalf : RenderTextureFormat.ARGB32; material.SetInt("_RayStepSize", settings.reflectionSettings.stepSize); material.SetInt("_AdditiveReflection", settings.reflectionSettings.blendType == SSRReflectionBlendType.Additive ? 1 : 0); material.SetInt("_BilateralUpsampling", bilateralUpsample ? 1 : 0); material.SetInt("_TreatBackfaceHitAsMiss", treatBackfaceHitAsMiss ? 1 : 0); material.SetInt("_AllowBackwardsRays", settings.reflectionSettings.reflectBackfaces ? 1 : 0); material.SetInt("_TraceBehindObjects", traceBehindObjects ? 1 : 0); material.SetInt("_MaxSteps", settings.reflectionSettings.iterationCount); material.SetInt("_FullResolutionFiltering", 0); material.SetInt("_HalfResolution", (settings.reflectionSettings.reflectionQuality != SSRResolution.High) ? 1 : 0); material.SetInt("_HighlightSuppression", highlightSuppression ? 1 : 0); /** The height in pixels of a 1m object if viewed from 1m away. */ float pixelsPerMeterAtOneMeter = sWidth / (-2.0f * (float)(Math.Tan(camera_.fieldOfView / 180.0 * Math.PI * 0.5))); material.SetFloat("_PixelsPerMeterAtOneMeter", pixelsPerMeterAtOneMeter); material.SetFloat("_ScreenEdgeFading", settings.screenEdgeMask.intensity); material.SetFloat("_ReflectionBlur", settings.reflectionSettings.reflectionBlur); material.SetFloat("_MaxRayTraceDistance", settings.reflectionSettings.maxDistance); material.SetFloat("_FadeDistance", settings.intensitySettings.fadeDistance); material.SetFloat("_LayerThickness", settings.reflectionSettings.widthModifier); material.SetFloat("_SSRMultiplier", settings.intensitySettings.reflectionMultiplier); material.SetFloat("_FresnelFade", settings.intensitySettings.fresnelFade); material.SetFloat("_FresnelFadePower", settings.intensitySettings.fresnelFadePower); Matrix4x4 P = camera_.projectionMatrix; Vector4 projInfo = new Vector4 ((-2.0f / (sWidth * P[0])), (-2.0f / (sHeight * P[5])), ((1.0f - P[2]) / P[0]), ((1.0f + P[6]) / P[5])); Vector3 cameraClipInfo = (float.IsPositiveInfinity(camera_.farClipPlane)) ? new Vector3(camera_.nearClipPlane, -1.0f, 1.0f) : new Vector3(camera_.nearClipPlane * camera_.farClipPlane, camera_.nearClipPlane - camera_.farClipPlane, camera_.farClipPlane); material.SetVector("_ReflectionBufferSize", new Vector2(rtW, rtH)); material.SetVector("_ScreenSize", new Vector2(sWidth, sHeight)); material.SetVector("_InvScreenSize", new Vector2((float)(1.0f / sWidth), (float)(1.0f / sHeight))); material.SetVector("_ProjInfo", projInfo); // used for unprojection material.SetVector("_CameraClipInfo", cameraClipInfo); Matrix4x4 warpToScreenSpaceMatrix = new Matrix4x4(); warpToScreenSpaceMatrix.SetRow(0, new Vector4(sx, 0.0f, 0.0f, sx)); warpToScreenSpaceMatrix.SetRow(1, new Vector4(0.0f, sy, 0.0f, sy)); warpToScreenSpaceMatrix.SetRow(2, new Vector4(0.0f, 0.0f, 1.0f, 0.0f)); warpToScreenSpaceMatrix.SetRow(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f)); Matrix4x4 projectToPixelMatrix = warpToScreenSpaceMatrix * P; material.SetMatrix("_ProjectToPixelMatrix", projectToPixelMatrix); material.SetMatrix("_WorldToCameraMatrix", camera_.worldToCameraMatrix); material.SetMatrix("_CameraToWorldMatrix", camera_.worldToCameraMatrix.inverse); if (m_CommandBuffer == null) { m_CommandBuffer = new CommandBuffer(); m_CommandBuffer.name = "Screen Space Reflections"; // RGB: Normals, A: Roughness. // Has the nice benefit of allowing us to control the filtering mode as well. m_CommandBuffer.GetTemporaryRT(kNormalAndRoughnessTexture, -1, -1, 0, FilterMode.Point, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Linear); m_CommandBuffer.GetTemporaryRT(kHitPointTexture, rtW, rtH, 0, FilterMode.Bilinear, RenderTextureFormat.ARGBHalf, RenderTextureReadWrite.Linear); for (int i = 0; i < maxMip; ++i) { // We explicitly interpolate during bilateral upsampling. m_CommandBuffer.GetTemporaryRT(kReflectionTextures[i], rtW >> i, rtH >> i, 0, FilterMode.Bilinear, intermediateFormat); } m_CommandBuffer.GetTemporaryRT(kFilteredReflections, rtW, rtH, 0, bilateralUpsample ? FilterMode.Point : FilterMode.Bilinear, intermediateFormat); m_CommandBuffer.GetTemporaryRT(kFinalReflectionTexture, rtW, rtH, 0, FilterMode.Point, intermediateFormat); m_CommandBuffer.Blit(BuiltinRenderTextureType.CameraTarget, kNormalAndRoughnessTexture, material, (int)PassIndex.BilateralKeyPack); m_CommandBuffer.Blit(BuiltinRenderTextureType.CameraTarget, kHitPointTexture, material, (int)PassIndex.RayTraceStep); m_CommandBuffer.Blit(BuiltinRenderTextureType.CameraTarget, kFilteredReflections, material, (int)PassIndex.HitPointToReflections); m_CommandBuffer.Blit(kFilteredReflections, kReflectionTextures[0], material, (int)PassIndex.PoissonBlur); for (int i = 1; i < maxMip; ++i) { int inputTex = kReflectionTextures[i - 1]; int lowMip = i; m_CommandBuffer.GetTemporaryRT(kBlurTexture, rtW >> lowMip, rtH >> lowMip, 0, FilterMode.Bilinear, intermediateFormat); m_CommandBuffer.SetGlobalVector("_Axis", new Vector4(1.0f, 0.0f, 0.0f, 0.0f)); m_CommandBuffer.SetGlobalFloat("_CurrentMipLevel", i - 1.0f); m_CommandBuffer.Blit(inputTex, kBlurTexture, material, (int)PassIndex.Blur); m_CommandBuffer.SetGlobalVector("_Axis", new Vector4(0.0f, 1.0f, 0.0f, 0.0f)); inputTex = kReflectionTextures[i]; m_CommandBuffer.Blit(kBlurTexture, inputTex, material, (int)PassIndex.Blur); m_CommandBuffer.ReleaseTemporaryRT(kBlurTexture); } m_CommandBuffer.Blit(kReflectionTextures[0], kFinalReflectionTexture, material, (int)PassIndex.CompositeSSR); m_CommandBuffer.GetTemporaryRT(kTempTexture, camera_.pixelWidth, camera_.pixelHeight, 0, FilterMode.Bilinear, intermediateFormat); m_CommandBuffer.Blit(BuiltinRenderTextureType.CameraTarget, kTempTexture, material, (int)PassIndex.CompositeFinal); m_CommandBuffer.Blit(kTempTexture, BuiltinRenderTextureType.CameraTarget); m_CommandBuffer.ReleaseTemporaryRT(kTempTexture); camera_.AddCommandBuffer(CameraEvent.AfterFinalPass, m_CommandBuffer); } } } }
/* * CID0005.cs - cs culture handler. * * 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 */ // Generated from "cs.txt". namespace I18N.West { using System; using System.Globalization; using I18N.Common; public class CID0005 : RootCulture { public CID0005() : base(0x0005) {} public CID0005(int culture) : base(culture) {} public override String Name { get { return "cs"; } } public override String ThreeLetterISOLanguageName { get { return "ces"; } } public override String ThreeLetterWindowsLanguageName { get { return "CSY"; } } public override String TwoLetterISOLanguageName { get { return "cs"; } } public override DateTimeFormatInfo DateTimeFormat { get { DateTimeFormatInfo dfi = base.DateTimeFormat; dfi.AMDesignator = "dop."; dfi.PMDesignator = "odp."; dfi.AbbreviatedDayNames = new String[] {"ne", "po", "\u00FAt", "st", "\u010dt", "p\u00E1", "so"}; dfi.DayNames = new String[] {"ned\u011Ble", "pond\u011Bl\u00ED", "\u00FAter\u00FD", "st\u0159eda", "\u010dtvrtek", "p\u00E1tek", "sobota"}; dfi.AbbreviatedMonthNames = new String[] {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII", ""}; dfi.MonthNames = new String[] {"leden", "\u00FAnor", "b\u0159ezen", "duben", "kv\u011Bten", "\u010Derven", "\u010Dervenec", "srpen", "z\u00E1\u0159\u00ED", "\u0159\u00EDjen", "listopad", "prosinec", ""}; dfi.DateSeparator = "."; dfi.TimeSeparator = ":"; dfi.LongDatePattern = "d. MMMM yyyy"; dfi.LongTimePattern = "H:mm:ss z"; dfi.ShortDatePattern = "d.M.yy"; dfi.ShortTimePattern = "H:mm"; dfi.FullDateTimePattern = "dddd, d. MMMM yyyy H:mm:ss z"; dfi.I18NSetDateTimePatterns(new String[] { "d:d.M.yy", "D:dddd, d. MMMM yyyy", "f:dddd, d. MMMM yyyy H:mm:ss z", "f:dddd, d. MMMM yyyy H:mm:ss z", "f:dddd, d. MMMM yyyy H:mm:ss", "f:dddd, d. MMMM yyyy H:mm", "F:dddd, d. MMMM yyyy HH:mm:ss", "g:d.M.yy H:mm:ss z", "g:d.M.yy H:mm:ss z", "g:d.M.yy H:mm:ss", "g:d.M.yy H:mm", "G:d.M.yy HH:mm:ss", "m:MMMM dd", "M:MMMM dd", "r:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", "R:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", "s:yyyy'-'MM'-'dd'T'HH':'mm':'ss", "t:H:mm:ss z", "t:H:mm:ss z", "t:H:mm:ss", "t:H:mm", "T:HH:mm:ss", "u:yyyy'-'MM'-'dd HH':'mm':'ss'Z'", "U:dddd, dd MMMM yyyy HH:mm:ss", "y:yyyy MMMM", "Y:yyyy MMMM", }); return dfi; } set { base.DateTimeFormat = value; // not used } } public override NumberFormatInfo NumberFormat { get { NumberFormatInfo nfi = base.NumberFormat; nfi.CurrencyDecimalSeparator = ","; nfi.CurrencyGroupSeparator = "\u00A0"; nfi.NumberGroupSeparator = "\u00A0"; nfi.PercentGroupSeparator = "\u00A0"; nfi.NegativeSign = "-"; nfi.NumberDecimalSeparator = ","; nfi.PercentDecimalSeparator = ","; nfi.PercentSymbol = "%"; nfi.PerMilleSymbol = "\u2030"; return nfi; } set { base.NumberFormat = value; // not used } } public override String ResolveLanguage(String name) { switch(name) { case "cs": return "\u010De\u0161tina"; } return base.ResolveLanguage(name); } public override String ResolveCountry(String name) { switch(name) { case "CZ": return "\u010Cesk\u00E1 republika"; } return base.ResolveCountry(name); } private class PrivateTextInfo : _I18NTextInfo { public PrivateTextInfo(int culture) : base(culture) {} public override int ANSICodePage { get { return 1250; } } public override int EBCDICCodePage { get { return 500; } } public override int MacCodePage { get { return 10029; } } public override int OEMCodePage { get { return 852; } } public override String ListSeparator { get { return ";"; } } }; // class PrivateTextInfo public override TextInfo TextInfo { get { return new PrivateTextInfo(LCID); } } }; // class CID0005 public class CNcs : CID0005 { public CNcs() : base() {} }; // class CNcs }; // namespace I18N.West
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using Microsoft.AspNetCore.Razor.Language; using Microsoft.AspNetCore.Razor.Language.IntegrationTests; using Microsoft.AspNetCore.Razor.TagHelpers; using Microsoft.CodeAnalysis.CSharp; using Xunit; namespace Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X.IntegrationTests { public class CodeGenerationIntegrationTest : IntegrationTestBase { private static readonly CSharpCompilation DefaultBaseCompilation = MvcShim.BaseCompilation.WithAssemblyName("AppCode"); public CodeGenerationIntegrationTest() : base(generateBaselines: null, projectDirectoryHint: "Microsoft.AspNetCore.Mvc.Razor.Extensions.Version1_X") { Configuration = RazorConfiguration.Create( RazorLanguageVersion.Version_1_1, "MVC-1.1", new[] { new AssemblyExtension("MVC-1.1", typeof(ExtensionInitializer).Assembly) }); } protected override CSharpCompilation BaseCompilation => DefaultBaseCompilation; protected override RazorConfiguration Configuration { get; } protected override CSharpParseOptions CSharpParseOptions => base.CSharpParseOptions.WithLanguageVersion(LanguageVersion.CSharp8); [Fact] public void InvalidNamespaceAtEOF_DesignTime() { // Arrange var projectItem = CreateProjectItemFromFile(); // Act var compiled = CompileToCSharp(projectItem, designTime: true); // Assert AssertDocumentNodeMatchesBaseline(compiled.CodeDocument.GetDocumentIntermediateNode()); AssertCSharpDocumentMatchesBaseline(compiled.CodeDocument.GetCSharpDocument()); AssertSourceMappingsMatchBaseline(compiled.CodeDocument); var diagnotics = compiled.CodeDocument.GetCSharpDocument().Diagnostics; Assert.Equal("RZ1007", Assert.Single(diagnotics).Id); } [Fact] public void IncompleteDirectives_DesignTime() { // Arrange AddCSharpSyntaxTree(@" public class MyService<TModel> { public string Html { get; set; } }"); var projectItem = CreateProjectItemFromFile(); // Act var compiled = CompileToCSharp(projectItem, designTime: true); // Assert AssertDocumentNodeMatchesBaseline(compiled.CodeDocument.GetDocumentIntermediateNode()); AssertCSharpDocumentMatchesBaseline(compiled.CodeDocument.GetCSharpDocument()); AssertSourceMappingsMatchBaseline(compiled.CodeDocument); // We expect this test to generate a bunch of errors. Assert.True(compiled.CodeDocument.GetCSharpDocument().Diagnostics.Count > 0); } [Fact] public void InheritsViewModel_DesignTime() { // Arrange AddCSharpSyntaxTree(@" using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Razor; public class MyBasePageForViews<TModel> : RazorPage { public override Task ExecuteAsync() { throw new System.NotImplementedException(); } } public class MyModel { } "); var projectItem = CreateProjectItemFromFile(); // Act var compiled = CompileToAssembly(projectItem, designTime: true); // Assert AssertDocumentNodeMatchesBaseline(compiled.CodeDocument.GetDocumentIntermediateNode()); AssertCSharpDocumentMatchesBaseline(compiled.CodeDocument.GetCSharpDocument()); AssertSourceMappingsMatchBaseline(compiled.CodeDocument); } [Fact] public void InheritsWithViewImports_DesignTime() { // Arrange AddCSharpSyntaxTree(@" using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Razor; public class MyBasePageForViews<TModel> : RazorPage { public override Task ExecuteAsync() { throw new System.NotImplementedException(); } } public class MyModel { }"); AddProjectItemFromText(@"@inherits MyBasePageForViews<TModel>"); var projectItem = CreateProjectItemFromFile(); // Act var compiled = CompileToAssembly(projectItem, designTime: true); // Assert AssertDocumentNodeMatchesBaseline(compiled.CodeDocument.GetDocumentIntermediateNode()); AssertCSharpDocumentMatchesBaseline(compiled.CodeDocument.GetCSharpDocument()); AssertSourceMappingsMatchBaseline(compiled.CodeDocument); } [Fact] public void Basic_DesignTime() { // Arrange var projectItem = CreateProjectItemFromFile(); // Act var compiled = CompileToAssembly(projectItem, designTime: true); // Assert AssertDocumentNodeMatchesBaseline(compiled.CodeDocument.GetDocumentIntermediateNode()); AssertCSharpDocumentMatchesBaseline(compiled.CodeDocument.GetCSharpDocument()); AssertSourceMappingsMatchBaseline(compiled.CodeDocument); } [Fact] public void Sections_DesignTime() { // Arrange AddCSharpSyntaxTree($@" using Microsoft.AspNetCore.Mvc.ViewFeatures; public class InputTestTagHelper : {typeof(TagHelper).FullName} {{ public ModelExpression For {{ get; set; }} }} "); var projectItem = CreateProjectItemFromFile(); // Act var compiled = CompileToAssembly(projectItem, designTime: true); // Assert AssertDocumentNodeMatchesBaseline(compiled.CodeDocument.GetDocumentIntermediateNode()); AssertCSharpDocumentMatchesBaseline(compiled.CodeDocument.GetCSharpDocument()); AssertSourceMappingsMatchBaseline(compiled.CodeDocument); } [Fact] public void _ViewImports_DesignTime() { // Arrange var projectItem = CreateProjectItemFromFile(); // Act var compiled = CompileToAssembly(projectItem, designTime: true); // Assert AssertDocumentNodeMatchesBaseline(compiled.CodeDocument.GetDocumentIntermediateNode()); AssertCSharpDocumentMatchesBaseline(compiled.CodeDocument.GetCSharpDocument()); AssertSourceMappingsMatchBaseline(compiled.CodeDocument); } [Fact] public void Inject_DesignTime() { // Arrange AddCSharpSyntaxTree(@" public class MyApp { public string MyProperty { get; set; } } "); var projectItem = CreateProjectItemFromFile(); // Act var compiled = CompileToAssembly(projectItem, designTime: true); // Assert AssertDocumentNodeMatchesBaseline(compiled.CodeDocument.GetDocumentIntermediateNode()); AssertCSharpDocumentMatchesBaseline(compiled.CodeDocument.GetCSharpDocument()); AssertSourceMappingsMatchBaseline(compiled.CodeDocument); } [Fact] public void InjectWithModel_DesignTime() { // Arrange AddCSharpSyntaxTree(@" public class MyModel { } public class MyService<TModel> { public string Html { get; set; } } public class MyApp { public string MyProperty { get; set; } }"); var projectItem = CreateProjectItemFromFile(); // Act var compiled = CompileToAssembly(projectItem, designTime: true); // Assert AssertDocumentNodeMatchesBaseline(compiled.CodeDocument.GetDocumentIntermediateNode()); AssertCSharpDocumentMatchesBaseline(compiled.CodeDocument.GetCSharpDocument()); AssertSourceMappingsMatchBaseline(compiled.CodeDocument); } [Fact] public void InjectWithSemicolon_DesignTime() { // Arrange AddCSharpSyntaxTree(@" public class MyModel { } public class MyApp { public string MyProperty { get; set; } } public class MyService<TModel> { public string Html { get; set; } } "); var projectItem = CreateProjectItemFromFile(); // Act var compiled = CompileToAssembly(projectItem, designTime: true); // Assert AssertDocumentNodeMatchesBaseline(compiled.CodeDocument.GetDocumentIntermediateNode()); AssertCSharpDocumentMatchesBaseline(compiled.CodeDocument.GetCSharpDocument()); AssertSourceMappingsMatchBaseline(compiled.CodeDocument); } [Fact] public void Model_DesignTime() { // Arrange var projectItem = CreateProjectItemFromFile(); // Act var compiled = CompileToAssembly(projectItem, designTime: true); // Assert AssertDocumentNodeMatchesBaseline(compiled.CodeDocument.GetDocumentIntermediateNode()); AssertCSharpDocumentMatchesBaseline(compiled.CodeDocument.GetCSharpDocument()); AssertSourceMappingsMatchBaseline(compiled.CodeDocument); } [Fact] public void MultipleModels_DesignTime() { // Arrange AddCSharpSyntaxTree(@" public class ThisShouldBeGenerated { }"); var projectItem = CreateProjectItemFromFile(); // Act var compiled = CompileToCSharp(projectItem, designTime: true); // Assert AssertDocumentNodeMatchesBaseline(compiled.CodeDocument.GetDocumentIntermediateNode()); AssertCSharpDocumentMatchesBaseline(compiled.CodeDocument.GetCSharpDocument()); AssertSourceMappingsMatchBaseline(compiled.CodeDocument); var diagnotics = compiled.CodeDocument.GetCSharpDocument().Diagnostics; Assert.Equal("RZ2001", Assert.Single(diagnotics).Id); } [Fact] public void ModelExpressionTagHelper_DesignTime() { // Arrange AddCSharpSyntaxTree($@" using Microsoft.AspNetCore.Mvc.ViewFeatures; public class InputTestTagHelper : {typeof(TagHelper).FullName} {{ public ModelExpression For {{ get; set; }} }} "); var projectItem = CreateProjectItemFromFile(); // Act var compiled = CompileToAssembly(projectItem, designTime: true); // Assert AssertDocumentNodeMatchesBaseline(compiled.CodeDocument.GetDocumentIntermediateNode()); AssertCSharpDocumentMatchesBaseline(compiled.CodeDocument.GetCSharpDocument()); AssertSourceMappingsMatchBaseline(compiled.CodeDocument); } [Fact] public void ViewComponentTagHelper_DesignTime() { // Arrange AddCSharpSyntaxTree($@" public class TestViewComponent {{ public string Invoke(string firstName) {{ return firstName; }} }} [{typeof(HtmlTargetElementAttribute).FullName}] public class AllTagHelper : {typeof(TagHelper).FullName} {{ public string Bar {{ get; set; }} }} "); var projectItem = CreateProjectItemFromFile(); // Act var compiled = CompileToAssembly(projectItem, designTime: true); // Assert AssertDocumentNodeMatchesBaseline(compiled.CodeDocument.GetDocumentIntermediateNode()); AssertCSharpDocumentMatchesBaseline(compiled.CodeDocument.GetCSharpDocument()); AssertSourceMappingsMatchBaseline(compiled.CodeDocument); } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Xml; using System.Resources; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using System.IO.Packaging; using System.Drawing.Imaging; using Daisy.SaveAsDAISY.Forms; using Daisy.SaveAsDAISY.Forms.Controls; namespace Daisy.SaveAsDAISY.Conversion { public partial class MultipleSub : Form { const string appRelationshipType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties"; const string wordRelationshipType = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument"; PackageRelationship packRelationship = null; const string appNamespace = "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes"; List<string> listDocuments; private ResourceManager Labels; Hashtable table = new Hashtable(); int subCount = 0; int masterSubFlag = 0; string fileOutputPath, versionInfo = ""; private Script mParser = null; private bool useAScript = false; String input = "", uId = ""; private string mProjectDirectory; string strBrtextBox = ""; TableLayoutPanel oTableLayoutPannel = new TableLayoutPanel(); public ConversionParameters UpdatedConversionParameters { get; private set; } public MultipleSub(ConversionParameters conversion) { UpdatedConversionParameters = conversion; InitializeComponent(); listDocuments = new List<string>(); this.Labels = AddInHelper.LabelsManager; btn_Up.Enabled = false; btn_Down.Enabled = false; btn_Delete.Enabled = false; btn_Populate.Enabled = false; this.versionInfo = UpdatedConversionParameters.Version; useAScript = UpdatedConversionParameters.PostProcessor != null; if (useAScript) { this.Text = UpdatedConversionParameters.PostProcessor.NiceName; } } /// <summary> /// Prpoperty to return Selected Documents /// </summary> public List<string> GetFileNames { get { return listDocuments; } } /// <summary> /// Prpoperty to return Output file path /// </summary> public string GetOutputFilePath { get { return fileOutputPath; } } public string pipeOutput { get { return strBrtextBox; } } /* Returns a Hash Table having information about Title,Creator,Publisher,UID*/ public Hashtable HTable { get { return table; } } /* Returns false when Form is diplayed to the user*/ public int DoTranslate() { this.ShowDialog(); return masterSubFlag; } /* User can take select Output folder and function returns the Output filename chosen by the user*/ private string GetPhysicalPath() { FolderBrowserDialog fbd = new FolderBrowserDialog(); fbd.Description = "Destination"; if (tBx_Browse.Text != "" && Directory.Exists(tBx_Browse.Text)) fbd.SelectedPath = tBx_Browse.Text; fbd.ShowDialog(); return fbd.SelectedPath; // return the path in which the user wants to create the file } /*Core function for Translation*/ private void btn_Ok_Click(object sender, EventArgs e) { CleanOutputDirDlg cleanUpDialog; if (!useAScript) { if (lBx_SubDocs.Items.Count == 0) { MessageBox.Show(Labels.GetString("SubdocsError"), "SaveAsDAISY", MessageBoxButtons.OK, MessageBoxIcon.Error); btn_Browse.Focus(); } else if (tBx_output.Text == "") { MessageBox.Show(Labels.GetString("ChoseDestinationFile"), Labels.GetString("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error); btn_Output.Focus(); } else if (Directory.Exists(Path.GetDirectoryName(tBx_output.Text)) == false) { MessageBox.Show("Directory " + string.Concat(Path.GetDirectoryName(tBx_output.Text), " ", "does not exist"), Labels.GetString("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error); btn_Output.Focus(); } else if (Path.GetFileNameWithoutExtension(tBx_output.Text) == "") { MessageBox.Show("Please provide proper filename", Labels.GetString("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error); btn_Output.Focus(); } else if (tBx_Title.Text.TrimEnd() == "") { MessageBox.Show("Please enter the Title", Labels.GetString("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error); tBx_Title.Focus(); } else { for (int i = 0; i < lBx_SubDocs.Items.Count; i++) { listDocuments.Add(lBx_SubDocs.Items[i].ToString()); btn_Delete.Enabled = true; btn_Populate.Enabled = true; } UpdatedConversionParameters = UpdatedConversionParameters.withParameter("Title", tBx_Title.Text) .withParameter("Creator", tBx_Creator.Text) .withParameter("Publisher", tBx_Publisher.Text) .withParameter("Subject", tBx_Subject.Text) .withParameter("MasterSub", "Yes"); if (tBx_Uid.Text != "") { if (uId == tBx_Uid.Text) UpdatedConversionParameters.withParameter("UID", "AUTO-UID-" + tBx_Uid.Text); else UpdatedConversionParameters.withParameter("UID", tBx_Uid.Text); } else UpdatedConversionParameters.withParameter("UID", "AUTO-UID-" + GenerateId().ToString()); if (Path.GetExtension(tBx_output.Text) == "") tBx_output.Text = tBx_output.Text + ".xml"; fileOutputPath = tBx_output.Text; UpdatedConversionParameters.OutputPath = fileOutputPath; // Now retrieved by the conversion parameters class while building the params hash /*ConverterSettings daisySt = new ConverterSettings(); String imgoption = daisySt.GetImageOption; String resampleValue = daisySt.GetResampleValue; String characterStyle = daisySt.GetCharacterStyle; String pagenumStyle = daisySt.GetPagenumStyle; if (imgoption != " ") { table.Add("ImageSizeOption", imgoption); table.Add("DPI", resampleValue); } if (characterStyle != " ") { table.Add("CharacterStyles", characterStyle); } if (pagenumStyle != " ") { table.Add("Custom", pagenumStyle); }*/ masterSubFlag = 1; this.Close(); } } else { string scriptOutput = string.Empty; for (int i = 0; i < mLayoutPanel.Controls.Count; i++) { if (mLayoutPanel.Controls[i] is BaseUserControl) { ((BaseUserControl)mLayoutPanel.Controls[i]).UpdateScriptParameterValue(); } } for (int i = 0; i < oTableLayoutPannel.Controls.Count; i++) { if (oTableLayoutPannel.Controls[i] is BaseUserControl) { ((BaseUserControl)oTableLayoutPannel.Controls[i]).UpdateScriptParameterValue(); } } foreach (var kv in UpdatedConversionParameters.PostProcessor.Parameters) { ScriptParameter p = kv.Value; if (p.IsParameterRequired && (p.Name == "outputPath" || p.Name == "output")) { PathDataType pathDataType = p.ParameterDataType as PathDataType; if (pathDataType == null) continue; if (pathDataType.IsFileOrDirectory == PathDataType.FileOrDirectory.File) { try { FileInfo outputFileInfo = new FileInfo(p.ParameterValue); if (!string.IsNullOrEmpty(pathDataType.FileExtension) && !pathDataType.FileExtension.Equals(outputFileInfo.Extension, StringComparison.InvariantCultureIgnoreCase)) { MessageBox.Show(string.Format("Please select {0} output file", pathDataType.FileExtension), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); mLayoutPanel.Controls[0].Controls[0].Controls[1].Focus(); return; } strBrtextBox = outputFileInfo.DirectoryName; scriptOutput = outputFileInfo.Name; } catch (ArgumentException ex) { AddinLogger.Error(ex); MessageBox.Show("Please select output file", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); mLayoutPanel.Controls[0].Controls[0].Controls[1].Focus(); return; } } else { strBrtextBox = p.ParameterValue; } break; } } cleanUpDialog = new CleanOutputDirDlg(strBrtextBox, scriptOutput); if (lBx_SubDocs.Items.Count == 0) { MessageBox.Show(Labels.GetString("SubdocsError"), "SaveAsDAISY", MessageBoxButtons.OK, MessageBoxIcon.Error); btn_Browse.Focus(); } else if (tBx_Title.Text.TrimEnd() == "") { MessageBox.Show("Please enter the Title", Labels.GetString("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error); tBx_Title.Focus(); } else if (strBrtextBox.TrimEnd() == "") { MessageBox.Show("Please select the Destination folder", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); mLayoutPanel.Controls[0].Controls[0].Controls[1].Focus(); } else if (cleanUpDialog.Clean(this) == DialogResult.Cancel) { mLayoutPanel.Controls[0].Controls[0].Controls[1].Focus(); } else { if (strBrtextBox != cleanUpDialog.OutputDir) { strBrtextBox = cleanUpDialog.OutputDir; foreach (var kv in UpdatedConversionParameters.PostProcessor.Parameters) { ScriptParameter p = kv.Value; if (p.IsParameterRequired && (p.Name == "outputPath" || p.Name == "output")) { p.ParameterValue = cleanUpDialog.OutputDir; } } } tBx_output.Text = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\SaveAsDAISY"; for (int i = 0; i < lBx_SubDocs.Items.Count; i++) { listDocuments.Add(lBx_SubDocs.Items[i].ToString()); btn_Delete.Enabled = true; btn_Populate.Enabled = true; } UpdatedConversionParameters.withParameter("Title", tBx_Title.Text) .withParameter("Creator", tBx_Creator.Text) .withParameter("Publisher", tBx_Publisher.Text) .withParameter("Subject", tBx_Subject.Text) .withParameter("MasterSub", "Yes") .withParameter("PipelineOutput", strBrtextBox); if (tBx_Uid.Text != "") if (uId == tBx_Uid.Text) UpdatedConversionParameters.withParameter("UID", "AUTO-UID-" + tBx_Uid.Text); else UpdatedConversionParameters.withParameter("UID", tBx_Uid.Text); else UpdatedConversionParameters.withParameter("UID", "AUTO-UID-" + GenerateId().ToString()); if (Path.GetExtension(tBx_output.Text) == "") tBx_output.Text = Path.Combine(tBx_output.Text, "MultipleNarrator" + ".xml"); fileOutputPath = tBx_output.Text; UpdatedConversionParameters.OutputPath = fileOutputPath; masterSubFlag = 1; this.Close(); } } } /*Function to Close UI*/ private void btn_Cancel_Click(object sender, EventArgs e) { string[] files = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\SaveAsDAISY\"); foreach (string file in files) { if (file.Contains(".PNG") || file.Contains(".png")) { File.Delete(file); } } this.Close(); } /*Function to select Output folder*/ private void btn_Browse_Click(object sender, EventArgs e) { //Browse button click String path = GetPhysicalPath(); if (path != "") { tBx_Browse.Text = path; SearchOption option = SearchOption.TopDirectoryOnly; string[] files = Directory.GetFiles(path, "*.docx", option); foreach (string input in files) { if (!Path.GetFileNameWithoutExtension(input).StartsWith("~$") && input.EndsWith(".docx")) { lBx_SubDocs.Items.Insert(subCount, input); subCount++; } } if (lBx_SubDocs.Items.Count > 0) { lBx_SubDocs.SetSelected(0, true); //btn_Up.Enabled = true; btn_Down.Enabled = true; btn_Delete.Enabled = true; btn_Populate.Enabled = true; } } } /* User can take select Output folder and function returns the Output filename chosen by the user*/ private string GetPhysicalPath_Output() { SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = "XML files (*.xml)|*.xml"; sfd.FilterIndex = 1; sfd.CheckPathExists = true; sfd.DefaultExt = ".xml"; sfd.ShowDialog(); return sfd.FileName; // return the path in which the user wants to create the file } /*Function to select Output File*/ private void btn_Output_Click(object sender, EventArgs e) { //Output buttonClick String path = GetPhysicalPath_Output(); fileOutputPath = path; if (path != "") tBx_output.Text = path; } /// <summary> /// Function to change the position of the Document /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_Up_Click(object sender, EventArgs e) { //Move up button click if (lBx_SubDocs.SelectedItem.ToString() != "") { int currentIndx = lBx_SubDocs.SelectedIndex; int upIndx = currentIndx - 1; String currentIndx_Value = lBx_SubDocs.Items[currentIndx].ToString(); String upIndx_Value = lBx_SubDocs.Items[upIndx].ToString(); lBx_SubDocs.Items[currentIndx] = upIndx_Value; lBx_SubDocs.Items[upIndx] = currentIndx_Value; lBx_SubDocs.SetSelected(upIndx, true); } } /// <summary> /// Function to change the position of the Document /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_Down_Click(object sender, EventArgs e) { //Move down button click if (lBx_SubDocs.SelectedItem.ToString() != "") { int currentIndx = lBx_SubDocs.SelectedIndex; int downIndx = currentIndx + 1; String currentIndx_Value = lBx_SubDocs.Items[currentIndx].ToString(); String downIndx_Value = lBx_SubDocs.Items[downIndx].ToString(); lBx_SubDocs.Items[currentIndx] = downIndx_Value; lBx_SubDocs.Items[downIndx] = currentIndx_Value; lBx_SubDocs.SetSelected(downIndx, true); } } /// <summary> /// Function to remove the Document /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btn_Delete_Click(object sender, EventArgs e) { //Remove button click int currentIndx = lBx_SubDocs.SelectedIndex; if (currentIndx >= 0) { lBx_SubDocs.Items.RemoveAt(currentIndx); subCount--; } lBx_SubDocs.Refresh(); if (lBx_SubDocs.Items.Count <= 0) { btn_Delete.Enabled = false; btn_Populate.Enabled = false; } else lBx_SubDocs.SetSelected(0, true); } /*Function to reset all the values in UI*/ private void btn_Reset_Click(object sender, EventArgs e) { tBx_Browse.Text = ""; tBx_output.Text = ""; tBx_Creator.Text = ""; tBx_Title.Text = ""; tBx_Subject.Text = ""; tBx_Publisher.Text = ""; tBx_Uid.Text = ""; lBx_SubDocs.Items.Clear(); btn_Up.Enabled = false; btn_Down.Enabled = false; btn_Delete.Enabled = false; btn_Populate.Enabled = false; subCount = 0; int counter = 0; if (useAScript ) //if (useAScript) { mLayoutPanel.Controls[0].Controls[0].Controls[1].Text = ""; foreach (Control c in oTableLayoutPannel.Controls) { if (oTableLayoutPannel.Controls[counter].Name == "EnumControl") { ComboBox comboBox = (ComboBox)oTableLayoutPannel.Controls[counter].Controls[1]; comboBox.SelectedIndex = 0; } else if (oTableLayoutPannel.Controls[counter].Name == "BoolControl") { CheckBox checkBox = (CheckBox)oTableLayoutPannel.Controls[counter].Controls[0]; checkBox.Checked = false; } counter++; } } //mLayoutPanel.Controls[0].Controls[0].Text = ""; } /*Function to select a document*/ private void button1_Click(object sender, EventArgs e) { //Add button click OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "Word Document(*.docx)|*.docx"; ofd.FilterIndex = 1; ofd.CheckPathExists = true; ofd.DefaultExt = ".docx"; ofd.ShowDialog(); if (ofd.FileName != "") { lBx_SubDocs.Items.Insert(subCount, ofd.FileName); subCount++; } lBx_SubDocs.Refresh(); if (lBx_SubDocs.Items.Count > 0) { lBx_SubDocs.SetSelected(0, true); btn_Delete.Enabled = true; btn_Populate.Enabled = true; } } /*Function to load form*/ private void MultipleSub_Load(object sender, EventArgs e) { tBx_Uid.Text = GenerateId().ToString(); uId = tBx_Uid.Text; if (!useAScript) { mLayoutPanel.Visible = false; oLayoutPanel.Visible = false; grpBox_Properties.Location = mLayoutPanel.Location; btnShow.Visible = false; btnHide.Visible = false; oLayoutPanel.Visible = false; btn_Ok.Location = new System.Drawing.Point(grpBox_Properties.Width - 220, grpBox_Properties.Location.Y + grpBox_Properties.Height + 3); btn_Reset.Location = new System.Drawing.Point(btn_Ok.Location.X + btn_Ok.Width + 7, btn_Ok.Location.Y); btn_Cancel.Location = new System.Drawing.Point(btn_Reset.Location.X + btn_Reset.Width + 7, btn_Ok.Location.Y); } else { this.Text = UpdatedConversionParameters.PostProcessor.NiceName; groupBoxXml.Visible = false; btnShow.Visible = true; btnHide.Visible = false; oLayoutPanel.Visible = false; int destinationInitialtabIndex = btn_Down.TabIndex + 1; int w = 0; int h = 0; //shaby (begin): Implementing TableLayoutPannel int oTableLayoutCurrentRow = 0; int oTableLayoutCurrentColumn = 0; oTableLayoutPannel.Visible = false; oTableLayoutPannel.Name = "oTableLayoutPannel"; oTableLayoutPannel.AutoSize = true; oTableLayoutPannel.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; //oTableLayoutPannel.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single; oTableLayoutPannel.TabIndex = btnShow.TabIndex + 1; //60 - 100 (reserved for advanced user controls) oTableLayoutPannel.RowStyles.Add(new RowStyle(SizeType.Percent, 100)); //shaby (end) : Implementing TableLayoutPannel foreach (var kv in UpdatedConversionParameters.PostProcessor.Parameters) { ScriptParameter p = kv.Value; if (p.Name != "input" && p.ParameterDataType is PathDataType && p.IsParameterRequired) { Control c = (Control)new PathBrowserControl(p, input, mProjectDirectory); c.Anchor = AnchorStyles.Right; c.Anchor = AnchorStyles.Top; mLayoutPanel.Controls.Add(c); mLayoutPanel.SetFlowBreak(c, true); c.TabIndex = destinationInitialtabIndex++; //reserved from 9 to 50 if (w < c.Width + c.Margin.Horizontal) w = c.Width + c.Margin.Horizontal + 30; h += c.Height + c.Margin.Vertical; } else if (!p.IsParameterRequired) { //TODO: if (p.ParameterDataType is PathDataType) continue; Control c = p.ParameterDataType is BoolDataType ? (Control)new BoolControl(p) : p.ParameterDataType is EnumDataType ? (Control)new EnumControl(p) : p.ParameterDataType is StringDataType ? (Control)new StrUserControl(p) : (Control)new IntUserControl(p); c.Anchor = AnchorStyles.Right; oTableLayoutPannel.Controls.Add(c, oTableLayoutCurrentColumn, oTableLayoutCurrentRow); this.Controls.Add(oTableLayoutPannel); oTableLayoutCurrentRow++; } } mLayoutPanel.Location = new System.Drawing.Point(groupBoxXml.Location.X, groupBoxXml.Location.Y); grpBox_Properties.Location = new System.Drawing.Point(mLayoutPanel.Location.X, mLayoutPanel.Location.Y + mLayoutPanel.Height); btnShow.Location = new System.Drawing.Point(grpBox_Properties.Location.X, grpBox_Properties.Location.Y + grpBox_Properties.Height); oTableLayoutPannel.Location = new System.Drawing.Point(btnShow.Location.X, btnShow.Location.Y); //btnHide.Location = new System.Drawing.Point(oLayoutPanel.Location.X, oLayoutPanel.Location.Y + 157); oTableLayoutPannel.Location = new System.Drawing.Point(btnShow.Location.X, btnShow.Location.Y); if (oTableLayoutPannel.Width > mLayoutPanel.Width) { mLayoutPanel.Controls[0].Width = oTableLayoutPannel.Width - 3; tableLayoutPanel1.Width = oTableLayoutPannel.Width - 4; tableLayoutPanel2.Width = oTableLayoutPannel.Width; } else { oTableLayoutPannel.Controls[0].Width = mLayoutPanel.Width - 3; tableLayoutPanel1.Width = mLayoutPanel.Width - 4; tableLayoutPanel2.Width = mLayoutPanel.Width; } btn_Ok.Location = new System.Drawing.Point(grpBox_Properties.Width - 232, grpBox_Properties.Location.Y + grpBox_Properties.Height + 3); btn_Reset.Location = new System.Drawing.Point(btn_Ok.Location.X + btn_Ok.Width + 7, btn_Ok.Location.Y); btn_Cancel.Location = new System.Drawing.Point(btn_Reset.Location.X + btn_Reset.Width + 7, btn_Ok.Location.Y); } } /* Function to Generate an unique ID */ public long GenerateId() { byte[] buffer = Guid.NewGuid().ToByteArray(); return BitConverter.ToInt64(buffer, 0); } /*Core Function to populate the document properties of the selcted document*/ private void btn_Populate_Click(object sender, EventArgs e) { if (tBx_Title.Text != "" || tBx_Creator.Text != "" || tBx_Publisher.Text != "" || tBx_Subject.Text != "") { DialogResult dr = MessageBox.Show("Do you want to overwrite the document properties?", "SaveAsDAISY", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (dr == DialogResult.Yes) { populateProperties(); } } else populateProperties(); } /*Function to populate the document properties of the selcted document*/ public void populateProperties() { String fileSelected = lBx_SubDocs.SelectedItem.ToString(); if (fileSelected != "") { String resultOpenSub = CheckFileOPen(fileSelected); if (resultOpenSub == "notopen") { Package pack = Package.Open(fileSelected, FileMode.Open, FileAccess.ReadWrite); tBx_Creator.Text = pack.PackageProperties.Creator; tBx_Subject.Text = pack.PackageProperties.Subject; pack.Close(); tBx_Title.Text = DocPropTitle(fileSelected); tBx_Publisher.Text = DocPropPublisher(fileSelected); } else MessageBox.Show(Labels.GetString("Populateopen"), "SaveAsDAISY", MessageBoxButtons.OK, MessageBoxIcon.Error); } } public String DocPropPublisher(String docFile) { Package pack = Package.Open(docFile, FileMode.Open, FileAccess.ReadWrite); foreach (PackageRelationship searchRelation in pack.GetRelationshipsByType(appRelationshipType)) { packRelationship = searchRelation; break; } Uri partUri = PackUriHelper.ResolvePartUri(packRelationship.SourceUri, packRelationship.TargetUri); PackagePart mainPartxml = pack.GetPart(partUri); XmlDocument doc = new XmlDocument(); doc.Load(mainPartxml.GetStream()); pack.Close(); NameTable nt = new NameTable(); XmlNamespaceManager nsManager = new XmlNamespaceManager(nt); nsManager.AddNamespace("vt", appNamespace); XmlNodeList node = doc.GetElementsByTagName("Company"); if (node != null) return node.Item(0).InnerText; else return ""; } public String DocPropTitle(String docFile) { int titleFlag = 0; String styleVal = ""; string temp = ""; Package pack; pack = Package.Open(docFile, FileMode.Open, FileAccess.ReadWrite); String title = pack.PackageProperties.Title; pack.Close(); if (title != "") return title; else { pack = Package.Open(docFile, FileMode.Open, FileAccess.ReadWrite); foreach (PackageRelationship searchRelation in pack.GetRelationshipsByType(wordRelationshipType)) { packRelationship = searchRelation; break; } Uri partUri = PackUriHelper.ResolvePartUri(packRelationship.SourceUri, packRelationship.TargetUri); PackagePart mainPartxml = pack.GetPart(partUri); XmlDocument doc = new XmlDocument(); doc.Load(mainPartxml.GetStream()); NameTable nt = new NameTable(); pack.Close(); XmlNamespaceManager nsManager = new XmlNamespaceManager(nt); nsManager.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main"); XmlNodeList getParagraph = doc.SelectNodes("//w:body/w:p/w:pPr/w:pStyle", nsManager); for (int j = 0; j < getParagraph.Count; j++) { XmlAttributeCollection paraGraphAttribute = getParagraph[j].Attributes; for (int i = 0; i < paraGraphAttribute.Count; i++) { if (paraGraphAttribute[i].Name == "w:val") { styleVal = paraGraphAttribute[i].Value; } if (styleVal != "" && styleVal == "Title") { XmlNodeList getStyle = getParagraph[j].ParentNode.ParentNode.SelectNodes("w:r", nsManager); if (getStyle != null) { for (int k = 0; k < getStyle.Count; k++) { XmlNode getText = getStyle[k].SelectSingleNode("w:t", nsManager); temp = temp + " " + getText.InnerText; } } titleFlag = 1; break; } if (titleFlag == 1) { break; } } if (titleFlag == 1) { break; } } title = temp; } return title; } /*Function to check whether selected document is open or not*/ public String CheckFileOPen(String listSubDocs) { AddinLogger.Info("Check if file opened : " + listSubDocs); String resultSubDoc = "notopen"; try { Package pack; pack = Package.Open(listSubDocs, FileMode.Open, FileAccess.ReadWrite); pack.Close(); } catch (Exception e) { AddinLogger.Error(e); resultSubDoc = "open"; } return resultSubDoc; } private void btnShow_Click(object sender, EventArgs e) { btnShow.Visible = false; btnHide.Visible = true; oTableLayoutPannel.Visible = true; //dynamically setting tab index for the usercontrols based on the order it is placed int oTableLayoutPannelTabIndex = oTableLayoutPannel.TabIndex; foreach (Control ctrl in oTableLayoutPannel.Controls) { //reserved tabIndex 61 - 100 for Advanced User-controls if (ctrl.Name == "EnumControl") ctrl.Controls[1].TabIndex = ++oTableLayoutPannelTabIndex; else if (ctrl.Name == "BoolControl") ctrl.Controls[0].TabIndex = ++oTableLayoutPannelTabIndex; } oTableLayoutPannel.Controls[0].Focus(); btnHide.Location = new System.Drawing.Point(oTableLayoutPannel.Location.X, oTableLayoutPannel.Location.Y + oTableLayoutPannel.Height + 2); //panelButton.Location = new System.Drawing.Point(oTableLayoutPannel.Width - 220, btnHide.Location.Y - 3); btn_Ok.Location = new System.Drawing.Point(oTableLayoutPannel.Width - 225, btnHide.Location.Y); btn_Reset.Location = new System.Drawing.Point(btn_Ok.Location.X + btn_Ok.Width + 7, btnHide.Location.Y); btn_Cancel.Location = new System.Drawing.Point(btn_Reset.Location.X + btn_Reset.Width + 7, btnHide.Location.Y); } private void btnHide_Click(object sender, EventArgs e) { btnShow.Visible = true; btnHide.Visible = false; oTableLayoutPannel.Visible = false; //panelButton.Location = new System.Drawing.Point(oTableLayoutPannel.Width - 220, btnShow.Location.Y - 3); btn_Ok.Location = new System.Drawing.Point(oTableLayoutPannel.Width - 225, btnShow.Location.Y); btn_Reset.Location = new System.Drawing.Point(btn_Ok.Location.X + btn_Ok.Width + 7, btnShow.Location.Y); btn_Cancel.Location = new System.Drawing.Point(btn_Reset.Location.X + btn_Reset.Width + 7, btnShow.Location.Y); } /*Function to update the changes in the document positions*/ private void lBx_SubDocs_SelectedIndexChanged(object sender, EventArgs e) { if (lBx_SubDocs.SelectedIndex == 0) btn_Up.Enabled = false; else btn_Up.Enabled = true; if (lBx_SubDocs.SelectedIndex == lBx_SubDocs.Items.Count - 1) btn_Down.Enabled = false; else btn_Down.Enabled = true; if (lBx_SubDocs.SelectedIndex >= 0) { btn_Delete.Enabled = true; btn_Populate.Enabled = true; } else { btn_Delete.Enabled = false; btn_Populate.Enabled = false; btn_Up.Enabled = false; btn_Down.Enabled = false; } if (lBx_SubDocs.Items.Count > 0) { btn_Delete.Enabled = true; btn_Populate.Enabled = true; } else { btn_Delete.Enabled = false; btn_Populate.Enabled = false; btn_Up.Enabled = false; btn_Down.Enabled = false; } } } }
using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.ComponentModel; using System.Windows.Forms.VisualStyles; namespace Oranikle.DesignBase.UI.Docking { internal class VS2005DockPaneCaption : DockPaneCaptionBase { private sealed class InertButton : InertButtonBase { private Bitmap m_image, m_imageAutoHide; public InertButton(VS2005DockPaneCaption dockPaneCaption, Bitmap image, Bitmap imageAutoHide) : base() { m_dockPaneCaption = dockPaneCaption; m_image = image; m_imageAutoHide = imageAutoHide; RefreshChanges(); } private VS2005DockPaneCaption m_dockPaneCaption; private VS2005DockPaneCaption DockPaneCaption { get { return m_dockPaneCaption; } } public bool IsAutoHide { get { return DockPaneCaption.DockPane.IsAutoHide; } } public override Bitmap Image { get { return IsAutoHide ? m_imageAutoHide : m_image; } } protected override void OnRefreshChanges() { if (DockPaneCaption.DockPane.DockPanel != null) { if (DockPaneCaption.TextColor != ForeColor) { ForeColor = DockPaneCaption.TextColor; Invalidate(); } } } } #region consts private const int _TextGapTop = 2; private const int _TextGapBottom = 0; private const int _TextGapLeft = 3; private const int _TextGapRight = 3; private const int _ButtonGapTop = 2; private const int _ButtonGapBottom = 1; private const int _ButtonGapBetween = 1; private const int _ButtonGapLeft = 1; private const int _ButtonGapRight = 2; #endregion private static Bitmap _imageButtonClose; private static Bitmap ImageButtonClose { get { if (_imageButtonClose == null) _imageButtonClose = Resources.DockPane_Close; return _imageButtonClose; } } private InertButton m_buttonClose; private InertButton ButtonClose { get { if (m_buttonClose == null) { m_buttonClose = new InertButton(this, ImageButtonClose, ImageButtonClose); m_toolTip.SetToolTip(m_buttonClose, ToolTipClose); m_buttonClose.Click += new EventHandler(Close_Click); Controls.Add(m_buttonClose); } return m_buttonClose; } } private static Bitmap _imageButtonAutoHide; private static Bitmap ImageButtonAutoHide { get { if (_imageButtonAutoHide == null) _imageButtonAutoHide = Resources.DockPane_AutoHide; return _imageButtonAutoHide; } } private static Bitmap _imageButtonDock; private static Bitmap ImageButtonDock { get { if (_imageButtonDock == null) _imageButtonDock = Resources.DockPane_Dock; return _imageButtonDock; } } private InertButton m_buttonAutoHide; private InertButton ButtonAutoHide { get { if (m_buttonAutoHide == null) { m_buttonAutoHide = new InertButton(this, ImageButtonDock, ImageButtonAutoHide); m_toolTip.SetToolTip(m_buttonAutoHide, ToolTipAutoHide); m_buttonAutoHide.Click += new EventHandler(AutoHide_Click); Controls.Add(m_buttonAutoHide); } return m_buttonAutoHide; } } private static Bitmap _imageButtonOptions; private static Bitmap ImageButtonOptions { get { if (_imageButtonOptions == null) _imageButtonOptions = Resources.DockPane_Option; return _imageButtonOptions; } } private InertButton m_buttonOptions; private InertButton ButtonOptions { get { if (m_buttonOptions == null) { m_buttonOptions = new InertButton(this, ImageButtonOptions, ImageButtonOptions); m_toolTip.SetToolTip(m_buttonOptions, ToolTipOptions); m_buttonOptions.Click += new EventHandler(Options_Click); Controls.Add(m_buttonOptions); } return m_buttonOptions; } } private IContainer m_components; private IContainer Components { get { return m_components; } } private ToolTip m_toolTip; public VS2005DockPaneCaption(DockPane pane) : base(pane) { SuspendLayout(); m_components = new Container(); m_toolTip = new ToolTip(Components); ResumeLayout(); } protected override void Dispose(bool disposing) { if (disposing) Components.Dispose(); base.Dispose(disposing); } private static int TextGapTop { get { return _TextGapTop; } } private static Font TextFont { get { return SystemInformation.MenuFont; } } private static int TextGapBottom { get { return _TextGapBottom; } } private static int TextGapLeft { get { return _TextGapLeft; } } private static int TextGapRight { get { return _TextGapRight; } } private static int ButtonGapTop { get { return _ButtonGapTop; } } private static int ButtonGapBottom { get { return _ButtonGapBottom; } } private static int ButtonGapLeft { get { return _ButtonGapLeft; } } private static int ButtonGapRight { get { return _ButtonGapRight; } } private static int ButtonGapBetween { get { return _ButtonGapBetween; } } private static string _toolTipClose; private static string ToolTipClose { get { if (_toolTipClose == null) _toolTipClose = Strings.DockPaneCaption_ToolTipClose; return _toolTipClose; } } private static string _toolTipOptions; private static string ToolTipOptions { get { if (_toolTipOptions == null) _toolTipOptions = Strings.DockPaneCaption_ToolTipOptions; return _toolTipOptions; } } private static string _toolTipAutoHide; private static string ToolTipAutoHide { get { if (_toolTipAutoHide == null) _toolTipAutoHide = Strings.DockPaneCaption_ToolTipAutoHide; return _toolTipAutoHide; } } private static Blend _activeBackColorGradientBlend; private static Blend ActiveBackColorGradientBlend { get { if (_activeBackColorGradientBlend == null) { Blend blend = new Blend(2); blend.Factors = new float[]{0.5F, 1.0F}; blend.Positions = new float[]{0.0F, 1.0F}; _activeBackColorGradientBlend = blend; } return _activeBackColorGradientBlend; } } private Color TextColor { get { if (DockPane.IsActivated) return DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.TextColor; else return DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.TextColor; } } private static TextFormatFlags _textFormat = TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis | TextFormatFlags.VerticalCenter; private TextFormatFlags TextFormat { get { if (RightToLeft == RightToLeft.No) return _textFormat; else return _textFormat | TextFormatFlags.RightToLeft | TextFormatFlags.Right; } } protected internal override int MeasureHeight() { int height = TextFont.Height + TextGapTop + TextGapBottom; if (height < ButtonClose.Image.Height + ButtonGapTop + ButtonGapBottom) height = ButtonClose.Image.Height + ButtonGapTop + ButtonGapBottom; return height; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint (e); DrawCaption(e.Graphics); } private void DrawCaption(Graphics g) { if (ClientRectangle.Width == 0 || ClientRectangle.Height == 0) return; if (DockPane.IsActivated) { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.LinearGradientMode; using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, startColor, endColor, gradientMode)) { brush.Blend = ActiveBackColorGradientBlend; g.FillRectangle(brush, ClientRectangle); } } else { Color startColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.StartColor; Color endColor = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.EndColor; LinearGradientMode gradientMode = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.LinearGradientMode; using (LinearGradientBrush brush = new LinearGradientBrush(ClientRectangle, startColor, endColor, gradientMode)) { g.FillRectangle(brush, ClientRectangle); } } Rectangle rectCaption = ClientRectangle; Rectangle rectCaptionText = rectCaption; rectCaptionText.X += TextGapLeft; rectCaptionText.Width -= TextGapLeft + TextGapRight; rectCaptionText.Width -= ButtonGapLeft + ButtonClose.Width + ButtonGapRight; if (ShouldShowAutoHideButton) rectCaptionText.Width -= ButtonAutoHide.Width + ButtonGapBetween; if (HasTabPageContextMenu) rectCaptionText.Width -= ButtonOptions.Width + ButtonGapBetween; rectCaptionText.Y += TextGapTop; rectCaptionText.Height -= TextGapTop + TextGapBottom; Color colorText; if (DockPane.IsActivated) colorText = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.TextColor; else colorText = DockPane.DockPanel.Skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.TextColor; TextRenderer.DrawText(g, DockPane.CaptionText, TextFont, DrawHelper.RtlTransform(this, rectCaptionText), colorText, TextFormat); } protected override void OnLayout(LayoutEventArgs levent) { SetButtonsPosition(); base.OnLayout (levent); } protected override void OnRefreshChanges() { SetButtons(); Invalidate(); } private bool CloseButtonEnabled { get { return (DockPane.ActiveContent != null)? DockPane.ActiveContent.DockHandler.CloseButton : false; } } /// <summary> /// Determines whether the close button is visible on the content /// </summary> private bool CloseButtonVisible { get { return (DockPane.ActiveContent != null) ? DockPane.ActiveContent.DockHandler.CloseButtonVisible : false; } } private bool ShouldShowAutoHideButton { get { return !DockPane.IsFloat; } } private void SetButtons() { ButtonClose.Enabled = CloseButtonEnabled; ButtonClose.Visible = CloseButtonVisible; ButtonAutoHide.Visible = ShouldShowAutoHideButton; ButtonOptions.Visible = HasTabPageContextMenu; ButtonClose.RefreshChanges(); ButtonAutoHide.RefreshChanges(); ButtonOptions.RefreshChanges(); SetButtonsPosition(); } private void SetButtonsPosition() { // set the size and location for close and auto-hide buttons Rectangle rectCaption = ClientRectangle; int buttonWidth = ButtonClose.Image.Width; int buttonHeight = ButtonClose.Image.Height; int height = rectCaption.Height - ButtonGapTop - ButtonGapBottom; if (buttonHeight < height) { buttonWidth = buttonWidth * (height / buttonHeight); buttonHeight = height; } Size buttonSize = new Size(buttonWidth, buttonHeight); int x = rectCaption.X + rectCaption.Width - 1 - ButtonGapRight - m_buttonClose.Width; int y = rectCaption.Y + ButtonGapTop; Point point = new Point(x, y); ButtonClose.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); // If the close button is not visible draw the auto hide button overtop. // Otherwise it is drawn to the left of the close button. if (CloseButtonVisible) point.Offset(-(buttonWidth + ButtonGapBetween), 0); ButtonAutoHide.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); if (ShouldShowAutoHideButton) point.Offset(-(buttonWidth + ButtonGapBetween), 0); ButtonOptions.Bounds = DrawHelper.RtlTransform(this, new Rectangle(point, buttonSize)); } private void Close_Click(object sender, EventArgs e) { DockPane.CloseActiveContent(); } private void AutoHide_Click(object sender, EventArgs e) { DockPane.DockState = DockHelper.ToggleAutoHideState(DockPane.DockState); if (DockHelper.IsDockStateAutoHide(DockPane.DockState)) DockPane.DockPanel.ActiveAutoHideContent = null; } private void Options_Click(object sender, EventArgs e) { ShowTabPageContextMenu(PointToClient(Control.MousePosition)); } protected override void OnRightToLeftChanged(EventArgs e) { base.OnRightToLeftChanged(e); PerformLayout(); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Binary { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.Serialization; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Binary.Structure; using Apache.Ignite.Core.Impl.Common; /// <summary> /// Binary reader implementation. /// </summary> internal class BinaryReader : IBinaryReader, IBinaryRawReader { /** Marshaller. */ private readonly Marshaller _marsh; /** Type descriptors. */ private readonly IDictionary<long, IBinaryTypeDescriptor> _descs; /** Parent builder. */ private readonly BinaryObjectBuilder _builder; /** Handles. */ private BinaryReaderHandleDictionary _hnds; /** Current position. */ private int _curPos; /** Current raw flag. */ private bool _curRaw; /** Detach flag. */ private bool _detach; /** Binary read mode. */ private BinaryMode _mode; /** Current type structure tracker. */ private BinaryStructureTracker _curStruct; /** Current schema. */ private int[] _curSchema; /** Current schema with positions. */ private Dictionary<int, int> _curSchemaMap; /** Current header. */ private BinaryObjectHeader _curHdr; /// <summary> /// Constructor. /// </summary> /// <param name="marsh">Marshaller.</param> /// <param name="descs">Descriptors.</param> /// <param name="stream">Input stream.</param> /// <param name="mode">The mode.</param> /// <param name="builder">Builder.</param> public BinaryReader (Marshaller marsh, IDictionary<long, IBinaryTypeDescriptor> descs, IBinaryStream stream, BinaryMode mode, BinaryObjectBuilder builder) { _marsh = marsh; _descs = descs; _mode = mode; _builder = builder; Stream = stream; } /// <summary> /// Gets the marshaller. /// </summary> public Marshaller Marshaller { get { return _marsh; } } /** <inheritdoc /> */ public IBinaryRawReader GetRawReader() { MarkRaw(); return this; } /** <inheritdoc /> */ public bool ReadBoolean(string fieldName) { return ReadField(fieldName, r => r.ReadBoolean(), BinaryUtils.TypeBool); } /** <inheritdoc /> */ public bool ReadBoolean() { return Stream.ReadBool(); } /** <inheritdoc /> */ public bool[] ReadBooleanArray(string fieldName) { return ReadField(fieldName, BinaryUtils.ReadBooleanArray, BinaryUtils.TypeArrayBool); } /** <inheritdoc /> */ public bool[] ReadBooleanArray() { return Read(BinaryUtils.ReadBooleanArray, BinaryUtils.TypeArrayBool); } /** <inheritdoc /> */ public byte ReadByte(string fieldName) { return ReadField(fieldName, ReadByte, BinaryUtils.TypeByte); } /** <inheritdoc /> */ public byte ReadByte() { return Stream.ReadByte(); } /** <inheritdoc /> */ public byte[] ReadByteArray(string fieldName) { return ReadField(fieldName, BinaryUtils.ReadByteArray, BinaryUtils.TypeArrayByte); } /** <inheritdoc /> */ public byte[] ReadByteArray() { return Read(BinaryUtils.ReadByteArray, BinaryUtils.TypeArrayByte); } /** <inheritdoc /> */ public short ReadShort(string fieldName) { return ReadField(fieldName, ReadShort, BinaryUtils.TypeShort); } /** <inheritdoc /> */ public short ReadShort() { return Stream.ReadShort(); } /** <inheritdoc /> */ public short[] ReadShortArray(string fieldName) { return ReadField(fieldName, BinaryUtils.ReadShortArray, BinaryUtils.TypeArrayShort); } /** <inheritdoc /> */ public short[] ReadShortArray() { return Read(BinaryUtils.ReadShortArray, BinaryUtils.TypeArrayShort); } /** <inheritdoc /> */ public char ReadChar(string fieldName) { return ReadField(fieldName, ReadChar, BinaryUtils.TypeChar); } /** <inheritdoc /> */ public char ReadChar() { return Stream.ReadChar(); } /** <inheritdoc /> */ public char[] ReadCharArray(string fieldName) { return ReadField(fieldName, BinaryUtils.ReadCharArray, BinaryUtils.TypeArrayChar); } /** <inheritdoc /> */ public char[] ReadCharArray() { return Read(BinaryUtils.ReadCharArray, BinaryUtils.TypeArrayChar); } /** <inheritdoc /> */ public int ReadInt(string fieldName) { return ReadField(fieldName, ReadInt, BinaryUtils.TypeInt); } /** <inheritdoc /> */ public int ReadInt() { return Stream.ReadInt(); } /** <inheritdoc /> */ public int[] ReadIntArray(string fieldName) { return ReadField(fieldName, BinaryUtils.ReadIntArray, BinaryUtils.TypeArrayInt); } /** <inheritdoc /> */ public int[] ReadIntArray() { return Read(BinaryUtils.ReadIntArray, BinaryUtils.TypeArrayInt); } /** <inheritdoc /> */ public long ReadLong(string fieldName) { return ReadField(fieldName, ReadLong, BinaryUtils.TypeLong); } /** <inheritdoc /> */ public long ReadLong() { return Stream.ReadLong(); } /** <inheritdoc /> */ public long[] ReadLongArray(string fieldName) { return ReadField(fieldName, BinaryUtils.ReadLongArray, BinaryUtils.TypeArrayLong); } /** <inheritdoc /> */ public long[] ReadLongArray() { return Read(BinaryUtils.ReadLongArray, BinaryUtils.TypeArrayLong); } /** <inheritdoc /> */ public float ReadFloat(string fieldName) { return ReadField(fieldName, ReadFloat, BinaryUtils.TypeFloat); } /** <inheritdoc /> */ public float ReadFloat() { return Stream.ReadFloat(); } /** <inheritdoc /> */ public float[] ReadFloatArray(string fieldName) { return ReadField(fieldName, BinaryUtils.ReadFloatArray, BinaryUtils.TypeArrayFloat); } /** <inheritdoc /> */ public float[] ReadFloatArray() { return Read(BinaryUtils.ReadFloatArray, BinaryUtils.TypeArrayFloat); } /** <inheritdoc /> */ public double ReadDouble(string fieldName) { return ReadField(fieldName, ReadDouble, BinaryUtils.TypeDouble); } /** <inheritdoc /> */ public double ReadDouble() { return Stream.ReadDouble(); } /** <inheritdoc /> */ public double[] ReadDoubleArray(string fieldName) { return ReadField(fieldName, BinaryUtils.ReadDoubleArray, BinaryUtils.TypeArrayDouble); } /** <inheritdoc /> */ public double[] ReadDoubleArray() { return Read(BinaryUtils.ReadDoubleArray, BinaryUtils.TypeArrayDouble); } /** <inheritdoc /> */ public decimal? ReadDecimal(string fieldName) { return ReadField(fieldName, BinaryUtils.ReadDecimal, BinaryUtils.TypeDecimal); } /** <inheritdoc /> */ public decimal? ReadDecimal() { return Read(BinaryUtils.ReadDecimal, BinaryUtils.TypeDecimal); } /** <inheritdoc /> */ public decimal?[] ReadDecimalArray(string fieldName) { return ReadField(fieldName, BinaryUtils.ReadDecimalArray, BinaryUtils.TypeArrayDecimal); } /** <inheritdoc /> */ public decimal?[] ReadDecimalArray() { return Read(BinaryUtils.ReadDecimalArray, BinaryUtils.TypeArrayDecimal); } /** <inheritdoc /> */ public DateTime? ReadTimestamp(string fieldName) { return ReadField(fieldName, BinaryUtils.ReadTimestamp, BinaryUtils.TypeTimestamp); } /** <inheritdoc /> */ public DateTime? ReadTimestamp() { return Read(BinaryUtils.ReadTimestamp, BinaryUtils.TypeTimestamp); } /** <inheritdoc /> */ public DateTime?[] ReadTimestampArray(string fieldName) { return ReadField(fieldName, BinaryUtils.ReadTimestampArray, BinaryUtils.TypeArrayTimestamp); } /** <inheritdoc /> */ public DateTime?[] ReadTimestampArray() { return Read(BinaryUtils.ReadTimestampArray, BinaryUtils.TypeArrayTimestamp); } /** <inheritdoc /> */ public string ReadString(string fieldName) { return ReadField(fieldName, BinaryUtils.ReadString, BinaryUtils.TypeString); } /** <inheritdoc /> */ public string ReadString() { return Read(BinaryUtils.ReadString, BinaryUtils.TypeString); } /** <inheritdoc /> */ public string[] ReadStringArray(string fieldName) { return ReadField(fieldName, r => BinaryUtils.ReadArray<string>(r, false), BinaryUtils.TypeArrayString); } /** <inheritdoc /> */ public string[] ReadStringArray() { return Read(r => BinaryUtils.ReadArray<string>(r, false), BinaryUtils.TypeArrayString); } /** <inheritdoc /> */ public Guid? ReadGuid(string fieldName) { return ReadField(fieldName, BinaryUtils.ReadGuid, BinaryUtils.TypeGuid); } /** <inheritdoc /> */ public Guid? ReadGuid() { return Read(BinaryUtils.ReadGuid, BinaryUtils.TypeGuid); } /** <inheritdoc /> */ public Guid?[] ReadGuidArray(string fieldName) { return ReadField(fieldName, r => BinaryUtils.ReadArray<Guid?>(r, false), BinaryUtils.TypeArrayGuid); } /** <inheritdoc /> */ public Guid?[] ReadGuidArray() { return Read(r => BinaryUtils.ReadArray<Guid?>(r, false), BinaryUtils.TypeArrayGuid); } /** <inheritdoc /> */ public T ReadEnum<T>(string fieldName) { return SeekField(fieldName) ? ReadEnum<T>() : default(T); } /** <inheritdoc /> */ public T ReadEnum<T>() { var hdr = ReadByte(); switch (hdr) { case BinaryUtils.HdrNull: return default(T); case BinaryUtils.TypeEnum: // Never read enums in binary mode when reading a field (we do not support half-binary objects) return ReadEnum0<T>(this, false); case BinaryUtils.HdrFull: // Unregistered enum written as serializable Stream.Seek(-1, SeekOrigin.Current); return ReadObject<T>(); default: throw new BinaryObjectException( string.Format("Invalid header on enum deserialization. Expected: {0} or {1} but was: {2}", BinaryUtils.TypeEnum, BinaryUtils.HdrFull, hdr)); } } /** <inheritdoc /> */ public T[] ReadEnumArray<T>(string fieldName) { return ReadField(fieldName, r => BinaryUtils.ReadArray<T>(r, true), BinaryUtils.TypeArrayEnum); } /** <inheritdoc /> */ public T[] ReadEnumArray<T>() { return Read(r => BinaryUtils.ReadArray<T>(r, true), BinaryUtils.TypeArrayEnum); } /** <inheritdoc /> */ public T ReadObject<T>(string fieldName) { if (_curRaw) throw new BinaryObjectException("Cannot read named fields after raw data is read."); if (SeekField(fieldName)) return Deserialize<T>(); return default(T); } /** <inheritdoc /> */ public T ReadObject<T>() { return Deserialize<T>(); } /** <inheritdoc /> */ public T[] ReadArray<T>(string fieldName) { return ReadField(fieldName, r => BinaryUtils.ReadArray<T>(r, true), BinaryUtils.TypeArray); } /** <inheritdoc /> */ public T[] ReadArray<T>() { return Read(r => BinaryUtils.ReadArray<T>(r, true), BinaryUtils.TypeArray); } /** <inheritdoc /> */ public ICollection ReadCollection(string fieldName) { return ReadCollection(fieldName, null, null); } /** <inheritdoc /> */ public ICollection ReadCollection() { return ReadCollection(null, null); } /** <inheritdoc /> */ public ICollection ReadCollection(string fieldName, CollectionFactory factory, CollectionAdder adder) { return ReadField(fieldName, r => BinaryUtils.ReadCollection(r, factory, adder), BinaryUtils.TypeCollection); } /** <inheritdoc /> */ public ICollection ReadCollection(CollectionFactory factory, CollectionAdder adder) { return Read(r => BinaryUtils.ReadCollection(r, factory, adder), BinaryUtils.TypeCollection); } /** <inheritdoc /> */ public IDictionary ReadDictionary(string fieldName) { return ReadDictionary(fieldName, null); } /** <inheritdoc /> */ public IDictionary ReadDictionary() { return ReadDictionary((DictionaryFactory)null); } /** <inheritdoc /> */ public IDictionary ReadDictionary(string fieldName, DictionaryFactory factory) { return ReadField(fieldName, r => BinaryUtils.ReadDictionary(r, factory), BinaryUtils.TypeDictionary); } /** <inheritdoc /> */ public IDictionary ReadDictionary(DictionaryFactory factory) { return Read(r => BinaryUtils.ReadDictionary(r, factory), BinaryUtils.TypeDictionary); } /// <summary> /// Enable detach mode for the next object read. /// </summary> public BinaryReader DetachNext() { _detach = true; return this; } /// <summary> /// Deserialize object. /// </summary> /// <returns>Deserialized object.</returns> public T Deserialize<T>() { T res; if (!TryDeserialize(out res) && default(T) != null) throw new BinaryObjectException(string.Format("Invalid data on deserialization. " + "Expected: '{0}' But was: null", typeof (T))); return res; } /// <summary> /// Deserialize object. /// </summary> /// <returns>Deserialized object.</returns> public bool TryDeserialize<T>(out T res) { int pos = Stream.Position; byte hdr = Stream.ReadByte(); var doDetach = _detach; // save detach flag into a var and reset so it does not go deeper _detach = false; switch (hdr) { case BinaryUtils.HdrNull: res = default(T); return false; case BinaryUtils.HdrHnd: res = ReadHandleObject<T>(pos); return true; case BinaryUtils.HdrFull: res = ReadFullObject<T>(pos); return true; case BinaryUtils.TypeBinary: res = ReadBinaryObject<T>(doDetach); return true; case BinaryUtils.TypeEnum: res = ReadEnum0<T>(this, _mode != BinaryMode.Deserialize); return true; } if (BinarySystemHandlers.TryReadSystemType(hdr, this, out res)) return true; throw new BinaryObjectException("Invalid header on deserialization [pos=" + pos + ", hdr=" + hdr + ']'); } /// <summary> /// Reads the binary object. /// </summary> private T ReadBinaryObject<T>(bool doDetach) { var len = Stream.ReadInt(); var binaryBytesPos = Stream.Position; if (_mode != BinaryMode.Deserialize) return TypeCaster<T>.Cast(ReadAsBinary(binaryBytesPos, len, doDetach)); Stream.Seek(len, SeekOrigin.Current); var offset = Stream.ReadInt(); var retPos = Stream.Position; Stream.Seek(binaryBytesPos + offset, SeekOrigin.Begin); _mode = BinaryMode.KeepBinary; try { return Deserialize<T>(); } finally { _mode = BinaryMode.Deserialize; Stream.Seek(retPos, SeekOrigin.Begin); } } /// <summary> /// Reads the binary object in binary form. /// </summary> private BinaryObject ReadAsBinary(int binaryBytesPos, int dataLen, bool doDetach) { try { Stream.Seek(dataLen + binaryBytesPos, SeekOrigin.Begin); var offs = Stream.ReadInt(); // offset inside data var pos = binaryBytesPos + offs; var hdr = BinaryObjectHeader.Read(Stream, pos); if (!doDetach) return new BinaryObject(_marsh, Stream.GetArray(), pos, hdr); Stream.Seek(pos, SeekOrigin.Begin); return new BinaryObject(_marsh, Stream.ReadByteArray(hdr.Length), 0, hdr); } finally { Stream.Seek(binaryBytesPos + dataLen + 4, SeekOrigin.Begin); } } /// <summary> /// Reads the full object. /// </summary> [SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "hashCode")] private T ReadFullObject<T>(int pos) { var hdr = BinaryObjectHeader.Read(Stream, pos); // Validate protocol version. BinaryUtils.ValidateProtocolVersion(hdr.Version); try { // Already read this object? object hndObj; if (_hnds != null && _hnds.TryGetValue(pos, out hndObj)) return (T) hndObj; if (hdr.IsUserType && _mode == BinaryMode.ForceBinary) { BinaryObject portObj; if (_detach) { Stream.Seek(pos, SeekOrigin.Begin); portObj = new BinaryObject(_marsh, Stream.ReadByteArray(hdr.Length), 0, hdr); } else portObj = new BinaryObject(_marsh, Stream.GetArray(), pos, hdr); T obj = _builder == null ? TypeCaster<T>.Cast(portObj) : TypeCaster<T>.Cast(_builder.Child(portObj)); AddHandle(pos, obj); return obj; } else { // Find descriptor. IBinaryTypeDescriptor desc; if (!_descs.TryGetValue(BinaryUtils.TypeKey(hdr.IsUserType, hdr.TypeId), out desc)) throw new BinaryObjectException("Unknown type ID: " + hdr.TypeId); // Instantiate object. if (desc.Type == null) throw new BinaryObjectException("No matching type found for object [typeId=" + desc.TypeId + ", typeName=" + desc.TypeName + ']'); // Preserve old frame. var oldHdr = _curHdr; int oldPos = _curPos; var oldStruct = _curStruct; bool oldRaw = _curRaw; var oldSchema = _curSchema; var oldSchemaMap = _curSchemaMap; // Set new frame. _curHdr = hdr; _curPos = pos; _curSchema = desc.Schema.Get(hdr.SchemaId); if (_curSchema == null) { _curSchema = ReadSchema(); desc.Schema.Add(hdr.SchemaId, _curSchema); } _curStruct = new BinaryStructureTracker(desc, desc.ReaderTypeStructure); _curRaw = false; // Read object. Stream.Seek(pos + BinaryObjectHeader.Size, SeekOrigin.Begin); object obj; var sysSerializer = desc.Serializer as IBinarySystemTypeSerializer; if (sysSerializer != null) obj = sysSerializer.ReadInstance(this); else { try { obj = FormatterServices.GetUninitializedObject(desc.Type); // Save handle. AddHandle(pos, obj); } catch (Exception e) { throw new BinaryObjectException("Failed to create type instance: " + desc.Type.AssemblyQualifiedName, e); } desc.Serializer.ReadBinary(obj, this); } _curStruct.UpdateReaderStructure(); // Restore old frame. _curHdr = oldHdr; _curPos = oldPos; _curStruct = oldStruct; _curRaw = oldRaw; _curSchema = oldSchema; _curSchemaMap = oldSchemaMap; // Process wrappers. We could introduce a common interface, but for only 2 if-else is faster. var wrappedSerializable = obj as SerializableObjectHolder; if (wrappedSerializable != null) return (T) wrappedSerializable.Item; var wrappedDateTime = obj as DateTimeHolder; if (wrappedDateTime != null) return TypeCaster<T>.Cast(wrappedDateTime.Item); return (T) obj; } } finally { // Advance stream pointer. Stream.Seek(pos + hdr.Length, SeekOrigin.Begin); } } /// <summary> /// Reads the schema. /// </summary> private int[] ReadSchema() { Stream.Seek(_curPos + _curHdr.SchemaOffset, SeekOrigin.Begin); var count = _curHdr.SchemaFieldCount; var offsetSize = _curHdr.SchemaFieldOffsetSize; var res = new int[count]; for (int i = 0; i < count; i++) { res[i] = Stream.ReadInt(); Stream.Seek(offsetSize, SeekOrigin.Current); } return res; } /// <summary> /// Reads the handle object. /// </summary> private T ReadHandleObject<T>(int pos) { // Get handle position. int hndPos = pos - Stream.ReadInt(); int retPos = Stream.Position; try { object hndObj; if (_builder == null || !_builder.TryGetCachedField(hndPos, out hndObj)) { if (_hnds == null || !_hnds.TryGetValue(hndPos, out hndObj)) { // No such handler, i.e. we trying to deserialize inner object before deserializing outer. Stream.Seek(hndPos, SeekOrigin.Begin); hndObj = Deserialize<T>(); } // Notify builder that we deserialized object on other location. if (_builder != null) _builder.CacheField(hndPos, hndObj); } return (T) hndObj; } finally { // Position stream to correct place. Stream.Seek(retPos, SeekOrigin.Begin); } } /// <summary> /// Adds a handle to the dictionary. /// </summary> /// <param name="pos">Position.</param> /// <param name="obj">Object.</param> private void AddHandle(int pos, object obj) { if (_hnds == null) _hnds = new BinaryReaderHandleDictionary(pos, obj); else _hnds.Add(pos, obj); } /// <summary> /// Underlying stream. /// </summary> public IBinaryStream Stream { get; private set; } /// <summary> /// Mark current output as raw. /// </summary> private void MarkRaw() { if (!_curRaw) { _curRaw = true; Stream.Seek(_curPos + _curHdr.GetRawOffset(Stream, _curPos), SeekOrigin.Begin); } } /// <summary> /// Determines whether header at current position is HDR_NULL. /// </summary> private bool IsNotNullHeader(byte expHdr) { var hdr = ReadByte(); if (hdr == BinaryUtils.HdrNull) return false; if (expHdr != hdr) throw new BinaryObjectException(string.Format("Invalid header on deserialization. " + "Expected: {0} but was: {1}", expHdr, hdr)); return true; } /// <summary> /// Seeks the field by name, reads header and returns true if field is present and header is not null. /// </summary> private bool SeekField(string fieldName, byte expHdr) { if (!SeekField(fieldName)) return false; // Expected read order, no need to seek. return IsNotNullHeader(expHdr); } /// <summary> /// Seeks the field by name. /// </summary> private bool SeekField(string fieldName) { if (_curRaw) throw new BinaryObjectException("Cannot read named fields after raw data is read."); if (!_curHdr.HasSchema) return false; var actionId = _curStruct.CurStructAction; var fieldId = _curStruct.GetFieldId(fieldName); if (_curSchema == null || actionId >= _curSchema.Length || fieldId != _curSchema[actionId]) { _curSchema = null; // read order is different, ignore schema for future reads _curSchemaMap = _curSchemaMap ?? _curHdr.ReadSchemaAsDictionary(Stream, _curPos); int pos; if (!_curSchemaMap.TryGetValue(fieldId, out pos)) return false; Stream.Seek(pos, SeekOrigin.Begin); } return true; } /// <summary> /// Seeks specified field and invokes provided func. /// </summary> private T ReadField<T>(string fieldName, Func<IBinaryStream, T> readFunc, byte expHdr) { return SeekField(fieldName, expHdr) ? readFunc(Stream) : default(T); } /// <summary> /// Seeks specified field and invokes provided func. /// </summary> private T ReadField<T>(string fieldName, Func<BinaryReader, T> readFunc, byte expHdr) { return SeekField(fieldName, expHdr) ? readFunc(this) : default(T); } /// <summary> /// Seeks specified field and invokes provided func. /// </summary> private T ReadField<T>(string fieldName, Func<T> readFunc, byte expHdr) { return SeekField(fieldName, expHdr) ? readFunc() : default(T); } /// <summary> /// Reads header and invokes specified func if the header is not null. /// </summary> private T Read<T>(Func<BinaryReader, T> readFunc, byte expHdr) { return IsNotNullHeader(expHdr) ? readFunc(this) : default(T); } /// <summary> /// Reads header and invokes specified func if the header is not null. /// </summary> private T Read<T>(Func<IBinaryStream, T> readFunc, byte expHdr) { return IsNotNullHeader(expHdr) ? readFunc(Stream) : default(T); } /// <summary> /// Reads the enum. /// </summary> private static T ReadEnum0<T>(BinaryReader reader, bool keepBinary) { var enumType = reader.ReadInt(); var enumValue = reader.ReadInt(); if (!keepBinary) return BinaryUtils.GetEnumValue<T>(enumValue, enumType, reader.Marshaller); return TypeCaster<T>.Cast(new BinaryEnum(enumType, enumValue, reader.Marshaller)); } } }
// MIT License // // Copyright (c) 2009-2017 Luca Piccioni // // 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. // // This file is automatically generated #pragma warning disable 649, 1572, 1573 // ReSharper disable RedundantUsingDirective using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; using Khronos; // ReSharper disable CheckNamespace // ReSharper disable InconsistentNaming // ReSharper disable JoinDeclarationAndInitializer namespace OpenGL { public partial class Gl { /// <summary> /// [GL] Value of GL_MAX_FRAGMENT_PROGRAM_LOCAL_PARAMETERS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_fragment_program")] public const int MAX_FRAGMENT_PROGRAM_LOCAL_PARAMETERS_NV = 0x8868; /// <summary> /// [GL] Value of GL_FRAGMENT_PROGRAM_NV symbol. /// </summary> [RequiredByFeature("GL_NV_fragment_program")] public const int FRAGMENT_PROGRAM_NV = 0x8870; /// <summary> /// [GL] Value of GL_FRAGMENT_PROGRAM_BINDING_NV symbol. /// </summary> [RequiredByFeature("GL_NV_fragment_program")] public const int FRAGMENT_PROGRAM_BINDING_NV = 0x8873; /// <summary> /// [GL] glProgramNamedParameter4fNV: Binding for glProgramNamedParameter4fNV. /// </summary> /// <param name="id"> /// A <see cref="T:uint"/>. /// </param> /// <param name="len"> /// A <see cref="T:int"/>. /// </param> /// <param name="name"> /// A <see cref="T:byte[]"/>. /// </param> /// <param name="x"> /// A <see cref="T:float"/>. /// </param> /// <param name="y"> /// A <see cref="T:float"/>. /// </param> /// <param name="z"> /// A <see cref="T:float"/>. /// </param> /// <param name="w"> /// A <see cref="T:float"/>. /// </param> [RequiredByFeature("GL_NV_fragment_program")] public static void ProgramNamedParameter4NV(uint id, int len, byte[] name, float x, float y, float z, float w) { Debug.Assert(name.Length >= 1); unsafe { fixed (byte* p_name = name) { Debug.Assert(Delegates.pglProgramNamedParameter4fNV != null, "pglProgramNamedParameter4fNV not implemented"); Delegates.pglProgramNamedParameter4fNV(id, len, p_name, x, y, z, w); LogCommand("glProgramNamedParameter4fNV", null, id, len, name, x, y, z, w ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glProgramNamedParameter4fvNV: Binding for glProgramNamedParameter4fvNV. /// </summary> /// <param name="id"> /// A <see cref="T:uint"/>. /// </param> /// <param name="len"> /// A <see cref="T:int"/>. /// </param> /// <param name="name"> /// A <see cref="T:byte[]"/>. /// </param> /// <param name="v"> /// A <see cref="T:float[]"/>. /// </param> [RequiredByFeature("GL_NV_fragment_program")] public static void ProgramNamedParameter4NV(uint id, int len, byte[] name, float[] v) { Debug.Assert(name.Length >= 1); Debug.Assert(v.Length >= 4); unsafe { fixed (byte* p_name = name) fixed (float* p_v = v) { Debug.Assert(Delegates.pglProgramNamedParameter4fvNV != null, "pglProgramNamedParameter4fvNV not implemented"); Delegates.pglProgramNamedParameter4fvNV(id, len, p_name, p_v); LogCommand("glProgramNamedParameter4fvNV", null, id, len, name, v ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glProgramNamedParameter4dNV: Binding for glProgramNamedParameter4dNV. /// </summary> /// <param name="id"> /// A <see cref="T:uint"/>. /// </param> /// <param name="len"> /// A <see cref="T:int"/>. /// </param> /// <param name="name"> /// A <see cref="T:byte[]"/>. /// </param> /// <param name="x"> /// A <see cref="T:double"/>. /// </param> /// <param name="y"> /// A <see cref="T:double"/>. /// </param> /// <param name="z"> /// A <see cref="T:double"/>. /// </param> /// <param name="w"> /// A <see cref="T:double"/>. /// </param> [RequiredByFeature("GL_NV_fragment_program")] public static void ProgramNamedParameter4NV(uint id, int len, byte[] name, double x, double y, double z, double w) { Debug.Assert(name.Length >= 1); unsafe { fixed (byte* p_name = name) { Debug.Assert(Delegates.pglProgramNamedParameter4dNV != null, "pglProgramNamedParameter4dNV not implemented"); Delegates.pglProgramNamedParameter4dNV(id, len, p_name, x, y, z, w); LogCommand("glProgramNamedParameter4dNV", null, id, len, name, x, y, z, w ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glProgramNamedParameter4dvNV: Binding for glProgramNamedParameter4dvNV. /// </summary> /// <param name="id"> /// A <see cref="T:uint"/>. /// </param> /// <param name="len"> /// A <see cref="T:int"/>. /// </param> /// <param name="name"> /// A <see cref="T:byte[]"/>. /// </param> /// <param name="v"> /// A <see cref="T:double[]"/>. /// </param> [RequiredByFeature("GL_NV_fragment_program")] public static void ProgramNamedParameter4NV(uint id, int len, byte[] name, double[] v) { Debug.Assert(name.Length >= 1); Debug.Assert(v.Length >= 4); unsafe { fixed (byte* p_name = name) fixed (double* p_v = v) { Debug.Assert(Delegates.pglProgramNamedParameter4dvNV != null, "pglProgramNamedParameter4dvNV not implemented"); Delegates.pglProgramNamedParameter4dvNV(id, len, p_name, p_v); LogCommand("glProgramNamedParameter4dvNV", null, id, len, name, v ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glGetProgramNamedParameterfvNV: Binding for glGetProgramNamedParameterfvNV. /// </summary> /// <param name="id"> /// A <see cref="T:uint"/>. /// </param> /// <param name="len"> /// A <see cref="T:int"/>. /// </param> /// <param name="name"> /// A <see cref="T:byte[]"/>. /// </param> /// <param name="params"> /// A <see cref="T:float[]"/>. /// </param> [RequiredByFeature("GL_NV_fragment_program")] public static void GetProgramNamedParameterNV(uint id, int len, byte[] name, [Out] float[] @params) { Debug.Assert(name.Length >= 1); Debug.Assert(@params.Length >= 4); unsafe { fixed (byte* p_name = name) fixed (float* p_params = @params) { Debug.Assert(Delegates.pglGetProgramNamedParameterfvNV != null, "pglGetProgramNamedParameterfvNV not implemented"); Delegates.pglGetProgramNamedParameterfvNV(id, len, p_name, p_params); LogCommand("glGetProgramNamedParameterfvNV", null, id, len, name, @params ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glGetProgramNamedParameterdvNV: Binding for glGetProgramNamedParameterdvNV. /// </summary> /// <param name="id"> /// A <see cref="T:uint"/>. /// </param> /// <param name="len"> /// A <see cref="T:int"/>. /// </param> /// <param name="name"> /// A <see cref="T:byte[]"/>. /// </param> /// <param name="params"> /// A <see cref="T:double[]"/>. /// </param> [RequiredByFeature("GL_NV_fragment_program")] public static void GetProgramNamedParameterNV(uint id, int len, byte[] name, [Out] double[] @params) { Debug.Assert(name.Length >= 1); Debug.Assert(@params.Length >= 4); unsafe { fixed (byte* p_name = name) fixed (double* p_params = @params) { Debug.Assert(Delegates.pglGetProgramNamedParameterdvNV != null, "pglGetProgramNamedParameterdvNV not implemented"); Delegates.pglGetProgramNamedParameterdvNV(id, len, p_name, p_params); LogCommand("glGetProgramNamedParameterdvNV", null, id, len, name, @params ); } } DebugCheckErrors(null); } internal static unsafe partial class Delegates { [RequiredByFeature("GL_NV_fragment_program")] [SuppressUnmanagedCodeSecurity] internal delegate void glProgramNamedParameter4fNV(uint id, int len, byte* name, float x, float y, float z, float w); [RequiredByFeature("GL_NV_fragment_program")] [ThreadStatic] internal static glProgramNamedParameter4fNV pglProgramNamedParameter4fNV; [RequiredByFeature("GL_NV_fragment_program")] [SuppressUnmanagedCodeSecurity] internal delegate void glProgramNamedParameter4fvNV(uint id, int len, byte* name, float* v); [RequiredByFeature("GL_NV_fragment_program")] [ThreadStatic] internal static glProgramNamedParameter4fvNV pglProgramNamedParameter4fvNV; [RequiredByFeature("GL_NV_fragment_program")] [SuppressUnmanagedCodeSecurity] internal delegate void glProgramNamedParameter4dNV(uint id, int len, byte* name, double x, double y, double z, double w); [RequiredByFeature("GL_NV_fragment_program")] [ThreadStatic] internal static glProgramNamedParameter4dNV pglProgramNamedParameter4dNV; [RequiredByFeature("GL_NV_fragment_program")] [SuppressUnmanagedCodeSecurity] internal delegate void glProgramNamedParameter4dvNV(uint id, int len, byte* name, double* v); [RequiredByFeature("GL_NV_fragment_program")] [ThreadStatic] internal static glProgramNamedParameter4dvNV pglProgramNamedParameter4dvNV; [RequiredByFeature("GL_NV_fragment_program")] [SuppressUnmanagedCodeSecurity] internal delegate void glGetProgramNamedParameterfvNV(uint id, int len, byte* name, float* @params); [RequiredByFeature("GL_NV_fragment_program")] [ThreadStatic] internal static glGetProgramNamedParameterfvNV pglGetProgramNamedParameterfvNV; [RequiredByFeature("GL_NV_fragment_program")] [SuppressUnmanagedCodeSecurity] internal delegate void glGetProgramNamedParameterdvNV(uint id, int len, byte* name, double* @params); [RequiredByFeature("GL_NV_fragment_program")] [ThreadStatic] internal static glGetProgramNamedParameterdvNV pglGetProgramNamedParameterdvNV; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Compute { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.Serialization; using System.Threading; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Compute; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Cluster; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Compute.Closure; using Apache.Ignite.Core.Impl.Unmanaged; using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils; /// <summary> /// Compute implementation. /// </summary> [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")] internal class ComputeImpl : PlatformTarget { /** */ private const int OpAffinity = 1; /** */ private const int OpBroadcast = 2; /** */ private const int OpExec = 3; /** */ private const int OpExecAsync = 4; /** */ private const int OpUnicast = 5; /** Underlying projection. */ private readonly ClusterGroupImpl _prj; /** Whether objects must be kept in binary form. */ private readonly ThreadLocal<bool> _keepBinary = new ThreadLocal<bool>(() => false); /// <summary> /// Constructor. /// </summary> /// <param name="target">Target.</param> /// <param name="marsh">Marshaller.</param> /// <param name="prj">Projection.</param> /// <param name="keepBinary">Binary flag.</param> public ComputeImpl(IUnmanagedTarget target, Marshaller marsh, ClusterGroupImpl prj, bool keepBinary) : base(target, marsh) { _prj = prj; _keepBinary.Value = keepBinary; } /// <summary> /// Grid projection to which this compute instance belongs. /// </summary> public IClusterGroup ClusterGroup { get { return _prj; } } /// <summary> /// Sets no-failover flag for the next executed task on this projection in the current thread. /// If flag is set, job will be never failed over even if remote node crashes or rejects execution. /// When task starts execution, the no-failover flag is reset, so all other task will use default /// failover policy, unless this flag is set again. /// </summary> public void WithNoFailover() { UU.ComputeWithNoFailover(Target); } /// <summary> /// Sets task timeout for the next executed task on this projection in the current thread. /// When task starts execution, the timeout is reset, so one timeout is used only once. /// </summary> /// <param name="timeout">Computation timeout in milliseconds.</param> public void WithTimeout(long timeout) { UU.ComputeWithTimeout(Target, timeout); } /// <summary> /// Sets keep-binary flag for the next executed Java task on this projection in the current /// thread so that task argument passed to Java and returned task results will not be /// deserialized. /// </summary> public void WithKeepBinary() { _keepBinary.Value = true; } /// <summary> /// Executes given Java task on the grid projection. If task for given name has not been deployed yet, /// then 'taskName' will be used as task class name to auto-deploy the task. /// </summary> public TReduceRes ExecuteJavaTask<TReduceRes>(string taskName, object taskArg) { IgniteArgumentCheck.NotNullOrEmpty(taskName, "taskName"); ICollection<IClusterNode> nodes = _prj.Predicate == null ? null : _prj.GetNodes(); try { TReduceRes res = DoOutInOp<TReduceRes>(OpExec, writer => { WriteTask(writer, taskName, taskArg, nodes); }); return res; } finally { _keepBinary.Value = false; } } /// <summary> /// Executes given Java task asynchronously on the grid projection. /// If task for given name has not been deployed yet, /// then 'taskName' will be used as task class name to auto-deploy the task. /// </summary> public Future<TReduceRes> ExecuteJavaTaskAsync<TReduceRes>(string taskName, object taskArg) { IgniteArgumentCheck.NotNullOrEmpty(taskName, "taskName"); ICollection<IClusterNode> nodes = _prj.Predicate == null ? null : _prj.GetNodes(); try { Future<TReduceRes> fut = null; DoOutInOp(OpExecAsync, writer => { WriteTask(writer, taskName, taskArg, nodes); }, input => { fut = GetFuture<TReduceRes>((futId, futTyp) => UU.TargetListenFutureAndGet(Target, futId, futTyp), _keepBinary.Value); }); return fut; } finally { _keepBinary.Value = false; } } /// <summary> /// Executes given task on the grid projection. For step-by-step explanation of task execution process /// refer to <see cref="IComputeTask{A,T,R}"/> documentation. /// </summary> /// <param name="task">Task to execute.</param> /// <param name="taskArg">Optional task argument.</param> /// <returns>Task result.</returns> public Future<TReduceRes> Execute<TArg, TJobRes, TReduceRes>(IComputeTask<TArg, TJobRes, TReduceRes> task, TArg taskArg) { IgniteArgumentCheck.NotNull(task, "task"); var holder = new ComputeTaskHolder<TArg, TJobRes, TReduceRes>((Ignite) _prj.Ignite, this, task, taskArg); long ptr = Marshaller.Ignite.HandleRegistry.Allocate(holder); var futTarget = UU.ComputeExecuteNative(Target, ptr, _prj.TopologyVersion); var future = holder.Future; future.SetTarget(futTarget); return future; } /// <summary> /// Executes given task on the grid projection. For step-by-step explanation of task execution process /// refer to <see cref="IComputeTask{A,T,R}"/> documentation. /// </summary> /// <param name="taskType">Task type.</param> /// <param name="taskArg">Optional task argument.</param> /// <returns>Task result.</returns> public Future<TReduceRes> Execute<TArg, TJobRes, TReduceRes>(Type taskType, TArg taskArg) { IgniteArgumentCheck.NotNull(taskType, "taskType"); object task = FormatterServices.GetUninitializedObject(taskType); var task0 = task as IComputeTask<TArg, TJobRes, TReduceRes>; if (task0 == null) throw new IgniteException("Task type doesn't implement IComputeTask: " + taskType.Name); return Execute(task0, taskArg); } /// <summary> /// Executes provided job on a node in this grid projection. The result of the /// job execution is returned from the result closure. /// </summary> /// <param name="clo">Job to execute.</param> /// <returns>Job result for this execution.</returns> public Future<TJobRes> Execute<TJobRes>(IComputeFunc<TJobRes> clo) { IgniteArgumentCheck.NotNull(clo, "clo"); return ExecuteClosures0(new ComputeSingleClosureTask<object, TJobRes, TJobRes>(), new ComputeOutFuncJob(clo.ToNonGeneric()), null, false); } /// <summary> /// Executes provided delegate on a node in this grid projection. The result of the /// job execution is returned from the result closure. /// </summary> /// <param name="func">Func to execute.</param> /// <returns>Job result for this execution.</returns> public Future<TJobRes> Execute<TJobRes>(Func<TJobRes> func) { IgniteArgumentCheck.NotNull(func, "func"); var wrappedFunc = new ComputeOutFuncWrapper(func, () => func()); return ExecuteClosures0(new ComputeSingleClosureTask<object, TJobRes, TJobRes>(), new ComputeOutFuncJob(wrappedFunc), null, false); } /// <summary> /// Executes collection of jobs on nodes within this grid projection. /// </summary> /// <param name="clos">Collection of jobs to execute.</param> /// <returns>Collection of job results for this execution.</returns> public Future<ICollection<TJobRes>> Execute<TJobRes>(IEnumerable<IComputeFunc<TJobRes>> clos) { IgniteArgumentCheck.NotNull(clos, "clos"); ICollection<IComputeJob> jobs = new List<IComputeJob>(GetCountOrZero(clos)); foreach (IComputeFunc<TJobRes> clo in clos) jobs.Add(new ComputeOutFuncJob(clo.ToNonGeneric())); return ExecuteClosures0(new ComputeMultiClosureTask<object, TJobRes, ICollection<TJobRes>>(jobs.Count), null, jobs, false); } /// <summary> /// Executes collection of jobs on nodes within this grid projection. /// </summary> /// <param name="clos">Collection of jobs to execute.</param> /// <param name="rdc">Reducer to reduce all job results into one individual return value.</param> /// <returns>Collection of job results for this execution.</returns> public Future<TReduceRes> Execute<TJobRes, TReduceRes>(IEnumerable<IComputeFunc<TJobRes>> clos, IComputeReducer<TJobRes, TReduceRes> rdc) { IgniteArgumentCheck.NotNull(clos, "clos"); ICollection<IComputeJob> jobs = new List<IComputeJob>(GetCountOrZero(clos)); foreach (var clo in clos) jobs.Add(new ComputeOutFuncJob(clo.ToNonGeneric())); return ExecuteClosures0(new ComputeReducingClosureTask<object, TJobRes, TReduceRes>(rdc), null, jobs, false); } /// <summary> /// Broadcasts given job to all nodes in grid projection. Every participating node will return a job result. /// </summary> /// <param name="clo">Job to broadcast to all projection nodes.</param> /// <returns>Collection of results for this execution.</returns> public Future<ICollection<TJobRes>> Broadcast<TJobRes>(IComputeFunc<TJobRes> clo) { IgniteArgumentCheck.NotNull(clo, "clo"); return ExecuteClosures0(new ComputeMultiClosureTask<object, TJobRes, ICollection<TJobRes>>(1), new ComputeOutFuncJob(clo.ToNonGeneric()), null, true); } /// <summary> /// Broadcasts given closure job with passed in argument to all nodes in grid projection. /// Every participating node will return a job result. /// </summary> /// <param name="clo">Job to broadcast to all projection nodes.</param> /// <param name="arg">Job closure argument.</param> /// <returns>Collection of results for this execution.</returns> public Future<ICollection<TJobRes>> Broadcast<TArg, TJobRes>(IComputeFunc<TArg, TJobRes> clo, TArg arg) { IgniteArgumentCheck.NotNull(clo, "clo"); return ExecuteClosures0(new ComputeMultiClosureTask<object, TJobRes, ICollection<TJobRes>>(1), new ComputeFuncJob(clo.ToNonGeneric(), arg), null, true); } /// <summary> /// Broadcasts given job to all nodes in grid projection. /// </summary> /// <param name="action">Job to broadcast to all projection nodes.</param> public Future<object> Broadcast(IComputeAction action) { IgniteArgumentCheck.NotNull(action, "action"); return ExecuteClosures0(new ComputeSingleClosureTask<object, object, object>(), new ComputeActionJob(action), opId: OpBroadcast); } /// <summary> /// Executes provided job on a node in this grid projection. /// </summary> /// <param name="action">Job to execute.</param> public Future<object> Run(IComputeAction action) { IgniteArgumentCheck.NotNull(action, "action"); return ExecuteClosures0(new ComputeSingleClosureTask<object, object, object>(), new ComputeActionJob(action)); } /// <summary> /// Executes collection of jobs on Ignite nodes within this grid projection. /// </summary> /// <param name="actions">Jobs to execute.</param> public Future<object> Run(IEnumerable<IComputeAction> actions) { IgniteArgumentCheck.NotNull(actions, "actions"); var actions0 = actions as ICollection; if (actions0 == null) { var jobs = actions.Select(a => new ComputeActionJob(a)).ToList(); return ExecuteClosures0(new ComputeSingleClosureTask<object, object, object>(), jobs: jobs, jobsCount: jobs.Count); } else { var jobs = actions.Select(a => new ComputeActionJob(a)); return ExecuteClosures0(new ComputeSingleClosureTask<object, object, object>(), jobs: jobs, jobsCount: actions0.Count); } } /// <summary> /// Executes provided closure job on a node in this grid projection. /// </summary> /// <param name="clo">Job to run.</param> /// <param name="arg">Job argument.</param> /// <returns>Job result for this execution.</returns> public Future<TJobRes> Apply<TArg, TJobRes>(IComputeFunc<TArg, TJobRes> clo, TArg arg) { IgniteArgumentCheck.NotNull(clo, "clo"); return ExecuteClosures0(new ComputeSingleClosureTask<TArg, TJobRes, TJobRes>(), new ComputeFuncJob(clo.ToNonGeneric(), arg), null, false); } /// <summary> /// Executes provided closure job on nodes within this grid projection. A new job is executed for /// every argument in the passed in collection. The number of actual job executions will be /// equal to size of the job arguments collection. /// </summary> /// <param name="clo">Job to run.</param> /// <param name="args">Job arguments.</param> /// <returns>Collection of job results.</returns> public Future<ICollection<TJobRes>> Apply<TArg, TJobRes>(IComputeFunc<TArg, TJobRes> clo, IEnumerable<TArg> args) { IgniteArgumentCheck.NotNull(clo, "clo"); IgniteArgumentCheck.NotNull(clo, "clo"); var jobs = new List<IComputeJob>(GetCountOrZero(args)); var func = clo.ToNonGeneric(); foreach (TArg arg in args) jobs.Add(new ComputeFuncJob(func, arg)); return ExecuteClosures0(new ComputeMultiClosureTask<TArg, TJobRes, ICollection<TJobRes>>(jobs.Count), null, jobs, false); } /// <summary> /// Executes provided closure job on nodes within this grid projection. A new job is executed for /// every argument in the passed in collection. The number of actual job executions will be /// equal to size of the job arguments collection. The returned job results will be reduced /// into an individual result by provided reducer. /// </summary> /// <param name="clo">Job to run.</param> /// <param name="args">Job arguments.</param> /// <param name="rdc">Reducer to reduce all job results into one individual return value.</param> /// <returns>Reduced job result for this execution.</returns> public Future<TReduceRes> Apply<TArg, TJobRes, TReduceRes>(IComputeFunc<TArg, TJobRes> clo, IEnumerable<TArg> args, IComputeReducer<TJobRes, TReduceRes> rdc) { IgniteArgumentCheck.NotNull(clo, "clo"); IgniteArgumentCheck.NotNull(clo, "clo"); IgniteArgumentCheck.NotNull(clo, "clo"); ICollection<IComputeJob> jobs = new List<IComputeJob>(GetCountOrZero(args)); var func = clo.ToNonGeneric(); foreach (TArg arg in args) jobs.Add(new ComputeFuncJob(func, arg)); return ExecuteClosures0(new ComputeReducingClosureTask<TArg, TJobRes, TReduceRes>(rdc), null, jobs, false); } /// <summary> /// Executes given job on the node where data for provided affinity key is located /// (a.k.a. affinity co-location). /// </summary> /// <param name="cacheName">Name of the cache to use for affinity co-location.</param> /// <param name="affinityKey">Affinity key.</param> /// <param name="action">Job to execute.</param> public Future<object> AffinityRun(string cacheName, object affinityKey, IComputeAction action) { IgniteArgumentCheck.NotNull(action, "action"); return ExecuteClosures0(new ComputeSingleClosureTask<object, object, object>(), new ComputeActionJob(action), opId: OpAffinity, writeAction: w => WriteAffinity(w, cacheName, affinityKey)); } /// <summary> /// Executes given job on the node where data for provided affinity key is located /// (a.k.a. affinity co-location). /// </summary> /// <param name="cacheName">Name of the cache to use for affinity co-location.</param> /// <param name="affinityKey">Affinity key.</param> /// <param name="clo">Job to execute.</param> /// <returns>Job result for this execution.</returns> /// <typeparam name="TJobRes">Type of job result.</typeparam> public Future<TJobRes> AffinityCall<TJobRes>(string cacheName, object affinityKey, IComputeFunc<TJobRes> clo) { IgniteArgumentCheck.NotNull(clo, "clo"); return ExecuteClosures0(new ComputeSingleClosureTask<object, TJobRes, TJobRes>(), new ComputeOutFuncJob(clo.ToNonGeneric()), opId: OpAffinity, writeAction: w => WriteAffinity(w, cacheName, affinityKey)); } /** <inheritDoc /> */ protected override T Unmarshal<T>(IBinaryStream stream) { bool keep = _keepBinary.Value; return Marshaller.Unmarshal<T>(stream, keep); } /// <summary> /// Internal routine for closure-based task execution. /// </summary> /// <param name="task">Task.</param> /// <param name="job">Job.</param> /// <param name="jobs">Jobs.</param> /// <param name="broadcast">Broadcast flag.</param> /// <returns>Future.</returns> private Future<TReduceRes> ExecuteClosures0<TArg, TJobRes, TReduceRes>( IComputeTask<TArg, TJobRes, TReduceRes> task, IComputeJob job, ICollection<IComputeJob> jobs, bool broadcast) { return ExecuteClosures0(task, job, jobs, broadcast ? OpBroadcast : OpUnicast, jobs == null ? 1 : jobs.Count); } /// <summary> /// Internal routine for closure-based task execution. /// </summary> /// <param name="task">Task.</param> /// <param name="job">Job.</param> /// <param name="jobs">Jobs.</param> /// <param name="opId">Op code.</param> /// <param name="jobsCount">Jobs count.</param> /// <param name="writeAction">Custom write action.</param> /// <returns>Future.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "User code can throw any exception")] private Future<TReduceRes> ExecuteClosures0<TArg, TJobRes, TReduceRes>( IComputeTask<TArg, TJobRes, TReduceRes> task, IComputeJob job = null, IEnumerable<IComputeJob> jobs = null, int opId = OpUnicast, int jobsCount = 0, Action<BinaryWriter> writeAction = null) { Debug.Assert(job != null || jobs != null); var holder = new ComputeTaskHolder<TArg, TJobRes, TReduceRes>((Ignite) _prj.Ignite, this, task, default(TArg)); var taskHandle = Marshaller.Ignite.HandleRegistry.Allocate(holder); var jobHandles = new List<long>(job != null ? 1 : jobsCount); try { Exception err = null; try { var futTarget = DoOutOpObject(opId, writer => { writer.WriteLong(taskHandle); if (job != null) { writer.WriteInt(1); jobHandles.Add(WriteJob(job, writer)); } else { writer.WriteInt(jobsCount); Debug.Assert(jobs != null, "jobs != null"); jobHandles.AddRange(jobs.Select(jobEntry => WriteJob(jobEntry, writer))); } holder.JobHandles(jobHandles); if (writeAction != null) writeAction(writer); }); holder.Future.SetTarget(futTarget); } catch (Exception e) { err = e; } if (err != null) { // Manual job handles release because they were not assigned to the task yet. foreach (var hnd in jobHandles) Marshaller.Ignite.HandleRegistry.Release(hnd); holder.CompleteWithError(taskHandle, err); } } catch (Exception e) { // This exception means that out-op failed. holder.CompleteWithError(taskHandle, e); } return holder.Future; } /// <summary> /// Writes the job. /// </summary> /// <param name="job">The job.</param> /// <param name="writer">The writer.</param> /// <returns>Handle to the job holder</returns> private long WriteJob(IComputeJob job, BinaryWriter writer) { var jobHolder = new ComputeJobHolder((Ignite) _prj.Ignite, job); var jobHandle = Marshaller.Ignite.HandleRegistry.Allocate(jobHolder); writer.WriteLong(jobHandle); try { writer.WriteObject(jobHolder); } catch (Exception) { Marshaller.Ignite.HandleRegistry.Release(jobHandle); throw; } return jobHandle; } /// <summary> /// Write task to the writer. /// </summary> /// <param name="writer">Writer.</param> /// <param name="taskName">Task name.</param> /// <param name="taskArg">Task arg.</param> /// <param name="nodes">Nodes.</param> private void WriteTask(BinaryWriter writer, string taskName, object taskArg, ICollection<IClusterNode> nodes) { writer.WriteString(taskName); writer.WriteBoolean(_keepBinary.Value); writer.Write(taskArg); WriteNodeIds(writer, nodes); } /// <summary> /// Write node IDs. /// </summary> /// <param name="writer">Writer.</param> /// <param name="nodes">Nodes.</param> private static void WriteNodeIds(BinaryWriter writer, ICollection<IClusterNode> nodes) { if (nodes == null) writer.WriteBoolean(false); else { writer.WriteBoolean(true); writer.WriteInt(nodes.Count); foreach (IClusterNode node in nodes) writer.WriteGuid(node.Id); } } /// <summary> /// Writes the affinity info. /// </summary> /// <param name="writer">The writer.</param> /// <param name="cacheName">Name of the cache to use for affinity co-location.</param> /// <param name="affinityKey">Affinity key.</param> private static void WriteAffinity(BinaryWriter writer, string cacheName, object affinityKey) { writer.WriteString(cacheName); writer.WriteObject(affinityKey); } /// <summary> /// Gets element count or zero. /// </summary> private static int GetCountOrZero(object collection) { var coll = collection as ICollection; return coll == null ? 0 : coll.Count; } } }