context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// The MIT License (MIT) // // Copyright (c) 2014-2017, Institute for Software & Systems Engineering // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. namespace ISSE.SafetyChecking.AnalysisModelTraverser { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.ExceptionServices; using System.Threading.Tasks; using ExecutableModel; using AnalysisModel; using ExecutedModel; using Utilities; using System.Globalization; /// <summary> /// A base class for model traversers that travserse an <see cref="AnalysisModel" /> to carry out certain actions. /// </summary> internal sealed class ModelTraverser : DisposableObject { public const int DeriveTransitionSizeFromModel = -1; private readonly LoadBalancer _loadBalancer; private readonly StateStorage _states; private readonly Worker[] _workers; private readonly TimeSpan _initializationTime; /// <summary> /// Initializes a new instance. /// </summary> /// <param name="createModel">Creates the model that should be checked.</param> /// <param name="output">The callback that should be used to output messages.</param> /// <param name="configuration">The analysis configuration that should be used.</param> internal ModelTraverser(AnalysisModelCreator createModel, AnalysisConfiguration configuration, int transitionSize, bool createStutteringState) { Requires.NotNull(createModel, nameof(createModel)); var stopwatch = new Stopwatch(); stopwatch.Start(); TransitionCollection.ValidateTransitionSizes(); var tasks = new Task[configuration.CpuCount]; var stacks = new StateStack[configuration.CpuCount]; _loadBalancer = new LoadBalancer(stacks); Context = new TraversalContext(_loadBalancer, configuration); _workers = new Worker[configuration.CpuCount]; for (var i = 0; i < configuration.CpuCount; ++i) { var index = i; tasks[i] = Task.Factory.StartNew(() => { stacks[index] = new StateStack(configuration.StackCapacity); _workers[index] = new Worker(index, Context, stacks[index], createModel.Create()); }); } Task.WaitAll(tasks); var firstModel = _workers[0].Model; if (transitionSize == DeriveTransitionSizeFromModel) { transitionSize = firstModel.TransitionSize; } var modelCapacity = configuration.ModelCapacity.DeriveModelByteSize(firstModel.ModelStateVectorSize, transitionSize); Context.ModelCapacity = modelCapacity; if (configuration.UseCompactStateStorage) _states = new CompactStateStorage(modelCapacity.SizeOfState, modelCapacity.NumberOfStates); else _states = new SparseStateStorage(modelCapacity.SizeOfState, modelCapacity.NumberOfStates); Context.States = _states; if (createStutteringState) Context.StutteringStateIndex = _states.ReserveStateIndex(); _initializationTime = stopwatch.Elapsed; stopwatch.Stop(); } /// <summary> /// Gets the context of the traversal. /// </summary> public TraversalContext Context { get; } /// <summary> /// Gets the <see cref="AnalysisModel" /> instances analyzed by the checker's <see cref="Worker" /> instances. /// </summary> public IEnumerable<AnalysisModel> AnalyzedModels => _workers.Select(worker => worker.Model); /// <summary> /// Traverses the model. /// </summary> private void TraverseModel() { Reset(); _workers[0].ComputeInitialStates(); if (_loadBalancer.IsTerminated) return; var tasks = new Task[_workers.Length]; for (var i = 0; i < _workers.Length; ++i) tasks[i] = Task.Factory.StartNew(_workers[i].Check); Task.WaitAll(tasks); } /// <summary> /// Traverses the model. /// </summary> public void TraverseModelAndReport() { Requires.That(IntPtr.Size == 8, "Model traversal is only supported in 64bit processes."); var stopwatch = new Stopwatch(); stopwatch.Start(); if (!Context.Configuration.ProgressReportsOnly) { Context.Output?.WriteLine($"Traverse model using {AnalyzedModels.Count()} CPU cores."); Context.Output?.WriteLine($"State vector has {AnalyzedModels.First().ModelStateVectorSize} bytes."); } try { TraverseModel(); RethrowTraversalException(); if (!Context.Configuration.ProgressReportsOnly) Context.Report(); } finally { stopwatch.Stop(); if (!Context.Configuration.ProgressReportsOnly) { var stateCount = Context.StateCount.ToString("N0", CultureInfo.InvariantCulture); var transitionCount = Context.TransitionCount.ToString("N0", CultureInfo.InvariantCulture); var computedTransitionCount = Context.ComputedTransitionCount.ToString("N0", CultureInfo.InvariantCulture); var statesPerSecond = ((long)(Context.TransitionCount / stopwatch.Elapsed.TotalSeconds)).ToString("N0", CultureInfo.InvariantCulture); var transitionsPerSecond = ((long)(Context.StateCount / stopwatch.Elapsed.TotalSeconds)).ToString("N0", CultureInfo.InvariantCulture); Context.Output?.WriteLine(String.Empty); Context.Output?.WriteLine("==============================================="); Context.Output?.WriteLine($"Initialization time: {_initializationTime}"); Context.Output?.WriteLine($"Model traversal time: {stopwatch.Elapsed}"); Context.Output?.WriteLine($"Saved states: {stateCount}"); Context.Output?.WriteLine($"Saved transitions: {transitionCount}"); Context.Output?.WriteLine($"Computed transitions: {computedTransitionCount}"); Context.Output?.WriteLine($"{statesPerSecond} states per second"); Context.Output?.WriteLine($"{transitionsPerSecond} transitions per second"); Context.Output?.WriteLine("==============================================="); Context.Output?.WriteLine(String.Empty); } } } /// <summary> /// Rethrows any exception thrown during the traversal process, if any. /// </summary> private void RethrowTraversalException() { if (Context.Exception == null) return; if (Context.Exception is ModelException) throw new AnalysisException(Context.Exception.InnerException, Context.CounterExample); ExceptionDispatchInfo.Capture(Context.Exception).Throw(); } /// <summary> /// Resets the checker so that a new invariant check can be started. /// </summary> private void Reset() { Context.Reset(); foreach (var worker in _workers) worker.Reset(); _states.Clear(_workers[0].TraversalModifierStateVectorSize); _loadBalancer.Reset(); } /// <summary> /// Disposes the object, releasing all managed and unmanaged resources. /// </summary> /// <param name="disposing">If true, indicates that the object is disposed; otherwise, the object is finalized.</param> protected override void OnDisposing(bool disposing) { // StateStorage must be freed manually. Reason is that invariant checker does not free up the // space, because it might be necessary for other usages of the ModelTraversers (e.g. StateGraphGenerator // which keeps the States for the StateGraph) if (!disposing) return; _workers.SafeDisposeAll(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Management.Automation; using System.Collections.Generic; using System.Management.Automation.Internal; using System.Management.Automation.Language; namespace Microsoft.PowerShell.Commands.Internal.Format { /// <summary> /// Facade class to provide context information to process /// exceptions. /// </summary> internal sealed class TerminatingErrorContext { internal TerminatingErrorContext(PSCmdlet command) { if (command == null) throw PSTraceSource.NewArgumentNullException("command"); _command = command; } internal void ThrowTerminatingError(ErrorRecord errorRecord) { _command.ThrowTerminatingError(errorRecord); } private PSCmdlet _command; } /// <summary> /// Helper class to invoke a command in a secondary pipeline. /// NOTE: this implementation does not return any error messages /// that invoked pipelines might generate. /// </summary> internal sealed class CommandWrapper : IDisposable { /// <summary> /// Initialize the command before executing. /// </summary> /// <param name="execContext">ExecutionContext used to create sub pipeline.</param> /// <param name="nameOfCommand">Name of the command to run.</param> /// <param name="typeOfCommand">Type of the command to run.</param> internal void Initialize(ExecutionContext execContext, string nameOfCommand, Type typeOfCommand) { _context = execContext; _commandName = nameOfCommand; _commandType = typeOfCommand; } /// <summary> /// Add a parameter to the command invocation. /// It needs to be called before any execution takes place. /// </summary> /// <param name="parameterName">Name of the parameter.</param> /// <param name="parameterValue">Value of the parameter.</param> internal void AddNamedParameter(string parameterName, object parameterValue) { _commandParameterList.Add( CommandParameterInternal.CreateParameterWithArgument( /*parameterAst*/null, parameterName, null, /*argumentAst*/null, parameterValue, false)); } /// <summary> /// Send an object to the pipeline. /// </summary> /// <param name="o">Object to process.</param> /// <returns>Array of objects out of the success pipeline.</returns> internal Array Process(object o) { if (_pp == null) { // if this is the first call, we need to initialize the // pipeline underneath DelayedInternalInitialize(); } return _pp.Step(o); } /// <summary> /// Shut down the pipeline. /// </summary> /// <returns>Array of objects out of the success pipeline.</returns> internal Array ShutDown() { if (_pp == null) { // if Process() never got called, no sub pipeline // ever got created, hence we just return an empty array return new object[0]; } PipelineProcessor ppTemp = _pp; _pp = null; return ppTemp.SynchronousExecuteEnumerate(AutomationNull.Value); } private void DelayedInternalInitialize() { _pp = new PipelineProcessor(); CmdletInfo cmdletInfo = new CmdletInfo(_commandName, _commandType, null, null, _context); CommandProcessor cp = new CommandProcessor(cmdletInfo, _context); foreach (CommandParameterInternal par in _commandParameterList) { cp.AddParameter(par); } _pp.Add(cp); } /// <summary> /// Just dispose the pipeline processor. /// </summary> public void Dispose() { if (_pp == null) return; _pp.Dispose(); _pp = null; } private PipelineProcessor _pp = null; private string _commandName = null; private Type _commandType; private List<CommandParameterInternal> _commandParameterList = new List<CommandParameterInternal>(); private ExecutionContext _context = null; } /// <summary> /// Base class for the command-let's we expose /// it contains a reference to the implementation /// class it wraps. /// </summary> public abstract class FrontEndCommandBase : PSCmdlet, IDisposable { #region Command Line Switches /// <summary> /// This parameter specifies the current pipeline object. /// </summary> [Parameter(ValueFromPipeline = true)] public PSObject InputObject { set; get; } = AutomationNull.Value; #endregion /// <summary> /// Hook up the calls from the implementation object /// and then call the implementation's Begin() /// </summary> protected override void BeginProcessing() { Diagnostics.Assert(this.implementation != null, "this.implementation is null"); this.implementation.OuterCmdletCall = new ImplementationCommandBase.OuterCmdletCallback(this.OuterCmdletCall); this.implementation.InputObjectCall = new ImplementationCommandBase.InputObjectCallback(this.InputObjectCall); this.implementation.WriteObjectCall = new ImplementationCommandBase.WriteObjectCallback(this.WriteObjectCall); this.implementation.CreateTerminatingErrorContext(); implementation.BeginProcessing(); } /// <summary> /// Call the implementation. /// </summary> protected override void ProcessRecord() { implementation.ProcessRecord(); } /// <summary> /// Call the implementation. /// </summary> protected override void EndProcessing() { implementation.EndProcessing(); } /// <summary> /// Call the implementation. /// </summary> protected override void StopProcessing() { implementation.StopProcessing(); } /// <summary> /// Callback for the implementation to obtain a reference to the Cmdlet object. /// </summary> /// <returns>Cmdlet reference.</returns> protected virtual PSCmdlet OuterCmdletCall() { return this; } /// <summary> /// Callback for the implementation to get the current pipeline object. /// </summary> /// <returns>Current object from the pipeline.</returns> protected virtual PSObject InputObjectCall() { // just bind to the input object parameter return this.InputObject; } /// <summary> /// Callback for the implementation to write objects. /// </summary> /// <param name="value">Object to be written.</param> protected virtual void WriteObjectCall(object value) { // just call Monad API this.WriteObject(value); } /// <summary> /// Reference to the implementation command that this class /// is wrapping. /// </summary> internal ImplementationCommandBase implementation = null; #region IDisposable Implementation /// <summary> /// Default implementation just delegates to internal helper. /// </summary> /// <remarks>This method calls GC.SuppressFinalize</remarks> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Dispose pattern implementation. /// </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { if (disposing) { InternalDispose(); } } /// <summary> /// Do-nothing implementation: derived classes will override as see fit. /// </summary> protected virtual void InternalDispose() { if (this.implementation == null) return; this.implementation.Dispose(); this.implementation = null; } #endregion } /// <summary> /// Implementation class to be called by the outer command /// In order to properly work, the callbacks have to be properly set by the outer command. /// </summary> internal class ImplementationCommandBase : IDisposable { /// <summary> /// Inner version of CommandBase.BeginProcessing() /// </summary> internal virtual void BeginProcessing() { } /// <summary> /// Inner version of CommandBase.ProcessRecord() /// </summary> internal virtual void ProcessRecord() { } /// <summary> /// Inner version of CommandBase.EndProcessing() /// </summary> internal virtual void EndProcessing() { } /// <summary> /// Inner version of CommandBase.StopProcessing() /// </summary> internal virtual void StopProcessing() { } /// <summary> /// Retrieve the current input pipeline object. /// </summary> internal virtual PSObject ReadObject() { // delegate to the front end object System.Diagnostics.Debug.Assert(this.InputObjectCall != null, "this.InputObjectCall is null"); return this.InputObjectCall(); } /// <summary> /// Write an object to the pipeline. /// </summary> /// <param name="o">Object to write to the pipeline.</param> internal virtual void WriteObject(object o) { // delegate to the front end object System.Diagnostics.Debug.Assert(this.WriteObjectCall != null, "this.WriteObjectCall is null"); this.WriteObjectCall(o); } // callback methods to get to the outer Monad Cmdlet /// <summary> /// Get a hold of the Monad outer Cmdlet. /// </summary> /// <returns></returns> internal virtual PSCmdlet OuterCmdlet() { // delegate to the front end object System.Diagnostics.Debug.Assert(this.OuterCmdletCall != null, "this.OuterCmdletCall is null"); return this.OuterCmdletCall(); } protected TerminatingErrorContext TerminatingErrorContext { get; private set; } internal void CreateTerminatingErrorContext() { TerminatingErrorContext = new TerminatingErrorContext(this.OuterCmdlet()); } /// <summary> /// Delegate definition to get to the outer command-let. /// </summary> internal delegate PSCmdlet OuterCmdletCallback(); /// <summary> /// Callback to get to the outer command-let. /// </summary> internal OuterCmdletCallback OuterCmdletCall; // callback to the methods to get an object and write an object /// <summary> /// Delegate definition to get to the current pipeline input object. /// </summary> internal delegate PSObject InputObjectCallback(); /// <summary> /// Delegate definition to write object. /// </summary> internal delegate void WriteObjectCallback(object o); /// <summary> /// Callback to read object. /// </summary> internal InputObjectCallback InputObjectCall; /// <summary> /// Callback to write object. /// </summary> internal WriteObjectCallback WriteObjectCall; #region IDisposable Implementation /// <summary> /// Default implementation just delegates to internal helper. /// </summary> /// <remarks>This method calls GC.SuppressFinalize</remarks> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (disposing) { InternalDispose(); } } /// <summary> /// Do-nothing implementation: derived classes will override as see fit. /// </summary> protected virtual void InternalDispose() { } #endregion } }
using System; namespace Org.BouncyCastle.Math.EC.Abc { /** * Class holding methods for point multiplication based on the window * &#964;-adic nonadjacent form (WTNAF). The algorithms are based on the * paper "Improved Algorithms for Arithmetic on Anomalous Binary Curves" * by Jerome A. Solinas. The paper first appeared in the Proceedings of * Crypto 1997. */ internal class Tnaf { private static readonly BigInteger MinusOne = BigInteger.One.Negate(); private static readonly BigInteger MinusTwo = BigInteger.Two.Negate(); private static readonly BigInteger MinusThree = BigInteger.Three.Negate(); private static readonly BigInteger Four = BigInteger.ValueOf(4); /** * The window width of WTNAF. The standard value of 4 is slightly less * than optimal for running time, but keeps space requirements for * precomputation low. For typical curves, a value of 5 or 6 results in * a better running time. When changing this value, the * <code>&#945;<sub>u</sub></code>'s must be computed differently, see * e.g. "Guide to Elliptic Curve Cryptography", Darrel Hankerson, * Alfred Menezes, Scott Vanstone, Springer-Verlag New York Inc., 2004, * p. 121-122 */ public const sbyte Width = 4; /** * 2<sup>4</sup> */ public const sbyte Pow2Width = 16; /** * The <code>&#945;<sub>u</sub></code>'s for <code>a=0</code> as an array * of <code>ZTauElement</code>s. */ public static readonly ZTauElement[] Alpha0 = { null, new ZTauElement(BigInteger.One, BigInteger.Zero), null, new ZTauElement(MinusThree, MinusOne), null, new ZTauElement(MinusOne, MinusOne), null, new ZTauElement(BigInteger.One, MinusOne), null }; /** * The <code>&#945;<sub>u</sub></code>'s for <code>a=0</code> as an array * of TNAFs. */ public static readonly sbyte[][] Alpha0Tnaf = { null, new sbyte[]{1}, null, new sbyte[]{-1, 0, 1}, null, new sbyte[]{1, 0, 1}, null, new sbyte[]{-1, 0, 0, 1} }; /** * The <code>&#945;<sub>u</sub></code>'s for <code>a=1</code> as an array * of <code>ZTauElement</code>s. */ public static readonly ZTauElement[] Alpha1 = { null, new ZTauElement(BigInteger.One, BigInteger.Zero), null, new ZTauElement(MinusThree, BigInteger.One), null, new ZTauElement(MinusOne, BigInteger.One), null, new ZTauElement(BigInteger.One, BigInteger.One), null }; /** * The <code>&#945;<sub>u</sub></code>'s for <code>a=1</code> as an array * of TNAFs. */ public static readonly sbyte[][] Alpha1Tnaf = { null, new sbyte[]{1}, null, new sbyte[]{-1, 0, 1}, null, new sbyte[]{1, 0, 1}, null, new sbyte[]{-1, 0, 0, -1} }; /** * Computes the norm of an element <code>&#955;</code> of * <code><b>Z</b>[&#964;]</code>. * @param mu The parameter <code>&#956;</code> of the elliptic curve. * @param lambda The element <code>&#955;</code> of * <code><b>Z</b>[&#964;]</code>. * @return The norm of <code>&#955;</code>. */ public static BigInteger Norm(sbyte mu, ZTauElement lambda) { BigInteger norm; // s1 = u^2 BigInteger s1 = lambda.u.Multiply(lambda.u); // s2 = u * v BigInteger s2 = lambda.u.Multiply(lambda.v); // s3 = 2 * v^2 BigInteger s3 = lambda.v.Multiply(lambda.v).ShiftLeft(1); if (mu == 1) { norm = s1.Add(s2).Add(s3); } else if (mu == -1) { norm = s1.Subtract(s2).Add(s3); } else { throw new ArgumentException("mu must be 1 or -1"); } return norm; } /** * Computes the norm of an element <code>&#955;</code> of * <code><b>R</b>[&#964;]</code>, where <code>&#955; = u + v&#964;</code> * and <code>u</code> and <code>u</code> are real numbers (elements of * <code><b>R</b></code>). * @param mu The parameter <code>&#956;</code> of the elliptic curve. * @param u The real part of the element <code>&#955;</code> of * <code><b>R</b>[&#964;]</code>. * @param v The <code>&#964;</code>-adic part of the element * <code>&#955;</code> of <code><b>R</b>[&#964;]</code>. * @return The norm of <code>&#955;</code>. */ public static SimpleBigDecimal Norm(sbyte mu, SimpleBigDecimal u, SimpleBigDecimal v) { SimpleBigDecimal norm; // s1 = u^2 SimpleBigDecimal s1 = u.Multiply(u); // s2 = u * v SimpleBigDecimal s2 = u.Multiply(v); // s3 = 2 * v^2 SimpleBigDecimal s3 = v.Multiply(v).ShiftLeft(1); if (mu == 1) { norm = s1.Add(s2).Add(s3); } else if (mu == -1) { norm = s1.Subtract(s2).Add(s3); } else { throw new ArgumentException("mu must be 1 or -1"); } return norm; } /** * Rounds an element <code>&#955;</code> of <code><b>R</b>[&#964;]</code> * to an element of <code><b>Z</b>[&#964;]</code>, such that their difference * has minimal norm. <code>&#955;</code> is given as * <code>&#955; = &#955;<sub>0</sub> + &#955;<sub>1</sub>&#964;</code>. * @param lambda0 The component <code>&#955;<sub>0</sub></code>. * @param lambda1 The component <code>&#955;<sub>1</sub></code>. * @param mu The parameter <code>&#956;</code> of the elliptic curve. Must * equal 1 or -1. * @return The rounded element of <code><b>Z</b>[&#964;]</code>. * @throws ArgumentException if <code>lambda0</code> and * <code>lambda1</code> do not have same scale. */ public static ZTauElement Round(SimpleBigDecimal lambda0, SimpleBigDecimal lambda1, sbyte mu) { int scale = lambda0.Scale; if (lambda1.Scale != scale) throw new ArgumentException("lambda0 and lambda1 do not have same scale"); if (!((mu == 1) || (mu == -1))) throw new ArgumentException("mu must be 1 or -1"); BigInteger f0 = lambda0.Round(); BigInteger f1 = lambda1.Round(); SimpleBigDecimal eta0 = lambda0.Subtract(f0); SimpleBigDecimal eta1 = lambda1.Subtract(f1); // eta = 2*eta0 + mu*eta1 SimpleBigDecimal eta = eta0.Add(eta0); if (mu == 1) { eta = eta.Add(eta1); } else { // mu == -1 eta = eta.Subtract(eta1); } // check1 = eta0 - 3*mu*eta1 // check2 = eta0 + 4*mu*eta1 SimpleBigDecimal threeEta1 = eta1.Add(eta1).Add(eta1); SimpleBigDecimal fourEta1 = threeEta1.Add(eta1); SimpleBigDecimal check1; SimpleBigDecimal check2; if (mu == 1) { check1 = eta0.Subtract(threeEta1); check2 = eta0.Add(fourEta1); } else { // mu == -1 check1 = eta0.Add(threeEta1); check2 = eta0.Subtract(fourEta1); } sbyte h0 = 0; sbyte h1 = 0; // if eta >= 1 if (eta.CompareTo(BigInteger.One) >= 0) { if (check1.CompareTo(MinusOne) < 0) { h1 = mu; } else { h0 = 1; } } else { // eta < 1 if (check2.CompareTo(BigInteger.Two) >= 0) { h1 = mu; } } // if eta < -1 if (eta.CompareTo(MinusOne) < 0) { if (check1.CompareTo(BigInteger.One) >= 0) { h1 = (sbyte)-mu; } else { h0 = -1; } } else { // eta >= -1 if (check2.CompareTo(MinusTwo) < 0) { h1 = (sbyte)-mu; } } BigInteger q0 = f0.Add(BigInteger.ValueOf(h0)); BigInteger q1 = f1.Add(BigInteger.ValueOf(h1)); return new ZTauElement(q0, q1); } /** * Approximate division by <code>n</code>. For an integer * <code>k</code>, the value <code>&#955; = s k / n</code> is * computed to <code>c</code> bits of accuracy. * @param k The parameter <code>k</code>. * @param s The curve parameter <code>s<sub>0</sub></code> or * <code>s<sub>1</sub></code>. * @param vm The Lucas Sequence element <code>V<sub>m</sub></code>. * @param a The parameter <code>a</code> of the elliptic curve. * @param m The bit length of the finite field * <code><b>F</b><sub>m</sub></code>. * @param c The number of bits of accuracy, i.e. the scale of the returned * <code>SimpleBigDecimal</code>. * @return The value <code>&#955; = s k / n</code> computed to * <code>c</code> bits of accuracy. */ public static SimpleBigDecimal ApproximateDivisionByN(BigInteger k, BigInteger s, BigInteger vm, sbyte a, int m, int c) { int _k = (m + 5)/2 + c; BigInteger ns = k.ShiftRight(m - _k - 2 + a); BigInteger gs = s.Multiply(ns); BigInteger hs = gs.ShiftRight(m); BigInteger js = vm.Multiply(hs); BigInteger gsPlusJs = gs.Add(js); BigInteger ls = gsPlusJs.ShiftRight(_k-c); if (gsPlusJs.TestBit(_k-c-1)) { // round up ls = ls.Add(BigInteger.One); } return new SimpleBigDecimal(ls, c); } /** * Computes the <code>&#964;</code>-adic NAF (non-adjacent form) of an * element <code>&#955;</code> of <code><b>Z</b>[&#964;]</code>. * @param mu The parameter <code>&#956;</code> of the elliptic curve. * @param lambda The element <code>&#955;</code> of * <code><b>Z</b>[&#964;]</code>. * @return The <code>&#964;</code>-adic NAF of <code>&#955;</code>. */ public static sbyte[] TauAdicNaf(sbyte mu, ZTauElement lambda) { if (!((mu == 1) || (mu == -1))) throw new ArgumentException("mu must be 1 or -1"); BigInteger norm = Norm(mu, lambda); // Ceiling of log2 of the norm int log2Norm = norm.BitLength; // If length(TNAF) > 30, then length(TNAF) < log2Norm + 3.52 int maxLength = log2Norm > 30 ? log2Norm + 4 : 34; // The array holding the TNAF sbyte[] u = new sbyte[maxLength]; int i = 0; // The actual length of the TNAF int length = 0; BigInteger r0 = lambda.u; BigInteger r1 = lambda.v; while(!((r0.Equals(BigInteger.Zero)) && (r1.Equals(BigInteger.Zero)))) { // If r0 is odd if (r0.TestBit(0)) { u[i] = (sbyte) BigInteger.Two.Subtract((r0.Subtract(r1.ShiftLeft(1))).Mod(Four)).IntValue; // r0 = r0 - u[i] if (u[i] == 1) { r0 = r0.ClearBit(0); } else { // u[i] == -1 r0 = r0.Add(BigInteger.One); } length = i; } else { u[i] = 0; } BigInteger t = r0; BigInteger s = r0.ShiftRight(1); if (mu == 1) { r0 = r1.Add(s); } else { // mu == -1 r0 = r1.Subtract(s); } r1 = t.ShiftRight(1).Negate(); i++; } length++; // Reduce the TNAF array to its actual length sbyte[] tnaf = new sbyte[length]; Array.Copy(u, 0, tnaf, 0, length); return tnaf; } /** * Applies the operation <code>&#964;()</code> to an * <code>F2mPoint</code>. * @param p The F2mPoint to which <code>&#964;()</code> is applied. * @return <code>&#964;(p)</code> */ public static F2mPoint Tau(F2mPoint p) { if (p.IsInfinity) return p; ECFieldElement x = p.X; ECFieldElement y = p.Y; return new F2mPoint(p.Curve, x.Square(), y.Square(), p.IsCompressed); } /** * Returns the parameter <code>&#956;</code> of the elliptic curve. * @param curve The elliptic curve from which to obtain <code>&#956;</code>. * The curve must be a Koblitz curve, i.e. <code>a</code> Equals * <code>0</code> or <code>1</code> and <code>b</code> Equals * <code>1</code>. * @return <code>&#956;</code> of the elliptic curve. * @throws ArgumentException if the given ECCurve is not a Koblitz * curve. */ public static sbyte GetMu(F2mCurve curve) { BigInteger a = curve.A.ToBigInteger(); sbyte mu; if (a.SignValue == 0) { mu = -1; } else if (a.Equals(BigInteger.One)) { mu = 1; } else { throw new ArgumentException("No Koblitz curve (ABC), TNAF multiplication not possible"); } return mu; } /** * Calculates the Lucas Sequence elements <code>U<sub>k-1</sub></code> and * <code>U<sub>k</sub></code> or <code>V<sub>k-1</sub></code> and * <code>V<sub>k</sub></code>. * @param mu The parameter <code>&#956;</code> of the elliptic curve. * @param k The index of the second element of the Lucas Sequence to be * returned. * @param doV If set to true, computes <code>V<sub>k-1</sub></code> and * <code>V<sub>k</sub></code>, otherwise <code>U<sub>k-1</sub></code> and * <code>U<sub>k</sub></code>. * @return An array with 2 elements, containing <code>U<sub>k-1</sub></code> * and <code>U<sub>k</sub></code> or <code>V<sub>k-1</sub></code> * and <code>V<sub>k</sub></code>. */ public static BigInteger[] GetLucas(sbyte mu, int k, bool doV) { if (!(mu == 1 || mu == -1)) throw new ArgumentException("mu must be 1 or -1"); BigInteger u0; BigInteger u1; BigInteger u2; if (doV) { u0 = BigInteger.Two; u1 = BigInteger.ValueOf(mu); } else { u0 = BigInteger.Zero; u1 = BigInteger.One; } for (int i = 1; i < k; i++) { // u2 = mu*u1 - 2*u0; BigInteger s = null; if (mu == 1) { s = u1; } else { // mu == -1 s = u1.Negate(); } u2 = s.Subtract(u0.ShiftLeft(1)); u0 = u1; u1 = u2; // System.out.println(i + ": " + u2); // System.out.println(); } BigInteger[] retVal = {u0, u1}; return retVal; } /** * Computes the auxiliary value <code>t<sub>w</sub></code>. If the width is * 4, then for <code>mu = 1</code>, <code>t<sub>w</sub> = 6</code> and for * <code>mu = -1</code>, <code>t<sub>w</sub> = 10</code> * @param mu The parameter <code>&#956;</code> of the elliptic curve. * @param w The window width of the WTNAF. * @return the auxiliary value <code>t<sub>w</sub></code> */ public static BigInteger GetTw(sbyte mu, int w) { if (w == 4) { if (mu == 1) { return BigInteger.ValueOf(6); } else { // mu == -1 return BigInteger.ValueOf(10); } } else { // For w <> 4, the values must be computed BigInteger[] us = GetLucas(mu, w, false); BigInteger twoToW = BigInteger.Zero.SetBit(w); BigInteger u1invert = us[1].ModInverse(twoToW); BigInteger tw; tw = BigInteger.Two.Multiply(us[0]).Multiply(u1invert).Mod(twoToW); //System.out.println("mu = " + mu); //System.out.println("tw = " + tw); return tw; } } /** * Computes the auxiliary values <code>s<sub>0</sub></code> and * <code>s<sub>1</sub></code> used for partial modular reduction. * @param curve The elliptic curve for which to compute * <code>s<sub>0</sub></code> and <code>s<sub>1</sub></code>. * @throws ArgumentException if <code>curve</code> is not a * Koblitz curve (Anomalous Binary Curve, ABC). */ public static BigInteger[] GetSi(F2mCurve curve) { if (!curve.IsKoblitz) throw new ArgumentException("si is defined for Koblitz curves only"); int m = curve.M; int a = curve.A.ToBigInteger().IntValue; sbyte mu = curve.GetMu(); int h = curve.H.IntValue; int index = m + 3 - a; BigInteger[] ui = GetLucas(mu, index, false); BigInteger dividend0; BigInteger dividend1; if (mu == 1) { dividend0 = BigInteger.One.Subtract(ui[1]); dividend1 = BigInteger.One.Subtract(ui[0]); } else if (mu == -1) { dividend0 = BigInteger.One.Add(ui[1]); dividend1 = BigInteger.One.Add(ui[0]); } else { throw new ArgumentException("mu must be 1 or -1"); } BigInteger[] si = new BigInteger[2]; if (h == 2) { si[0] = dividend0.ShiftRight(1); si[1] = dividend1.ShiftRight(1).Negate(); } else if (h == 4) { si[0] = dividend0.ShiftRight(2); si[1] = dividend1.ShiftRight(2).Negate(); } else { throw new ArgumentException("h (Cofactor) must be 2 or 4"); } return si; } /** * Partial modular reduction modulo * <code>(&#964;<sup>m</sup> - 1)/(&#964; - 1)</code>. * @param k The integer to be reduced. * @param m The bitlength of the underlying finite field. * @param a The parameter <code>a</code> of the elliptic curve. * @param s The auxiliary values <code>s<sub>0</sub></code> and * <code>s<sub>1</sub></code>. * @param mu The parameter &#956; of the elliptic curve. * @param c The precision (number of bits of accuracy) of the partial * modular reduction. * @return <code>&#961; := k partmod (&#964;<sup>m</sup> - 1)/(&#964; - 1)</code> */ public static ZTauElement PartModReduction(BigInteger k, int m, sbyte a, BigInteger[] s, sbyte mu, sbyte c) { // d0 = s[0] + mu*s[1]; mu is either 1 or -1 BigInteger d0; if (mu == 1) { d0 = s[0].Add(s[1]); } else { d0 = s[0].Subtract(s[1]); } BigInteger[] v = GetLucas(mu, m, true); BigInteger vm = v[1]; SimpleBigDecimal lambda0 = ApproximateDivisionByN( k, s[0], vm, a, m, c); SimpleBigDecimal lambda1 = ApproximateDivisionByN( k, s[1], vm, a, m, c); ZTauElement q = Round(lambda0, lambda1, mu); // r0 = n - d0*q0 - 2*s1*q1 BigInteger r0 = k.Subtract(d0.Multiply(q.u)).Subtract( BigInteger.ValueOf(2).Multiply(s[1]).Multiply(q.v)); // r1 = s1*q0 - s0*q1 BigInteger r1 = s[1].Multiply(q.u).Subtract(s[0].Multiply(q.v)); return new ZTauElement(r0, r1); } /** * Multiplies a {@link org.bouncycastle.math.ec.F2mPoint F2mPoint} * by a <code>BigInteger</code> using the reduced <code>&#964;</code>-adic * NAF (RTNAF) method. * @param p The F2mPoint to Multiply. * @param k The <code>BigInteger</code> by which to Multiply <code>p</code>. * @return <code>k * p</code> */ public static F2mPoint MultiplyRTnaf(F2mPoint p, BigInteger k) { F2mCurve curve = (F2mCurve) p.Curve; int m = curve.M; sbyte a = (sbyte) curve.A.ToBigInteger().IntValue; sbyte mu = curve.GetMu(); BigInteger[] s = curve.GetSi(); ZTauElement rho = PartModReduction(k, m, a, s, mu, (sbyte)10); return MultiplyTnaf(p, rho); } /** * Multiplies a {@link org.bouncycastle.math.ec.F2mPoint F2mPoint} * by an element <code>&#955;</code> of <code><b>Z</b>[&#964;]</code> * using the <code>&#964;</code>-adic NAF (TNAF) method. * @param p The F2mPoint to Multiply. * @param lambda The element <code>&#955;</code> of * <code><b>Z</b>[&#964;]</code>. * @return <code>&#955; * p</code> */ public static F2mPoint MultiplyTnaf(F2mPoint p, ZTauElement lambda) { F2mCurve curve = (F2mCurve)p.Curve; sbyte mu = curve.GetMu(); sbyte[] u = TauAdicNaf(mu, lambda); F2mPoint q = MultiplyFromTnaf(p, u); return q; } /** * Multiplies a {@link org.bouncycastle.math.ec.F2mPoint F2mPoint} * by an element <code>&#955;</code> of <code><b>Z</b>[&#964;]</code> * using the <code>&#964;</code>-adic NAF (TNAF) method, given the TNAF * of <code>&#955;</code>. * @param p The F2mPoint to Multiply. * @param u The the TNAF of <code>&#955;</code>.. * @return <code>&#955; * p</code> */ public static F2mPoint MultiplyFromTnaf(F2mPoint p, sbyte[] u) { F2mCurve curve = (F2mCurve)p.Curve; F2mPoint q = (F2mPoint) curve.Infinity; for (int i = u.Length - 1; i >= 0; i--) { q = Tau(q); if (u[i] == 1) { q = (F2mPoint)q.AddSimple(p); } else if (u[i] == -1) { q = (F2mPoint)q.SubtractSimple(p); } } return q; } /** * Computes the <code>[&#964;]</code>-adic window NAF of an element * <code>&#955;</code> of <code><b>Z</b>[&#964;]</code>. * @param mu The parameter &#956; of the elliptic curve. * @param lambda The element <code>&#955;</code> of * <code><b>Z</b>[&#964;]</code> of which to compute the * <code>[&#964;]</code>-adic NAF. * @param width The window width of the resulting WNAF. * @param pow2w 2<sup>width</sup>. * @param tw The auxiliary value <code>t<sub>w</sub></code>. * @param alpha The <code>&#945;<sub>u</sub></code>'s for the window width. * @return The <code>[&#964;]</code>-adic window NAF of * <code>&#955;</code>. */ public static sbyte[] TauAdicWNaf(sbyte mu, ZTauElement lambda, sbyte width, BigInteger pow2w, BigInteger tw, ZTauElement[] alpha) { if (!((mu == 1) || (mu == -1))) throw new ArgumentException("mu must be 1 or -1"); BigInteger norm = Norm(mu, lambda); // Ceiling of log2 of the norm int log2Norm = norm.BitLength; // If length(TNAF) > 30, then length(TNAF) < log2Norm + 3.52 int maxLength = log2Norm > 30 ? log2Norm + 4 + width : 34 + width; // The array holding the TNAF sbyte[] u = new sbyte[maxLength]; // 2^(width - 1) BigInteger pow2wMin1 = pow2w.ShiftRight(1); // Split lambda into two BigIntegers to simplify calculations BigInteger r0 = lambda.u; BigInteger r1 = lambda.v; int i = 0; // while lambda <> (0, 0) while (!((r0.Equals(BigInteger.Zero))&&(r1.Equals(BigInteger.Zero)))) { // if r0 is odd if (r0.TestBit(0)) { // uUnMod = r0 + r1*tw Mod 2^width BigInteger uUnMod = r0.Add(r1.Multiply(tw)).Mod(pow2w); sbyte uLocal; // if uUnMod >= 2^(width - 1) if (uUnMod.CompareTo(pow2wMin1) >= 0) { uLocal = (sbyte) uUnMod.Subtract(pow2w).IntValue; } else { uLocal = (sbyte) uUnMod.IntValue; } // uLocal is now in [-2^(width-1), 2^(width-1)-1] u[i] = uLocal; bool s = true; if (uLocal < 0) { s = false; uLocal = (sbyte)-uLocal; } // uLocal is now >= 0 if (s) { r0 = r0.Subtract(alpha[uLocal].u); r1 = r1.Subtract(alpha[uLocal].v); } else { r0 = r0.Add(alpha[uLocal].u); r1 = r1.Add(alpha[uLocal].v); } } else { u[i] = 0; } BigInteger t = r0; if (mu == 1) { r0 = r1.Add(r0.ShiftRight(1)); } else { // mu == -1 r0 = r1.Subtract(r0.ShiftRight(1)); } r1 = t.ShiftRight(1).Negate(); i++; } return u; } /** * Does the precomputation for WTNAF multiplication. * @param p The <code>ECPoint</code> for which to do the precomputation. * @param a The parameter <code>a</code> of the elliptic curve. * @return The precomputation array for <code>p</code>. */ public static F2mPoint[] GetPreComp(F2mPoint p, sbyte a) { F2mPoint[] pu; pu = new F2mPoint[16]; pu[1] = p; sbyte[][] alphaTnaf; if (a == 0) { alphaTnaf = Tnaf.Alpha0Tnaf; } else { // a == 1 alphaTnaf = Tnaf.Alpha1Tnaf; } int precompLen = alphaTnaf.Length; for (int i = 3; i < precompLen; i = i + 2) { pu[i] = Tnaf.MultiplyFromTnaf(p, alphaTnaf[i]); } return pu; } } }
// 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; namespace System.Linq.Expressions { /// <summary> /// Strongly-typed and parameterized string resources. /// </summary> internal static class Strings { /// <summary> /// A string like "reducible nodes must override Expression.Reduce()" /// </summary> internal static string ReducibleMustOverrideReduce { get { return SR.ReducibleMustOverrideReduce; } } /// <summary> /// A string like "node cannot reduce to itself or null" /// </summary> internal static string MustReduceToDifferent { get { return SR.MustReduceToDifferent; } } /// <summary> /// A string like "cannot assign from the reduced node type to the original node type" /// </summary> internal static string ReducedNotCompatible { get { return SR.ReducedNotCompatible; } } /// <summary> /// A string like "Setter must have parameters." /// </summary> internal static string SetterHasNoParams { get { return SR.SetterHasNoParams; } } /// <summary> /// A string like "Property cannot have a managed pointer type." /// </summary> internal static string PropertyCannotHaveRefType { get { return SR.PropertyCannotHaveRefType; } } /// <summary> /// A string like "Indexing parameters of getter and setter must match." /// </summary> internal static string IndexesOfSetGetMustMatch { get { return SR.IndexesOfSetGetMustMatch; } } /// <summary> /// A string like "Accessor method should not have VarArgs." /// </summary> internal static string AccessorsCannotHaveVarArgs { get { return SR.AccessorsCannotHaveVarArgs; } } /// <summary> /// A string like "Accessor indexes cannot be passed ByRef." /// </summary> internal static string AccessorsCannotHaveByRefArgs { get { return SR.AccessorsCannotHaveByRefArgs; } } /// <summary> /// A string like "Bounds count cannot be less than 1" /// </summary> internal static string BoundsCannotBeLessThanOne { get { return SR.BoundsCannotBeLessThanOne; } } /// <summary> /// A string like "type must not be ByRef" /// </summary> internal static string TypeMustNotBeByRef { get { return SR.TypeMustNotBeByRef; } } /// <summary> /// A string like "Type doesn't have constructor with a given signature" /// </summary> internal static string TypeDoesNotHaveConstructorForTheSignature { get { return SR.TypeDoesNotHaveConstructorForTheSignature; } } /// <summary> /// A string like "Setter should have void type." /// </summary> internal static string SetterMustBeVoid { get { return SR.SetterMustBeVoid; } } /// <summary> /// A string like "Property type must match the value type of setter" /// </summary> internal static string PropertyTyepMustMatchSetter { get { return SR.PropertyTyepMustMatchSetter; } } /// <summary> /// A string like "Both accessors must be static." /// </summary> internal static string BothAccessorsMustBeStatic { get { return SR.BothAccessorsMustBeStatic; } } /// <summary> /// A string like "Static field requires null instance, non-static field requires non-null instance." /// </summary> internal static string OnlyStaticFieldsHaveNullInstance { get { return SR.OnlyStaticFieldsHaveNullInstance; } } /// <summary> /// A string like "Static property requires null instance, non-static property requires non-null instance." /// </summary> internal static string OnlyStaticPropertiesHaveNullInstance { get { return SR.OnlyStaticPropertiesHaveNullInstance; } } /// <summary> /// A string like "Static method requires null instance, non-static method requires non-null instance." /// </summary> internal static string OnlyStaticMethodsHaveNullInstance { get { return SR.OnlyStaticMethodsHaveNullInstance; } } /// <summary> /// A string like "Property cannot have a void type." /// </summary> internal static string PropertyTypeCannotBeVoid { get { return SR.PropertyTypeCannotBeVoid; } } /// <summary> /// A string like "Can only unbox from an object or interface type to a value type." /// </summary> internal static string InvalidUnboxType { get { return SR.InvalidUnboxType; } } /// <summary> /// A string like "Expression must be writeable" /// </summary> internal static string ExpressionMustBeWriteable { get { return SR.ExpressionMustBeWriteable; } } /// <summary> /// A string like "Argument must not have a value type." /// </summary> internal static string ArgumentMustNotHaveValueType { get { return SR.ArgumentMustNotHaveValueType; } } /// <summary> /// A string like "must be reducible node" /// </summary> internal static string MustBeReducible { get { return SR.MustBeReducible; } } /// <summary> /// A string like "All test values must have the same type." /// </summary> internal static string AllTestValuesMustHaveSameType { get { return SR.AllTestValuesMustHaveSameType; } } /// <summary> /// A string like "All case bodies and the default body must have the same type." /// </summary> internal static string AllCaseBodiesMustHaveSameType { get { return SR.AllCaseBodiesMustHaveSameType; } } /// <summary> /// A string like "Default body must be supplied if case bodies are not System.Void." /// </summary> internal static string DefaultBodyMustBeSupplied { get { return SR.DefaultBodyMustBeSupplied; } } /// <summary> /// A string like "MethodBuilder does not have a valid TypeBuilder" /// </summary> internal static string MethodBuilderDoesNotHaveTypeBuilder { get { return SR.MethodBuilderDoesNotHaveTypeBuilder; } } /// <summary> /// A string like "Label type must be System.Void if an expression is not supplied" /// </summary> internal static string LabelMustBeVoidOrHaveExpression { get { return SR.LabelMustBeVoidOrHaveExpression; } } /// <summary> /// A string like "Type must be System.Void for this label argument" /// </summary> internal static string LabelTypeMustBeVoid { get { return SR.LabelTypeMustBeVoid; } } /// <summary> /// A string like "Quoted expression must be a lambda" /// </summary> internal static string QuotedExpressionMustBeLambda { get { return SR.QuotedExpressionMustBeLambda; } } /// <summary> /// A string like "Variable '{0}' uses unsupported type '{1}'. Reference types are not supported for variables." /// </summary> internal static string VariableMustNotBeByRef(object p0, object p1) { return SR.Format(SR.VariableMustNotBeByRef, p0, p1); } /// <summary> /// A string like "Found duplicate parameter '{0}'. Each ParameterExpression in the list must be a unique object." /// </summary> internal static string DuplicateVariable(object p0) { return SR.Format(SR.DuplicateVariable, p0); } /// <summary> /// A string like "Start and End must be well ordered" /// </summary> internal static string StartEndMustBeOrdered { get { return SR.StartEndMustBeOrdered; } } /// <summary> /// A string like "fault cannot be used with catch or finally clauses" /// </summary> internal static string FaultCannotHaveCatchOrFinally { get { return SR.FaultCannotHaveCatchOrFinally; } } /// <summary> /// A string like "try must have at least one catch, finally, or fault clause" /// </summary> internal static string TryMustHaveCatchFinallyOrFault { get { return SR.TryMustHaveCatchFinallyOrFault; } } /// <summary> /// A string like "Body of catch must have the same type as body of try." /// </summary> internal static string BodyOfCatchMustHaveSameTypeAsBodyOfTry { get { return SR.BodyOfCatchMustHaveSameTypeAsBodyOfTry; } } /// <summary> /// A string like "Extension node must override the property {0}." /// </summary> internal static string ExtensionNodeMustOverrideProperty(object p0) { return SR.Format(SR.ExtensionNodeMustOverrideProperty, p0); } /// <summary> /// A string like "User-defined operator method '{0}' must be static." /// </summary> internal static string UserDefinedOperatorMustBeStatic(object p0) { return SR.Format(SR.UserDefinedOperatorMustBeStatic, p0); } /// <summary> /// A string like "User-defined operator method '{0}' must not be void." /// </summary> internal static string UserDefinedOperatorMustNotBeVoid(object p0) { return SR.Format(SR.UserDefinedOperatorMustNotBeVoid, p0); } /// <summary> /// A string like "No coercion operator is defined between types '{0}' and '{1}'." /// </summary> internal static string CoercionOperatorNotDefined(object p0, object p1) { return SR.Format(SR.CoercionOperatorNotDefined, p0, p1); } /// <summary> /// A string like "The unary operator {0} is not defined for the type '{1}'." /// </summary> internal static string UnaryOperatorNotDefined(object p0, object p1) { return SR.Format(SR.UnaryOperatorNotDefined, p0, p1); } /// <summary> /// A string like "The binary operator {0} is not defined for the types '{1}' and '{2}'." /// </summary> internal static string BinaryOperatorNotDefined(object p0, object p1, object p2) { return SR.Format(SR.BinaryOperatorNotDefined, p0, p1, p2); } /// <summary> /// A string like "Reference equality is not defined for the types '{0}' and '{1}'." /// </summary> internal static string ReferenceEqualityNotDefined(object p0, object p1) { return SR.Format(SR.ReferenceEqualityNotDefined, p0, p1); } /// <summary> /// A string like "The operands for operator '{0}' do not match the parameters of method '{1}'." /// </summary> internal static string OperandTypesDoNotMatchParameters(object p0, object p1) { return SR.Format(SR.OperandTypesDoNotMatchParameters, p0, p1); } /// <summary> /// A string like "The return type of overload method for operator '{0}' does not match the parameter type of conversion method '{1}'." /// </summary> internal static string OverloadOperatorTypeDoesNotMatchConversionType(object p0, object p1) { return SR.Format(SR.OverloadOperatorTypeDoesNotMatchConversionType, p0, p1); } /// <summary> /// A string like "Conversion is not supported for arithmetic types without operator overloading." /// </summary> internal static string ConversionIsNotSupportedForArithmeticTypes { get { return SR.ConversionIsNotSupportedForArithmeticTypes; } } /// <summary> /// A string like "Argument must be array" /// </summary> internal static string ArgumentMustBeArray { get { return SR.ArgumentMustBeArray; } } /// <summary> /// A string like "Argument must be boolean" /// </summary> internal static string ArgumentMustBeBoolean { get { return SR.ArgumentMustBeBoolean; } } /// <summary> /// A string like "The user-defined equality method '{0}' must return a boolean value." /// </summary> internal static string EqualityMustReturnBoolean(object p0) { return SR.Format(SR.EqualityMustReturnBoolean, p0); } /// <summary> /// A string like "Argument must be either a FieldInfo or PropertyInfo" /// </summary> internal static string ArgumentMustBeFieldInfoOrPropertyInfo { get { return SR.ArgumentMustBeFieldInfoOrPropertyInfo; } } /// <summary> /// A string like "Argument must be either a FieldInfo, PropertyInfo or MethodInfo" /// </summary> internal static string ArgumentMustBeFieldInfoOrPropertyInfoOrMethod { get { return SR.ArgumentMustBeFieldInfoOrPropertyInfoOrMethod; } } /// <summary> /// A string like "Argument must be an instance member" /// </summary> internal static string ArgumentMustBeInstanceMember { get { return SR.ArgumentMustBeInstanceMember; } } /// <summary> /// A string like "Argument must be of an integer type" /// </summary> internal static string ArgumentMustBeInteger { get { return SR.ArgumentMustBeInteger; } } /// <summary> /// A string like "Argument for array index must be of type Int32" /// </summary> internal static string ArgumentMustBeArrayIndexType { get { return SR.ArgumentMustBeArrayIndexType; } } /// <summary> /// A string like "Argument must be single dimensional array type" /// </summary> internal static string ArgumentMustBeSingleDimensionalArrayType { get { return SR.ArgumentMustBeSingleDimensionalArrayType; } } /// <summary> /// A string like "Argument types do not match" /// </summary> internal static string ArgumentTypesMustMatch { get { return SR.ArgumentTypesMustMatch; } } /// <summary> /// A string like "Cannot auto initialize elements of value type through property '{0}', use assignment instead" /// </summary> internal static string CannotAutoInitializeValueTypeElementThroughProperty(object p0) { return SR.Format(SR.CannotAutoInitializeValueTypeElementThroughProperty, p0); } /// <summary> /// A string like "Cannot auto initialize members of value type through property '{0}', use assignment instead" /// </summary> internal static string CannotAutoInitializeValueTypeMemberThroughProperty(object p0) { return SR.Format(SR.CannotAutoInitializeValueTypeMemberThroughProperty, p0); } /// <summary> /// A string like "The type used in TypeAs Expression must be of reference or nullable type, {0} is neither" /// </summary> internal static string IncorrectTypeForTypeAs(object p0) { return SR.Format(SR.IncorrectTypeForTypeAs, p0); } /// <summary> /// A string like "Coalesce used with type that cannot be null" /// </summary> internal static string CoalesceUsedOnNonNullType { get { return SR.CoalesceUsedOnNonNullType; } } /// <summary> /// A string like "An expression of type '{0}' cannot be used to initialize an array of type '{1}'" /// </summary> internal static string ExpressionTypeCannotInitializeArrayType(object p0, object p1) { return SR.Format(SR.ExpressionTypeCannotInitializeArrayType, p0, p1); } /// <summary> /// A string like " Argument type '{0}' does not match the corresponding member type '{1}'" /// </summary> internal static string ArgumentTypeDoesNotMatchMember(object p0, object p1) { return SR.Format(SR.ArgumentTypeDoesNotMatchMember, p0, p1); } /// <summary> /// A string like " The member '{0}' is not declared on type '{1}' being created" /// </summary> internal static string ArgumentMemberNotDeclOnType(object p0, object p1) { return SR.Format(SR.ArgumentMemberNotDeclOnType, p0, p1); } /// <summary> /// A string like "Expression of type '{0}' cannot be used for return type '{1}'" /// </summary> internal static string ExpressionTypeDoesNotMatchReturn(object p0, object p1) { return SR.Format(SR.ExpressionTypeDoesNotMatchReturn, p0, p1); } /// <summary> /// A string like "Expression of type '{0}' cannot be used for assignment to type '{1}'" /// </summary> internal static string ExpressionTypeDoesNotMatchAssignment(object p0, object p1) { return SR.Format(SR.ExpressionTypeDoesNotMatchAssignment, p0, p1); } /// <summary> /// A string like "Expression of type '{0}' cannot be used for label of type '{1}'" /// </summary> internal static string ExpressionTypeDoesNotMatchLabel(object p0, object p1) { return SR.Format(SR.ExpressionTypeDoesNotMatchLabel, p0, p1); } /// <summary> /// A string like "Expression of type '{0}' cannot be invoked" /// </summary> internal static string ExpressionTypeNotInvocable(object p0) { return SR.Format(SR.ExpressionTypeNotInvocable, p0); } /// <summary> /// A string like "Field '{0}' is not defined for type '{1}'" /// </summary> internal static string FieldNotDefinedForType(object p0, object p1) { return SR.Format(SR.FieldNotDefinedForType, p0, p1); } /// <summary> /// A string like "Instance field '{0}' is not defined for type '{1}'" /// </summary> internal static string InstanceFieldNotDefinedForType(object p0, object p1) { return SR.Format(SR.InstanceFieldNotDefinedForType, p0, p1); } /// <summary> /// A string like "Field '{0}.{1}' is not defined for type '{2}'" /// </summary> internal static string FieldInfoNotDefinedForType(object p0, object p1, object p2) { return SR.Format(SR.FieldInfoNotDefinedForType, p0, p1, p2); } /// <summary> /// A string like "Incorrect number of indexes" /// </summary> internal static string IncorrectNumberOfIndexes { get { return SR.IncorrectNumberOfIndexes; } } /// <summary> /// A string like "Incorrect number of parameters supplied for lambda declaration" /// </summary> internal static string IncorrectNumberOfLambdaDeclarationParameters { get { return SR.IncorrectNumberOfLambdaDeclarationParameters; } } /// <summary> /// A string like " Incorrect number of members for constructor" /// </summary> internal static string IncorrectNumberOfMembersForGivenConstructor { get { return SR.IncorrectNumberOfMembersForGivenConstructor; } } /// <summary> /// A string like "Incorrect number of arguments for the given members " /// </summary> internal static string IncorrectNumberOfArgumentsForMembers { get { return SR.IncorrectNumberOfArgumentsForMembers; } } /// <summary> /// A string like "Lambda type parameter must be derived from System.Delegate" /// </summary> internal static string LambdaTypeMustBeDerivedFromSystemDelegate { get { return SR.LambdaTypeMustBeDerivedFromSystemDelegate; } } /// <summary> /// A string like "Member '{0}' not field or property" /// </summary> internal static string MemberNotFieldOrProperty(object p0) { return SR.Format(SR.MemberNotFieldOrProperty, p0); } /// <summary> /// A string like "Method {0} contains generic parameters" /// </summary> internal static string MethodContainsGenericParameters(object p0) { return SR.Format(SR.MethodContainsGenericParameters, p0); } /// <summary> /// A string like "Method {0} is a generic method definition" /// </summary> internal static string MethodIsGeneric(object p0) { return SR.Format(SR.MethodIsGeneric, p0); } /// <summary> /// A string like "The method '{0}.{1}' is not a property accessor" /// </summary> internal static string MethodNotPropertyAccessor(object p0, object p1) { return SR.Format(SR.MethodNotPropertyAccessor, p0, p1); } /// <summary> /// A string like "The property '{0}' has no 'get' accessor" /// </summary> internal static string PropertyDoesNotHaveGetter(object p0) { return SR.Format(SR.PropertyDoesNotHaveGetter, p0); } /// <summary> /// A string like "The property '{0}' has no 'set' accessor" /// </summary> internal static string PropertyDoesNotHaveSetter(object p0) { return SR.Format(SR.PropertyDoesNotHaveSetter, p0); } /// <summary> /// A string like "The property '{0}' has no 'get' or 'set' accessors" /// </summary> internal static string PropertyDoesNotHaveAccessor(object p0) { return SR.Format(SR.PropertyDoesNotHaveAccessor, p0); } /// <summary> /// A string like "'{0}' is not a member of type '{1}'" /// </summary> internal static string NotAMemberOfType(object p0, object p1) { return SR.Format(SR.NotAMemberOfType, p0, p1); } /// <summary> /// A string like "The expression '{0}' is not supported for type '{1}'" /// </summary> internal static string ExpressionNotSupportedForType(object p0, object p1) { return SR.Format(SR.ExpressionNotSupportedForType, p0, p1); } /// <summary> /// A string like "The expression '{0}' is not supported for nullable type '{1}'" /// </summary> internal static string ExpressionNotSupportedForNullableType(object p0, object p1) { return SR.Format(SR.ExpressionNotSupportedForNullableType, p0, p1); } /// <summary> /// A string like "ParameterExpression of type '{0}' cannot be used for delegate parameter of type '{1}'" /// </summary> internal static string ParameterExpressionNotValidAsDelegate(object p0, object p1) { return SR.Format(SR.ParameterExpressionNotValidAsDelegate, p0, p1); } /// <summary> /// A string like "Property '{0}' is not defined for type '{1}'" /// </summary> internal static string PropertyNotDefinedForType(object p0, object p1) { return SR.Format(SR.PropertyNotDefinedForType, p0, p1); } /// <summary> /// A string like "Instance property '{0}' is not defined for type '{1}'" /// </summary> internal static string InstancePropertyNotDefinedForType(object p0, object p1) { return SR.Format(SR.InstancePropertyNotDefinedForType, p0, p1); } /// <summary> /// A string like "Instance property '{0}' that takes no argument is not defined for type '{1}'" /// </summary> internal static string InstancePropertyWithoutParameterNotDefinedForType(object p0, object p1) { return SR.Format(SR.InstancePropertyWithoutParameterNotDefinedForType, p0, p1); } /// <summary> /// A string like "Instance property '{0}{1}' is not defined for type '{2}'" /// </summary> internal static string InstancePropertyWithSpecifiedParametersNotDefinedForType(object p0, object p1, object p2) { return SR.Format(SR.InstancePropertyWithSpecifiedParametersNotDefinedForType, p0, p1, p2); } /// <summary> /// A string like "Method '{0}' declared on type '{1}' cannot be called with instance of type '{2}'" /// </summary> internal static string InstanceAndMethodTypeMismatch(object p0, object p1, object p2) { return SR.Format(SR.InstanceAndMethodTypeMismatch, p0, p1, p2); } /// <summary> /// A string like "Type '{0}' does not have a default constructor" /// </summary> internal static string TypeMissingDefaultConstructor(object p0) { return SR.Format(SR.TypeMissingDefaultConstructor, p0); } /// <summary> /// A string like "List initializers must contain at least one initializer" /// </summary> internal static string ListInitializerWithZeroMembers { get { return SR.ListInitializerWithZeroMembers; } } /// <summary> /// A string like "Element initializer method must be named 'Add'" /// </summary> internal static string ElementInitializerMethodNotAdd { get { return SR.ElementInitializerMethodNotAdd; } } /// <summary> /// A string like "Parameter '{0}' of element initializer method '{1}' must not be a pass by reference parameter" /// </summary> internal static string ElementInitializerMethodNoRefOutParam(object p0, object p1) { return SR.Format(SR.ElementInitializerMethodNoRefOutParam, p0, p1); } /// <summary> /// A string like "Element initializer method must have at least 1 parameter" /// </summary> internal static string ElementInitializerMethodWithZeroArgs { get { return SR.ElementInitializerMethodWithZeroArgs; } } /// <summary> /// A string like "Element initializer method must be an instance method" /// </summary> internal static string ElementInitializerMethodStatic { get { return SR.ElementInitializerMethodStatic; } } /// <summary> /// A string like "Type '{0}' is not IEnumerable" /// </summary> internal static string TypeNotIEnumerable(object p0) { return SR.Format(SR.TypeNotIEnumerable, p0); } /// <summary> /// A string like "Unexpected coalesce operator." /// </summary> internal static string UnexpectedCoalesceOperator { get { return SR.UnexpectedCoalesceOperator; } } /// <summary> /// A string like "Cannot cast from type '{0}' to type '{1}" /// </summary> internal static string InvalidCast(object p0, object p1) { return SR.Format(SR.InvalidCast, p0, p1); } /// <summary> /// A string like "Unhandled binary: {0}" /// </summary> internal static string UnhandledBinary(object p0) { return SR.Format(SR.UnhandledBinary, p0); } /// <summary> /// A string like "Unhandled binding " /// </summary> internal static string UnhandledBinding { get { return SR.UnhandledBinding; } } /// <summary> /// A string like "Unhandled Binding Type: {0}" /// </summary> internal static string UnhandledBindingType(object p0) { return SR.Format(SR.UnhandledBindingType, p0); } /// <summary> /// A string like "Unhandled convert: {0}" /// </summary> internal static string UnhandledConvert(object p0) { return SR.Format(SR.UnhandledConvert, p0); } /// <summary> /// A string like "Unhandled Expression Type: {0}" /// </summary> internal static string UnhandledExpressionType(object p0) { return SR.Format(SR.UnhandledExpressionType, p0); } /// <summary> /// A string like "Unhandled unary: {0}" /// </summary> internal static string UnhandledUnary(object p0) { return SR.Format(SR.UnhandledUnary, p0); } /// <summary> /// A string like "Unknown binding type" /// </summary> internal static string UnknownBindingType { get { return SR.UnknownBindingType; } } /// <summary> /// A string like "The user-defined operator method '{1}' for operator '{0}' must have identical parameter and return types." /// </summary> internal static string UserDefinedOpMustHaveConsistentTypes(object p0, object p1) { return SR.Format(SR.UserDefinedOpMustHaveConsistentTypes, p0, p1); } /// <summary> /// A string like "The user-defined operator method '{1}' for operator '{0}' must return the same type as its parameter or a derived type." /// </summary> internal static string UserDefinedOpMustHaveValidReturnType(object p0, object p1) { return SR.Format(SR.UserDefinedOpMustHaveValidReturnType, p0, p1); } /// <summary> /// A string like "The user-defined operator method '{1}' for operator '{0}' must have associated boolean True and False operators." /// </summary> internal static string LogicalOperatorMustHaveBooleanOperators(object p0, object p1) { return SR.Format(SR.LogicalOperatorMustHaveBooleanOperators, p0, p1); } /// <summary> /// A string like "No method '{0}' exists on type '{1}'." /// </summary> internal static string MethodDoesNotExistOnType(object p0, object p1) { return SR.Format(SR.MethodDoesNotExistOnType, p0, p1); } /// <summary> /// A string like "No method '{0}' on type '{1}' is compatible with the supplied arguments." /// </summary> internal static string MethodWithArgsDoesNotExistOnType(object p0, object p1) { return SR.Format(SR.MethodWithArgsDoesNotExistOnType, p0, p1); } /// <summary> /// A string like "No generic method '{0}' on type '{1}' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic. " /// </summary> internal static string GenericMethodWithArgsDoesNotExistOnType(object p0, object p1) { return SR.Format(SR.GenericMethodWithArgsDoesNotExistOnType, p0, p1); } /// <summary> /// A string like "More than one method '{0}' on type '{1}' is compatible with the supplied arguments." /// </summary> internal static string MethodWithMoreThanOneMatch(object p0, object p1) { return SR.Format(SR.MethodWithMoreThanOneMatch, p0, p1); } /// <summary> /// A string like "More than one property '{0}' on type '{1}' is compatible with the supplied arguments." /// </summary> internal static string PropertyWithMoreThanOneMatch(object p0, object p1) { return SR.Format(SR.PropertyWithMoreThanOneMatch, p0, p1); } /// <summary> /// A string like "An incorrect number of type args were specified for the declaration of a Func type." /// </summary> internal static string IncorrectNumberOfTypeArgsForFunc { get { return SR.IncorrectNumberOfTypeArgsForFunc; } } /// <summary> /// A string like "An incorrect number of type args were specified for the declaration of an Action type." /// </summary> internal static string IncorrectNumberOfTypeArgsForAction { get { return SR.IncorrectNumberOfTypeArgsForAction; } } /// <summary> /// A string like "Argument type cannot be System.Void." /// </summary> internal static string ArgumentCannotBeOfTypeVoid { get { return SR.ArgumentCannotBeOfTypeVoid; } } /// <summary> /// A string like "Invalid operation: '{0}'" /// </summary> internal static string InvalidOperation(object p0) { return SR.Format(SR.InvalidOperation, p0); } /// <summary> /// A string like "{0} must be greater than or equal to {1}" /// </summary> internal static string OutOfRange(object p0, object p1) { return SR.Format(SR.OutOfRange, p0, p1); } /// <summary> /// A string like "Cannot redefine label '{0}' in an inner block." /// </summary> internal static string LabelTargetAlreadyDefined(object p0) { return SR.Format(SR.LabelTargetAlreadyDefined, p0); } /// <summary> /// A string like "Cannot jump to undefined label '{0}'." /// </summary> internal static string LabelTargetUndefined(object p0) { return SR.Format(SR.LabelTargetUndefined, p0); } /// <summary> /// A string like "Control cannot leave a finally block." /// </summary> internal static string ControlCannotLeaveFinally { get { return SR.ControlCannotLeaveFinally; } } /// <summary> /// A string like "Control cannot leave a filter test." /// </summary> internal static string ControlCannotLeaveFilterTest { get { return SR.ControlCannotLeaveFilterTest; } } /// <summary> /// A string like "Cannot jump to ambiguous label '{0}'." /// </summary> internal static string AmbiguousJump(object p0) { return SR.Format(SR.AmbiguousJump, p0); } /// <summary> /// A string like "Control cannot enter a try block." /// </summary> internal static string ControlCannotEnterTry { get { return SR.ControlCannotEnterTry; } } /// <summary> /// A string like "Control cannot enter an expression--only statements can be jumped into." /// </summary> internal static string ControlCannotEnterExpression { get { return SR.ControlCannotEnterExpression; } } /// <summary> /// A string like "Cannot jump to non-local label '{0}' with a value. Only jumps to labels defined in outer blocks can pass values." /// </summary> internal static string NonLocalJumpWithValue(object p0) { return SR.Format(SR.NonLocalJumpWithValue, p0); } /// <summary> /// A string like "Extension should have been reduced." /// </summary> internal static string ExtensionNotReduced { get { return SR.ExtensionNotReduced; } } /// <summary> /// A string like "CompileToMethod cannot compile constant '{0}' because it is a non-trivial value, such as a live object. Instead, create an expression tree that can construct this value." /// </summary> internal static string CannotCompileConstant(object p0) { return SR.Format(SR.CannotCompileConstant, p0); } /// <summary> /// A string like "Dynamic expressions are not supported by CompileToMethod. Instead, create an expression tree that uses System.Runtime.CompilerServices.CallSite." /// </summary> internal static string CannotCompileDynamic { get { return SR.CannotCompileDynamic; } } /// <summary> /// A string like "Invalid lvalue for assignment: {0}." /// </summary> internal static string InvalidLvalue(object p0) { return SR.Format(SR.InvalidLvalue, p0); } /// <summary> /// A string like "Invalid member type: {0}." /// </summary> internal static string InvalidMemberType(object p0) { return SR.Format(SR.InvalidMemberType, p0); } /// <summary> /// A string like "unknown lift type: '{0}'." /// </summary> internal static string UnknownLiftType(object p0) { return SR.Format(SR.UnknownLiftType, p0); } /// <summary> /// A string like "Invalid output directory." /// </summary> internal static string InvalidOutputDir { get { return SR.InvalidOutputDir; } } /// <summary> /// A string like "Invalid assembly name or file extension." /// </summary> internal static string InvalidAsmNameOrExtension { get { return SR.InvalidAsmNameOrExtension; } } /// <summary> /// A string like "Cannot create instance of {0} because it contains generic parameters" /// </summary> internal static string IllegalNewGenericParams(object p0) { return SR.Format(SR.IllegalNewGenericParams, p0); } /// <summary> /// A string like "variable '{0}' of type '{1}' referenced from scope '{2}', but it is not defined" /// </summary> internal static string UndefinedVariable(object p0, object p1, object p2) { return SR.Format(SR.UndefinedVariable, p0, p1, p2); } /// <summary> /// A string like "Cannot close over byref parameter '{0}' referenced in lambda '{1}'" /// </summary> internal static string CannotCloseOverByRef(object p0, object p1) { return SR.Format(SR.CannotCloseOverByRef, p0, p1); } /// <summary> /// A string like "Unexpected VarArgs call to method '{0}'" /// </summary> internal static string UnexpectedVarArgsCall(object p0) { return SR.Format(SR.UnexpectedVarArgsCall, p0); } /// <summary> /// A string like "Rethrow statement is valid only inside a Catch block." /// </summary> internal static string RethrowRequiresCatch { get { return SR.RethrowRequiresCatch; } } /// <summary> /// A string like "Try expression is not allowed inside a filter body." /// </summary> internal static string TryNotAllowedInFilter { get { return SR.TryNotAllowedInFilter; } } /// <summary> /// A string like "When called from '{0}', rewriting a node of type '{1}' must return a non-null value of the same type. Alternatively, override '{2}' and change it to not visit children of this type." /// </summary> internal static string MustRewriteToSameNode(object p0, object p1, object p2) { return SR.Format(SR.MustRewriteToSameNode, p0, p1, p2); } /// <summary> /// A string like "Rewriting child expression from type '{0}' to type '{1}' is not allowed, because it would change the meaning of the operation. If this is intentional, override '{2}' and change it to allow this rewrite." /// </summary> internal static string MustRewriteChildToSameType(object p0, object p1, object p2) { return SR.Format(SR.MustRewriteChildToSameType, p0, p1, p2); } /// <summary> /// A string like "Rewritten expression calls operator method '{0}', but the original node had no operator method. If this is intentional, override '{1}' and change it to allow this rewrite." /// </summary> internal static string MustRewriteWithoutMethod(object p0, object p1) { return SR.Format(SR.MustRewriteWithoutMethod, p0, p1); } /// <summary> /// A string like "TryExpression is not supported as an argument to method '{0}' because it has an argument with by-ref type. Construct the tree so the TryExpression is not nested inside of this expression." /// </summary> internal static string TryNotSupportedForMethodsWithRefArgs(object p0) { return SR.Format(SR.TryNotSupportedForMethodsWithRefArgs, p0); } /// <summary> /// A string like "TryExpression is not supported as a child expression when accessing a member on type '{0}' because it is a value type. Construct the tree so the TryExpression is not nested inside of this expression." /// </summary> internal static string TryNotSupportedForValueTypeInstances(object p0) { return SR.Format(SR.TryNotSupportedForValueTypeInstances, p0); } /// <summary> /// A string like "Dynamic operations can only be performed in homogeneous AppDomain." /// </summary> internal static string HomogeneousAppDomainRequired { get { return SR.HomogeneousAppDomainRequired; } } /// <summary> /// A string like "Test value of type '{0}' cannot be used for the comparison method parameter of type '{1}'" /// </summary> internal static string TestValueTypeDoesNotMatchComparisonMethodParameter(object p0, object p1) { return SR.Format(SR.TestValueTypeDoesNotMatchComparisonMethodParameter, p0, p1); } /// <summary> /// A string like "Switch value of type '{0}' cannot be used for the comparison method parameter of type '{1}'" /// </summary> internal static string SwitchValueTypeDoesNotMatchComparisonMethodParameter(object p0, object p1) { return SR.Format(SR.SwitchValueTypeDoesNotMatchComparisonMethodParameter, p0, p1); } /// <summary> /// A string like "DebugInfoGenerator created by CreatePdbGenerator can only be used with LambdaExpression.CompileToMethod." /// </summary> internal static string PdbGeneratorNeedsExpressionCompiler { get { return SR.PdbGeneratorNeedsExpressionCompiler; } } #if FEATURE_COMPILE /// <summary> /// A string like "The operator '{0}' is not implemented for type '{1}'" /// </summary> internal static string OperatorNotImplementedForType(object p0, object p1) { return SR.Format(SR.OperatorNotImplementedForType, p0, p1); } #endif /// <summary> /// A string like "The constructor should not be static" /// </summary> internal static string NonStaticConstructorRequired { get { return SR.NonStaticConstructorRequired; } } /// <summary> /// A string like "The constructor should not be declared on an abstract class" /// </summary> internal static string NonAbstractConstructorRequired { get { return SR.NonAbstractConstructorRequired; } } } }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using System; using Glass.Mapper.Configuration; using Sitecore.Data; using Sitecore.Data.Items; using Sitecore.Data.Managers; using Sitecore.Globalization; namespace Glass.Mapper.Sc.Configuration { /// <summary> /// Class SitecoreTypeConfiguration /// </summary> public class SitecoreTypeConfiguration : AbstractTypeConfiguration { /// <summary> /// Gets or sets the template id. /// </summary> /// <value>The template id.</value> public ID TemplateId { get; set; } /// <summary> /// Gets or sets the branch id. /// </summary> /// <value>The branch id.</value> public ID BranchId { get; set; } /// <summary> /// Gets or sets the id config. /// </summary> /// <value>The id config.</value> public SitecoreIdConfiguration IdConfig { get; set; } /// <summary> /// Gets or sets the language config. /// </summary> /// <value>The language config.</value> public SitecoreInfoConfiguration LanguageConfig { get; set; } /// <summary> /// Gets or sets the version config. /// </summary> /// <value>The version config.</value> public SitecoreInfoConfiguration VersionConfig { get; set; } /// <summary> /// Gets or sets the item config /// </summary> public SitecoreItemConfiguration ItemConfig { get; set; } /// <summary> /// Indicates that the class is used in a code first scenario. /// </summary> /// <value><c>true</c> if [code first]; otherwise, <c>false</c>.</value> public bool CodeFirst { get; set; } /// <summary> /// Overrides the default template name when using code first /// </summary> /// <value>The name of the template.</value> public string TemplateName { get; set; } /// <summary> /// Adds the property. /// </summary> /// <param name="property">The property.</param> public override void AddProperty(AbstractPropertyConfiguration property) { if (property is SitecoreIdConfiguration) IdConfig = property as SitecoreIdConfiguration; var infoProperty = property as SitecoreInfoConfiguration; if (infoProperty != null && infoProperty.Type == SitecoreInfoType.Language) LanguageConfig = infoProperty; else if (infoProperty != null && infoProperty.Type == SitecoreInfoType.Version) VersionConfig = infoProperty; if (property is SitecoreItemConfiguration) ItemConfig = property as SitecoreItemConfiguration; base.AddProperty(property); } public ID GetId(object target) { ID id; if (IdConfig == null) { id = ID.Null; } else if (IdConfig.PropertyInfo.PropertyType == typeof(Guid)) { var guidId = (Guid)IdConfig.PropertyInfo.GetValue(target, null); id = new ID(guidId); } else if (IdConfig.PropertyInfo.PropertyType == typeof(ID)) { id = IdConfig.PropertyInfo.GetValue(target, null) as ID; } else { throw new NotSupportedException("Cannot get ID for item"); } return id; } /// <summary> /// Resolves the item. /// </summary> /// <param name="target">The target.</param> /// <param name="database">The database.</param> /// <returns> /// Item. /// </returns> /// <exception cref="System.NotSupportedException">You can not save a class that does not contain a property that represents the item ID. Ensure that at least one property has been marked to contain the Sitecore ID. /// or /// Cannot get ID for item</exception> public Item ResolveItem(object target, Database database) { if (target == null) return null; ID id; Language language = null; int versionNumber = -1; if (ItemConfig != null) { var item = ItemConfig.PropertyGetter(target) as Item; if (item != null) return item; } if (IdConfig == null) throw new NotSupportedException( "You can not save a class that does not contain a property that represents the item ID. Ensure that at least one property has been marked to contain the Sitecore ID. Type: {0}".Formatted(target.GetType().FullName)); id = GetId(target); language = GetLanguage(target); if (VersionConfig != null) { var valueInt = VersionConfig.PropertyInfo.GetValue(target, null); if (valueInt is int) { versionNumber = (int) valueInt; } else if(valueInt is string) { int.TryParse(valueInt as string, out versionNumber); } } if (language != null && versionNumber > 0) { return database.GetItem(id, language, new global::Sitecore.Data.Version(versionNumber)); } else if (language != null) { return database.GetItem(id, language); } else { return database.GetItem(id); } } /// <summary> /// Gets the language. /// </summary> /// <param name="target">The target.</param> /// <returns></returns> public Language GetLanguage(object target) { Language language = null; if (LanguageConfig != null) { object langValue = LanguageConfig.PropertyInfo.GetValue(target, null); if (langValue == null) { language = Language.Current; } else if (langValue is Language) { language = langValue as Language; } else if (langValue is string) { language = LanguageManager.GetLanguage(langValue as string); } } return language; } /// <summary> /// Called to map each property automatically /// </summary> /// <param name="property"></param> /// <returns></returns> protected override AbstractPropertyConfiguration AutoMapProperty(System.Reflection.PropertyInfo property) { string name = property.Name; SitecoreInfoType infoType; if (name.ToLowerInvariant() == "id") { var idConfig = new SitecoreIdConfiguration(); idConfig.PropertyInfo = property; return idConfig; } if (name.ToLowerInvariant() == "parent") { var parentConfig = new SitecoreParentConfiguration(); parentConfig.PropertyInfo = property; return parentConfig; } if (name.ToLowerInvariant() == "children") { var childrenConfig = new SitecoreChildrenConfiguration(); childrenConfig.PropertyInfo = property; return childrenConfig; } if (name.ToLowerInvariant() == "item" && property.PropertyType == typeof(Item)) { var itemConfig = new SitecoreItemConfiguration(); itemConfig.PropertyInfo = property; return itemConfig; } if (Enum.TryParse(name, true, out infoType)) { SitecoreInfoConfiguration infoConfig = new SitecoreInfoConfiguration(); infoConfig.PropertyInfo = property; infoConfig.Type = infoType; return infoConfig; } SitecoreFieldConfiguration fieldConfig = new SitecoreFieldConfiguration(); fieldConfig.FieldName = name; fieldConfig.PropertyInfo = property; return fieldConfig; } } }
/* * Copyright 2012-2015 Aerospike, Inc. * * Portions may be licensed to Aerospike, Inc. under one or more contributor * license agreements. * * 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 Aerospike.Client { public class AdminCommand { // Commands private const byte AUTHENTICATE = 0; private const byte CREATE_USER = 1; private const byte DROP_USER = 2; private const byte SET_PASSWORD = 3; private const byte CHANGE_PASSWORD = 4; private const byte GRANT_ROLES = 5; private const byte REVOKE_ROLES = 6; private const byte QUERY_USERS = 9; private const byte CREATE_ROLE = 10; private const byte DROP_ROLE = 11; private const byte GRANT_PRIVILEGES = 12; private const byte REVOKE_PRIVILEGES = 13; private const byte QUERY_ROLES = 16; // Field IDs private const byte USER = 0; private const byte PASSWORD = 1; private const byte OLD_PASSWORD = 2; private const byte CREDENTIAL = 3; private const byte ROLES = 10; private const byte ROLE = 11; private const byte PRIVILEGES = 12; // Misc private const ulong MSG_VERSION = 0L; private const ulong MSG_TYPE = 2L; private const int FIELD_HEADER_SIZE = 5; private const int HEADER_SIZE = 24; private const int HEADER_REMAINING = 16; private const int RESULT_CODE = 9; private const int QUERY_END = 50; private byte[] dataBuffer; private int dataOffset; public AdminCommand() { dataBuffer = ThreadLocalData.GetBuffer(); dataOffset = 8; } public AdminCommand(byte[] dataBuffer) { this.dataBuffer = dataBuffer; dataOffset = 8; } public void Authenticate(Connection conn, byte[] user, byte[] password) { SetAuthenticate(user, password); conn.Write(dataBuffer, dataOffset); conn.ReadFully(dataBuffer, HEADER_SIZE); int result = dataBuffer[RESULT_CODE]; if (result != 0) { throw new AerospikeException(result, "Authentication failed"); } } public int SetAuthenticate(byte[] user, byte[] password) { WriteHeader(AUTHENTICATE, 2); WriteField(USER, user); WriteField(CREDENTIAL, password); WriteSize(); return dataOffset; } public void CreateUser(Cluster cluster, AdminPolicy policy, string user, string password, IList<string> roles) { WriteHeader(CREATE_USER, 3); WriteField(USER, user); WriteField(PASSWORD, password); WriteRoles(roles); ExecuteCommand(cluster, policy); } public void DropUser(Cluster cluster, AdminPolicy policy, string user) { WriteHeader(DROP_USER, 1); WriteField(USER, user); ExecuteCommand(cluster, policy); } public void SetPassword(Cluster cluster, AdminPolicy policy, byte[] user, string password) { WriteHeader(SET_PASSWORD, 2); WriteField(USER, user); WriteField(PASSWORD, password); ExecuteCommand(cluster, policy); } public void ChangePassword(Cluster cluster, AdminPolicy policy, byte[] user, string password) { WriteHeader(CHANGE_PASSWORD, 3); WriteField(USER, user); WriteField(OLD_PASSWORD, cluster.password); WriteField(PASSWORD, password); ExecuteCommand(cluster, policy); } public void GrantRoles(Cluster cluster, AdminPolicy policy, string user, IList<string> roles) { WriteHeader(GRANT_ROLES, 2); WriteField(USER, user); WriteRoles(roles); ExecuteCommand(cluster, policy); } public void RevokeRoles(Cluster cluster, AdminPolicy policy, string user, IList<string> roles) { WriteHeader(REVOKE_ROLES, 2); WriteField(USER, user); WriteRoles(roles); ExecuteCommand(cluster, policy); } public void CreateRole(Cluster cluster, AdminPolicy policy, string roleName, IList<Privilege> privileges) { WriteHeader(CREATE_ROLE, 2); WriteField(ROLE, roleName); WritePrivileges(privileges); ExecuteCommand(cluster, policy); } public void DropRole(Cluster cluster, AdminPolicy policy, string roleName) { WriteHeader(DROP_ROLE, 1); WriteField(ROLE, roleName); ExecuteCommand(cluster, policy); } public void GrantPrivileges(Cluster cluster, AdminPolicy policy, string roleName, IList<Privilege> privileges) { WriteHeader(GRANT_PRIVILEGES, 2); WriteField(ROLE, roleName); WritePrivileges(privileges); ExecuteCommand(cluster, policy); } public void RevokePrivileges(Cluster cluster, AdminPolicy policy, string roleName, IList<Privilege> privileges) { WriteHeader(REVOKE_PRIVILEGES, 2); WriteField(ROLE, roleName); WritePrivileges(privileges); ExecuteCommand(cluster, policy); } private void WriteRoles(IList<string> roles) { int offset = dataOffset + FIELD_HEADER_SIZE; dataBuffer[offset++] = (byte)roles.Count; foreach (string role in roles) { int len = ByteUtil.StringToUtf8(role, dataBuffer, offset + 1); dataBuffer[offset] = (byte)len; offset += len + 1; } int size = offset - dataOffset - FIELD_HEADER_SIZE; WriteFieldHeader(ROLES, size); dataOffset = offset; } private void WritePrivileges(IList<Privilege> privileges) { int offset = dataOffset + FIELD_HEADER_SIZE; dataBuffer[offset++] = (byte)privileges.Count; foreach (Privilege privilege in privileges) { dataBuffer[offset++] = (byte)privilege.code; if (privilege.CanScope()) { if (!(privilege.setName == null || privilege.setName.Length == 0) && (privilege.ns == null || privilege.ns.Length == 0)) { throw new AerospikeException(ResultCode.INVALID_PRIVILEGE, "Admin privilege '" + privilege.PrivilegeCodeToString() + "' has a set scope with an empty namespace."); } int len = ByteUtil.StringToUtf8(privilege.ns, dataBuffer, offset + 1); dataBuffer[offset] = (byte)len; offset += len + 1; len = ByteUtil.StringToUtf8(privilege.setName, dataBuffer, offset + 1); dataBuffer[offset] = (byte)len; offset += len + 1; } else { if (! (privilege.ns == null || privilege.ns.Length == 0) || ! (privilege.setName == null || privilege.setName.Length == 0)) { throw new AerospikeException(ResultCode.INVALID_PRIVILEGE, "Admin global privilege '" + privilege.PrivilegeCodeToString() + "' has namespace/set scope which is invalid."); } } } int size = offset - dataOffset - FIELD_HEADER_SIZE; WriteFieldHeader(PRIVILEGES, size); dataOffset = offset; } private void WriteSize() { // Write total size of message which is the current offset. ulong size = ((ulong)dataOffset - 8) | (MSG_VERSION << 56) | (MSG_TYPE << 48); ByteUtil.LongToBytes(size, dataBuffer, 0); } void WriteHeader(byte command, byte fieldCount) { // Authenticate header is almost all zeros Array.Clear(dataBuffer, dataOffset, 16); dataBuffer[dataOffset + 2] = command; dataBuffer[dataOffset + 3] = fieldCount; dataOffset += 16; } private void WriteField(byte id, string str) { int len = ByteUtil.StringToUtf8(str, dataBuffer, dataOffset + FIELD_HEADER_SIZE); WriteFieldHeader(id, len); dataOffset += len; } private void WriteField(byte id, byte[] bytes) { Array.Copy(bytes, 0, dataBuffer, dataOffset + FIELD_HEADER_SIZE, bytes.Length); WriteFieldHeader(id, bytes.Length); dataOffset += bytes.Length; } private void WriteFieldHeader(byte id, int size) { ByteUtil.IntToBytes((uint)size + 1, dataBuffer, dataOffset); dataOffset += 4; dataBuffer[dataOffset++] = id; } private void ExecuteCommand(Cluster cluster, AdminPolicy policy) { WriteSize(); Node node = cluster.GetRandomNode(); int timeout = (policy == null) ? 1000 : policy.timeout; Connection conn = node.GetConnection(timeout); try { conn.Write(dataBuffer, dataOffset); conn.ReadFully(dataBuffer, HEADER_SIZE); node.PutConnection(conn); } catch (Exception) { // Garbage may be in socket. Do not put back into pool. conn.Close(); throw; } int result = dataBuffer[RESULT_CODE]; if (result != 0) { throw new AerospikeException(result); } } private void ExecuteQuery(Cluster cluster, AdminPolicy policy) { WriteSize(); Node node = cluster.GetRandomNode(); int timeout = (policy == null) ? 1000 : policy.timeout; int status = 0; Connection conn = node.GetConnection(timeout); try { conn.Write(dataBuffer, dataOffset); status = ReadBlocks(conn); node.PutConnection(conn); } catch (Exception e) { // Garbage may be in socket. Do not put back into pool. conn.Close(); throw new AerospikeException(e); } if (status != QUERY_END && status > 0) { throw new AerospikeException(status, "Query failed."); } } private int ReadBlocks(Connection conn) { int status = 0; while (status == 0) { conn.ReadFully(dataBuffer, 8); long size = ByteUtil.BytesToLong(dataBuffer, 0); int receiveSize = ((int)(size & 0xFFFFFFFFFFFFL)); if (receiveSize > 0) { if (receiveSize > dataBuffer.Length) { dataBuffer = ThreadLocalData.ResizeBuffer(receiveSize); } conn.ReadFully(dataBuffer, receiveSize); status = ParseBlock(receiveSize); } } return status; } public static string HashPassword(string password) { return BCrypt.Net.BCrypt.HashPassword(password, "$2a$10$7EqJtq98hPqEX7fNZaFWoO"); } internal virtual int ParseBlock(int receiveSize) { return QUERY_END; } public sealed class UserCommand : AdminCommand { internal readonly List<User> list; public UserCommand(int capacity) { list = new List<User>(capacity); } public User QueryUser(Cluster cluster, AdminPolicy policy, string user) { base.WriteHeader(QUERY_USERS, 1); base.WriteField(USER, user); base.ExecuteQuery(cluster, policy); return (list.Count > 0) ? list[0] : null; } public List<User> QueryUsers(Cluster cluster, AdminPolicy policy) { base.WriteHeader(QUERY_USERS, 0); base.ExecuteQuery(cluster, policy); return list; } internal override int ParseBlock(int receiveSize) { base.dataOffset = 0; while (base.dataOffset < receiveSize) { int resultCode = base.dataBuffer[base.dataOffset + 1]; if (resultCode != 0) { return resultCode; } User user = new User(); int fieldCount = base.dataBuffer[base.dataOffset + 3]; base.dataOffset += HEADER_REMAINING; for (int i = 0; i < fieldCount; i++) { int len = ByteUtil.BytesToInt(base.dataBuffer, base.dataOffset); base.dataOffset += 4; int id = base.dataBuffer[base.dataOffset++]; len--; if (id == USER) { user.name = ByteUtil.Utf8ToString(base.dataBuffer, base.dataOffset, len); base.dataOffset += len; } else if (id == ROLES) { ParseRoles(user); } else { base.dataOffset += len; } } if (user.name == null && user.roles == null) { continue; } if (user.roles == null) { user.roles = new List<string>(0); } list.Add(user); } return 0; } internal void ParseRoles(User user) { int size = base.dataBuffer[base.dataOffset++]; user.roles = new List<string>(size); for (int i = 0; i < size; i++) { int len = base.dataBuffer[base.dataOffset++]; string role = ByteUtil.Utf8ToString(base.dataBuffer, base.dataOffset, len); base.dataOffset += len; user.roles.Add(role); } } } public sealed class RoleCommand : AdminCommand { internal readonly List<Role> list; public RoleCommand(int capacity) { list = new List<Role>(capacity); } public Role QueryRole(Cluster cluster, AdminPolicy policy, string roleName) { base.WriteHeader(QUERY_ROLES, 1); base.WriteField(ROLE, roleName); base.ExecuteQuery(cluster, policy); return (list.Count > 0) ? list[0] : null; } public List<Role> QueryRoles(Cluster cluster, AdminPolicy policy) { base.WriteHeader(QUERY_ROLES, 0); base.ExecuteQuery(cluster, policy); return list; } internal override int ParseBlock(int receiveSize) { base.dataOffset = 0; while (base.dataOffset < receiveSize) { int resultCode = base.dataBuffer[base.dataOffset + 1]; if (resultCode != 0) { return resultCode; } Role role = new Role(); int fieldCount = base.dataBuffer[base.dataOffset + 3]; base.dataOffset += HEADER_REMAINING; for (int i = 0; i < fieldCount; i++) { int len = ByteUtil.BytesToInt(base.dataBuffer, base.dataOffset); base.dataOffset += 4; int id = base.dataBuffer[base.dataOffset++]; len--; if (id == ROLE) { role.name = ByteUtil.Utf8ToString(base.dataBuffer, base.dataOffset, len); base.dataOffset += len; } else if (id == PRIVILEGES) { ParsePrivileges(role); } else { base.dataOffset += len; } } if (role.name == null && role.privileges == null) { continue; } if (role.privileges == null) { role.privileges = new List<Privilege>(0); } list.Add(role); } return 0; } internal void ParsePrivileges(Role role) { int size = base.dataBuffer[base.dataOffset++]; role.privileges = new List<Privilege>(size); for (int i = 0; i < size; i++) { Privilege priv = new Privilege(); priv.code = (PrivilegeCode)base.dataBuffer[base.dataOffset++]; if (priv.CanScope()) { int len = base.dataBuffer[base.dataOffset++]; priv.ns = ByteUtil.Utf8ToString(base.dataBuffer, base.dataOffset, len); base.dataOffset += len; len = base.dataBuffer[base.dataOffset++]; priv.setName = ByteUtil.Utf8ToString(base.dataBuffer, base.dataOffset, len); base.dataOffset += len; } role.privileges.Add(priv); } } } } }
/**************************************************************************\ Copyright Microsoft Corporation. All Rights Reserved. \**************************************************************************/ // // A consolidated file of native values and enums. // // The naming convention for enums is to use the native prefix of common types // as the enum name, where this makes sense to do. // One exception is WM_, which is called WindowMessage here. // namespace MS.Internal.Interop { using System; /// <summary> /// APPDOCLISTTYPE. ADLT_* /// </summary> internal enum ADLT { RECENT = 0, // The recently used documents list FREQUENT, // The frequently used documents list } /// <summary> /// DATAOBJ_GET_ITEM_FLAGS. DOGIF_*. /// </summary> [Flags] internal enum DOGIF { DEFAULT = 0x0000, TRAVERSE_LINK = 0x0001, // if the item is a link get the target NO_HDROP = 0x0002, // don't fallback and use CF_HDROP clipboard format NO_URL = 0x0004, // don't fallback and use URL clipboard format ONLY_IF_ONE = 0x0008, // only return the item if there is one item in the array } /// <summary>FileDialog AddPlace options. FDAP_*</summary> internal enum FDAP : uint { BOTTOM = 0x00000000, TOP = 0x00000001, } /// <summary>IFileDialog options. FOS_*</summary> [Flags] internal enum FOS : uint { OVERWRITEPROMPT = 0x00000002, STRICTFILETYPES = 0x00000004, NOCHANGEDIR = 0x00000008, PICKFOLDERS = 0x00000020, FORCEFILESYSTEM = 0x00000040, ALLNONSTORAGEITEMS = 0x00000080, NOVALIDATE = 0x00000100, ALLOWMULTISELECT = 0x00000200, PATHMUSTEXIST = 0x00000800, FILEMUSTEXIST = 0x00001000, CREATEPROMPT = 0x00002000, SHAREAWARE = 0x00004000, NOREADONLYRETURN = 0x00008000, NOTESTFILECREATE = 0x00010000, HIDEMRUPLACES = 0x00020000, HIDEPINNEDPLACES = 0x00040000, NODEREFERENCELINKS = 0x00100000, DONTADDTORECENT = 0x02000000, FORCESHOWHIDDEN = 0x10000000, DEFAULTNOMINIMODE = 0x20000000, FORCEPREVIEWPANEON = 0x40000000, } /// <summary>FDE_OVERWRITE_RESPONSE. FDEOR_*</summary> internal enum FDEOR { DEFAULT = 0x00000000, ACCEPT = 0x00000001, REFUSE = 0x00000002, } /// <summary>FDE_SHAREVIOLATION_RESPONSE. FDESVR_*</summary> internal enum FDESVR { DEFAULT = 0x00000000, ACCEPT = 0x00000001, REFUSE = 0x00000002, } /// <summary> /// GetPropertyStoreFlags. GPS_*. /// </summary> /// <remarks> /// These are new for Vista, but are used in downlevel components /// </remarks> [Flags] internal enum GPS { // If no flags are specified (GPS_DEFAULT), a read-only property store is returned that includes properties for the file or item. // In the case that the shell item is a file, the property store contains: // 1. properties about the file from the file system // 2. properties from the file itself provided by the file's property handler, unless that file is offline, // see GPS_OPENSLOWITEM // 3. if requested by the file's property handler and supported by the file system, properties stored in the // alternate property store. // // Non-file shell items should return a similar read-only store // // Specifying other GPS_ flags modifies the store that is returned DEFAULT = 0x00000000, HANDLERPROPERTIESONLY = 0x00000001, // only include properties directly from the file's property handler READWRITE = 0x00000002, // Writable stores will only include handler properties TEMPORARY = 0x00000004, // A read/write store that only holds properties for the lifetime of the IShellItem object FASTPROPERTIESONLY = 0x00000008, // do not include any properties from the file's property handler (because the file's property handler will hit the disk) OPENSLOWITEM = 0x00000010, // include properties from a file's property handler, even if it means retrieving the file from offline storage. DELAYCREATION = 0x00000020, // delay the creation of the file's property handler until those properties are read, written, or enumerated BESTEFFORT = 0x00000040, // For readonly stores, succeed and return all available properties, even if one or more sources of properties fails. Not valid with GPS_READWRITE. NO_OPLOCK = 0x00000080, // some data sources protect the read property store with an oplock, this disables that MASK_VALID = 0x000000FF, } /// <summary>Flags for Known Folder APIs. KF_FLAG_*</summary> /// <remarks>native enum was called KNOWN_FOLDER_FLAG</remarks> [Flags] internal enum KF_FLAG : uint { DEFAULT = 0x00000000, // Make sure that the folder already exists or create it and apply security specified in folder definition // If folder can not be created then function will return failure and no folder path (IDList) will be returned // If folder is located on the network the function may take long time to execute CREATE = 0x00008000, // If this flag is specified then the folder path is returned and no verification is performed // Use this flag is you want to get folder's path (IDList) and do not need to verify folder's existence // // If this flag is NOT specified then Known Folder API will try to verify that the folder exists // If folder does not exist or can not be accessed then function will return failure and no folder path (IDList) will be returned // If folder is located on the network the function may take long time to execute DONT_VERIFY = 0x00004000, // Set folder path as is and do not try to substitute parts of the path with environments variables. // If flag is not specified then Known Folder will try to replace parts of the path with some // known environment variables (%USERPROFILE%, %APPDATA% etc.) DONT_UNEXPAND = 0x00002000, // Get file system based IDList if available. If the flag is not specified the Known Folder API // will try to return aliased IDList by default. Example for FOLDERID_Documents - // Aliased - [desktop]\[user]\[Documents] - exact location is determined by shell namespace layout and might change // Non aliased - [desktop]\[computer]\[disk_c]\[users]\[user]\[Documents] - location is determined by folder location in the file system NO_ALIAS = 0x00001000, // Initialize the folder with desktop.ini settings // If folder can not be initialized then function will return failure and no folder path will be returned // If folder is located on the network the function may take long time to execute INIT = 0x00000800, // Get the default path, will also verify folder existence unless KF_FLAG_DONT_VERIFY is also specified DEFAULT_PATH = 0x00000400, // Get the not-parent-relative default path. Only valid with KF_FLAG_DEFAULT_PATH NOT_PARENT_RELATIVE = 0x00000200, // Build simple IDList SIMPLE_IDLIST = 0x00000100, // only return the aliased IDLists, don't fallback to file system path ALIAS_ONLY = 0x80000000, } /// <summary> /// KNOWNDESTCATEGORY. KDC_* /// </summary> internal enum KDC { FREQUENT = 1, RECENT, } /// <summary> /// MSGFLT_*, for ChangeWindowMessageFilter[Ex]. /// </summary> /// <remarks>New in Vista. Realiased in Windows 7.</remarks> internal enum MSGFLT { RESET = 0, // MSGFLT_ADD in Vista. ALLOW = 1, // MSGFLT_REMOVE in Vista. DISALLOW = 2, } internal enum MSGFLTINFO { NONE = 0, ALREADYALLOWED_FORWND = 1, ALREADYDISALLOWED_FORWND = 2, ALLOWED_HIGHER = 3, } // IShellFolder::GetAttributesOf flags [Flags] internal enum SFGAO : uint { /// <summary>Objects can be copied</summary> /// <remarks>DROPEFFECT_COPY</remarks> CANCOPY = 0x1, /// <summary>Objects can be moved</summary> /// <remarks>DROPEFFECT_MOVE</remarks> CANMOVE = 0x2, /// <summary>Objects can be linked</summary> /// <remarks> /// DROPEFFECT_LINK. /// /// If this bit is set on an item in the shell folder, a /// 'Create Shortcut' menu item will be added to the File /// menu and context menus for the item. If the user selects /// that command, your IContextMenu::InvokeCommand() will be called /// with 'link'. /// That flag will also be used to determine if 'Create Shortcut' /// should be added when the item in your folder is dragged to another /// folder. /// </remarks> CANLINK = 0x4, /// <summary>supports BindToObject(IID_IStorage)</summary> STORAGE = 0x00000008, /// <summary>Objects can be renamed</summary> CANRENAME = 0x00000010, /// <summary>Objects can be deleted</summary> CANDELETE = 0x00000020, /// <summary>Objects have property sheets</summary> HASPROPSHEET = 0x00000040, // unused = 0x00000080, /// <summary>Objects are drop target</summary> DROPTARGET = 0x00000100, CAPABILITYMASK = 0x00000177, // unused = 0x00000200, // unused = 0x00000400, // unused = 0x00000800, // unused = 0x00001000, /// <summary>Object is encrypted (use alt color)</summary> ENCRYPTED = 0x00002000, /// <summary>'Slow' object</summary> ISSLOW = 0x00004000, /// <summary>Ghosted icon</summary> GHOSTED = 0x00008000, /// <summary>Shortcut (link)</summary> LINK = 0x00010000, /// <summary>Shared</summary> SHARE = 0x00020000, /// <summary>Read-only</summary> READONLY = 0x00040000, /// <summary> Hidden object</summary> HIDDEN = 0x00080000, DISPLAYATTRMASK = 0x000FC000, /// <summary> May contain children with SFGAO_FILESYSTEM</summary> FILESYSANCESTOR = 0x10000000, /// <summary>Support BindToObject(IID_IShellFolder)</summary> FOLDER = 0x20000000, /// <summary>Is a win32 file system object (file/folder/root)</summary> FILESYSTEM = 0x40000000, /// <summary>May contain children with SFGAO_FOLDER (may be slow)</summary> HASSUBFOLDER = 0x80000000, CONTENTSMASK = 0x80000000, /// <summary>Invalidate cached information (may be slow)</summary> VALIDATE = 0x01000000, /// <summary>Is this removeable media?</summary> REMOVABLE = 0x02000000, /// <summary> Object is compressed (use alt color)</summary> COMPRESSED = 0x04000000, /// <summary>Supports IShellFolder, but only implements CreateViewObject() (non-folder view)</summary> BROWSABLE = 0x08000000, /// <summary>Is a non-enumerated object (should be hidden)</summary> NONENUMERATED = 0x00100000, /// <summary>Should show bold in explorer tree</summary> NEWCONTENT = 0x00200000, /// <summary>Obsolete</summary> CANMONIKER = 0x00400000, /// <summary>Obsolete</summary> HASSTORAGE = 0x00400000, /// <summary>Supports BindToObject(IID_IStream)</summary> STREAM = 0x00400000, /// <summary>May contain children with SFGAO_STORAGE or SFGAO_STREAM</summary> STORAGEANCESTOR = 0x00800000, /// <summary>For determining storage capabilities, ie for open/save semantics</summary> STORAGECAPMASK = 0x70C50008, /// <summary> /// Attributes that are masked out for PKEY_SFGAOFlags because they are considered /// to cause slow calculations or lack context /// (SFGAO_VALIDATE | SFGAO_ISSLOW | SFGAO_HASSUBFOLDER and others) /// </summary> PKEYSFGAOMASK = 0x81044000, } /// <summary> /// SHAddToRecentDocuments flags. SHARD_* /// </summary> internal enum SHARD { /// <summary> /// The pv parameter points to a pointer to an item identifier list (PIDL) that identifies the document's file object. /// PIDLs that identify non-file objects are not accepted. /// </summary> PIDL = 0x00000001, /// <summary> /// The pv parameter points to a null-terminated ANSI string with the path and file name of the object. /// </summary> PATHA = 0x00000002, /// <summary> /// The pv parameter points to a null-terminated Unicode string with the path and file name of the object. /// </summary> PATHW = 0x00000003, /// <summary> /// The pv parameter points to a SHARDAPPIDINFO structure that pairs an IShellItem that identifies the item /// with an Application User Model ID (AppID) that associates it with a particular process or application. /// </summary> /// <remarks> /// Windows 7 and later. /// </remarks> APPIDINFO = 0x00000004, /// <summary> /// The pv parameter points to a SHARDAPPIDINFOIDLIST structure that pairs an absolute PIDL that identifies the item /// with an AppID that associates it with a particular process or application. /// </summary> /// <remarks> /// Windows 7 and later. /// </remarks> APPIDINFOIDLIST = 0x00000005, /// <summary> /// The pv parameter is an interface pointer to an IShellLink object. /// </summary> /// <remarks> /// Windows 7 and later. /// </remarks> LINK = 0x00000006, // indicates the data type is a pointer to an IShellLink instance /// <summary> /// The pv parameter points to a SHARDAPPIDINFOLINK structure that pairs an IShellLink that identifies the item /// with an AppID that associates it with a particular process or application. /// </summary> /// <remarks> /// Windows 7 and later. /// </remarks> APPIDINFOLINK = 0x00000007, /// <summary> /// The pv parameter is an interface pointer to an IShellItem object. /// </summary> /// <remarks> /// Windows 7 and later. /// </remarks> SHELLITEM = 0x00000008, } /// <summary> /// IShellFolder::EnumObjects grfFlags bits. Also called SHCONT /// </summary> [Flags] internal enum SHCONTF { CHECKING_FOR_CHILDREN = 0x0010, // hint that client is checking if (what) child items the folder contains - not all details (e.g. short file name) are needed FOLDERS = 0x0020, // only want folders enumerated (SFGAO_FOLDER) NONFOLDERS = 0x0040, // include non folders (items without SFGAO_FOLDER) INCLUDEHIDDEN = 0x0080, // show items normally hidden (items with SFGAO_HIDDEN) INIT_ON_FIRST_NEXT = 0x0100, // DEFUNCT - this is always assumed NETPRINTERSRCH = 0x0200, // hint that client is looking for printers SHAREABLE = 0x0400, // hint that client is looking sharable resources (local drives or hidden root shares) STORAGE = 0x0800, // include all items with accessible storage and their ancestors NAVIGATION_ENUM = 0x1000, // mark child folders to indicate that they should provide a "navigation" enumeration by default FASTITEMS = 0x2000, // hint that client is only interested in items that can be enumerated quickly FLATLIST = 0x4000, // enumerate items as flat list even if folder is stacked ENABLE_ASYNC = 0x8000, // inform enumerator that client is listening for change notifications so enumerator does not need to be complete, items can be reported via change notifications } /// <summary> /// IShellFolder::GetDisplayNameOf/SetNameOf uFlags. Also called SHGDNF. /// </summary> /// <remarks> /// For compatibility with SIGDN, these bits must all sit in the LOW word. /// </remarks> [Flags] internal enum SHGDN { SHGDN_NORMAL = 0x0000, // default (display purpose) SHGDN_INFOLDER = 0x0001, // displayed under a folder (relative) SHGDN_FOREDITING = 0x1000, // for in-place editing SHGDN_FORADDRESSBAR = 0x4000, // UI friendly parsing name (remove ugly stuff) SHGDN_FORPARSING = 0x8000, // parsing name for ParseDisplayName() } /// <summary>ShellItem attribute flags. SIATTRIBFLAGS_*</summary> internal enum SIATTRIBFLAGS { AND = 0x00000001, OR = 0x00000002, APPCOMPAT = 0x00000003, } /// <summary> /// SHELLITEMCOMPAREHINTF. SICHINT_*. /// </summary> [Flags] internal enum SICHINT : uint { /// <summary>iOrder based on display in a folder view</summary> DISPLAY = 0x00000000, /// <summary>exact instance compare</summary> ALLFIELDS = 0x80000000, /// <summary>iOrder based on canonical name (better performance)</summary> CANONICAL = 0x10000000, /// <summary>Windows 7 and later.</summary> TEST_FILESYSPATH_IF_NOT_EQUAL = 0x20000000, }; /// <summary>ShellItem GetDisplayName options. SIGDN_*</summary> internal enum SIGDN : uint { // lower word (& with 0xFFFF) NORMALDISPLAY = 0x00000000, // SHGDN_NORMAL PARENTRELATIVEPARSING = 0x80018001, // SHGDN_INFOLDER | SHGDN_FORPARSING DESKTOPABSOLUTEPARSING = 0x80028000, // SHGDN_FORPARSING PARENTRELATIVEEDITING = 0x80031001, // SHGDN_INFOLDER | SHGDN_FOREDITING DESKTOPABSOLUTEEDITING = 0x8004c000, // SHGDN_FORPARSING | SHGDN_FORADDRESSBAR FILESYSPATH = 0x80058000, // SHGDN_FORPARSING URL = 0x80068000, // SHGDN_FORPARSING PARENTRELATIVEFORADDRESSBAR = 0x8007c001, // SHGDN_INFOLDER | SHGDN_FORPARSING | SHGDN_FORADDRESSBAR PARENTRELATIVE = 0x80080001, // SHGDN_INFOLDER } /// <summary>IShellLinkW::GetPath flags. SLGP_*</summary> [Flags] internal enum SLGP { SHORTPATH = 0x1, UNCPRIORITY = 0x2, RAWPATH = 0x4 } /// <summary> /// SystemMetrics. SM_* /// </summary> internal enum SM { CXSCREEN = 0, CYSCREEN = 1, CXVSCROLL = 2, CYHSCROLL = 3, CYCAPTION = 4, CXBORDER = 5, CYBORDER = 6, CXFIXEDFRAME = 7, CYFIXEDFRAME = 8, CYVTHUMB = 9, CXHTHUMB = 10, CXICON = 11, CYICON = 12, CXCURSOR = 13, CYCURSOR = 14, CYMENU = 15, CXFULLSCREEN = 16, CYFULLSCREEN = 17, CYKANJIWINDOW = 18, MOUSEPRESENT = 19, CYVSCROLL = 20, CXHSCROLL = 21, DEBUG = 22, SWAPBUTTON = 23, CXMIN = 28, CYMIN = 29, CXSIZE = 30, CYSIZE = 31, CXFRAME = 32, CXSIZEFRAME = CXFRAME, CYFRAME = 33, CYSIZEFRAME = CYFRAME, CXMINTRACK = 34, CYMINTRACK = 35, CXDOUBLECLK = 36, CYDOUBLECLK = 37, CXICONSPACING = 38, CYICONSPACING = 39, MENUDROPALIGNMENT = 40, PENWINDOWS = 41, DBCSENABLED = 42, CMOUSEBUTTONS = 43, SECURE = 44, CXEDGE = 45, CYEDGE = 46, CXMINSPACING = 47, CYMINSPACING = 48, CXSMICON = 49, CYSMICON = 50, CYSMCAPTION = 51, CXSMSIZE = 52, CYSMSIZE = 53, CXMENUSIZE = 54, CYMENUSIZE = 55, ARRANGE = 56, CXMINIMIZED = 57, CYMINIMIZED = 58, CXMAXTRACK = 59, CYMAXTRACK = 60, CXMAXIMIZED = 61, CYMAXIMIZED = 62, NETWORK = 63, CLEANBOOT = 67, CXDRAG = 68, CYDRAG = 69, SHOWSOUNDS = 70, CXMENUCHECK = 71, CYMENUCHECK = 72, SLOWMACHINE = 73, MIDEASTENABLED = 74, MOUSEWHEELPRESENT = 75, XVIRTUALSCREEN = 76, YVIRTUALSCREEN = 77, CXVIRTUALSCREEN = 78, CYVIRTUALSCREEN = 79, CMONITORS = 80, SAMEDISPLAYFORMAT = 81, IMMENABLED = 82, CXFOCUSBORDER = 83, CYFOCUSBORDER = 84, TABLETPC = 86, MEDIACENTER = 87, REMOTESESSION = 0x1000, REMOTECONTROL = 0x2001, } /// <summary> /// Flags for ITaskbarList3 SetTabProperties. STPF_* /// </summary> /// <remarks>The native enum was called STPFLAG.</remarks> [Flags] internal enum STPF { NONE = 0x00000000, USEAPPTHUMBNAILALWAYS = 0x00000001, USEAPPTHUMBNAILWHENACTIVE = 0x00000002, USEAPPPEEKALWAYS = 0x00000004, USEAPPPEEKWHENACTIVE = 0x00000008, } /// <summary> /// STR_GPS_* /// </summary> /// <remarks> /// When requesting a property store through IShellFolder, you can specify the equivalent of /// GPS_DEFAULT by passing in a null IBindCtx parameter. /// /// You can specify the equivalent of GPS_READWRITE by passing a mode of STGM_READWRITE | STGM_EXCLUSIVE /// in the bind context /// /// Here are the string versions of GPS_ flags, passed to IShellFolder::BindToObject() via IBindCtx::RegisterObjectParam() /// These flags are valid when requesting an IPropertySetStorage or IPropertyStore handler /// /// The meaning of these flags are described above. /// /// There is no STR_ equivalent for GPS_TEMPORARY because temporary property stores /// are provided by IShellItem2 only -- not by the underlying IShellFolder. /// </remarks> internal static class STR_GPS { public const string HANDLERPROPERTIESONLY = "GPS_HANDLERPROPERTIESONLY"; public const string FASTPROPERTIESONLY = "GPS_FASTPROPERTIESONLY"; public const string OPENSLOWITEM = "GPS_OPENSLOWITEM"; public const string DELAYCREATION = "GPS_DELAYCREATION"; public const string BESTEFFORT = "GPS_BESTEFFORT"; public const string NO_OPLOCK = "GPS_NO_OPLOCK"; } /// <summary> /// Flags for Setting Taskbar Progress state. TBPF_* /// </summary> /// <remarks> /// The native enum was called TBPFLAG. /// </remarks> [Flags] internal enum TBPF { NOPROGRESS = 0x00000000, INDETERMINATE = 0x00000001, NORMAL = 0x00000002, ERROR = 0x00000004, PAUSED = 0x00000008, } /// <summary> /// THUMBBUTTON mask. THB_* /// </summary> [Flags] internal enum THB : uint { BITMAP = 0x0001, ICON = 0x0002, TOOLTIP = 0x0004, FLAGS = 0x0008, } /// <summary> /// THUMBBUTTON flags. THBF_* /// </summary> [Flags] internal enum THBF : uint { ENABLED = 0x0000, DISABLED = 0x0001, DISMISSONCLICK = 0x0002, NOBACKGROUND = 0x0004, HIDDEN = 0x0008, // Added post-beta NONINTERACTIVE = 0x0010, } /// <summary> /// Window message values, WM_* /// </summary> internal enum WindowMessage { WM_NULL = 0x0000, WM_CREATE = 0x0001, WM_DESTROY = 0x0002, WM_MOVE = 0x0003, WM_SIZE = 0x0005, WM_ACTIVATE = 0x0006, WM_SETFOCUS = 0x0007, WM_KILLFOCUS = 0x0008, WM_ENABLE = 0x000A, WM_SETREDRAW = 0x000B, WM_SETTEXT = 0x000C, WM_GETTEXT = 0x000D, WM_GETTEXTLENGTH = 0x000E, WM_PAINT = 0x000F, WM_CLOSE = 0x0010, WM_QUERYENDSESSION = 0x0011, WM_QUIT = 0x0012, WM_QUERYOPEN = 0x0013, WM_ERASEBKGND = 0x0014, WM_SYSCOLORCHANGE = 0x0015, WM_ENDSESSION = 0x0016, WM_SHOWWINDOW = 0x0018, WM_CTLCOLOR = 0x0019, WM_WININICHANGE = 0x001A, WM_SETTINGCHANGE = 0x001A, WM_DEVMODECHANGE = 0x001B, WM_ACTIVATEAPP = 0x001C, WM_FONTCHANGE = 0x001D, WM_TIMECHANGE = 0x001E, WM_CANCELMODE = 0x001F, WM_SETCURSOR = 0x0020, WM_MOUSEACTIVATE =0x0021, WM_CHILDACTIVATE = 0x0022, WM_QUEUESYNC = 0x0023, WM_GETMINMAXINFO = 0x0024, WM_PAINTICON = 0x0026, WM_ICONERASEBKGND = 0x0027, WM_NEXTDLGCTL = 0x0028, WM_SPOOLERSTATUS = 0x002A, WM_DRAWITEM = 0x002B, WM_MEASUREITEM = 0x002C, WM_DELETEITEM = 0x002D, WM_VKEYTOITEM = 0x002E, WM_CHARTOITEM = 0x002F, WM_SETFONT = 0x0030, WM_GETFONT = 0x0031, WM_SETHOTKEY = 0x0032, WM_GETHOTKEY = 0x0033, WM_QUERYDRAGICON = 0x0037, WM_COMPAREITEM = 0x0039, WM_GETOBJECT = 0x003D, WM_COMPACTING = 0x0041, WM_COMMNOTIFY = 0x0044, WM_WINDOWPOSCHANGING = 0x0046, WM_WINDOWPOSCHANGED = 0x0047, WM_POWER = 0x0048, WM_COPYDATA = 0x004A, WM_CANCELJOURNAL = 0x004B, WM_NOTIFY = 0x004E, WM_INPUTLANGCHANGEREQUEST = 0x0050, WM_INPUTLANGCHANGE = 0x0051, WM_TCARD = 0x0052, WM_HELP = 0x0053, WM_USERCHANGED = 0x0054, WM_NOTIFYFORMAT = 0x0055, WM_CONTEXTMENU = 0x007B, WM_STYLECHANGING = 0x007C, WM_STYLECHANGED = 0x007D, WM_DISPLAYCHANGE = 0x007E, WM_GETICON = 0x007F, WM_SETICON = 0x0080, WM_NCCREATE = 0x0081, WM_NCDESTROY = 0x0082, WM_NCCALCSIZE = 0x0083, WM_NCHITTEST = 0x0084, WM_NCPAINT = 0x0085, WM_NCACTIVATE = 0x0086, WM_GETDLGCODE = 0x0087, WM_SYNCPAINT = 0x0088, WM_MOUSEQUERY = 0x009B, WM_NCMOUSEMOVE = 0x00A0, WM_NCLBUTTONDOWN = 0x00A1, WM_NCLBUTTONUP = 0x00A2, WM_NCLBUTTONDBLCLK = 0x00A3, WM_NCRBUTTONDOWN = 0x00A4, WM_NCRBUTTONUP = 0x00A5, WM_NCRBUTTONDBLCLK = 0x00A6, WM_NCMBUTTONDOWN = 0x00A7, WM_NCMBUTTONUP = 0x00A8, WM_NCMBUTTONDBLCLK = 0x00A9, WM_NCXBUTTONDOWN = 0x00AB, WM_NCXBUTTONUP = 0x00AC, WM_NCXBUTTONDBLCLK = 0x00AD, WM_INPUT = 0x00FF, WM_KEYFIRST = 0x0100, WM_KEYDOWN = 0x0100, WM_KEYUP = 0x0101, WM_CHAR = 0x0102, WM_DEADCHAR = 0x0103, WM_SYSKEYDOWN = 0x0104, WM_SYSKEYUP = 0x0105, WM_SYSCHAR = 0x0106, WM_SYSDEADCHAR = 0x0107, WM_KEYLAST = 0x0108, WM_IME_STARTCOMPOSITION = 0x010D, WM_IME_ENDCOMPOSITION = 0x010E, WM_IME_COMPOSITION = 0x010F, WM_IME_KEYLAST = 0x010F, WM_INITDIALOG = 0x0110, WM_COMMAND = 0x0111, WM_SYSCOMMAND = 0x0112, WM_TIMER = 0x0113, WM_HSCROLL = 0x0114, WM_VSCROLL = 0x0115, WM_INITMENU = 0x0116, WM_INITMENUPOPUP = 0x0117, WM_MENUSELECT = 0x011F, WM_MENUCHAR = 0x0120, WM_ENTERIDLE = 0x0121, WM_UNINITMENUPOPUP = 0x0125, WM_CHANGEUISTATE = 0x0127, WM_UPDATEUISTATE = 0x0128, WM_QUERYUISTATE = 0x0129, WM_CTLCOLORMSGBOX = 0x0132, WM_CTLCOLOREDIT = 0x0133, WM_CTLCOLORLISTBOX = 0x0134, WM_CTLCOLORBTN = 0x0135, WM_CTLCOLORDLG = 0x0136, WM_CTLCOLORSCROLLBAR = 0x0137, WM_CTLCOLORSTATIC = 0x0138, WM_MOUSEMOVE = 0x0200, WM_MOUSEFIRST = WM_MOUSEMOVE, WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202, WM_LBUTTONDBLCLK = 0x0203, WM_RBUTTONDOWN = 0x0204, WM_RBUTTONUP = 0x0205, WM_RBUTTONDBLCLK = 0x0206, WM_MBUTTONDOWN = 0x0207, WM_MBUTTONUP = 0x0208, WM_MBUTTONDBLCLK = 0x0209, WM_MOUSEWHEEL = 0x020A, WM_XBUTTONDOWN = 0x020B, WM_XBUTTONUP = 0x020C, WM_XBUTTONDBLCLK = 0x020D, WM_MOUSEHWHEEL = 0x020E, WM_MOUSELAST = WM_MOUSEHWHEEL, WM_PARENTNOTIFY = 0x0210, WM_ENTERMENULOOP = 0x0211, WM_EXITMENULOOP = 0x0212, WM_NEXTMENU = 0x0213, WM_SIZING = 0x0214, WM_CAPTURECHANGED = 0x0215, WM_MOVING = 0x0216, WM_POWERBROADCAST = 0x0218, WM_DEVICECHANGE = 0x0219, WM_IME_SETCONTEXT = 0x0281, WM_IME_NOTIFY = 0x0282, WM_IME_CONTROL = 0x0283, WM_IME_COMPOSITIONFULL = 0x0284, WM_IME_SELECT = 0x0285, WM_IME_CHAR = 0x0286, WM_IME_REQUEST = 0x0288, WM_IME_KEYDOWN = 0x0290, WM_IME_KEYUP = 0x0291, WM_MDICREATE = 0x0220, WM_MDIDESTROY = 0x0221, WM_MDIACTIVATE = 0x0222, WM_MDIRESTORE = 0x0223, WM_MDINEXT = 0x0224, WM_MDIMAXIMIZE = 0x0225, WM_MDITILE = 0x0226, WM_MDICASCADE = 0x0227, WM_MDIICONARRANGE = 0x0228, WM_MDIGETACTIVE = 0x0229, WM_MDISETMENU = 0x0230, WM_ENTERSIZEMOVE = 0x0231, WM_EXITSIZEMOVE = 0x0232, WM_DROPFILES = 0x0233, WM_MDIREFRESHMENU = 0x0234, WM_MOUSEHOVER = 0x02A1, WM_NCMOUSELEAVE = 0x02A2, WM_MOUSELEAVE = 0x02A3, WM_WTSSESSION_CHANGE = 0x02b1, WM_TABLET_DEFBASE = 0x02C0, WM_TABLET_MAXOFFSET = 0x20, WM_TABLET_ADDED = WM_TABLET_DEFBASE + 8, WM_TABLET_DELETED = WM_TABLET_DEFBASE + 9, WM_TABLET_FLICK = WM_TABLET_DEFBASE + 11, WM_TABLET_QUERYSYSTEMGESTURESTATUS = WM_TABLET_DEFBASE + 12, WM_CUT = 0x0300, WM_COPY = 0x0301, WM_PASTE = 0x0302, WM_CLEAR = 0x0303, WM_UNDO = 0x0304, WM_RENDERFORMAT = 0x0305, WM_RENDERALLFORMATS = 0x0306, WM_DESTROYCLIPBOARD = 0x0307, WM_DRAWCLIPBOARD = 0x0308, WM_PAINTCLIPBOARD = 0x0309, WM_VSCROLLCLIPBOARD = 0x030A, WM_SIZECLIPBOARD = 0x030B, WM_ASKCBFORMATNAME = 0x030C, WM_CHANGECBCHAIN = 0x030D, WM_HSCROLLCLIPBOARD = 0x030E, WM_QUERYNEWPALETTE = 0x030F, WM_PALETTEISCHANGING = 0x0310, WM_PALETTECHANGED = 0x0311, WM_HOTKEY = 0x0312, WM_PRINT = 0x0317, WM_PRINTCLIENT = 0x0318, WM_APPCOMMAND = 0x0319, WM_THEMECHANGED = 0x031A, WM_DWMCOMPOSITIONCHANGED = 0x031E, WM_DWMNCRENDERINGCHANGED = 0x031F, WM_DWMCOLORIZATIONCOLORCHANGED = 0x0320, WM_DWMWINDOWMAXIMIZEDCHANGE = 0x0321, WM_HANDHELDFIRST = 0x0358, WM_HANDHELDLAST = 0x035F, WM_AFXFIRST = 0x0360, WM_AFXLAST = 0x037F, WM_PENWINFIRST = 0x0380, WM_PENWINLAST = 0x038F, #region Windows 7 WM_DWMSENDICONICTHUMBNAIL = 0x0323, WM_DWMSENDICONICLIVEPREVIEWBITMAP = 0x0326, #endregion WM_USER = 0x0400, WM_APP = 0x8000, } /// <summary> /// Common native constants. /// </summary> internal static class Win32Constant { internal const int MAX_PATH = 260; internal const int INFOTIPSIZE = 1024; internal const int TRUE = 1; internal const int FALSE = 0; } }
using org.javarosa.core.data; using org.javarosa.core.model; using org.javarosa.core.model.instance; using org.javarosa.core.model.utils; using org.javarosa.core.services.transport.payload; using org.javarosa.xform.util; using System; using System.Collections; using System.Text; using System.Xml; namespace org.javarosa.model.xform{ /* * Copyright (C) 2009 JavaRosa ,Copyright (C) 2014 Simbacode * * 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. */ /** * A visitor-esque class which walks a FormInstance and constructs an XML document * containing its instance. * * The XML node elements are constructed in a depth-first manner, consistent with * standard XML document parsing. * * @author Acellam Guy , Clayton Sims * */ public class XFormSerializingVisitor : IInstanceSerializingVisitor { /** The XML document containing the instance that is to be returned */ XmlDocument theXmlDoc; /** The serializer to be used in constructing XML for AnswerData elements */ IAnswerDataSerializer serializer; /** The root of the xml document which should be included in the serialization **/ TreeReference rootRef; /** The schema to be used to serialize answer data */ FormDef schema; //not used ArrayList dataPointers; private void init() { theXmlDoc = null; schema = null; dataPointers = new ArrayList(); } public virtual byte[] serializeInstance(FormInstance model, IDataReference ref_) { init(); rootRef = model.unpackReference2(ref_); if (this.serializer == null) { this.setAnswerDataSerializer(new XFormAnswerDataSerializer()); } model.accept(this); if (theXmlDoc != null) { return Encoding.UTF8.GetBytes(XFormSerializer.getString(theXmlDoc)); } else { return null; } } public virtual byte[] serializeInstance(FormInstance model) { return serializeInstance(model, new XPathReference("/")); } public virtual byte[] serializeInstance(FormInstance model, FormDef formDef) { //LEGACY: Should remove init(); this.schema = formDef; return serializeInstance(model); } public IDataPayload createSerializedPayload (FormInstance model) { return createSerializedPayload(model, (IDataReference)new XPathReference("/")); } public IDataPayload createSerializedPayload (FormInstance model, IDataReference ref_) { init(); rootRef = model.unpackReference2(ref_); if(this.serializer == null) { this.setAnswerDataSerializer(new XFormAnswerDataSerializer()); } model.accept(this); if(theXmlDoc != null) { byte[] form = Encoding.UTF8.GetBytes(XFormSerializer.getString(theXmlDoc)); if(dataPointers.Count == 0) { return new ByteArrayPayload(form, null, IDataPayload_Fields.PAYLOAD_TYPE_XML); } MultiMessagePayload payload = new MultiMessagePayload(); payload.addPayload(new ByteArrayPayload(form, null, IDataPayload_Fields.PAYLOAD_TYPE_XML)); IEnumerator en = dataPointers.GetEnumerator(); while(en.MoveNext()) { IDataPointer pointer = (IDataPointer)en.Current; payload.addPayload(new DataPointerPayload(pointer)); } return payload; } else { return null; } } /* * (non-Javadoc) * @see org.javarosa.core.model.utils.ITreeVisitor#visit(org.javarosa.core.model.DataModelTree) */ public void visit(FormInstance tree) { theXmlDoc = new XmlDocument(); //TreeElement root = tree.getRoot(); TreeElement root = tree.resolveReference(rootRef); //For some reason resolveReference won't ever return the root, so we'll //catch that case and just start at the root. if(root == null) { root = tree.getRoot(); } for (int i = 0; i< root.getNumChildren(); i++){ TreeElement childAt = root.getChildAt(i); } if (root != null) { theXmlDoc.AppendChild(serializeNode(root)); } XmlElement top =(XmlElement)theXmlDoc.FirstChild; String[] prefixes = tree.getNamespacePrefixes(); for(int i = 0 ; i < prefixes.Length; ++i ) { top.Prefix =prefixes[i]; } if (tree.schema != null) { //top.setNamespace(tree.schema); top.SetAttribute(top.Name, tree.schema, top.Value); top.Prefix =tree.schema; } } public XmlElement serializeNode (TreeElement instanceNode) { XmlElement e = theXmlDoc.CreateElement(instanceNode.getName());//TODO Name //don't serialize template nodes or non-relevant nodes if (!instanceNode.isRelevant() || instanceNode.getMult() == TreeReference.INDEX_TEMPLATE) return null; if (instanceNode.getValue() != null) { Object serializedAnswer = serializer.serializeAnswerData(instanceNode.getValue(), instanceNode.dataType); if (serializedAnswer is XmlElement) { e = (XmlElement)serializedAnswer; } else if (serializedAnswer is String) { e = e.OwnerDocument.CreateElement(instanceNode.getName()); XmlText xmlText = theXmlDoc.CreateTextNode( (String)serializedAnswer);//TODO name e.AppendChild(xmlText); } else { throw new SystemException("Can't handle serialized output for" + instanceNode.getValue().ToString() + ", " + serializedAnswer); } if(serializer.containsExternalData(instanceNode.getValue())) { IDataPointer[] pointer = serializer.retrieveExternalDataPointer(instanceNode.getValue()); for(int i = 0 ; i < pointer.Length ; ++i) { dataPointers.Add(pointer[i]); } } } else { //make sure all children of the same tag name are written en bloc ArrayList childNames = new ArrayList(); for (int i = 0; i < instanceNode.getNumChildren(); i++) { String childName = instanceNode.getChildAt(i).getName(); Console.WriteLine("CHILDNAME: " + childName); if (!childNames.Contains(childName)) childNames.Add(childName); } for (int i = 0; i < childNames.Count; i++) { String childName = (String)childNames[i]; int mult = instanceNode.getChildMultiplicity(childName); for (int j = 0; j < mult; j++) { XmlElement child = serializeNode(instanceNode.getChild(childName, j)); if (child != null) { e.AppendChild(child); } } } } XmlElement e1 = e.OwnerDocument.CreateElement(instanceNode.getName()); e.ParentNode.ReplaceChild(e1, e); // add hard-coded attributes for (int i = 0; i < instanceNode.getAttributeCount(); i++) { String namespace_ = instanceNode.getAttributeNamespace(i); String name = instanceNode.getAttributeName(i); String val = instanceNode.getAttributeValue(i); e.SetAttribute(name,namespace_, val); } return e; } /* * (non-Javadoc) * @see org.javarosa.core.model.utils.IInstanceSerializingVisitor#setAnswerDataSerializer(org.javarosa.core.model.IAnswerDataSerializer) */ public void setAnswerDataSerializer(IAnswerDataSerializer ads) { this.serializer = ads; } public IInstanceSerializingVisitor newInstance() { XFormSerializingVisitor modelSerializer = new XFormSerializingVisitor(); modelSerializer.setAnswerDataSerializer(this.serializer); return modelSerializer; } } }
// // Copyright (c) 2004-2021 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. // namespace NLog.Internal { using System; using System.IO; using System.Linq; using System.Reflection; using NLog.Common; #if SILVERLIGHT && !WINDOWS_PHONE using System.Windows; #endif /// <summary> /// Helpers for <see cref="Assembly"/>. /// </summary> internal static class AssemblyHelpers { #if !NETSTANDARD1_3 /// <summary> /// Load from url /// </summary> /// <param name="assemblyFileName">file or path, including .dll</param> /// <param name="baseDirectory">basepath, optional</param> /// <returns></returns> public static Assembly LoadFromPath(string assemblyFileName, string baseDirectory = null) { string fullFileName = baseDirectory == null ? assemblyFileName : Path.Combine(baseDirectory, assemblyFileName); InternalLogger.Info("Loading assembly file: {0}", fullFileName); #if NETSTANDARD1_5 try { var assemblyName = System.Runtime.Loader.AssemblyLoadContext.GetAssemblyName(fullFileName); return Assembly.Load(assemblyName); } catch (Exception ex) { // this doesn't usually work InternalLogger.Warn(ex, "Fallback to AssemblyLoadContext.Default.LoadFromAssemblyPath for file: {0}", fullFileName); return System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(fullFileName); } #elif SILVERLIGHT && !WINDOWS_PHONE var stream = Application.GetResourceStream(new Uri(assemblyFileName, UriKind.Relative)); var assemblyPart = new AssemblyPart(); Assembly assembly = assemblyPart.Load(stream.Stream); return assembly; #else Assembly asm = Assembly.LoadFrom(fullFileName); return asm; #endif } #endif /// <summary> /// Load from url /// </summary> /// <param name="assemblyName">name without .dll</param> /// <returns></returns> public static Assembly LoadFromName(string assemblyName) { InternalLogger.Info("Loading assembly: {0}", assemblyName); #if NETSTANDARD1_0 || WINDOWS_PHONE var name = new AssemblyName(assemblyName); return Assembly.Load(name); #elif SILVERLIGHT && !WINDOWS_PHONE //as embedded resource var assemblyFile = assemblyName + ".dll"; var stream = Application.GetResourceStream(new Uri(assemblyFile, UriKind.Relative)); var assemblyPart = new AssemblyPart(); Assembly assembly = assemblyPart.Load(stream.Stream); return assembly; #else try { Assembly assembly = Assembly.Load(assemblyName); return assembly; } catch (FileNotFoundException) { var name = new AssemblyName(assemblyName); InternalLogger.Trace("Try find '{0}' in current domain", assemblyName); var loadedAssembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(domainAssembly => IsAssemblyMatch(name, domainAssembly.GetName())); if (loadedAssembly != null) { InternalLogger.Trace("Found '{0}' in current domain", assemblyName); return loadedAssembly; } InternalLogger.Trace("Haven't found' '{0}' in current domain", assemblyName); throw; } #endif } private static bool IsAssemblyMatch(AssemblyName expected, AssemblyName actual) { if (expected.Name != actual.Name) return false; if (expected.Version != null && expected.Version != actual.Version) return false; #if !NETSTANDARD1_3 && !NETSTANDARD1_5 if (expected.CultureInfo != null && expected.CultureInfo.Name != actual.CultureInfo.Name) return false; #endif var expectedKeyToken = expected.GetPublicKeyToken(); var correctToken = expectedKeyToken == null || expectedKeyToken.SequenceEqual(actual.GetPublicKeyToken()); return correctToken; } #if !SILVERLIGHT && !NETSTANDARD1_3 public static string GetAssemblyFileLocation(Assembly assembly) { string fullName = string.Empty; try { if (assembly == null) { return string.Empty; } fullName = assembly.FullName; #if NETSTANDARD if (string.IsNullOrEmpty(assembly.Location)) { // Assembly with no actual location should be skipped (Avoid PlatformNotSupportedException) InternalLogger.Warn("Ignoring assembly location because location is empty: {0}", fullName); return string.Empty; } #endif Uri assemblyCodeBase; if (!Uri.TryCreate(assembly.CodeBase, UriKind.RelativeOrAbsolute, out assemblyCodeBase)) { InternalLogger.Warn("Ignoring assembly location because code base is unknown: '{0}' ({1})", assembly.CodeBase, fullName); return string.Empty; } var assemblyLocation = Path.GetDirectoryName(assemblyCodeBase.LocalPath); if (string.IsNullOrEmpty(assemblyLocation)) { InternalLogger.Warn("Ignoring assembly location because it is not a valid directory: '{0}' ({1})", assemblyCodeBase.LocalPath, fullName); return string.Empty; } DirectoryInfo directoryInfo = new DirectoryInfo(assemblyLocation); if (!directoryInfo.Exists) { InternalLogger.Warn("Ignoring assembly location because directory doesn't exists: '{0}' ({1})", assemblyLocation, fullName); return string.Empty; } InternalLogger.Debug("Found assembly location directory: '{0}' ({1})", directoryInfo.FullName, fullName); return directoryInfo.FullName; } catch (System.PlatformNotSupportedException ex) { InternalLogger.Warn(ex, "Ignoring assembly location because assembly lookup is not supported: {0}", fullName); if (ex.MustBeRethrown()) { throw; } return string.Empty; } catch (System.Security.SecurityException ex) { InternalLogger.Warn(ex, "Ignoring assembly location because assembly lookup is not allowed: {0}", fullName); if (ex.MustBeRethrown()) { throw; } return string.Empty; } catch (UnauthorizedAccessException ex) { InternalLogger.Warn(ex, "Ignoring assembly location because assembly lookup is not allowed: {0}", fullName); if (ex.MustBeRethrown()) { throw; } return string.Empty; } } #endif } }
// This file was created automatically, do not modify the contents of this file. // ReSharper disable InvalidXmlDocComment // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable MemberCanBePrivate.Global using System; using System.Runtime.InteropServices; // Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\CoreUObject\Public\UObject\Object.h:45 namespace UnrealEngine { public partial class UObject : UObjectBaseUtility { public UObject(IntPtr adress) : base(adress) { } public UObject(UObject Parent = null, string Name = "Object") : base(IntPtr.Zero) { NativePointer = E_NewObject_UObject(Parent, Name); NativeManager.AddNativeWrapper(NativePointer, this); } #region DLLInmport [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_NewObject_UObject(IntPtr Parent, string Name); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UObject_AbortInsideMemberFunction(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UObject_AreNativePropertiesIdenticalTo(IntPtr self, IntPtr other); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UObject_BeginDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UObject_CanCheckDefaultSubObjects(IntPtr self, bool bForceCheck, bool bResult); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UObject_CanCreateInCurrentContext(IntPtr self, IntPtr template); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UObject_CanModify(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UObject_CheckDefaultSubobjects(IntPtr self, bool bForceCheck); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UObject_CheckDefaultSubobjectsInternal(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UObject_ConditionalBeginDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UObject_ConditionalFinishDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UObject_ConditionalPostLoad(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UObject_ConditionalPostLoadSubobjects(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UObject_DestroyNonNativeProperties(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UObject_ExecuteUbergraph(IntPtr self, int entryPoint); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UObject_FinishDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern ObjectPointerDescription E_UObject_GetArchetype(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern StringWrapper E_UObject_GetDefaultConfigFilename(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern StringWrapper E_UObject_GetDesc(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern StringWrapper E_UObject_GetDetailedInfo(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern StringWrapper E_UObject_GetDetailedInfoInternal(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern StringWrapper E_UObject_GetGlobalUserConfigFilename(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern ObjectPointerDescription E_UObject_GetWorld(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern ObjectPointerDescription E_UObject_GetWorldChecked(IntPtr self, bool bSupported); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UObject_ImplementsGetWorld(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UObject_InstanceSubobjectTemplates(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UObject_IsAsset(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UObject_IsBasedOnArchetype(IntPtr self, IntPtr someObject); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UObject_IsEditorOnly(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UObject_IsFullNameStableForNetworking(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UObject_IsInBlueprint(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UObject_IsLocalizedResource(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UObject_IsNameStableForNetworking(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UObject_IsPostLoadThreadSafe(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UObject_IsReadyForFinishDestroy(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UObject_IsSafeForRootSet(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UObject_IsSelected(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UObject_IsSupportedForNetworking(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UObject_LoadConfig(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UObject_MarkAsEditorOnlySubobject(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UObject_Modify(IntPtr self, bool bAlwaysMarkDirty); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UObject_NeedsLoadForClient(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UObject_NeedsLoadForEditorGame(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UObject_NeedsLoadForServer(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UObject_OverridePerObjectConfigSection(IntPtr self, string sectionName); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UObject_PostCDOContruct(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UObject_PostEditImport(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UObject_PostInitProperties(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UObject_PostLoad(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UObject_PostNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UObject_PostRename(IntPtr self, IntPtr oldOuter, string oldName); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UObject_PostRepNotifies(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UObject_PostSaveRoot(IntPtr self, bool bCleanupIsRequired); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UObject_PreDestroyFromReplication(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UObject_PreNetReceive(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UObject_ReinitializeProperties(IntPtr self, IntPtr sourceObject); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UObject_ReloadConfig(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_UObject_Rename(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UObject_SaveConfig(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UObject_ShutdownAfterError(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern StringWrapper E_UObject_SourceFileTagName(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UObject_UpdateDefaultConfigFile(IntPtr self, string specificFileLocation); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_UObject_UpdateGlobalUserConfigFile(IntPtr self); #endregion #region ExternMethods /// <summary> /// Abort with a member function call at the top of the callstack, helping to ensure that most platforms will stuff this object's memory into the resulting minidump. /// </summary> public void AbortInsideMemberFunction() => E_UObject_AbortInsideMemberFunction(this); /// <summary> /// Returns whether native properties are identical to the one of the passed in component. /// </summary> /// <param name="other">Other component to compare against</param> /// <return>true</return> public virtual bool AreNativePropertiesIdenticalTo(UObject other) => E_UObject_AreNativePropertiesIdenticalTo(this, other); /// <summary> /// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an /// <para>asynchronous cleanup process. </para> /// </summary> public virtual void BeginDestroy() => E_UObject_BeginDestroy(this); /// <summary> /// Checks it's ok to perform subobjects check at this time. /// </summary> protected bool CanCheckDefaultSubObjects(bool bForceCheck, bool bResult) => E_UObject_CanCheckDefaultSubObjects(this, bForceCheck, bResult); /// <summary> /// Determines if you can create an object from the supplied template in the current context (editor, client only, dedicated server, game/listen) /// <para>This calls NeedsLoadForClient & NeedsLoadForServer </para> /// </summary> public bool CanCreateInCurrentContext(UObject template) => E_UObject_CanCreateInCurrentContext(this, template); /// <summary> /// Utility to allow overrides of Modify to avoid doing work if this object cannot be safely modified /// </summary> public bool CanModify() => E_UObject_CanModify(this); /// <summary> /// Checks default sub-object assumptions. /// </summary> /// <param name="bForceCheck">Force checks even if not enabled globally.</param> /// <return>true</return> public bool CheckDefaultSubobjects(bool bForceCheck = false) => E_UObject_CheckDefaultSubobjects(this, bForceCheck); /// <summary> /// Checks default sub-object assumptions. /// </summary> /// <return>true</return> protected virtual bool CheckDefaultSubobjectsInternal() => E_UObject_CheckDefaultSubobjectsInternal(this); /// <summary> /// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an /// <para>asynchronous cleanup process. </para> /// </summary> public bool ConditionalBeginDestroy() => E_UObject_ConditionalBeginDestroy(this); /// <summary> /// Called when an object is actually destroyed, memory should never be accessed again /// </summary> public bool ConditionalFinishDestroy() => E_UObject_ConditionalFinishDestroy(this); /// <summary> /// PostLoad if needed. /// </summary> public void ConditionalPostLoad() => E_UObject_ConditionalPostLoad(this); /// <summary> /// Instances subobjects and components for objects being loaded from disk, if necessary. Ensures that references /// <para>between nested components are fixed up correctly. </para> /// subobjects and components for a subobject root. /// </summary> /// <param name="outerInstanceGraph">when calling this method on subobjects, specifies the instancing graph which contains all instanced</param> public void ConditionalPostLoadSubobjects() => E_UObject_ConditionalPostLoadSubobjects(this); /// <summary> /// Destroy properties that won't be destroyed by the native destructor /// </summary> public void DestroyNonNativeProperties() => E_UObject_DestroyNonNativeProperties(this); /// <summary> /// Execute the ubergraph from a specific entry point /// </summary> public void ExecuteUbergraph(int entryPoint) => E_UObject_ExecuteUbergraph(this, entryPoint); /// <summary> /// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed. /// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para> /// </summary> public virtual void FinishDestroy() => E_UObject_FinishDestroy(this); /// <summary> /// Return the template this object is based on. /// </summary> /// <return>the</return> public UObject GetArchetype() => E_UObject_GetArchetype(this); /// <summary> /// Get the default config filename for the specified UObject /// </summary> public string GetDefaultConfigFilename() => E_UObject_GetDefaultConfigFilename(this); /// <summary> /// Return a one line description of an object for viewing in the thumbnail view of the generic browser /// </summary> public virtual string GetDesc() => E_UObject_GetDesc(this); /// <summary> /// This will return detail info about this specific object. (e.g. AudioComponent will return the name of the cue, /// <para>ParticleSystemComponent will return the name of the ParticleSystem) The idea here is that in many places </para> /// you have a component of interest but what you really want is some characteristic that you can use to track /// <para>down where it came from. </para> /// @note safe to call on NULL object pointers! /// </summary> public string GetDetailedInfo() => E_UObject_GetDetailedInfo(this); /// <summary> /// This function actually does the work for the GetDetailedInfo() and is virtual. /// <para>It should only be called from GetDetailedInfo as GetDetailedInfo is safe to call on NULL object pointers </para> /// </summary> protected virtual string GetDetailedInfoInternal() => E_UObject_GetDetailedInfoInternal(this); /// <summary> /// Get the global user override config filename for the specified UObject /// </summary> public string GetGlobalUserConfigFilename() => E_UObject_GetGlobalUserConfigFilename(this); /// <summary> /// Returns what UWorld this object is contained within. /// <para>By default this will follow its Outer chain, but it should be overridden if that will not work. </para> /// </summary> public virtual UWorld GetWorld() => E_UObject_GetWorld(this); /// <summary> /// Internal function used by UEngine::GetWorldFromContextObject() /// </summary> public UWorld GetWorldChecked(bool bSupported) => E_UObject_GetWorldChecked(this, bSupported); /// <summary> /// Checks to see if GetWorld() is implemented on a specific class /// </summary> public bool ImplementsGetWorld() => E_UObject_ImplementsGetWorld(this); /// <summary> /// Wrapper for calling UClass::InstanceSubobjectTemplates() for this object. /// </summary> public void InstanceSubobjectTemplates() => E_UObject_InstanceSubobjectTemplates(this); /// <summary> /// Returns true if this object is considered an asset. /// </summary> public virtual bool IsAsset() => E_UObject_IsAsset(this); /// <summary> /// Determine if this object has SomeObject in its archetype chain. /// </summary> public bool IsBasedOnArchetype(UObject someObject) => E_UObject_IsBasedOnArchetype(this, someObject); /// <summary> /// Called during saving to determine if the object is forced to be editor only or not /// </summary> /// <return>true</return> public virtual bool IsEditorOnly() => E_UObject_IsEditorOnly(this); /// <summary> /// IsFullNameStableForNetworking means an object can be referred to its full path name over the network /// </summary> public virtual bool IsFullNameStableForNetworking() => E_UObject_IsFullNameStableForNetworking(this); /// <summary> /// Returns whether this object is contained in or part of a blueprint object /// </summary> public bool IsInBlueprint() => E_UObject_IsInBlueprint(this); /// <summary> /// Returns true if this object is considered a localized resource. /// </summary> public virtual bool IsLocalizedResource() => E_UObject_IsLocalizedResource(this); /// <summary> /// IsNameStableForNetworking means an object can be referred to its path name (relative to outer) over the network /// </summary> public virtual bool IsNameStableForNetworking() => E_UObject_IsNameStableForNetworking(this); /// <summary> /// Called during async load to determine if PostLoad can be called on the loading thread. /// </summary> /// <return>true</return> public virtual bool IsPostLoadThreadSafe() => E_UObject_IsPostLoadThreadSafe(this); /// <summary> /// Called to check if the object is ready for FinishDestroy. This is called after BeginDestroy to check the completion of the /// <para>potentially asynchronous object cleanup. </para> /// </summary> /// <return>True</return> public virtual bool IsReadyForFinishDestroy() => E_UObject_IsReadyForFinishDestroy(this); /// <summary> /// Returns true if this object is safe to add to the root set. /// </summary> public virtual bool IsSafeForRootSet() => E_UObject_IsSafeForRootSet(this); /// <summary> /// Test the selection state of a UObject /// <para>@todo UE4 this doesn't belong here, but it doesn't belong anywhere else any better </para> /// </summary> /// <return>true</return> public bool IsSelected() => E_UObject_IsSelected(this); /// <summary> /// IsSupportedForNetworking means an object can be referenced over the network /// </summary> public virtual bool IsSupportedForNetworking() => E_UObject_IsSupportedForNetworking(this); /// <summary> /// Imports property values from an .ini file. /// </summary> /// <param name="class">the class to use for determining which section of the ini to retrieve text values from</param> /// <param name="filename">indicates the filename to load values from; if not specified, uses ConfigClass's ClassConfigName</param> /// <param name="propagationFlags">indicates how this call to LoadConfig should be propagated; expects a bitmask of UE4::ELoadConfigPropagationFlags values.</param> /// <param name="propertyToLoad">if specified, only the ini value for the specified property will be imported.</param> public void LoadConfig() => E_UObject_LoadConfig(this); /// <summary> /// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds /// </summary> public virtual void MarkAsEditorOnlySubobject() => E_UObject_MarkAsEditorOnlySubobject(this); /// <summary> /// Note that the object will be modified. If we are currently recording into the /// <para>transaction buffer (undo/redo), save a copy of this object into the buffer and </para> /// marks the package as needing to be saved. /// <para>currently recording an active undo/redo transaction </para> /// </summary> /// <param name="bAlwaysMarkDirty">if true, marks the package dirty even if we aren't</param> /// <return>true</return> public virtual bool Modify(bool bAlwaysMarkDirty) => E_UObject_Modify(this, bAlwaysMarkDirty); /// <summary> /// Called during saving to determine the load flags to save with the object. /// <para>If false, this object will be discarded on clients </para> /// </summary> /// <return>true</return> public virtual bool NeedsLoadForClient() => E_UObject_NeedsLoadForClient(this); /// <summary> /// Called during saving to include this object in client/servers running in editor builds, even if they wouldn't normally be. /// <para>If false, this object will still get loaded if NeedsLoadForServer/Client are true </para> /// </summary> /// <return>true</return> public virtual bool NeedsLoadForEditorGame() => E_UObject_NeedsLoadForEditorGame(this); /// <summary> /// Called during saving to determine the load flags to save with the object. /// <para>If false, this object will be discarded on servers </para> /// </summary> /// <return>true</return> public virtual bool NeedsLoadForServer() => E_UObject_NeedsLoadForServer(this); /// <summary> /// Allows PerObjectConfig classes, to override the ini section name used for the PerObjectConfig object. /// </summary> /// <param name="sectionName">Reference to the unmodified config section name, that can be altered/modified</param> public virtual void OverridePerObjectConfigSection(string sectionName) => E_UObject_OverridePerObjectConfigSection(this, sectionName); /// <summary> /// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion /// <para>in the construction of the default materials </para> /// </summary> public virtual void PostCDOContruct() => E_UObject_PostCDOContruct(this); /// <summary> /// Called after importing property values for this object (paste, duplicate or .t3d import) /// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para> /// are unsupported by the script serialization /// </summary> public virtual void PostEditImport() => E_UObject_PostEditImport(this); /// <summary> /// Called after the C++ constructor and after the properties have been initialized, including those loaded from config. /// <para>This is called before any serialization or other setup has happened. </para> /// </summary> public virtual void PostInitProperties() => E_UObject_PostInitProperties(this); /// <summary> /// Do any object-specific cleanup required immediately after loading an object. /// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para> /// </summary> public virtual void PostLoad() => E_UObject_PostLoad(this); /// <summary> /// Called right after receiving a bunch /// </summary> public virtual void PostNetReceive() => E_UObject_PostNetReceive(this); /// <summary> /// Called at the end of Rename(), but only if the rename was actually carried out /// </summary> public virtual void PostRename(UObject oldOuter, string oldName) => E_UObject_PostRename(this, oldOuter, oldName); /// <summary> /// Called right after calling all OnRep notifies (called even when there are no notifies) /// </summary> public virtual void PostRepNotifies() => E_UObject_PostRepNotifies(this); /// <summary> /// Called from within SavePackage on the passed in base/root object. /// <para>This function is called after the package has been saved and can perform cleanup. </para> /// </summary> /// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param> public virtual void PostSaveRoot(bool bCleanupIsRequired) => E_UObject_PostSaveRoot(this, bCleanupIsRequired); /// <summary> /// Called right before being marked for destruction due to network replication /// </summary> public virtual void PreDestroyFromReplication() => E_UObject_PreDestroyFromReplication(this); /// <summary> /// Called right before receiving a bunch /// </summary> public virtual void PreNetReceive() => E_UObject_PreNetReceive(this); /// <summary> /// Wrapper function for InitProperties() which handles safely tearing down this object before re-initializing it /// <para>from the specified source object. </para> /// </summary> /// <param name="sourceObject">the object to use for initializing property values in this object. If not specified, uses this object's archetype.</param> /// <param name="instanceGraph">contains the mappings of instanced objects and components to their templates</param> public void ReinitializeProperties(UObject sourceObject = null) => E_UObject_ReinitializeProperties(this, sourceObject); /// <summary> /// Wrapper method for LoadConfig that is used when reloading the config data for objects at runtime which have already loaded their config data at least once. /// <para>Allows the objects the receive a callback that its configuration data has been reloaded. </para> /// </summary> /// <param name="class">the class to use for determining which section of the ini to retrieve text values from</param> /// <param name="filename">indicates the filename to load values from; if not specified, uses ConfigClass's ClassConfigName</param> /// <param name="propagationFlags">indicates how this call to LoadConfig should be propagated; expects a bitmask of UE4::ELoadConfigPropagationFlags values.</param> /// <param name="propertyToLoad">if specified, only the ini value for the specified property will be imported</param> public void ReloadConfig() => E_UObject_ReloadConfig(this); /// <summary> /// Rename this object to a unique name, or change its outer. /// <para>@warning Unless ForceNoResetLoaders is passed in, this will cause a flush of all level streaming. </para> /// </summary> /// <param name="newName">The new name of the object, if null then NewOuter should be set</param> /// <param name="newOuter">New Outer this object will be placed within, if null it will use the current outer</param> /// <param name="flags">Flags to specify what happens during the rename</param> public virtual bool Rename() => E_UObject_Rename(this); /// <summary> /// Save configuration out to ini files /// <para>@warning Must be safe to call on class-default object </para> /// </summary> public void SaveConfig() => E_UObject_SaveConfig(this); /// <summary> /// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources. /// </summary> public virtual void ShutdownAfterError() => E_UObject_ShutdownAfterError(this); /// <summary> /// Get the common tag name used for all asset source file import paths /// </summary> public string SourceFileTagName() => E_UObject_SourceFileTagName(this); /// <summary> /// Saves just the section(s) for this class into the default ini file for the class (with just the changes from base) /// </summary> public void UpdateDefaultConfigFile(string specificFileLocation) => E_UObject_UpdateDefaultConfigFile(this, specificFileLocation); /// <summary> /// Saves just the section(s) for this class into the global user ini file for the class (with just the changes from base) /// </summary> public void UpdateGlobalUserConfigFile() => E_UObject_UpdateGlobalUserConfigFile(this); #endregion public static implicit operator IntPtr(UObject self) { return self?.NativePointer ?? IntPtr.Zero; } public static implicit operator UObject(ObjectPointerDescription PtrDesc) { return NativeManager.GetWrapper<UObject>(PtrDesc); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System.Collections.Generic { [DebuggerTypeProxy(typeof(IDictionaryDebugView<,>))] [DebuggerDisplay("Count = {Count}")] public class SortedDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue> { private KeyCollection _keys; private ValueCollection _values; private TreeSet<KeyValuePair<TKey, TValue>> _set; public SortedDictionary() : this((IComparer<TKey>)null) { } public SortedDictionary(IDictionary<TKey, TValue> dictionary) : this(dictionary, null) { } public SortedDictionary(IDictionary<TKey, TValue> dictionary, IComparer<TKey> comparer) { if (dictionary == null) { throw new ArgumentNullException(nameof(dictionary)); } _set = new TreeSet<KeyValuePair<TKey, TValue>>(new KeyValuePairComparer(comparer)); foreach (KeyValuePair<TKey, TValue> pair in dictionary) { _set.Add(pair); } } public SortedDictionary(IComparer<TKey> comparer) { _set = new TreeSet<KeyValuePair<TKey, TValue>>(new KeyValuePairComparer(comparer)); } void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair) { _set.Add(keyValuePair); } bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair) { TreeSet<KeyValuePair<TKey, TValue>>.Node node = _set.FindNode(keyValuePair); if (node == null) { return false; } if (keyValuePair.Value == null) { return node.Item.Value == null; } else { return EqualityComparer<TValue>.Default.Equals(node.Item.Value, keyValuePair.Value); } } bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair) { TreeSet<KeyValuePair<TKey, TValue>>.Node node = _set.FindNode(keyValuePair); if (node == null) { return false; } if (EqualityComparer<TValue>.Default.Equals(node.Item.Value, keyValuePair.Value)) { _set.Remove(keyValuePair); return true; } return false; } bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return false; } } public TValue this[TKey key] { get { if (key == null) { throw new ArgumentNullException(nameof(key)); } TreeSet<KeyValuePair<TKey, TValue>>.Node node = _set.FindNode(new KeyValuePair<TKey, TValue>(key, default(TValue))); if (node == null) { throw new KeyNotFoundException(); } return node.Item.Value; } set { if (key == null) { throw new ArgumentNullException(nameof(key)); } TreeSet<KeyValuePair<TKey, TValue>>.Node node = _set.FindNode(new KeyValuePair<TKey, TValue>(key, default(TValue))); if (node == null) { _set.Add(new KeyValuePair<TKey, TValue>(key, value)); } else { node.Item = new KeyValuePair<TKey, TValue>(node.Item.Key, value); _set.UpdateVersion(); } } } public int Count { get { return _set.Count; } } public IComparer<TKey> Comparer { get { return ((KeyValuePairComparer)_set.Comparer).keyComparer; } } public KeyCollection Keys { get { if (_keys == null) _keys = new KeyCollection(this); return _keys; } } ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { return Keys; } } IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys { get { return Keys; } } public ValueCollection Values { get { if (_values == null) _values = new ValueCollection(this); return _values; } } ICollection<TValue> IDictionary<TKey, TValue>.Values { get { return Values; } } IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values { get { return Values; } } public void Add(TKey key, TValue value) { if (key == null) { throw new ArgumentNullException(nameof(key)); } _set.Add(new KeyValuePair<TKey, TValue>(key, value)); } public void Clear() { _set.Clear(); } public bool ContainsKey(TKey key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } return _set.Contains(new KeyValuePair<TKey, TValue>(key, default(TValue))); } public bool ContainsValue(TValue value) { bool found = false; if (value == null) { _set.InOrderTreeWalk(delegate (TreeSet<KeyValuePair<TKey, TValue>>.Node node) { if (node.Item.Value == null) { found = true; return false; // stop the walk } return true; }); } else { EqualityComparer<TValue> valueComparer = EqualityComparer<TValue>.Default; _set.InOrderTreeWalk(delegate (TreeSet<KeyValuePair<TKey, TValue>>.Node node) { if (valueComparer.Equals(node.Item.Value, value)) { found = true; return false; // stop the walk } return true; }); } return found; } public void CopyTo(KeyValuePair<TKey, TValue>[] array, int index) { _set.CopyTo(array, index); } public Enumerator GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } public bool Remove(TKey key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } return _set.Remove(new KeyValuePair<TKey, TValue>(key, default(TValue))); } public bool TryGetValue(TKey key, out TValue value) { if (key == null) { throw new ArgumentNullException(nameof(key)); } TreeSet<KeyValuePair<TKey, TValue>>.Node node = _set.FindNode(new KeyValuePair<TKey, TValue>(key, default(TValue))); if (node == null) { value = default(TValue); return false; } value = node.Item.Value; return true; } void ICollection.CopyTo(Array array, int index) { ((ICollection)_set).CopyTo(array, index); } bool IDictionary.IsFixedSize { get { return false; } } bool IDictionary.IsReadOnly { get { return false; } } ICollection IDictionary.Keys { get { return (ICollection)Keys; } } ICollection IDictionary.Values { get { return (ICollection)Values; } } object IDictionary.this[object key] { get { if (IsCompatibleKey(key)) { TValue value; if (TryGetValue((TKey)key, out value)) { return value; } } return null; } set { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (value == null && !(default(TValue) == null)) throw new ArgumentNullException(nameof(value)); try { TKey tempKey = (TKey)key; try { this[tempKey] = (TValue)value; } catch (InvalidCastException) { throw new ArgumentException(SR.Format(SR.Arg_WrongType, value, typeof(TValue)), nameof(value)); } } catch (InvalidCastException) { throw new ArgumentException(SR.Format(SR.Arg_WrongType, key, typeof(TKey)), nameof(key)); } } } void IDictionary.Add(object key, object value) { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (value == null && !(default(TValue) == null)) throw new ArgumentNullException(nameof(value)); try { TKey tempKey = (TKey)key; try { Add(tempKey, (TValue)value); } catch (InvalidCastException) { throw new ArgumentException(SR.Format(SR.Arg_WrongType, value, typeof(TValue)), nameof(value)); } } catch (InvalidCastException) { throw new ArgumentException(SR.Format(SR.Arg_WrongType, key, typeof(TKey)), nameof(key)); } } bool IDictionary.Contains(object key) { if (IsCompatibleKey(key)) { return ContainsKey((TKey)key); } return false; } private static bool IsCompatibleKey(object key) { if (key == null) { throw new ArgumentNullException(nameof(key)); } return (key is TKey); } IDictionaryEnumerator IDictionary.GetEnumerator() { return new Enumerator(this, Enumerator.DictEntry); } void IDictionary.Remove(object key) { if (IsCompatibleKey(key)) { Remove((TKey)key); } } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return ((ICollection)_set).SyncRoot; } } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(this, Enumerator.KeyValuePair); } [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")] public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDictionaryEnumerator { private TreeSet<KeyValuePair<TKey, TValue>>.Enumerator _treeEnum; private int _getEnumeratorRetType; // What should Enumerator.Current return? internal const int KeyValuePair = 1; internal const int DictEntry = 2; internal Enumerator(SortedDictionary<TKey, TValue> dictionary, int getEnumeratorRetType) { _treeEnum = dictionary._set.GetEnumerator(); _getEnumeratorRetType = getEnumeratorRetType; } public bool MoveNext() { return _treeEnum.MoveNext(); } public void Dispose() { _treeEnum.Dispose(); } public KeyValuePair<TKey, TValue> Current { get { return _treeEnum.Current; } } internal bool NotStartedOrEnded { get { return _treeEnum.NotStartedOrEnded; } } internal void Reset() { _treeEnum.Reset(); } void IEnumerator.Reset() { _treeEnum.Reset(); } object IEnumerator.Current { get { if (NotStartedOrEnded) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } if (_getEnumeratorRetType == DictEntry) { return new DictionaryEntry(Current.Key, Current.Value); } else { return new KeyValuePair<TKey, TValue>(Current.Key, Current.Value); } } } object IDictionaryEnumerator.Key { get { if (NotStartedOrEnded) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return Current.Key; } } object IDictionaryEnumerator.Value { get { if (NotStartedOrEnded) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return Current.Value; } } DictionaryEntry IDictionaryEnumerator.Entry { get { if (NotStartedOrEnded) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return new DictionaryEntry(Current.Key, Current.Value); } } } [DebuggerTypeProxy(typeof(DictionaryKeyCollectionDebugView<,>))] [DebuggerDisplay("Count = {Count}")] public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey> { private SortedDictionary<TKey, TValue> _dictionary; public KeyCollection(SortedDictionary<TKey, TValue> dictionary) { if (dictionary == null) { throw new ArgumentNullException(nameof(dictionary)); } _dictionary = dictionary; } public Enumerator GetEnumerator() { return new Enumerator(_dictionary); } IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator() { return new Enumerator(_dictionary); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(_dictionary); } public void CopyTo(TKey[] array, int index) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < Count) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } _dictionary._set.InOrderTreeWalk(delegate (TreeSet<KeyValuePair<TKey, TValue>>.Node node) { array[index++] = node.Item.Key; return true; }); } void ICollection.CopyTo(Array array, int index) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); } if (array.GetLowerBound(0) != 0) { throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < _dictionary.Count) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } TKey[] keys = array as TKey[]; if (keys != null) { CopyTo(keys, index); } else { try { object[] objects = (object[])array; _dictionary._set.InOrderTreeWalk(delegate (TreeSet<KeyValuePair<TKey, TValue>>.Node node) { objects[index++] = node.Item.Key; return true; }); } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } } } public int Count { get { return _dictionary.Count; } } bool ICollection<TKey>.IsReadOnly { get { return true; } } void ICollection<TKey>.Add(TKey item) { throw new NotSupportedException(SR.NotSupported_KeyCollectionSet); } void ICollection<TKey>.Clear() { throw new NotSupportedException(SR.NotSupported_KeyCollectionSet); } bool ICollection<TKey>.Contains(TKey item) { return _dictionary.ContainsKey(item); } bool ICollection<TKey>.Remove(TKey item) { throw new NotSupportedException(SR.NotSupported_KeyCollectionSet); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return ((ICollection)_dictionary).SyncRoot; } } [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")] public struct Enumerator : IEnumerator<TKey>, IEnumerator { private SortedDictionary<TKey, TValue>.Enumerator _dictEnum; internal Enumerator(SortedDictionary<TKey, TValue> dictionary) { _dictEnum = dictionary.GetEnumerator(); } public void Dispose() { _dictEnum.Dispose(); } public bool MoveNext() { return _dictEnum.MoveNext(); } public TKey Current { get { return _dictEnum.Current.Key; } } object IEnumerator.Current { get { if (_dictEnum.NotStartedOrEnded) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return Current; } } void IEnumerator.Reset() { _dictEnum.Reset(); } } } [DebuggerTypeProxy(typeof(DictionaryValueCollectionDebugView<,>))] [DebuggerDisplay("Count = {Count}")] public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue> { private SortedDictionary<TKey, TValue> _dictionary; public ValueCollection(SortedDictionary<TKey, TValue> dictionary) { if (dictionary == null) { throw new ArgumentNullException(nameof(dictionary)); } _dictionary = dictionary; } public Enumerator GetEnumerator() { return new Enumerator(_dictionary); } IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator() { return new Enumerator(_dictionary); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(_dictionary); } public void CopyTo(TValue[] array, int index) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < Count) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } _dictionary._set.InOrderTreeWalk(delegate (TreeSet<KeyValuePair<TKey, TValue>>.Node node) { array[index++] = node.Item.Value; return true; }); } void ICollection.CopyTo(Array array, int index) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array)); } if (array.GetLowerBound(0) != 0) { throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array)); } if (index < 0) { throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - index < _dictionary.Count) { throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall); } TValue[] values = array as TValue[]; if (values != null) { CopyTo(values, index); } else { try { object[] objects = (object[])array; _dictionary._set.InOrderTreeWalk(delegate (TreeSet<KeyValuePair<TKey, TValue>>.Node node) { objects[index++] = node.Item.Value; return true; }); } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array)); } } } public int Count { get { return _dictionary.Count; } } bool ICollection<TValue>.IsReadOnly { get { return true; } } void ICollection<TValue>.Add(TValue item) { throw new NotSupportedException(SR.NotSupported_ValueCollectionSet); } void ICollection<TValue>.Clear() { throw new NotSupportedException(SR.NotSupported_ValueCollectionSet); } bool ICollection<TValue>.Contains(TValue item) { return _dictionary.ContainsValue(item); } bool ICollection<TValue>.Remove(TValue item) { throw new NotSupportedException(SR.NotSupported_ValueCollectionSet); } bool ICollection.IsSynchronized { get { return false; } } object ICollection.SyncRoot { get { return ((ICollection)_dictionary).SyncRoot; } } [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")] public struct Enumerator : IEnumerator<TValue>, IEnumerator { private SortedDictionary<TKey, TValue>.Enumerator _dictEnum; internal Enumerator(SortedDictionary<TKey, TValue> dictionary) { _dictEnum = dictionary.GetEnumerator(); } public void Dispose() { _dictEnum.Dispose(); } public bool MoveNext() { return _dictEnum.MoveNext(); } public TValue Current { get { return _dictEnum.Current.Value; } } object IEnumerator.Current { get { if (_dictEnum.NotStartedOrEnded) { throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen); } return Current; } } void IEnumerator.Reset() { _dictEnum.Reset(); } } } internal sealed class KeyValuePairComparer : Comparer<KeyValuePair<TKey, TValue>> { internal IComparer<TKey> keyComparer; public KeyValuePairComparer(IComparer<TKey> keyComparer) { if (keyComparer == null) { this.keyComparer = Comparer<TKey>.Default; } else { this.keyComparer = keyComparer; } } public override int Compare(KeyValuePair<TKey, TValue> x, KeyValuePair<TKey, TValue> y) { return keyComparer.Compare(x.Key, y.Key); } } } /// <summary> /// This class is intended as a helper for backwards compatibility with existing SortedDictionaries. /// TreeSet has been converted into SortedSet<T>, which will be exposed publicly. SortedDictionaries /// have the problem where they have already been serialized to disk as having a backing class named /// TreeSet. To ensure that we can read back anything that has already been written to disk, we need to /// make sure that we have a class named TreeSet that does everything the way it used to. /// /// The only thing that makes it different from SortedSet is that it throws on duplicates /// </summary> /// <typeparam name="T"></typeparam> internal sealed class TreeSet<T> : SortedSet<T> { public TreeSet() : base() { } public TreeSet(IComparer<T> comparer) : base(comparer) { } public TreeSet(ICollection<T> collection) : base(collection) { } public TreeSet(ICollection<T> collection, IComparer<T> comparer) : base(collection, comparer) { } internal override bool AddIfNotPresent(T item) { bool ret = base.AddIfNotPresent(item); if (!ret) { throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, item)); } return ret; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; //just drop this script to empty game object on first scene you game start at, this all what you have to do //no coding is required //then you can view logs , warnings , errors and exceptions inside your game //just draw circle on your game to view all logs public class InGameLog : MonoBehaviour { class Log { public int count = 1; public LogType logType ; public string condition ; public string stacktrace ; } //contains all uncollapsed log List<Log> logs = new List<Log>(); //contains all collapsed logs List<Log> collapsedLogs = new List<Log>(); //contain logs which should only appear to user , for example if you switch off show logs + switch off show warnings //and your mode is collapse,then this list will contains only collapsed errors List<Log> currentLog = new List<Log>(); //used to check if the new coming logs is already exist or new one Dictionary<string , Log> logsDic = new Dictionary<string , Log>(); [HideInInspector] //show hide In Game Logs public bool show = false ; //collapse logs bool collapse ; //to deside if you want to clean logs for new loaded scene bool clearOnNewSceneLoaded ; //show or hide logs bool showLog = true ; //show or hide warnings bool showWarning = true ; //show or hide errors bool showError = true ; //total number of logs int numOfLogs=0; //total number of warnings int numOfLogsWarning=0; //total number of errors int numOfLogsError=0; //total number of collapsed logs int numOfCollapsedLogs=0 ; //total number of collapsed warnings int numOfCollapsedLogsWarning =0; //total number of collapsed errors int numOfCollapsedLogsError =0; //maximum number of allowed logs to view public int maxAllowedLog = 1000 ; //fram rate per seconds int fps ; //show fps even if in game logs is hidden bool alwaysShowFps; //used to check if you have In Game Logs multiple time in different scene //only one should work and other should be deleted static bool created = false ; // gui Texture2D logIcon ; Texture2D warningIcon ; Texture2D errorIcon ; GUIContent logContent ; GUIContent warningContent ; GUIContent errorContent ; GUIStyle barStyle ; GUIStyle buttonActiveStyle ; GUIStyle backStyle ; GUIStyle evenLogStyle ; GUIStyle oddLogStyle ; GUIStyle logButtonStyle ; GUIStyle selectedLogStyle ; GUIStyle stackLabelStyle ; GUIStyle scrollerStyle ; GUISkin inGameLogsScrollerSkin ; void Awake() { //initialize gui and styles for gui porpose logIcon = getImage("log_icon" ,32,32); warningIcon = getImage("warning_icon" ,32,32); errorIcon = getImage("error_icon" ,32,32); logContent = new GUIContent("",logIcon,"show or hide logs"); warningContent = new GUIContent("",warningIcon,"show or hide warnings"); errorContent = new GUIContent("",errorIcon,"show or hide errors"); barStyle = new GUIStyle(); barStyle.border = new RectOffset(1,1,1,1); barStyle.normal.background = Resources.Load("bar",typeof(Texture2D)) as Texture2D ; barStyle.active.background = Resources.Load("button_active",typeof(Texture2D)) as Texture2D ; barStyle.alignment = TextAnchor.MiddleCenter ; barStyle.margin = new RectOffset(1,1,1,1); barStyle.padding = new RectOffset(4,4,4,4); barStyle.wordWrap = true ; barStyle.clipping = TextClipping.Clip; buttonActiveStyle = new GUIStyle(); buttonActiveStyle.border = new RectOffset(1,1,1,1); buttonActiveStyle.normal.background = getImage("button_active" ,32,32); buttonActiveStyle.alignment = TextAnchor.MiddleCenter ; buttonActiveStyle.margin = new RectOffset(1,1,1,1); buttonActiveStyle.padding = new RectOffset(4,4,4,4); backStyle = new GUIStyle(); backStyle.normal.background = getImage("even_log" ,16,16); evenLogStyle = new GUIStyle(); evenLogStyle.wordWrap = true; oddLogStyle = new GUIStyle(); oddLogStyle.normal.background = getImage("odd_log" ,16,16); oddLogStyle.wordWrap = true ; logButtonStyle = new GUIStyle(); logButtonStyle.wordWrap = true; selectedLogStyle = new GUIStyle(); selectedLogStyle.normal.background = getImage("selected" ,16,16); selectedLogStyle.normal.textColor = Color.white ; selectedLogStyle.wordWrap = true; stackLabelStyle = new GUIStyle(); stackLabelStyle.wordWrap = true ; scrollerStyle = new GUIStyle(); scrollerStyle.normal.background = getImage("bar" ,32,32); inGameLogsScrollerSkin = Resources.Load("InGameLogsScrollerSkin",typeof(GUISkin)) as GUISkin ; Application.RegisterLogCallback (new Application.LogCallback (CaptureLog)); //if( !created ) //{ // DontDestroyOnLoad( gameObject ); // Application.RegisterLogCallback (new Application.LogCallback (CaptureLog)); // created = true ; //} //else //{ // Debug.LogWarning("tow manager is exists delete the second"); // DestroyImmediate( gameObject ); //} } void OnEnable() { if( logs.Count == 0 )//if recompile while in play mode clear(); } void OnDisable() { } void Start () { //load user config show = (PlayerPrefs.GetInt( "InGameLogs_show" )==1)?true:false; show = false; collapse = (PlayerPrefs.GetInt( "InGameLogs_collapse" )==1)?true:false; clearOnNewSceneLoaded = (PlayerPrefs.GetInt( "InGameLogs_clearOnNewSceneLoaded" )==1)?true:false; showLog = (PlayerPrefs.GetInt( "InGameLogs_showLog" ,1) ==1)?true:false; showWarning = (PlayerPrefs.GetInt( "InGameLogs_showWarning" ,1) ==1)?true:false; showError = (PlayerPrefs.GetInt( "InGameLogs_showError" ,1) ==1)?true:false; alwaysShowFps = (PlayerPrefs.GetInt( "InGameLogs_alwaysShowFps" ) ==1)?true:false; } //clear all logs void clear() { logs.Clear(); collapsedLogs.Clear(); currentLog.Clear(); logsDic.Clear(); selectedIndex = -1; numOfLogs = 0; numOfLogsWarning = 0; numOfLogsError = 0; numOfCollapsedLogs = 0; numOfCollapsedLogsWarning = 0; numOfCollapsedLogsError = 0; } Rect logsRect ; Rect stackRect ; Vector2 scrollPosition; Vector2 scrollPosition2; int selectedIndex = -1; Log selectedLog ; float oldDrag ; float oldDrag2 ; int startIndex; //try to make texture GUI type Texture2D getImage(string path , int width , int height ) { Texture2D texture = ( Texture2D )Resources.Load( path , typeof(Texture2D )); return texture ; /*Texture2D guiTexture = new Texture2D( width, height, TextureFormat.ATC_RGBA8, false); byte[] data = texture.EncodeToPNG(); guiTexture.LoadImage( data ); return guiTexture;*/ } //calculate what is the currentLog : collapsed or not , hide or view warnings ...... void calculateCurrentLog() { currentLog.Clear(); if( collapse ) { for( int i = 0 ; i < collapsedLogs.Count ; i++ ) { Log log = collapsedLogs[i]; if( log.logType == LogType.Log && !showLog ) continue; if( log.logType == LogType.Warning && !showWarning ) continue; if( log.logType == LogType.Error && !showError ) continue; if( log.logType == LogType.Exception && !showError ) continue; currentLog.Add( log ); } } else { for( int i = 0 ; i < logs.Count ; i++ ) { Log log = logs[i]; if( log.logType == LogType.Log && !showLog ) continue; if( log.logType == LogType.Warning && !showWarning ) continue; if( log.logType == LogType.Error && !showError ) continue; if( log.logType == LogType.Exception && !showError ) continue; currentLog.Add( log ); } } } void OnGUI() { if( !show ) { if( alwaysShowFps ) { GUILayout.Label( "fps = " + fps ); } return ; } logsRect.x = 0f ; logsRect.y = 0f ; logsRect.width = Screen.width ; logsRect.height = Screen.height * 0.75f ; stackRect.x = 0f ; stackRect.y = Screen.height * 0.75f ; stackRect.width = Screen.width ; stackRect.height = Screen.height * 0.25f ; GUI.skin = inGameLogsScrollerSkin ; GUILayout.Space(10f); GUILayout.BeginArea( logsRect , backStyle ); GUILayout.BeginHorizontal( barStyle ); if( GUILayout.Button( "Clear" , barStyle , GUILayout.Height(50))) { clear(); } if( GUILayout.Button( "Collapse" , (collapse)?buttonActiveStyle:barStyle, GUILayout.Height(50))) { collapse = !collapse ; calculateCurrentLog(); } if( GUILayout.Button( "Clear On New\nScene Loaded" , (clearOnNewSceneLoaded)?buttonActiveStyle:barStyle, GUILayout.Height(50))) { clearOnNewSceneLoaded = !clearOnNewSceneLoaded ; } if( GUILayout.Button( "Always\nShow Fps" , (alwaysShowFps)?buttonActiveStyle:barStyle,GUILayout.Height(50))) { alwaysShowFps = !alwaysShowFps ; } GUILayout.FlexibleSpace(); GUILayout.Label( fps.ToString() ,barStyle ); string logsText = " " ; if( collapse ){ if( numOfCollapsedLogs>=maxAllowedLog ) logsText+= "+"; logsText+= numOfCollapsedLogs ; } else { if( numOfLogs>=maxAllowedLog ) logsText+= "+"; logsText+= numOfLogs ; } string logsWarningText = " " ; if( collapse ){ if( numOfCollapsedLogsWarning>=maxAllowedLog ) logsWarningText+= "+"; logsWarningText+= numOfCollapsedLogsWarning ; } else { if( numOfLogsWarning>=maxAllowedLog ) logsWarningText+= "+"; logsWarningText+= numOfLogsWarning ; } string logsErrorText = " " ; if( collapse ){ if( numOfCollapsedLogsError>=maxAllowedLog ) logsErrorText+= "+"; logsErrorText+= numOfCollapsedLogsError ; } else { if( numOfLogsError>=maxAllowedLog ) logsErrorText+= "+"; logsErrorText+= numOfLogsError ; } logContent.text = logsText ; if( GUILayout.Button( logContent ,(showLog)?buttonActiveStyle:barStyle, GUILayout.Height(50))) { showLog = !showLog ; calculateCurrentLog(); } warningContent.text = logsWarningText ; if( GUILayout.Button( warningContent,(showWarning)?buttonActiveStyle:barStyle, GUILayout.Height(50))) { showWarning = !showWarning ; calculateCurrentLog(); } errorContent.text = logsErrorText ; if( GUILayout.Button( errorContent ,(showError)?buttonActiveStyle:barStyle, GUILayout.Height(50))) { showError = !showError ; calculateCurrentLog(); } if( GUILayout.Button( " Hide " ,barStyle, GUILayout.Height(50))) { show = false; } GUILayout.EndHorizontal(); setStartPos(); float drag = getDrag(); if( drag != 0 && logsRect.Contains( new Vector2(startPos.x , Screen.height- startPos.y) ) ) { scrollPosition.y += (drag - oldDrag) ; } scrollPosition = GUILayout.BeginScrollView( scrollPosition ); oldDrag = drag ; int totalVisibleCount = (int)(Screen.height * 0.75f / 30) ; int totalCount = getTotalCount() ; /*if( totalCount < 100 ) inGameLogsScrollerSkin.verticalScrollbarThumb.fixedHeight = 0; else inGameLogsScrollerSkin.verticalScrollbarThumb.fixedHeight = 64;*/ totalVisibleCount = Mathf.Min( totalVisibleCount , totalCount - startIndex ); int index = 0 ; int beforeHeight = startIndex*30 ; selectedIndex = Mathf.Clamp( selectedIndex , -1 , totalCount -1); if( beforeHeight > 0 ) { //fill invisible gap befor scroller to make proper scroller pos GUILayout.BeginHorizontal( GUILayout.Height( beforeHeight ) ); GUILayout.Label(" "); GUILayout.EndHorizontal(); } int endIndex = startIndex + totalVisibleCount ; endIndex = Mathf.Clamp( endIndex , 0 ,totalCount ); for( int i = startIndex ; (startIndex + index) < endIndex ; i++ ) { if( i >= currentLog.Count ) break; Log log = currentLog[i]; if( log.logType == LogType.Log && !showLog ) continue; if( log.logType == LogType.Warning && !showWarning ) continue; if( log.logType == LogType.Error && !showError ) continue; if( log.logType == LogType.Exception && !showError ) continue; if( index >= totalVisibleCount ) { break; } GUIContent content = null; if( log.logType == LogType.Log ) content = logContent ; else if( log.logType == LogType.Warning ) content = warningContent ; else content = errorContent ; content.text = log.condition ; if( selectedIndex == (startIndex + index) ) { selectedLog = log ; GUILayout.BeginHorizontal( selectedLogStyle ); GUILayout.Label( content ,selectedLogStyle ); //GUILayout.FlexibleSpace(); if( collapse ) GUILayout.Label( log.count.ToString() ,barStyle ,GUILayout.Width(50)); //else // GUILayout.Label( (startIndex + index).ToString() , barStyle ,GUILayout.Width(50)); GUILayout.EndHorizontal(); } else { GUILayout.BeginHorizontal( ((startIndex +index)%2 == 0 )? evenLogStyle : oddLogStyle , GUILayout.Height(30 ) ); if( GUILayout.Button( content ,logButtonStyle ) ) { selectedIndex = startIndex + index ; } //GUILayout.FlexibleSpace(); if( collapse ) GUILayout.Label( log.count.ToString() , barStyle ,GUILayout.Width(50)); //else // GUILayout.Label( (startIndex+index).ToString() , barStyle ,GUILayout.Width(50)); GUILayout.EndHorizontal(); } index++; } int afterHeight = (totalCount - ( startIndex + totalVisibleCount ))*30 ; if( afterHeight > 0 ) { //fill invisible gap after scroller to make proper scroller pos GUILayout.BeginHorizontal( GUILayout.Height(afterHeight ) ); GUILayout.Label(" "); GUILayout.EndHorizontal(); } GUILayout.EndScrollView(); GUILayout.EndArea(); GUILayout.BeginArea( stackRect , backStyle ); if( selectedIndex != -1 ) { float drag2 = getDrag(); if( drag2 != 0 && stackRect.Contains( new Vector2(startPos.x , Screen.height- startPos.y) ) ) { scrollPosition2.y += drag2 - oldDrag2 ; } oldDrag2 = drag2 ; scrollPosition2 = GUILayout.BeginScrollView( scrollPosition2 ); GUILayout.BeginHorizontal( ); if( selectedLog != null ) { string stacktrace = ( string.IsNullOrEmpty(selectedLog.stacktrace))?"stacktrace is empty":selectedLog.stacktrace; GUILayout.Label( stacktrace , stackLabelStyle ); } GUILayout.EndHorizontal(); GUILayout.EndScrollView(); } GUILayout.EndArea(); } List<Vector2> gestureDetector = new List<Vector2>(); Vector2 gestureSum = Vector2.zero ; float gestureLength = 0; bool isGestureDone() { if( Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer ) { if( Input.touches.Length != 1 ) { gestureDetector.Clear(); } else { if( Input.touches[0].phase == TouchPhase.Canceled || Input.touches[0].phase == TouchPhase.Ended ) gestureDetector.Clear(); else if( Input.touches[0].phase == TouchPhase.Moved ) { Vector2 p = Input.touches[0].position; if( gestureDetector.Count == 0 || (p - gestureDetector[ gestureDetector.Count-1]).magnitude > 10 ) gestureDetector.Add( p ) ; } } } else { if( Input.GetMouseButtonUp(0) ) { gestureDetector.Clear(); } else { if( Input.GetMouseButton(0)) { Vector2 p = new Vector2( Input.mousePosition.x , Input.mousePosition.y ); if( gestureDetector.Count == 0 || (p - gestureDetector[ gestureDetector.Count-1]).magnitude > 10 ) gestureDetector.Add( p ); } } } if( gestureDetector.Count < 10 ) return false; gestureSum = Vector2.zero ; gestureLength = 0 ; Vector2 prevDelta = Vector2.zero ; for( int i = 0 ; i < gestureDetector.Count - 2 ; i++ ) { Vector2 delta = gestureDetector[i+1] - gestureDetector[i] ; float deltaLength = delta.magnitude ; gestureSum += delta ; gestureLength += deltaLength ; float dot = Vector2.Dot( delta , prevDelta ) ; if( dot < 0f ) { gestureDetector.Clear(); return false; } prevDelta = delta ; } int gestureBase = (Screen.width + Screen.height ) / 4 ; if( gestureLength > gestureBase && gestureSum.magnitude < gestureBase/2 ) { gestureDetector.Clear(); return true ; } return false ; } int getTotalCount() { int count = 0 ; if( collapse ) { if( showLog ) count += numOfCollapsedLogs ; if( showWarning ) count += numOfCollapsedLogsWarning ; if( showError ) count += numOfCollapsedLogsError ; } else { if( showLog ) count += numOfLogs ; if( showWarning ) count += numOfLogsWarning ; if( showError ) count += numOfLogsError ; } return count ; } //calculate pos of first click on screen Vector2 startPos ; void setStartPos() { if( Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer ) { if( Input.touches.Length == 1 && Input.touches[0].phase == TouchPhase.Began ) { startPos = Input.touches[0].position ; } } else { if( Input.GetMouseButtonDown(0) ) { startPos = new Vector2( Input.mousePosition.x , Input.mousePosition.y ); } } } //calculate drag amount , this is used for scrolling float getDrag() { if( Application.platform == RuntimePlatform.Android || Application.platform == RuntimePlatform.IPhonePlayer ) { if( Input.touches.Length != 1 ) { return 0 ; } return Input.touches[0].position.y - startPos.y ; } else { if( Input.GetMouseButton(0) ) { return Input.mousePosition.y - startPos.y ; } else { return 0; } } } //calculate the start index of visible log void calculateStartIndex() { startIndex = (int)(scrollPosition.y /30) ; startIndex = Mathf.Clamp( startIndex , 0 , getTotalCount() ); } float elapsed ; int _fps = 0; void Update() { elapsed += Time.deltaTime ; _fps ++ ; if( elapsed >= 1f ) { fps = _fps ; _fps = 0; elapsed =0f; } calculateStartIndex(); if( isGestureDone() ) { show = !show; } elapsed += Time.deltaTime ; if( elapsed > 1) { elapsed = 0; //be sure no body else take control of log Application.RegisterLogCallback (new Application.LogCallback (CaptureLog)); } } void CaptureLog (string condition, string stacktrace, LogType type) { bool newLogAdded = false ; Log log = null; bool skip = false ; if( logsDic.ContainsKey( condition ) ) { logsDic[ condition ].count ++; log = logsDic[ condition ] ; } else { if(type == LogType.Log ) { if( numOfCollapsedLogs >= maxAllowedLog) skip = true ; } else if( type == LogType.Warning ) { if( numOfCollapsedLogsWarning >= maxAllowedLog) skip = true ; } else if( numOfCollapsedLogsError >= maxAllowedLog ) skip = true ; if( !skip ) { if( type == LogType.Log ) numOfCollapsedLogs++; else if( type == LogType.Warning ) numOfCollapsedLogsWarning++; else numOfCollapsedLogsError++; log = new Log(){ logType = type , condition = condition , stacktrace = stacktrace }; collapsedLogs.Add( log ); logsDic.Add( condition , log ); if( collapse ) { skip = false ; if( log.logType == LogType.Log && !showLog ) skip = true; if( log.logType == LogType.Warning && !showWarning ) skip = true; if( log.logType == LogType.Error && !showError ) skip = true; if( log.logType == LogType.Exception && !showError ) skip = true; if( !skip) { currentLog.Add( log ); newLogAdded=true; } } } } skip = false; if(type == LogType.Log ) { if( numOfLogs >= maxAllowedLog) skip = true ; } else if( type == LogType.Warning ) { if( numOfLogsWarning >= maxAllowedLog) skip = true ; } else if( numOfLogsError >= maxAllowedLog ) skip = true ; if( !skip ) { if( type == LogType.Log ) numOfLogs++; else if( type == LogType.Warning ) numOfLogsWarning++; else numOfLogsError++; logs.Add( log ); if( !collapse ) { skip = false ; if( log.logType == LogType.Log && !showLog ) skip = true; if( log.logType == LogType.Warning && !showWarning ) skip = true; if( log.logType == LogType.Error && !showError ) skip = true; if( log.logType == LogType.Exception && !showError ) skip = true; if( !skip) { currentLog.Add( log ); newLogAdded=true; } } } if( newLogAdded ) { calculateStartIndex(); int totalCount = getTotalCount(); int totalVisibleCount = (int)(Screen.height * 0.75f / 30) ; if( startIndex >= ( totalCount - totalVisibleCount )) scrollPosition.y += 30 ; } } //new scene is loaded void OnLevelWasLoaded() { if( clearOnNewSceneLoaded ) clear(); } //save user config void OnApplicationQuit() { PlayerPrefs.SetInt( "InGameLogs_show" ,(show==true)?1:0); PlayerPrefs.SetInt( "InGameLogs_collapse" ,(collapse==true)?1:0); PlayerPrefs.SetInt( "InGameLogs_clearOnNewSceneLoaded" ,(clearOnNewSceneLoaded==true)?1:0); PlayerPrefs.SetInt( "InGameLogs_showLog" ,(showLog==true)?1:0) ; PlayerPrefs.SetInt( "InGameLogs_showWarning" ,(showWarning==true)?1:0) ; PlayerPrefs.SetInt( "InGameLogs_showError" ,(showError==true)?1:0) ; PlayerPrefs.SetInt( "InGameLogs_alwaysShowFps" ,(alwaysShowFps==true)?1:0) ; PlayerPrefs.Save(); } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Diagnostics.Log; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Options; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Versions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV1 { using ProviderId = Int32; internal partial class DiagnosticIncrementalAnalyzer : BaseDiagnosticIncrementalAnalyzer { private static readonly int s_stateTypeCount = Enum.GetNames(typeof(StateType)).Count(); private static readonly ImmutableArray<StateType> s_documentScopeStateTypes = ImmutableArray.Create<StateType>(StateType.Syntax, StateType.Document); private readonly int _correlationId; private readonly DiagnosticAnalyzerService _owner; private readonly MemberRangeMap _memberRangeMap; private readonly DiagnosticAnalyzersAndStates _analyzersAndState; private readonly AnalyzerExecutor _executor; private DiagnosticLogAggregator _diagnosticLogAggregator; public DiagnosticIncrementalAnalyzer(DiagnosticAnalyzerService owner, int correlationId, Workspace workspace, AnalyzerManager analyzerManager) { _owner = owner; _correlationId = correlationId; _memberRangeMap = new MemberRangeMap(); _analyzersAndState = new DiagnosticAnalyzersAndStates(this, workspace, analyzerManager); _executor = new AnalyzerExecutor(this); _diagnosticLogAggregator = new DiagnosticLogAggregator(_owner); } public override Task DocumentOpenAsync(Document document, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Diagnostics_DocumentOpen, GetOpenLogMessage, document, cancellationToken)) { // we remove whatever information we used to have on document open/close and re-calcuate diagnostics // we had to do this since some diagnostic provider change its behavior based on whether the document is opend or not. // so we can't use cached information. return RemoveAllCacheDataAsync(document, cancellationToken); } } public override Task DocumentResetAsync(Document document, CancellationToken cancellationToken) { using (Logger.LogBlock(FunctionId.Diagnostics_DocumentReset, GetResetLogMessage, document, cancellationToken)) { // we don't need the info for closed file _memberRangeMap.Remove(document.Id); // we remove whatever information we used to have on document open/close and re-calcuate diagnostics // we had to do this since some diagnostic provider change its behavior based on whether the document is opend or not. // so we can't use cached information. return RemoveAllCacheDataAsync(document, cancellationToken); } } private bool CheckOption(Workspace workspace, string language, bool documentOpened) { var optionService = workspace.Services.GetService<IOptionService>(); if (optionService == null || optionService.GetOption(ServiceFeatureOnOffOptions.ClosedFileDiagnostic, language)) { return true; } if (documentOpened) { return true; } return false; } public override async Task AnalyzeSyntaxAsync(Document document, CancellationToken cancellationToken) { await AnalyzeSyntaxAsync(document, diagnosticIds: null, skipClosedFileChecks: false, cancellationToken: cancellationToken).ConfigureAwait(false); } private async Task AnalyzeSyntaxAsync(Document document, ImmutableHashSet<string> diagnosticIds, bool skipClosedFileChecks, CancellationToken cancellationToken) { try { if (!skipClosedFileChecks && !CheckOption(document.Project.Solution.Workspace, document.Project.Language, document.IsOpen())) { return; } var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false); var dataVersion = await document.GetSyntaxVersionAsync(cancellationToken).ConfigureAwait(false); var versions = new VersionArgument(textVersion, dataVersion); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var fullSpan = root == null ? null : (TextSpan?)root.FullSpan; var userDiagnosticDriver = new DiagnosticAnalyzerDriver(document, fullSpan, root, _diagnosticLogAggregator, cancellationToken); var options = document.Project.CompilationOptions; var openedDocument = document.IsOpen(); foreach (var providerAndId in await _analyzersAndState.GetAllProviderAndIdsAsync(document.Project, cancellationToken).ConfigureAwait(false)) { var provider = providerAndId.Key; var providerId = providerAndId.Value; if (IsAnalyzerSuppressed(provider, options, userDiagnosticDriver)) { await HandleSuppressedAnalyzerAsync(document, StateType.Syntax, providerId, provider, cancellationToken).ConfigureAwait(false); } else if (ShouldRunProviderForStateType(StateType.Syntax, provider, userDiagnosticDriver, diagnosticIds) && (skipClosedFileChecks || ShouldRunProviderForClosedFile(openedDocument, provider))) { var data = await _executor.GetSyntaxAnalysisDataAsync(provider, providerId, versions, userDiagnosticDriver).ConfigureAwait(false); if (data.FromCache) { RaiseDiagnosticsUpdated(StateType.Syntax, document.Id, providerId, new SolutionArgument(document), data.Items); continue; } var state = _analyzersAndState.GetOrCreateDiagnosticState(StateType.Syntax, providerId, provider, document.Project.Id, document.Project.Language); await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false); RaiseDiagnosticsUpdatedIfNeeded(StateType.Syntax, document, providerId, data.OldItems, data.Items); } } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } public override async Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, CancellationToken cancellationToken) { await AnalyzeDocumentAsync(document, bodyOpt, diagnosticIds: null, skipClosedFileChecks: false, cancellationToken: cancellationToken).ConfigureAwait(false); } private async Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, ImmutableHashSet<string> diagnosticIds, bool skipClosedFileChecks, CancellationToken cancellationToken) { try { if (!skipClosedFileChecks && !CheckOption(document.Project.Solution.Workspace, document.Project.Language, document.IsOpen())) { return; } var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false); var projectVersion = await document.Project.GetDependentVersionAsync(cancellationToken).ConfigureAwait(false); var dataVersion = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false); var versions = new VersionArgument(textVersion, dataVersion, projectVersion); if (bodyOpt == null) { await AnalyzeDocumentAsync(document, versions, diagnosticIds, skipClosedFileChecks, cancellationToken).ConfigureAwait(false); } else { // only open file can go this route await AnalyzeBodyDocumentAsync(document, bodyOpt, versions, cancellationToken).ConfigureAwait(false); } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private async Task AnalyzeBodyDocumentAsync(Document document, SyntaxNode member, VersionArgument versions, CancellationToken cancellationToken) { try { // syntax facts service must exist, otherwise, this method won't have called. var syntaxFacts = document.Project.LanguageServices.GetService<ISyntaxFactsService>(); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var memberId = syntaxFacts.GetMethodLevelMemberId(root, member); var spanBasedDriver = new DiagnosticAnalyzerDriver(document, member.FullSpan, root, _diagnosticLogAggregator, cancellationToken); var documentBasedDriver = new DiagnosticAnalyzerDriver(document, root.FullSpan, root, _diagnosticLogAggregator, cancellationToken); var options = document.Project.CompilationOptions; foreach (var providerAndId in await _analyzersAndState.GetAllProviderAndIdsAsync(document.Project, cancellationToken).ConfigureAwait(false)) { var provider = providerAndId.Key; var providerId = providerAndId.Value; bool supportsSemanticInSpan; if (IsAnalyzerSuppressed(provider, options, spanBasedDriver)) { await HandleSuppressedAnalyzerAsync(document, StateType.Document, providerId, provider, cancellationToken).ConfigureAwait(false); } else if (ShouldRunProviderForStateType(StateType.Document, provider, spanBasedDriver, out supportsSemanticInSpan)) { var userDiagnosticDriver = supportsSemanticInSpan ? spanBasedDriver : documentBasedDriver; var ranges = _memberRangeMap.GetSavedMemberRange(providerId, document); var data = await _executor.GetDocumentBodyAnalysisDataAsync( provider, providerId, versions, userDiagnosticDriver, root, member, memberId, supportsSemanticInSpan, ranges).ConfigureAwait(false); _memberRangeMap.UpdateMemberRange(providerId, document, versions.TextVersion, memberId, member.FullSpan, ranges); var state = _analyzersAndState.GetOrCreateDiagnosticState(StateType.Document, providerId, provider, document.Project.Id, document.Project.Language); await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false); if (data.FromCache) { RaiseDiagnosticsUpdated(StateType.Document, document.Id, providerId, new SolutionArgument(document), data.Items); continue; } RaiseDiagnosticsUpdatedIfNeeded(StateType.Document, document, providerId, data.OldItems, data.Items); } } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private async Task AnalyzeDocumentAsync(Document document, VersionArgument versions, ImmutableHashSet<string> diagnosticIds, bool skipClosedFileChecks, CancellationToken cancellationToken) { try { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var fullSpan = root == null ? null : (TextSpan?)root.FullSpan; var userDiagnosticDriver = new DiagnosticAnalyzerDriver(document, fullSpan, root, _diagnosticLogAggregator, cancellationToken); bool openedDocument = document.IsOpen(); var options = document.Project.CompilationOptions; foreach (var providerAndId in await _analyzersAndState.GetAllProviderAndIdsAsync(document.Project, cancellationToken).ConfigureAwait(false)) { var provider = providerAndId.Key; var providerId = providerAndId.Value; if (IsAnalyzerSuppressed(provider, options, userDiagnosticDriver)) { await HandleSuppressedAnalyzerAsync(document, StateType.Document, providerId, provider, cancellationToken).ConfigureAwait(false); } else if (ShouldRunProviderForStateType(StateType.Document, provider, userDiagnosticDriver, diagnosticIds) && (skipClosedFileChecks || ShouldRunProviderForClosedFile(openedDocument, provider))) { var data = await _executor.GetDocumentAnalysisDataAsync(provider, providerId, versions, userDiagnosticDriver).ConfigureAwait(false); if (data.FromCache) { RaiseDiagnosticsUpdated(StateType.Document, document.Id, providerId, new SolutionArgument(document), data.Items); continue; } if (openedDocument) { _memberRangeMap.Touch(providerId, document, versions.TextVersion); } var state = _analyzersAndState.GetOrCreateDiagnosticState(StateType.Document, providerId, provider, document.Project.Id, document.Project.Language); await state.PersistAsync(document, data.ToPersistData(), cancellationToken).ConfigureAwait(false); RaiseDiagnosticsUpdatedIfNeeded(StateType.Document, document, providerId, data.OldItems, data.Items); } } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } public override async Task AnalyzeProjectAsync(Project project, bool semanticsChanged, CancellationToken cancellationToken) { await AnalyzeProjectAsync(project, diagnosticIds: null, skipClosedFileChecks: false, cancellationToken: cancellationToken).ConfigureAwait(false); } private async Task AnalyzeProjectAsync(Project project, ImmutableHashSet<string> diagnosticIds, bool skipClosedFileChecks, CancellationToken cancellationToken) { try { if (!skipClosedFileChecks && !CheckOption(project.Solution.Workspace, project.Language, documentOpened: project.Documents.Any(d => d.IsOpen()))) { return; } var projectVersion = await project.GetDependentVersionAsync(cancellationToken).ConfigureAwait(false); var semanticVersion = await project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false); var userDiagnosticDriver = new DiagnosticAnalyzerDriver(project, _diagnosticLogAggregator, cancellationToken); var options = project.CompilationOptions; var versions = new VersionArgument(VersionStamp.Default, semanticVersion, projectVersion); foreach (var providerAndId in await _analyzersAndState.GetAllProviderAndIdsAsync(project, cancellationToken).ConfigureAwait(false)) { var provider = providerAndId.Key; var providerId = providerAndId.Value; if (IsAnalyzerSuppressed(provider, options, userDiagnosticDriver)) { await HandleSuppressedAnalyzerAsync(project, providerId, provider, cancellationToken).ConfigureAwait(false); } else if (ShouldRunProviderForStateType(StateType.Project, provider, userDiagnosticDriver, diagnosticIds) && (skipClosedFileChecks || ShouldRunProviderForClosedFile(openedDocument: false, provider: provider))) { var data = await _executor.GetProjectAnalysisDataAsync(provider, providerId, versions, userDiagnosticDriver).ConfigureAwait(false); if (data.FromCache) { RaiseDiagnosticsUpdated(StateType.Project, project.Id, providerId, new SolutionArgument(project), data.Items); continue; } var state = _analyzersAndState.GetOrCreateDiagnosticState(StateType.Project, providerId, provider, project.Id, project.Language); await state.PersistAsync(project, data.ToPersistData(), cancellationToken).ConfigureAwait(false); RaiseDiagnosticsUpdatedIfNeeded(project, providerId, data.OldItems, data.Items); } } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } public override void RemoveDocument(DocumentId documentId) { using (Logger.LogBlock(FunctionId.Diagnostics_RemoveDocument, GetRemoveLogMessage, documentId, CancellationToken.None)) { _memberRangeMap.Remove(documentId); foreach (var stateProviderIdAndType in _analyzersAndState.GetAllExistingDiagnosticStates(documentId.ProjectId)) { var state = stateProviderIdAndType.Item1; var providerId = stateProviderIdAndType.Item2; var type = stateProviderIdAndType.Item3; if (state != null) { state.Remove(documentId); } var solutionArgs = new SolutionArgument(null, documentId.ProjectId, documentId); RaiseDiagnosticsUpdated(type, documentId, providerId, solutionArgs, ImmutableArray<DiagnosticData>.Empty); } } } public override void RemoveProject(ProjectId projectId) { using (Logger.LogBlock(FunctionId.Diagnostics_RemoveProject, GetRemoveLogMessage, projectId, CancellationToken.None)) { foreach (var stateProviderIdAndType in _analyzersAndState.GetAllExistingDiagnosticStates(projectId, StateType.Project)) { var state = stateProviderIdAndType.Item1; var providerId = stateProviderIdAndType.Item2; if (state != null) { state.Remove(projectId); } var solutionArgs = new SolutionArgument(null, projectId, null); RaiseDiagnosticsUpdated(StateType.Project, projectId, providerId, solutionArgs, ImmutableArray<DiagnosticData>.Empty); } _analyzersAndState.RemoveProjectAnalyzersAndStates(projectId); } } public override async Task<bool> TryAppendDiagnosticsForSpanAsync(Document document, TextSpan range, List<DiagnosticData> diagnostics, CancellationToken cancellationToken) { try { var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false); var syntaxVersion = await document.GetSyntaxVersionAsync(cancellationToken).ConfigureAwait(false); var semanticVersion = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var result = true; result &= await TryGetLatestDiagnosticsAsync( StateType.Syntax, document, range, root, diagnostics, false, (t, d) => t.Equals(textVersion) && d.Equals(syntaxVersion), GetSyntaxDiagnosticsAsync, cancellationToken).ConfigureAwait(false); result &= await TryGetLatestDiagnosticsAsync( StateType.Document, document, range, root, diagnostics, false, (t, d) => t.Equals(textVersion) && d.Equals(semanticVersion), GetSemanticDiagnosticsAsync, cancellationToken).ConfigureAwait(false); return result; } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } public override async Task<IEnumerable<DiagnosticData>> GetDiagnosticsForSpanAsync(Document document, TextSpan range, CancellationToken cancellationToken) { try { var textVersion = await document.GetTextVersionAsync(cancellationToken).ConfigureAwait(false); var syntaxVersion = await document.GetSyntaxVersionAsync(cancellationToken).ConfigureAwait(false); var semanticVersion = await document.Project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false); var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var result = true; using (var diagnostics = SharedPools.Default<List<DiagnosticData>>().GetPooledObject()) { result &= await TryGetLatestDiagnosticsAsync( StateType.Syntax, document, range, root, diagnostics.Object, true, (t, d) => t.Equals(textVersion) && d.Equals(syntaxVersion), GetSyntaxDiagnosticsAsync, cancellationToken).ConfigureAwait(false); result &= await TryGetLatestDiagnosticsAsync( StateType.Document, document, range, root, diagnostics.Object, true, (t, d) => t.Equals(textVersion) && d.Equals(semanticVersion), GetSemanticDiagnosticsAsync, cancellationToken).ConfigureAwait(false); // must be always up-to-date Debug.Assert(result); if (diagnostics.Object.Count > 0) { return diagnostics.Object.ToImmutableArray(); } return SpecializedCollections.EmptyEnumerable<DiagnosticData>(); } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private async Task<bool> TryGetLatestDiagnosticsAsync( StateType stateType, Document document, TextSpan range, SyntaxNode root, List<DiagnosticData> diagnostics, bool requireUpToDateDocumentDiagnostic, Func<VersionStamp, VersionStamp, bool> versionCheck, Func<ProviderId, DiagnosticAnalyzer, DiagnosticAnalyzerDriver, Task<IEnumerable<DiagnosticData>>> getDiagnostics, CancellationToken cancellationToken) { try { bool result = true; var fullSpan = root == null ? null : (TextSpan?)root.FullSpan; // Share the diagnostic analyzer driver across all analyzers. var spanBasedDriver = new DiagnosticAnalyzerDriver(document, range, root, _diagnosticLogAggregator, cancellationToken); var documentBasedDriver = new DiagnosticAnalyzerDriver(document, fullSpan, root, _diagnosticLogAggregator, cancellationToken); var options = document.Project.CompilationOptions; foreach (var providerAndId in await _analyzersAndState.GetAllProviderAndIdsAsync(document.Project, cancellationToken).ConfigureAwait(false)) { var provider = providerAndId.Key; var providerId = providerAndId.Value; bool supportsSemanticInSpan; if (!IsAnalyzerSuppressed(provider, options, spanBasedDriver) && ShouldRunProviderForStateType(stateType, provider, spanBasedDriver, out supportsSemanticInSpan)) { var userDiagnosticDriver = supportsSemanticInSpan ? spanBasedDriver : documentBasedDriver; result &= await TryGetLatestDiagnosticsAsync( provider, providerId, stateType, document, range, root, diagnostics, requireUpToDateDocumentDiagnostic, versionCheck, getDiagnostics, supportsSemanticInSpan, userDiagnosticDriver, cancellationToken).ConfigureAwait(false); } } return result; } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private async Task<bool> TryGetLatestDiagnosticsAsync( DiagnosticAnalyzer provider, ProviderId providerId, StateType stateType, Document document, TextSpan range, SyntaxNode root, List<DiagnosticData> diagnostics, bool requireUpToDateDocumentDiagnostic, Func<VersionStamp, VersionStamp, bool> versionCheck, Func<ProviderId, DiagnosticAnalyzer, DiagnosticAnalyzerDriver, Task<IEnumerable<DiagnosticData>>> getDiagnostics, bool supportsSemanticInSpan, DiagnosticAnalyzerDriver userDiagnosticDriver, CancellationToken cancellationToken) { try { var shouldInclude = (Func<DiagnosticData, bool>)(d => range.IntersectsWith(d.TextSpan)); // make sure we get state even when none of our analyzer has ran yet. // but this shouldn't create analyzer that doesnt belong to this project (language) var state = _analyzersAndState.GetOrCreateDiagnosticState(stateType, providerId, provider, document.Project.Id, document.Project.Language); if (state == null) { if (!requireUpToDateDocumentDiagnostic) { // the provider never ran yet. return true; } } else { // see whether we can use existing info var existingData = await state.TryGetExistingDataAsync(document, cancellationToken).ConfigureAwait(false); if (existingData != null && versionCheck(existingData.TextVersion, existingData.DataVersion)) { if (existingData.Items == null) { return true; } diagnostics.AddRange(existingData.Items.Where(shouldInclude)); return true; } } // check whether we want up-to-date document wide diagnostics if (stateType == StateType.Document && !supportsSemanticInSpan && !requireUpToDateDocumentDiagnostic) { return false; } var dx = await getDiagnostics(providerId, provider, userDiagnosticDriver).ConfigureAwait(false); if (dx != null) { // no state yet diagnostics.AddRange(dx.Where(shouldInclude)); } return true; } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private bool ShouldRunProviderForClosedFile(bool openedDocument, DiagnosticAnalyzer provider) { // we have opened document, doesnt matter if (openedDocument) { return true; } return _owner.GetDiagnosticDescriptors(provider).Any(d => d.DefaultSeverity != DiagnosticSeverity.Hidden); } private bool ShouldRunProviderForStateType(StateType stateTypeId, DiagnosticAnalyzer provider, DiagnosticAnalyzerDriver driver, ImmutableHashSet<string> diagnosticIds) { return ShouldRunProviderForStateType(stateTypeId, provider, driver, diagnosticIds, _owner.GetDiagnosticDescriptors); } private static bool ShouldRunProviderForStateType(StateType stateTypeId, DiagnosticAnalyzer provider, DiagnosticAnalyzerDriver driver, ImmutableHashSet<string> diagnosticIds, Func<DiagnosticAnalyzer, ImmutableArray<DiagnosticDescriptor>> getDescriptor) { bool discarded; return ShouldRunProviderForStateType(stateTypeId, provider, driver, out discarded, diagnosticIds, getDescriptor); } private static bool ShouldRunProviderForStateType(StateType stateTypeId, DiagnosticAnalyzer provider, DiagnosticAnalyzerDriver driver, out bool supportsSemanticInSpan, ImmutableHashSet<string> diagnosticIds = null, Func<DiagnosticAnalyzer, ImmutableArray<DiagnosticDescriptor>> getDescriptor = null) { Debug.Assert(!IsAnalyzerSuppressed(provider, driver.Project.CompilationOptions, driver)); supportsSemanticInSpan = false; if (diagnosticIds != null && getDescriptor(provider).All(d => !diagnosticIds.Contains(d.Id))) { return false; } switch (stateTypeId) { case StateType.Syntax: return provider.SupportsSyntaxDiagnosticAnalysis(driver); case StateType.Document: return provider.SupportsSemanticDiagnosticAnalysis(driver, out supportsSemanticInSpan); case StateType.Project: return provider.SupportsProjectDiagnosticAnalysis(driver); default: throw ExceptionUtilities.Unreachable; } } private static bool IsAnalyzerSuppressed(DiagnosticAnalyzer provider, CompilationOptions options, DiagnosticAnalyzerDriver driver) { if (options != null && CompilationWithAnalyzers.IsDiagnosticAnalyzerSuppressed(provider, options, driver.CatchAnalyzerExceptionHandler)) { // All diagnostics that are generated by this DiagnosticAnalyzer will be suppressed, so we need not run the analyzer. return true; } return false; } // internal for testing purposes only. internal void ForceAnalyzeAllDocuments(Project project, DiagnosticAnalyzer analyzer, CancellationToken cancellationToken) { var diagnosticIds = _owner.GetDiagnosticDescriptors(analyzer).Select(d => d.Id).ToImmutableHashSet(); ReanalyzeAllDocumentsAsync(project, diagnosticIds, cancellationToken).Wait(cancellationToken); } public override void LogAnalyzerCountSummary() { DiagnosticAnalyzerLogger.LogAnalyzerCrashCountSummary(_correlationId, _diagnosticLogAggregator); DiagnosticAnalyzerLogger.LogAnalyzerTypeCountSummary(_correlationId, _diagnosticLogAggregator); // reset the log aggregator _diagnosticLogAggregator = new DiagnosticLogAggregator(_owner); } private static bool CheckSyntaxVersions(Document document, AnalysisData existingData, VersionArgument versions) { if (existingData == null) { return false; } return document.CanReusePersistedTextVersion(versions.TextVersion, existingData.TextVersion) && document.CanReusePersistedSyntaxTreeVersion(versions.DataVersion, existingData.DataVersion); } private static bool CheckSemanticVersions(Document document, AnalysisData existingData, VersionArgument versions) { if (existingData == null) { return false; } return document.CanReusePersistedTextVersion(versions.TextVersion, existingData.TextVersion) && document.Project.CanReusePersistedDependentSemanticVersion(versions.ProjectVersion, versions.DataVersion, existingData.DataVersion); } private static bool CheckSemanticVersions(Project project, AnalysisData existingData, VersionArgument versions) { if (existingData == null) { return false; } return project.CanReusePersistedDependentSemanticVersion(versions.ProjectVersion, versions.DataVersion, existingData.DataVersion); } private void RaiseDiagnosticsUpdatedIfNeeded( StateType type, Document document, ProviderId providerId, ImmutableArray<DiagnosticData> existingItems, ImmutableArray<DiagnosticData> newItems) { var noItems = existingItems.Length == 0 && newItems.Length == 0; if (!noItems) { RaiseDiagnosticsUpdated(type, document.Id, providerId, new SolutionArgument(document), newItems); } } private void RaiseDiagnosticsUpdatedIfNeeded(Project project, ProviderId providerId, ImmutableArray<DiagnosticData> existingItems, ImmutableArray<DiagnosticData> newItems) { var noItems = existingItems.Length == 0 && newItems.Length == 0; if (!noItems) { RaiseDiagnosticsUpdated(StateType.Project, project.Id, providerId, new SolutionArgument(project), newItems); } } private void RaiseDiagnosticsUpdated( StateType type, object key, ProviderId providerId, SolutionArgument solution, ImmutableArray<DiagnosticData> diagnostics) { if (_owner != null) { var id = new ArgumentKey(providerId, type, key); _owner.RaiseDiagnosticsUpdated(this, new DiagnosticsUpdatedArgs(id, _analyzersAndState.Workspace, solution.Solution, solution.ProjectId, solution.DocumentId, diagnostics)); } } private ImmutableArray<DiagnosticData> UpdateDocumentDiagnostics( AnalysisData existingData, ImmutableArray<TextSpan> range, ImmutableArray<DiagnosticData> memberDiagnostics, SyntaxTree tree, SyntaxNode member, int memberId) { // get old span var oldSpan = range[memberId]; // get old diagnostics var diagnostics = existingData.Items; // check quick exit cases if (diagnostics.Length == 0 && memberDiagnostics.Length == 0) { return diagnostics; } // simple case if (diagnostics.Length == 0 && memberDiagnostics.Length > 0) { return memberDiagnostics; } // regular case var result = new List<DiagnosticData>(); // update member location Contract.Requires(member.FullSpan.Start == oldSpan.Start); var delta = member.FullSpan.End - oldSpan.End; var replaced = false; foreach (var diagnostic in diagnostics) { if (diagnostic.TextSpan.Start < oldSpan.Start) { result.Add(diagnostic); continue; } if (!replaced) { result.AddRange(memberDiagnostics); replaced = true; } if (oldSpan.End <= diagnostic.TextSpan.Start) { result.Add(UpdatePosition(diagnostic, tree, delta)); continue; } } // if it haven't replaced, replace it now if (!replaced) { result.AddRange(memberDiagnostics); replaced = true; } return result.ToImmutableArray(); } private DiagnosticData UpdatePosition(DiagnosticData diagnostic, SyntaxTree tree, int delta) { var start = Math.Min(Math.Max(diagnostic.TextSpan.Start + delta, 0), tree.Length); var newSpan = new TextSpan(start, start >= tree.Length ? 0 : diagnostic.TextSpan.Length); var mappedLineInfo = tree.GetMappedLineSpan(newSpan); var originalLineInfo = tree.GetLineSpan(newSpan); return new DiagnosticData( diagnostic.Id, diagnostic.Category, diagnostic.Message, diagnostic.MessageFormat, diagnostic.Severity, diagnostic.DefaultSeverity, diagnostic.IsEnabledByDefault, diagnostic.WarningLevel, diagnostic.CustomTags, diagnostic.Workspace, diagnostic.ProjectId, diagnostic.DocumentId, newSpan, mappedFilePath: mappedLineInfo.HasMappedPath ? mappedLineInfo.Path : null, mappedStartLine: mappedLineInfo.StartLinePosition.Line, mappedStartColumn: mappedLineInfo.StartLinePosition.Character, mappedEndLine: mappedLineInfo.EndLinePosition.Line, mappedEndColumn: mappedLineInfo.EndLinePosition.Character, originalFilePath: originalLineInfo.Path, originalStartLine: originalLineInfo.StartLinePosition.Line, originalStartColumn: originalLineInfo.StartLinePosition.Character, originalEndLine: originalLineInfo.EndLinePosition.Line, originalEndColumn: originalLineInfo.EndLinePosition.Character, description: diagnostic.Description, helpLink: diagnostic.HelpLink); } private static IEnumerable<DiagnosticData> GetDiagnosticData(Document document, TextSpan? span, IEnumerable<Diagnostic> diagnostics) { return diagnostics != null ? diagnostics.Where(dx => ShouldIncludeDiagnostic(dx, span)).Select(d => DiagnosticData.Create(document, d)) : null; } private static bool ShouldIncludeDiagnostic(Diagnostic diagnostic, TextSpan? span) { if (diagnostic == null) { return false; } if (span == null) { return true; } if (diagnostic.Location == null) { return false; } return span.Value.Contains(diagnostic.Location.SourceSpan); } private static IEnumerable<DiagnosticData> GetDiagnosticData(Project project, IEnumerable<Diagnostic> diagnostics) { return diagnostics != null ? diagnostics.Select(d => DiagnosticData.Create(project, d)) : null; } private static async Task<IEnumerable<DiagnosticData>> GetSyntaxDiagnosticsAsync(ProviderId providerId, DiagnosticAnalyzer provider, DiagnosticAnalyzerDriver userDiagnosticDriver) { using (Logger.LogBlock(FunctionId.Diagnostics_SyntaxDiagnostic, GetSyntaxLogMessage, userDiagnosticDriver.Document, userDiagnosticDriver.Span, providerId, userDiagnosticDriver.CancellationToken)) { try { Contract.ThrowIfNull(provider); var diagnostics = await userDiagnosticDriver.GetSyntaxDiagnosticsAsync(provider).ConfigureAwait(false); return GetDiagnosticData(userDiagnosticDriver.Document, userDiagnosticDriver.Span, diagnostics); } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } } private static async Task<IEnumerable<DiagnosticData>> GetSemanticDiagnosticsAsync(ProviderId providerId, DiagnosticAnalyzer provider, DiagnosticAnalyzerDriver userDiagnosticDriver) { using (Logger.LogBlock(FunctionId.Diagnostics_SemanticDiagnostic, GetSemanticLogMessage, userDiagnosticDriver.Document, userDiagnosticDriver.Span, providerId, userDiagnosticDriver.CancellationToken)) { try { Contract.ThrowIfNull(provider); var diagnostics = await userDiagnosticDriver.GetSemanticDiagnosticsAsync(provider).ConfigureAwait(false); return GetDiagnosticData(userDiagnosticDriver.Document, userDiagnosticDriver.Span, diagnostics); } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } } private static async Task<IEnumerable<DiagnosticData>> GetProjectDiagnosticsAsync(ProviderId providerId, DiagnosticAnalyzer provider, DiagnosticAnalyzerDriver userDiagnosticDriver, Action<Project, DiagnosticAnalyzer, CancellationToken> forceAnalyzeAllDocuments) { using (Logger.LogBlock(FunctionId.Diagnostics_ProjectDiagnostic, GetProjectLogMessage, userDiagnosticDriver.Project, providerId, userDiagnosticDriver.CancellationToken)) { try { Contract.ThrowIfNull(provider); var diagnostics = await userDiagnosticDriver.GetProjectDiagnosticsAsync(provider, forceAnalyzeAllDocuments).ConfigureAwait(false); return GetDiagnosticData(userDiagnosticDriver.Project, diagnostics); } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } } private async Task RemoveAllCacheDataAsync(Document document, CancellationToken cancellationToken) { var allExistingStates = _analyzersAndState.GetAllExistingDiagnosticStates(document.Project.Id, document.Project.Language); await RemoveCacheDataAsync(document, allExistingStates, cancellationToken).ConfigureAwait(false); } private async Task RemoveCacheDataAsync(Document document, IEnumerable<Tuple<DiagnosticState, ProviderId, StateType>> states, CancellationToken cancellationToken) { try { // Compiler + User diagnostics foreach (var stateProviderIdAndType in states) { var state = stateProviderIdAndType.Item1; if (state == null) { continue; } var providerId = stateProviderIdAndType.Item2; var type = stateProviderIdAndType.Item3; await RemoveCacheDataAsync(document, state, providerId, type, cancellationToken).ConfigureAwait(false); } } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private async Task RemoveCacheDataAsync(Document document, DiagnosticState state, ProviderId providerId, StateType type, CancellationToken cancellationToken) { try { // remove memory cache state.Remove(document.Id); // remove persistent cache await state.PersistAsync(document, AnalysisData.Empty, cancellationToken).ConfigureAwait(false); // raise diagnostic updated event var documentId = type == StateType.Project ? null : document.Id; var projectId = document.Project.Id; var key = documentId ?? (object)projectId; var solutionArgs = new SolutionArgument(document.Project.Solution, projectId, documentId); RaiseDiagnosticsUpdated(type, key, providerId, solutionArgs, ImmutableArray<DiagnosticData>.Empty); } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private async Task RemoveCacheDataAsync(Project project, DiagnosticState state, ProviderId providerId, CancellationToken cancellationToken) { try { // remove memory cache state.Remove(project.Id); // remove persistent cache await state.PersistAsync(project, AnalysisData.Empty, cancellationToken).ConfigureAwait(false); // raise diagnostic updated event var solutionArgs = new SolutionArgument(project); RaiseDiagnosticsUpdated(StateType.Project, project.Id, providerId, solutionArgs, ImmutableArray<DiagnosticData>.Empty); } catch (Exception e) when (FatalError.ReportUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } } private async Task RemoveCacheDataAsync(Project project, IEnumerable<Tuple<DiagnosticState, ProviderId, StateType>> states, CancellationToken cancellationToken) { foreach (var document in project.Documents) { await RemoveCacheDataAsync(document, states, cancellationToken).ConfigureAwait(false); } } private async Task HandleSuppressedAnalyzerAsync(Document document, StateType type, ProviderId providerId, DiagnosticAnalyzer provider, CancellationToken cancellationToken) { var state = _analyzersAndState.GetOrCreateDiagnosticState(type, providerId, provider, document.Project.Id, document.Project.Language); var existingData = await state.TryGetExistingDataAsync(document, cancellationToken).ConfigureAwait(false); if (existingData != null && existingData.Items.Length > 0) { await RemoveCacheDataAsync(document, state, providerId, type, cancellationToken).ConfigureAwait(false); } } private async Task HandleSuppressedAnalyzerAsync(Project project, ProviderId providerId, DiagnosticAnalyzer provider, CancellationToken cancellationToken) { var state = _analyzersAndState.GetOrCreateDiagnosticState(StateType.Project, providerId, provider, project.Id, project.Language); var existingData = await state.TryGetExistingDataAsync(project, cancellationToken).ConfigureAwait(false); if (existingData != null && existingData.Items.Length > 0) { await RemoveCacheDataAsync(project, state, providerId, cancellationToken).ConfigureAwait(false); } } private static string GetSyntaxLogMessage(Document document, TextSpan? span, int providerId) { return string.Format("syntax: {0}, {1}, {2}", document.FilePath ?? document.Name, span.HasValue ? span.Value.ToString() : "Full", providerId.ToString()); } private static string GetSemanticLogMessage(Document document, TextSpan? span, int providerId) { return string.Format("semantic: {0}, {1}, {2}", document.FilePath ?? document.Name, span.HasValue ? span.Value.ToString() : "Full", providerId.ToString()); } private static string GetProjectLogMessage(Project project, int providerId) { return string.Format("project: {0}, {1}", project.FilePath ?? project.Name, providerId.ToString()); } private static string GetResetLogMessage(Document document) { return string.Format("document reset: {0}", document.FilePath ?? document.Name); } private static string GetOpenLogMessage(Document document) { return string.Format("document open: {0}", document.FilePath ?? document.Name); } private static string GetRemoveLogMessage(DocumentId id) { return string.Format("document remove: {0}", id.ToString()); } private static string GetRemoveLogMessage(ProjectId id) { return string.Format("project remove: {0}", id.ToString()); } #region unused public override Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } #endregion } }
using System; using System.CodeDom; using IronAHK.Rusty; namespace IronAHK.Scripting { partial class Emit { bool stmt; void EmitExpressionStatement(CodeExpression expr) { stmt = true; EmitExpression(expr); stmt = false; } void EmitExpression(CodeExpression expr) { if (expr is CodeMethodInvokeExpression) EmitInvoke((CodeMethodInvokeExpression)expr); else if (expr is CodeArrayCreateExpression) EmitArray((CodeArrayCreateExpression)expr); else if (expr is CodePrimitiveExpression) EmitPrimitive((CodePrimitiveExpression)expr); else if (expr is CodeBinaryOperatorExpression) EmitBinary((CodeBinaryOperatorExpression)expr); else if (expr is CodeTernaryOperatorExpression) EmitTernary((CodeTernaryOperatorExpression)expr); else if (expr is CodeVariableReferenceExpression) EmitVariableReference((CodeVariableReferenceExpression)expr); else if (expr is CodeArgumentReferenceExpression) EmitArgumentReference((CodeArgumentReferenceExpression)expr); else if (expr is CodeFieldReferenceExpression) EmitFieldReference((CodeFieldReferenceExpression)expr); else if (expr is CodeTypeReferenceExpression) EmitTypeReference((CodeTypeReferenceExpression)expr); else if (expr is CodeArrayIndexerExpression) EmitArrayIndexer((CodeArrayIndexerExpression)expr); else if (expr is CodePropertyReferenceExpression) EmitPropertyReference((CodePropertyReferenceExpression)expr); else throw new ArgumentException("Unrecognised expression: " + expr.GetType()); } #region Methods void EmitInvoke(CodeMethodInvokeExpression invoke) { if (invoke.Method.TargetObject is CodeTypeReferenceExpression && Type.GetType(((CodeTypeReferenceExpression)invoke.Method.TargetObject).Type.BaseType) == typeof(Script)) { string name = invoke.Method.MethodName; if (name == Parser.InternalMethods.LabelCall.MethodName && invoke.Parameters.Count == 1) { EmitGoto(new CodeGotoStatement((string)((CodePrimitiveExpression)invoke.Parameters[0]).Value)); return; } else if (name == Parser.InternalMethods.IfElse.MethodName && invoke.Parameters.Count == 1) { EmitExpression(invoke.Parameters[0]); return; } else if (name == Parser.InternalMethods.IfLegacy.MethodName && invoke.Parameters.Count == 3 && invoke.Parameters[1] is CodePrimitiveExpression && (((CodePrimitiveExpression)invoke.Parameters[1]).Value as string) == Parser.IsTxt) { EmitExpression(invoke.Parameters[0]); writer.Write(Parser.SingleSpace); writer.Write(Parser.IsTxt); writer.Write(Parser.SingleSpace); EmitExpression(invoke.Parameters[2]); return; } else if (name == Parser.InternalMethods.Operate.MethodName && invoke.Parameters.Count == 3) { EmitExpression(invoke.Parameters[1]); writer.Write(Parser.SingleSpace); var op = (Script.Operator)Enum.Parse(typeof(Script.Operator), ((CodeFieldReferenceExpression)invoke.Parameters[0]).FieldName); writer.Write(ScriptOperator(op)); writer.Write(Parser.SingleSpace); EmitExpression(invoke.Parameters[2]); return; } else if (name == Parser.InternalMethods.ExtendArray.MethodName && invoke.Parameters.Count == 1) return; else if (name == Parser.InternalMethods.SetObject.MethodName && invoke.Parameters.Count == 4) { EmitExpression(invoke.Parameters[1]); EmitExpression(invoke.Parameters[2]); EmitExpression(invoke.Parameters[0]); writer.Write(Parser.SingleSpace); writer.Write(Parser.AssignPre); writer.Write(Parser.Equal); writer.Write(Parser.SingleSpace); EmitExpression(invoke.Parameters[3]); return; } else if (name == Parser.InternalMethods.Index.MethodName && invoke.Parameters.Count == 2) { EmitExpression(invoke.Parameters[0]); writer.Write(Parser.ArrayOpen); EmitExpression(invoke.Parameters[1]); writer.Write(Parser.ArrayClose); return; } else if (name == Parser.InternalMethods.Dictionary.MethodName && invoke.Parameters.Count == 2) { writer.Write(Parser.BlockOpen); writer.Write(Parser.SingleSpace); var parts = new CodeExpressionCollection[2]; for (int i = 0; i < parts.Length; i++) parts[i] = ((CodeArrayCreateExpression)invoke.Parameters[i]).Initializers; bool first = true; for (int i = 0; i < parts[0].Count; i++) { if (first) first = false; else { writer.Write(Parser.DefaultMulticast); writer.Write(Parser.SingleSpace); } depth++; EmitExpression(parts[0][i]); writer.Write(Parser.SingleSpace); writer.Write(Parser.AssignPre); writer.Write(Parser.SingleSpace); EmitExpression(parts[1][i]); depth--; } writer.Write(Parser.SingleSpace); writer.Write(Parser.BlockClose); return; } } if (invoke.Method.TargetObject != null && !(invoke.Method.TargetObject is CodeTypeReferenceExpression && IsInternalType((CodeTypeReferenceExpression)invoke.Method.TargetObject))) { depth++; EmitExpression(invoke.Method.TargetObject); writer.Write(Parser.Concatenate); depth--; } writer.Write(invoke.Method.MethodName); writer.Write(Parser.ParenOpen); for (int i = 0; i < invoke.Parameters.Count; i++) { depth++; if (i > 0) { writer.Write(Parser.DefaultMulticast); writer.Write(Parser.SingleSpace); } EmitExpression(invoke.Parameters[i]); depth--; } writer.Write(Parser.ParenClose); } void EmitReturn(CodeMethodReturnStatement returns) { writer.Write(Parser.FlowReturn); if (returns.Expression != null) { writer.Write(Parser.SingleSpace); depth++; EmitExpression(returns.Expression); depth--; } } #endregion #region Variables void EmitArrayIndexer(CodeArrayIndexerExpression array) { if (array.TargetObject is CodePropertyReferenceExpression && ((CodePropertyReferenceExpression)array.TargetObject).PropertyName == Parser.VarProperty && array.Indices.Count == 1 && array.Indices[0] is CodePrimitiveExpression) { var name = ((CodePrimitiveExpression)array.Indices[0]).Value as string; if (name != null) { var sep = name.IndexOf(Parser.ScopeVar); if (sep != -1) name = name.Substring(sep + 1); writer.Write(name); return; } } EmitExpression(array.TargetObject); foreach (CodeExpression index in array.Indices) { writer.Write(Parser.ArrayOpen); EmitExpression(index); writer.Write(Parser.ArrayClose); } } void EmitVariableDeclaration(CodeVariableDeclarationStatement var) { writer.Write(var.Name); writer.Write(Parser.SingleSpace); writer.Write(Parser.AssignPre); writer.Write(Parser.Equal); writer.Write(Parser.SingleSpace); if (var.InitExpression == null) writer.Write(Parser.NullTxt); else { depth++; EmitExpression(var.InitExpression); depth--; } } void EmitVariableReference(CodeVariableReferenceExpression var) { writer.Write(var.VariableName); } void EmitArgumentReference(CodeArgumentReferenceExpression arg) { writer.Write(arg.ParameterName); } void EmitAssignment(CodeAssignStatement assign) { EmitExpression(assign.Left); writer.Write(Parser.SingleSpace); writer.Write(Parser.AssignPre); writer.Write(Parser.Equal); writer.Write(Parser.SingleSpace); EmitExpression(assign.Right); } void EmitArray(CodeArrayCreateExpression array) { writer.Write(Parser.ArrayOpen); bool first = true; depth++; foreach (CodeExpression expr in array.Initializers) { if (first) first = false; else { writer.Write(Parser.DefaultMulticast); writer.Write(Parser.SingleSpace); } EmitExpression(expr); } depth--; writer.Write(Parser.ArrayClose); } void EmitFieldReference(CodeFieldReferenceExpression field) { if (field.TargetObject != null) { depth++; EmitExpression(field.TargetObject); depth--; } writer.Write(field.FieldName); } #region Complex void EmitComplexReference(CodePrimitiveExpression var) { if (var.Value is string) writer.Write((string)var.Value); else throw new ArgumentOutOfRangeException(); } void EmitComplexReference(CodeArrayCreateExpression var) { foreach (CodeExpression part in var.Initializers) { if (part is CodePrimitiveExpression) EmitComplexReference((CodePrimitiveExpression)part); else if (part is CodeMethodInvokeExpression) EmitComplexReference((CodeMethodInvokeExpression)part); else throw new ArgumentOutOfRangeException(); } } void EmitComplexReference(CodeMethodInvokeExpression var) { if (var.Method.MethodName == Parser.InternalMethods.Concat.MethodName && var.Parameters.Count == 1) EmitComplexReference((CodeArrayCreateExpression)var.Parameters[0]); else throw new ArgumentOutOfRangeException(); } #endregion #endregion #region Operators void EmitBinary(CodeBinaryOperatorExpression binary) { bool stmt = this.stmt; if (stmt) this.stmt = false; else writer.Write(Parser.ParenOpen); depth++; EmitExpression(binary.Left); depth--; writer.Write(Parser.SingleSpace); writer.Write(Operator(binary.Operator)); writer.Write(Parser.SingleSpace); depth++; EmitExpression(binary.Right); depth--; if (!stmt) writer.Write(Parser.ParenClose); } void EmitTernary(CodeTernaryOperatorExpression ternary) { depth++; EmitExpression(ternary.Condition); depth--; writer.Write(Parser.SingleSpace); writer.Write(Parser.TernaryA); writer.Write(Parser.SingleSpace); depth++; EmitExpression(ternary.TrueBranch); depth--; writer.Write(Parser.SingleSpace); writer.Write(Parser.TernaryB); writer.Write(Parser.SingleSpace); depth++; EmitExpression(ternary.FalseBranch); depth--; } #endregion #region Misc void EmitPropertyReference(CodePropertyReferenceExpression property) { EmitExpression(property.TargetObject); writer.Write(property.PropertyName); } void EmitPrimitive(CodePrimitiveExpression primitive) { if (primitive.Value == null) writer.Write(Parser.NullTxt); else if (primitive.Value is string) { writer.Write(Parser.StringBound); writer.Write((string)primitive.Value); writer.Write(Parser.StringBound); } else if (primitive.Value is decimal) writer.Write(((decimal)primitive.Value).ToString()); else if (primitive.Value is double) writer.Write(((double)primitive.Value).ToString()); else if (primitive.Value is float) writer.Write(((float)primitive.Value).ToString()); else if (primitive.Value is int) writer.Write(((int)primitive.Value).ToString()); else if (primitive.Value is bool) writer.Write(((bool)primitive.Value) ? Parser.TrueTxt : Parser.FalseTxt); else throw new ArgumentException("Unrecognised primitive: " + primitive.Value); } void EmitTypeReference(CodeTypeReferenceExpression type) { if (IsInternalType(type)) return; writer.Write(type.Type.BaseType); } bool IsInternalType(CodeTypeReferenceExpression type) { string name = type.Type.BaseType; return name == typeof(Core).FullName || name == typeof(Script).FullName; } #endregion } }
/* * SubSonic - http://subsonicproject.com * * The contents of this file are subject to the Mozilla Public * License Version 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. */ using System; using MbUnit.Framework; using NorthwindAccess; namespace SubSonic.Tests.MsAccess.SqlQuery { [TestFixture] public class AggregateTests { [Test] public void Acc_Exec_AggregateExpression() { double result = new Select(Aggregate.Sum("UnitPrice*Quantity", "ProductSales")) .From(OrderDetail.Schema) .ExecuteScalar<double>(); result = Math.Round(result, 2); Assert.IsTrue(result == 1354458.59); } [Test] public void Acc_Exec_AggregateAvg() { const double expected = 28.8664; // overload #1 double result = new Select(Aggregate.Avg("UnitPrice")) .From(Product.Schema) .ExecuteScalar<double>(); Assert.AreEqual(expected, result); // overload #2 result = new Select(Aggregate.Avg(Product.UnitPriceColumn)) .From(Product.Schema) .ExecuteScalar<double>(); Assert.AreEqual(expected, result); // overload #3 result = new Select(Aggregate.Avg("UnitPrice", "AverageUnitPrice")) .From(Product.Schema) .ExecuteScalar<double>(); Assert.AreEqual(expected, result); // overload #4 result = new Select(Aggregate.Avg(Product.UnitPriceColumn, "AverageUnitPrice")) .From(Product.Schema) .ExecuteScalar<double>(); Assert.AreEqual(expected, result); } [Test] public void Acc_Exec_AggregateMax() { const double expected = 263.5; // overload #1 double result = new Select(Aggregate.Max("UnitPrice")) .From(Product.Schema) .ExecuteScalar<double>(); Assert.AreEqual(expected, result); // overload #2 result = new Select(Aggregate.Max(Product.UnitPriceColumn)) .From(Product.Schema) .ExecuteScalar<double>(); Assert.AreEqual(expected, result); // overload #3 result = new Select(Aggregate.Max("UnitPrice", "MostExpensive")) .From(Product.Schema) .ExecuteScalar<double>(); Assert.AreEqual(expected, result); // overload #4 result = new Select(Aggregate.Max(Product.UnitPriceColumn, "MostExpensive")) .From(Product.Schema) .ExecuteScalar<double>(); Assert.AreEqual(expected, result); } [Test] public void Acc_Exec_AggregateMin() { const double expected = 2.50; // overload #1 double result = new Select(Aggregate.Min("UnitPrice")) .From(Product.Schema) .ExecuteScalar<double>(); Assert.AreEqual(expected, result); // overload #2 result = new Select(Aggregate.Min(Product.UnitPriceColumn)) .From(Product.Schema) .ExecuteScalar<double>(); Assert.AreEqual(expected, result); // overload #3 result = new Select(Aggregate.Min("UnitPrice", "CheapestProduct")) .From(Product.Schema) .ExecuteScalar<double>(); Assert.AreEqual(expected, result); // overload #4 result = new Select(Aggregate.Min(Product.UnitPriceColumn, "CheapestProduct")) .From(Product.Schema) .ExecuteScalar<double>(); Assert.AreEqual(expected, result); } [Test] public void Acc_Exec_AggregateStandardDeviation() { const double expected = 33.8151114580251; // overload #1 double result = new Select(Aggregate.StandardDeviation("UnitPrice")) .From(Product.Schema) .ExecuteScalar<double>(); Assert.AreApproximatelyEqual<double, double>(expected, result, 0.00000000001d); // overload #2 result = new Select(Aggregate.StandardDeviation(Product.UnitPriceColumn)) .From(Product.Schema) .ExecuteScalar<double>(); Assert.AreApproximatelyEqual<double, double>(expected, result, 0.00000000001d); // overload #3 result = new Select(Aggregate.StandardDeviation("UnitPrice", "CheapestProduct")) .From(Product.Schema) .ExecuteScalar<double>(); Assert.AreApproximatelyEqual<double, double>(expected, result, 0.00000000001d); // overload #4 result = new Select(Aggregate.StandardDeviation(Product.UnitPriceColumn, "CheapestProduct")) .From(Product.Schema) .ExecuteScalar<double>(); Assert.AreApproximatelyEqual<double, double>(expected, result, 0.00000000001d); } [Test] public void Acc_Exec_SingleAggregateWithWhere() { int records = new Select(Aggregate.GroupBy("ProductID"), Aggregate.Avg("UnitPrice")) .From("Order Details") .Where(Aggregate.Avg("UnitPrice")) .IsGreaterThan(50) .GetRecordCount(); Assert.AreEqual(7, records); } [Test] public void Acc_Exec_AggregateWithWhereAndHaving() { int records = new Select(Aggregate.GroupBy("ProductID"), Aggregate.Avg("UnitPrice")) .From("Order Details") .Where("Quantity").IsEqualTo(120) .Where(Aggregate.Avg("UnitPrice")) .IsGreaterThan(10) .GetRecordCount(); Assert.AreEqual(5, records); } [Test] public void Acc_Exec_AggregateWithWhereNotHaving() { int records = new Select(Aggregate.GroupBy("ProductID"), Aggregate.Avg("UnitPrice")) .From("Order Details") .Where("Quantity").IsEqualTo(120) .GetRecordCount(); Assert.AreEqual(7, records); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics.Contracts; using System.Net; using System.Net.Sockets; using System.Runtime; using System.Text; using System.Threading.Tasks; namespace System.ServiceModel.Channels { internal class SocketConnection : IConnection { private static EventHandler<SocketAsyncEventArgs> s_onReceiveAsyncCompleted; private static EventHandler<SocketAsyncEventArgs> s_onSocketSendCompleted; // common state private Socket _socket; private bool _noDelay = false; private TimeSpan _sendTimeout; private TimeSpan _receiveTimeout; private CloseState _closeState; private bool _aborted; // close state private static Action<object> s_onWaitForFinComplete = new Action<object>(OnWaitForFinComplete); private TimeoutHelper _closeTimeoutHelper; private bool _isShutdown; // read state private SocketAsyncEventArgs _asyncReadEventArgs; private TimeSpan _readFinTimeout; private int _asyncReadSize; private byte[] _readBuffer; private int _asyncReadBufferSize; private object _asyncReadState; private Action<object> _asyncReadCallback; private Exception _asyncReadException; private bool _asyncReadPending; // write state private SocketAsyncEventArgs _asyncWriteEventArgs; private object _asyncWriteState; private Action<object> _asyncWriteCallback; private Exception _asyncWriteException; private bool _asyncWritePending; private static Action<SocketConnection> s_onSendTimeout; private static Action<SocketConnection> s_onReceiveTimeout; private IOTimer<SocketConnection> _receiveTimer; private IOTimer<SocketConnection> _sendTimer; private string _timeoutErrorString; private TransferOperation _timeoutErrorTransferOperation; private ConnectionBufferPool _connectionBufferPool; private string _remoteEndpointAddressString; public SocketConnection(Socket socket, ConnectionBufferPool connectionBufferPool) { _connectionBufferPool = connectionBufferPool ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(connectionBufferPool)); _socket = socket ?? throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(socket)); _closeState = CloseState.Open; _readBuffer = _connectionBufferPool.Take(); _asyncReadBufferSize = _readBuffer.Length; _sendTimeout = _receiveTimeout = TimeSpan.MaxValue; _closeState = CloseState.Open; _socket.SendBufferSize = _socket.ReceiveBufferSize = _asyncReadBufferSize; _sendTimeout = _receiveTimeout = TimeSpan.MaxValue; } public int AsyncReadBufferSize { get { return _asyncReadBufferSize; } } public byte[] AsyncReadBuffer { get { return _readBuffer; } } private object ThisLock { get { return this; } } private IOTimer<SocketConnection> SendTimer { get { if (_sendTimer == null) { if (s_onSendTimeout == null) { s_onSendTimeout = OnSendTimeout; } _sendTimer = new IOTimer<SocketConnection>(s_onSendTimeout, this); } return _sendTimer; } } private IOTimer<SocketConnection> ReceiveTimer { get { if (_receiveTimer == null) { if (s_onReceiveTimeout == null) { s_onReceiveTimeout = OnReceiveTimeout; } _receiveTimer = new IOTimer<SocketConnection>(s_onReceiveTimeout, this); } return _receiveTimer; } } private IPEndPoint RemoteEndPoint { get { if (!_socket.Connected) { return null; } return (IPEndPoint)_socket.RemoteEndPoint; } } private string RemoteEndpointAddressString { get { if (_remoteEndpointAddressString == null) { IPEndPoint remote = RemoteEndPoint; if (remote == null) { return string.Empty; } _remoteEndpointAddressString = remote.Address + ":" + remote.Port; } return _remoteEndpointAddressString; } } private static void OnReceiveAsyncCompleted(object sender, SocketAsyncEventArgs e) { ((SocketConnection)e.UserToken).OnReceiveAsync(sender, e); } private static void OnSendAsyncCompleted(object sender, SocketAsyncEventArgs e) { ((SocketConnection)e.UserToken).OnSendAsync(sender, e); } private static void OnWaitForFinComplete(object state) { // Callback for read on a socket which has had Shutdown called on it. When // the response FIN packet is received from the remote host, the pending // read will complete with 0 bytes read. If more than 0 bytes has been read, // then something has gone wrong as we should have no pending data to be received. SocketConnection thisPtr = (SocketConnection)state; try { int bytesRead; try { bytesRead = thisPtr.EndRead(); if (bytesRead > 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new CommunicationException(SR.Format(SR.SocketCloseReadReceivedData, thisPtr.RemoteEndPoint))); } } catch (TimeoutException timeoutException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException( SR.Format(SR.SocketCloseReadTimeout, thisPtr.RemoteEndPoint, thisPtr._readFinTimeout), timeoutException)); } thisPtr.ContinueClose(thisPtr._closeTimeoutHelper.RemainingTime()); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } Fx.Exception.TraceUnhandledException(e); // The user has no opportunity to clean up the connection in the async and linger // code path, ensure cleanup finishes. thisPtr.Abort(); } } private static void OnReceiveTimeout(SocketConnection socketConnection) { try { socketConnection.Abort(SR.Format(SR.SocketAbortedReceiveTimedOut, socketConnection._receiveTimeout), TransferOperation.Read); } catch (SocketException) { // Guard against unhandled SocketException in timer callbacks } } private static void OnSendTimeout(SocketConnection socketConnection) { try { socketConnection.Abort(4, // TraceEventType.Warning SR.Format(SR.SocketAbortedSendTimedOut, socketConnection._sendTimeout), TransferOperation.Write); } catch (SocketException) { // Guard against unhandled SocketException in timer callbacks } } public void Abort() { Abort(null, TransferOperation.Undefined); } private void Abort(string timeoutErrorString, TransferOperation transferOperation) { int traceEventType = 4; // TraceEventType.Warning; // we could be timing out a cached connection Abort(traceEventType, timeoutErrorString, transferOperation); } private void Abort(int traceEventType) { Abort(traceEventType, null, TransferOperation.Undefined); } private void Abort(int traceEventType, string timeoutErrorString, TransferOperation transferOperation) { lock (ThisLock) { if (_closeState == CloseState.Closed) { return; } _timeoutErrorString = timeoutErrorString; _timeoutErrorTransferOperation = transferOperation; _aborted = true; _closeState = CloseState.Closed; if (!_asyncReadPending) { DisposeReadEventArgs(); } if (!_asyncWritePending) { DisposeWriteEventArgs(); } DisposeReceiveTimer(); DisposeSendTimer(); } _socket.LingerState = new LingerOption(true, 0); _socket.Shutdown(SocketShutdown.Both); _socket.Dispose(); } private void AbortRead() { lock (ThisLock) { if (_asyncReadPending) { if (_closeState != CloseState.Closed) { SetUserToken(_asyncReadEventArgs, null); _asyncReadPending = false; CancelReceiveTimer(); } else { DisposeReadEventArgs(); } } } } private void CancelReceiveTimer() { if (_receiveTimer != null) { _receiveTimer.Cancel(); } } private void CancelSendTimer() { _sendTimer?.Cancel(); } private void CloseAsyncAndLinger() { _readFinTimeout = _closeTimeoutHelper.RemainingTime(); try { // A FIN (shutdown) packet has already been sent to the remote host and we're waiting for the remote // host to send a FIN back. A pending read on a socket will complete returning zero bytes when a FIN // packet is received. if (BeginReadCore(0, 1, _readFinTimeout, s_onWaitForFinComplete, this) == AsyncCompletionResult.Queued) { return; } int bytesRead = EndRead(); // Any NetTcp session handshake will have been completed at this point so if any data is returned, something // very wrong has happened. if (bytesRead > 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new CommunicationException(SR.Format(SR.SocketCloseReadReceivedData, RemoteEndPoint))); } } catch (TimeoutException timeoutException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException( SR.Format(SR.SocketCloseReadTimeout, RemoteEndPoint, _readFinTimeout), timeoutException)); } ContinueClose(_closeTimeoutHelper.RemainingTime()); } public void Close(TimeSpan timeout, bool asyncAndLinger) { lock (ThisLock) { if (_closeState == CloseState.Closing || _closeState == CloseState.Closed) { // already closing or closed, so just return return; } _closeState = CloseState.Closing; } _closeTimeoutHelper = new TimeoutHelper(timeout); // first we shutdown our send-side Shutdown(timeout); CloseCore(asyncAndLinger); } private void CloseCore(bool asyncAndLinger) { if (asyncAndLinger) { CloseAsyncAndLinger(); } else { CloseSync(); } } private void CloseSync() { byte[] dummy = new byte[1]; // A FIN (shutdown) packet has already been sent to the remote host and we're waiting for the remote // host to send a FIN back. A pending read on a socket will complete returning zero bytes when a FIN // packet is received. int bytesRead; _readFinTimeout = _closeTimeoutHelper.RemainingTime(); try { bytesRead = ReadCore(dummy, 0, 1, _readFinTimeout, true); // Any NetTcp session handshake will have been completed at this point so if any data is returned, something // very wrong has happened. if (bytesRead > 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new CommunicationException(SR.Format(SR.SocketCloseReadReceivedData, RemoteEndPoint))); } } catch (TimeoutException timeoutException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException( SR.Format(SR.SocketCloseReadTimeout, RemoteEndPoint, _readFinTimeout), timeoutException)); } // finally we call Close with whatever time is remaining ContinueClose(_closeTimeoutHelper.RemainingTime()); } private void ContinueClose(TimeSpan timeout) { // Use linger to attempt a graceful socket shutdown. Allowing a clean shutdown handshake // will allow the service side to close it's socket gracefully too. A hard shutdown would // cause the server to receive an exception which affects performance and scalability. _socket.LingerState = new LingerOption(true, (int)timeout.TotalSeconds); _socket.Shutdown(SocketShutdown.Both); _socket.Dispose(); lock (ThisLock) { // Abort could have been called on a separate thread and cleaned up // our buffers/completion here if (_closeState != CloseState.Closed) { if (!_asyncReadPending) { DisposeReadEventArgs(); } if (!_asyncWritePending) { DisposeWriteEventArgs(); } } _closeState = CloseState.Closed; DisposeReceiveTimer(); DisposeSendTimer(); } } private void Shutdown(TimeSpan timeout) { lock (ThisLock) { if (_isShutdown) { return; } _isShutdown = true; } ShutdownCore(timeout); } private void ShutdownCore(TimeSpan timeout) { // Attempt to close the socket gracefully by sending a shutdown (FIN) packet try { _socket.Shutdown(SocketShutdown.Send); } catch (SocketException socketException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( ConvertSendException(socketException, TimeSpan.MaxValue)); } catch (ObjectDisposedException objectDisposedException) { Exception exceptionToThrow = ConvertObjectDisposedException(objectDisposedException, TransferOperation.Undefined); if (ReferenceEquals(exceptionToThrow, objectDisposedException)) { throw; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exceptionToThrow); } } } private void ThrowIfNotOpen() { if (_closeState == CloseState.Closing || _closeState == CloseState.Closed) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( ConvertObjectDisposedException(new ObjectDisposedException( this.GetType().ToString(), SR.SocketConnectionDisposed), TransferOperation.Undefined)); } } private void ThrowIfClosed() { if (_closeState == CloseState.Closed) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( ConvertObjectDisposedException(new ObjectDisposedException( this.GetType().ToString(), SR.SocketConnectionDisposed), TransferOperation.Undefined)); } } private Exception ConvertSendException(SocketException socketException, TimeSpan remainingTime) { return ConvertTransferException(socketException, _sendTimeout, socketException, TransferOperation.Write, _aborted, _timeoutErrorString, _timeoutErrorTransferOperation, this, remainingTime); } private Exception ConvertReceiveException(SocketException socketException, TimeSpan remainingTime) { return ConvertTransferException(socketException, _receiveTimeout, socketException, TransferOperation.Read, _aborted, _timeoutErrorString, _timeoutErrorTransferOperation, this, remainingTime); } internal static Exception ConvertTransferException(SocketException socketException, TimeSpan timeout, Exception originalException) { return ConvertTransferException(socketException, timeout, originalException, TransferOperation.Undefined, false, null, TransferOperation.Undefined, null, TimeSpan.MaxValue); } private Exception ConvertObjectDisposedException(ObjectDisposedException originalException, TransferOperation transferOperation) { if (_timeoutErrorString != null) { return ConvertTimeoutErrorException(originalException, transferOperation, _timeoutErrorString, _timeoutErrorTransferOperation); } else if (_aborted) { return new CommunicationObjectAbortedException(SR.SocketConnectionDisposed, originalException); } else { return originalException; } } private static Exception ConvertTransferException(SocketException socketException, TimeSpan timeout, Exception originalException, TransferOperation transferOperation, bool aborted, string timeoutErrorString, TransferOperation timeoutErrorTransferOperation, SocketConnection socketConnection, TimeSpan remainingTime) { if ((int)socketException.SocketErrorCode == UnsafeNativeMethods.ERROR_INVALID_HANDLE) { return new CommunicationObjectAbortedException(socketException.Message, socketException); } if (timeoutErrorString != null) { return ConvertTimeoutErrorException(originalException, transferOperation, timeoutErrorString, timeoutErrorTransferOperation); } // 10053 can occur due to our timeout sockopt firing, so map to TimeoutException in that case if ((int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAECONNABORTED && remainingTime <= TimeSpan.Zero) { TimeoutException timeoutException = new TimeoutException(SR.Format(SR.TcpConnectionTimedOut, timeout), originalException); return timeoutException; } if ((int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAENETRESET || (int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAECONNABORTED || (int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAECONNRESET) { if (aborted) { return new CommunicationObjectAbortedException(SR.TcpLocalConnectionAborted, originalException); } else { CommunicationException communicationException = new CommunicationException(SR.Format(SR.TcpConnectionResetError, timeout), originalException); return communicationException; } } else if ((int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAETIMEDOUT) { TimeoutException timeoutException = new TimeoutException(SR.Format(SR.TcpConnectionTimedOut, timeout), originalException); return timeoutException; } else { if (aborted) { return new CommunicationObjectAbortedException(SR.Format(SR.TcpTransferError, (int)socketException.SocketErrorCode, socketException.Message), originalException); } else { CommunicationException communicationException = new CommunicationException(SR.Format(SR.TcpTransferError, (int)socketException.SocketErrorCode, socketException.Message), originalException); return communicationException; } } } private static Exception ConvertTimeoutErrorException(Exception originalException, TransferOperation transferOperation, string timeoutErrorString, TransferOperation timeoutErrorTransferOperation) { Contract.Assert(timeoutErrorString != null, "Argument timeoutErrorString must not be null."); if (transferOperation == timeoutErrorTransferOperation) { return new TimeoutException(timeoutErrorString, originalException); } else { return new CommunicationException(timeoutErrorString, originalException); } } public AsyncCompletionResult BeginWrite(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout, Action<object> callback, object state) { if (WcfEventSource.Instance.SocketAsyncWriteStartIsEnabled()) { TraceWriteStart(size, true); } return BeginWriteCore(buffer, offset, size, immediate, timeout, callback, state); } private void TraceWriteStart(int size, bool async) { if (!async) { WcfEventSource.Instance.SocketWriteStart(_socket.GetHashCode(), size, RemoteEndpointAddressString); } else { WcfEventSource.Instance.SocketAsyncWriteStart(_socket.GetHashCode(), size, RemoteEndpointAddressString); } } private AsyncCompletionResult BeginWriteCore(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout, Action<object> callback, object state) { ConnectionUtilities.ValidateBufferBounds(buffer, offset, size); bool abortWrite = true; try { lock (ThisLock) { Contract.Assert(!_asyncWritePending, "Called BeginWrite twice."); ThrowIfClosed(); EnsureWriteEventArgs(); SetImmediate(immediate); SetWriteTimeout(timeout, false); SetUserToken(_asyncWriteEventArgs, this); _asyncWritePending = true; _asyncWriteCallback = callback; _asyncWriteState = state; } _asyncWriteEventArgs.SetBuffer(buffer, offset, size); if (_socket.SendAsync(_asyncWriteEventArgs)) { abortWrite = false; return AsyncCompletionResult.Queued; } HandleSendAsyncCompleted(); abortWrite = false; return AsyncCompletionResult.Completed; } catch (SocketException socketException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( ConvertSendException(socketException, TimeSpan.MaxValue)); } catch (ObjectDisposedException objectDisposedException) { Exception exceptionToThrow = ConvertObjectDisposedException(objectDisposedException, TransferOperation.Write); if (ReferenceEquals(exceptionToThrow, objectDisposedException)) { throw; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exceptionToThrow); } } finally { if (abortWrite) { AbortWrite(); } } } public void EndWrite() { EndWriteCore(); } private void EndWriteCore() { if (_asyncWriteException != null) { AbortWrite(); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(_asyncWriteException); } lock (ThisLock) { if (!_asyncWritePending) { Contract.Assert(false, "SocketConnection.EndWrite called with no write pending."); throw new Exception("SocketConnection.EndWrite called with no write pending."); } SetUserToken(_asyncWriteEventArgs, null); _asyncWritePending = false; if (_closeState == CloseState.Closed) { DisposeWriteEventArgs(); } } } private void FinishWrite() { Action<object> asyncWriteCallback = _asyncWriteCallback; object asyncWriteState = _asyncWriteState; _asyncWriteState = null; _asyncWriteCallback = null; asyncWriteCallback(asyncWriteState); } public void Write(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout) { WriteCore(buffer, offset, size, immediate, timeout); } private void WriteCore(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout) { // as per http://support.microsoft.com/default.aspx?scid=kb%3ben-us%3b201213 // we shouldn't write more than 64K synchronously to a socket const int maxSocketWrite = 64 * 1024; ConnectionUtilities.ValidateBufferBounds(buffer, offset, size); TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); try { SetImmediate(immediate); int bytesToWrite = size; while (bytesToWrite > 0) { SetWriteTimeout(timeoutHelper.RemainingTime(), true); size = Math.Min(bytesToWrite, maxSocketWrite); _socket.Send(buffer, offset, size, SocketFlags.None); bytesToWrite -= size; offset += size; timeout = timeoutHelper.RemainingTime(); } } catch (SocketException socketException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( ConvertSendException(socketException, timeoutHelper.RemainingTime())); } catch (ObjectDisposedException objectDisposedException) { Exception exceptionToThrow = ConvertObjectDisposedException(objectDisposedException, TransferOperation.Write); if (ReferenceEquals(exceptionToThrow, objectDisposedException)) { throw; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exceptionToThrow); } } } public void Write(byte[] buffer, int offset, int size, bool immediate, TimeSpan timeout, BufferManager bufferManager) { try { Write(buffer, offset, size, immediate, timeout); } finally { bufferManager.ReturnBuffer(buffer); } } public int Read(byte[] buffer, int offset, int size, TimeSpan timeout) { ConnectionUtilities.ValidateBufferBounds(buffer, offset, size); ThrowIfNotOpen(); int bytesRead = ReadCore(buffer, offset, size, timeout, false); if (WcfEventSource.Instance.SocketReadStopIsEnabled()) { TraceSocketReadStop(bytesRead, false); } return bytesRead; } private int ReadCore(byte[] buffer, int offset, int size, TimeSpan timeout, bool closing) { int bytesRead = 0; TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); try { SetReadTimeout(timeoutHelper.RemainingTime(), true, closing); bytesRead = _socket.Receive(buffer, offset, size, SocketFlags.None); } catch (SocketException socketException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( ConvertReceiveException(socketException, timeoutHelper.RemainingTime())); } catch (ObjectDisposedException objectDisposedException) { Exception exceptionToThrow = ConvertObjectDisposedException(objectDisposedException, TransferOperation.Read); if (ReferenceEquals(exceptionToThrow, objectDisposedException)) { throw; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exceptionToThrow); } } return bytesRead; } public virtual AsyncCompletionResult BeginRead(int offset, int size, TimeSpan timeout, Action<object> callback, object state) { ConnectionUtilities.ValidateBufferBounds(AsyncReadBufferSize, offset, size); this.ThrowIfNotOpen(); var completionResult = this.BeginReadCore(offset, size, timeout, callback, state); if (completionResult == AsyncCompletionResult.Completed && WcfEventSource.Instance.SocketReadStopIsEnabled()) { TraceSocketReadStop(_asyncReadSize, true); } return completionResult; } private void TraceSocketReadStop(int bytesRead, bool async) { if (!async) { WcfEventSource.Instance.SocketReadStop((_socket != null) ? _socket.GetHashCode() : -1, bytesRead, RemoteEndpointAddressString); } else { WcfEventSource.Instance.SocketAsyncReadStop((_socket != null) ? _socket.GetHashCode() : -1, bytesRead, RemoteEndpointAddressString); } } private AsyncCompletionResult BeginReadCore(int offset, int size, TimeSpan timeout, Action<object> callback, object state) { bool abortRead = true; lock (ThisLock) { ThrowIfClosed(); EnsureReadEventArgs(); _asyncReadState = state; _asyncReadCallback = callback; SetUserToken(_asyncReadEventArgs, this); _asyncReadPending = true; SetReadTimeout(timeout, false, false); } try { if (offset != _asyncReadEventArgs.Offset || size != _asyncReadEventArgs.Count) { _asyncReadEventArgs.SetBuffer(offset, size); } if (ReceiveAsync()) { abortRead = false; return AsyncCompletionResult.Queued; } HandleReceiveAsyncCompleted(); _asyncReadSize = _asyncReadEventArgs.BytesTransferred; abortRead = false; return AsyncCompletionResult.Completed; } catch (SocketException socketException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ConvertReceiveException(socketException, TimeSpan.MaxValue)); } catch (ObjectDisposedException objectDisposedException) { Exception exceptionToThrow = ConvertObjectDisposedException(objectDisposedException, TransferOperation.Read); if (ReferenceEquals(exceptionToThrow, objectDisposedException)) { throw; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(exceptionToThrow); } } finally { if (abortRead) { AbortRead(); } } } private bool ReceiveAsync() { return _socket.ReceiveAsync(_asyncReadEventArgs); } private void OnReceiveAsync(object sender, SocketAsyncEventArgs eventArgs) { Contract.Assert(eventArgs != null, "Argument 'eventArgs' cannot be NULL."); CancelReceiveTimer(); try { HandleReceiveAsyncCompleted(); _asyncReadSize = eventArgs.BytesTransferred; } catch (SocketException socketException) { _asyncReadException = ConvertReceiveException(socketException, TimeSpan.MaxValue); } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } _asyncReadException = exception; } FinishRead(); } private void HandleReceiveAsyncCompleted() { if (_asyncReadEventArgs.SocketError == SocketError.Success) { return; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SocketException((int)_asyncReadEventArgs.SocketError)); } private void FinishRead() { if (_asyncReadException != null && WcfEventSource.Instance.SocketReadStopIsEnabled()) { TraceSocketReadStop(_asyncReadSize, true); } Action<object> asyncReadCallback = _asyncReadCallback; object asyncReadState = _asyncReadState; _asyncReadState = null; _asyncReadCallback = null; asyncReadCallback(asyncReadState); } // Both BeginRead/ReadAsync paths completed themselves. EndRead's only job is to deliver the result. public int EndRead() { return EndReadCore(); } // Both BeginRead/ReadAsync paths completed themselves. EndRead's only job is to deliver the result. private int EndReadCore() { if (_asyncReadException != null) { AbortRead(); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(_asyncReadException); } lock (ThisLock) { if (!_asyncReadPending) { Contract.Assert(false, "SocketConnection.EndRead called with no read pending."); throw new Exception("SocketConnection.EndRead called with no read pending."); } SetUserToken(_asyncReadEventArgs, null); _asyncReadPending = false; if (_closeState == CloseState.Closed) { DisposeReadEventArgs(); } } return _asyncReadSize; } // This method should be called inside ThisLock private void DisposeReadEventArgs() { if (_asyncReadEventArgs != null) { _asyncReadEventArgs.Completed -= s_onReceiveAsyncCompleted; _asyncReadEventArgs.Dispose(); } // We release the buffer only if there is no outstanding I/O TryReturnReadBuffer(); } // This method should be called inside ThisLock private void DisposeReceiveTimer() { if (_receiveTimer != null) { _receiveTimer.Dispose(); } } private void OnSendAsync(object sender, SocketAsyncEventArgs eventArgs) { Contract.Assert(eventArgs != null, "Argument 'eventArgs' cannot be NULL."); CancelSendTimer(); try { HandleSendAsyncCompleted(); Contract.Assert(eventArgs.BytesTransferred == _asyncWriteEventArgs.Count, "The socket SendAsync did not send all the bytes."); } catch (SocketException socketException) { _asyncWriteException = ConvertSendException(socketException, TimeSpan.MaxValue); } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } _asyncWriteException = exception; } FinishWrite(); } private void HandleSendAsyncCompleted() { if (_asyncWriteEventArgs.SocketError == SocketError.Success) { return; } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SocketException((int)_asyncWriteEventArgs.SocketError)); } // This method should be called inside ThisLock private void DisposeWriteEventArgs() { if (_asyncWriteEventArgs != null) { _asyncWriteEventArgs.Completed -= s_onSocketSendCompleted; _asyncWriteEventArgs.Dispose(); } } // This method should be called inside ThisLock private void DisposeSendTimer() { if (_sendTimer != null) { _sendTimer.Dispose(); } } private void AbortWrite() { lock (ThisLock) { if (_asyncWritePending) { if (_closeState != CloseState.Closed) { SetUserToken(_asyncWriteEventArgs, null); _asyncWritePending = false; CancelSendTimer(); } else { DisposeWriteEventArgs(); } } } } // This method should be called inside ThisLock private void ReturnReadBuffer() { // We release the buffer only if there is no outstanding I/O this.TryReturnReadBuffer(); } // This method should be called inside ThisLock private void TryReturnReadBuffer() { // The buffer must not be returned and nulled when an abort occurs. Since the buffer // is also accessed by higher layers, code that has not yet realized the stack is // aborted may be attempting to read from the buffer. if (_readBuffer != null && !_aborted) { _connectionBufferPool.Return(_readBuffer); _readBuffer = null; } } private void SetUserToken(SocketAsyncEventArgs args, object userToken) { // The socket args can be pinned by the overlapped callback. Ensure SocketConnection is // only pinned when there is outstanding IO. if (args != null) { args.UserToken = userToken; } } private void SetImmediate(bool immediate) { if (immediate != _noDelay) { lock (ThisLock) { ThrowIfNotOpen(); _socket.NoDelay = immediate; } _noDelay = immediate; } } private void SetReadTimeout(TimeSpan timeout, bool synchronous, bool closing) { if (synchronous) { CancelReceiveTimer(); // 0 == infinite for winsock timeouts, so we should preempt and throw if (timeout <= TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new TimeoutException(SR.Format(SR.TcpConnectionTimedOut, timeout))); } if (UpdateTimeout(_receiveTimeout, timeout)) { lock (ThisLock) { if (!closing || _closeState != CloseState.Closing) { ThrowIfNotOpen(); } _socket.ReceiveTimeout = TimeoutHelper.ToMilliseconds(timeout); } _receiveTimeout = timeout; } } else { _receiveTimeout = timeout; if (timeout == TimeSpan.MaxValue) { CancelReceiveTimer(); } else { ReceiveTimer.ScheduleAfter(timeout); } } } private void SetWriteTimeout(TimeSpan timeout, bool synchronous) { if (synchronous) { CancelSendTimer(); // 0 == infinite for winsock timeouts, so we should preempt and throw if (timeout <= TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new TimeoutException(SR.Format(SR.TcpConnectionTimedOut, timeout))); } if (UpdateTimeout(_sendTimeout, timeout)) { lock (ThisLock) { ThrowIfNotOpen(); _socket.SendTimeout = TimeoutHelper.ToMilliseconds(timeout); } _sendTimeout = timeout; } } else { _sendTimeout = timeout; if (timeout == TimeSpan.MaxValue) { CancelSendTimer(); } else { SendTimer.ScheduleAfter(timeout); } } } private bool UpdateTimeout(TimeSpan oldTimeout, TimeSpan newTimeout) { if (oldTimeout == newTimeout) { return false; } long threshold = oldTimeout.Ticks / 10; long delta = Math.Max(oldTimeout.Ticks, newTimeout.Ticks) - Math.Min(oldTimeout.Ticks, newTimeout.Ticks); return delta > threshold; } // This method should be called inside ThisLock private void EnsureReadEventArgs() { if (_asyncReadEventArgs == null) { // Init ReadAsync state if (s_onReceiveAsyncCompleted == null) { s_onReceiveAsyncCompleted = new EventHandler<SocketAsyncEventArgs>(OnReceiveAsyncCompleted); } _asyncReadEventArgs = new SocketAsyncEventArgs(); _asyncReadEventArgs.SetBuffer(_readBuffer, 0, _readBuffer.Length); _asyncReadEventArgs.Completed += s_onReceiveAsyncCompleted; } } // This method should be called inside ThisLock private void EnsureWriteEventArgs() { if (_asyncWriteEventArgs == null) { // Init SendAsync state if (s_onSocketSendCompleted == null) { s_onSocketSendCompleted = new EventHandler<SocketAsyncEventArgs>(OnSendAsyncCompleted); } _asyncWriteEventArgs = new SocketAsyncEventArgs(); _asyncWriteEventArgs.Completed += s_onSocketSendCompleted; } } public object GetCoreTransport() { return _socket; } private enum CloseState { Open, Closing, Closed, } private enum TransferOperation { Write, Read, Undefined, } } internal class SocketConnectionInitiator : IConnectionInitiator { private int _bufferSize; private ConnectionBufferPool _connectionBufferPool; public SocketConnectionInitiator(int bufferSize) { _bufferSize = bufferSize; _connectionBufferPool = new ConnectionBufferPool(bufferSize); } private IConnection CreateConnection(IPAddress address, int port) { Socket socket = null; try { AddressFamily addressFamily = address.AddressFamily; socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp); socket.Connect(new IPEndPoint(address, port)); return new SocketConnection(socket, _connectionBufferPool); } catch { socket.Dispose(); throw; } } private async Task<IConnection> CreateConnectionAsync(IPAddress address, int port) { Socket socket = null; try { AddressFamily addressFamily = address.AddressFamily; socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp); await socket.ConnectAsync(new IPEndPoint(address, port)); return new SocketConnection(socket, _connectionBufferPool); } catch { socket.Dispose(); throw; } } public static Exception ConvertConnectException(SocketException socketException, Uri remoteUri, TimeSpan timeSpent, Exception innerException) { if ((int)socketException.SocketErrorCode == UnsafeNativeMethods.ERROR_INVALID_HANDLE) { return new CommunicationObjectAbortedException(socketException.Message, socketException); } if ((int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAEADDRNOTAVAIL || (int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAECONNREFUSED || (int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAENETDOWN || (int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAENETUNREACH || (int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAEHOSTDOWN || (int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAEHOSTUNREACH || (int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAETIMEDOUT) { if (timeSpent == TimeSpan.MaxValue) { return new EndpointNotFoundException(SR.Format(SR.TcpConnectError, remoteUri.AbsoluteUri, (int)socketException.SocketErrorCode, socketException.Message), innerException); } else { return new EndpointNotFoundException(SR.Format(SR.TcpConnectErrorWithTimeSpan, remoteUri.AbsoluteUri, (int)socketException.SocketErrorCode, socketException.Message, timeSpent), innerException); } } else if ((int)socketException.SocketErrorCode == UnsafeNativeMethods.WSAENOBUFS) { return new OutOfMemoryException(SR.TcpConnectNoBufs, innerException); } else if ((int)socketException.SocketErrorCode == UnsafeNativeMethods.ERROR_NOT_ENOUGH_MEMORY || (int)socketException.SocketErrorCode == UnsafeNativeMethods.ERROR_NO_SYSTEM_RESOURCES || (int)socketException.SocketErrorCode == UnsafeNativeMethods.ERROR_OUTOFMEMORY) { return new OutOfMemoryException(SR.InsufficentMemory, socketException); } else { if (timeSpent == TimeSpan.MaxValue) { return new CommunicationException(SR.Format(SR.TcpConnectError, remoteUri.AbsoluteUri, (int)socketException.SocketErrorCode, socketException.Message), innerException); } else { return new CommunicationException(SR.Format(SR.TcpConnectErrorWithTimeSpan, remoteUri.AbsoluteUri, (int)socketException.SocketErrorCode, socketException.Message, timeSpent), innerException); } } } private static async Task<IPAddress[]> GetIPAddressesAsync(Uri uri) { if (uri.HostNameType == UriHostNameType.IPv4 || uri.HostNameType == UriHostNameType.IPv6) { IPAddress ipAddress = IPAddress.Parse(uri.DnsSafeHost); return new IPAddress[] { ipAddress }; } IPAddress[] addresses = null; try { addresses = await DnsCache.ResolveAsync(uri); } catch (SocketException socketException) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new EndpointNotFoundException(SR.Format(SR.UnableToResolveHost, uri.Host), socketException)); } if (addresses.Length == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new EndpointNotFoundException(SR.Format(SR.UnableToResolveHost, uri.Host))); } return addresses; } private static TimeoutException CreateTimeoutException(Uri uri, TimeSpan timeout, IPAddress[] addresses, int invalidAddressCount, SocketException innerException) { StringBuilder addressStringBuilder = new StringBuilder(); for (int i = 0; i < invalidAddressCount; i++) { if (addresses[i] == null) { continue; } if (addressStringBuilder.Length > 0) { addressStringBuilder.Append(", "); } addressStringBuilder.Append(addresses[i].ToString()); } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new TimeoutException( SR.Format(SR.TcpConnectingToViaTimedOut, uri.AbsoluteUri, timeout.ToString(), invalidAddressCount, addresses.Length, addressStringBuilder.ToString()), innerException)); } public IConnection Connect(Uri uri, TimeSpan timeout) { int port = uri.Port; IPAddress[] addresses = SocketConnectionInitiator.GetIPAddressesAsync(uri).GetAwaiter().GetResult(); IConnection socketConnection = null; SocketException lastException = null; if (port == -1) { port = TcpUri.DefaultPort; } int invalidAddressCount = 0; TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); for (int i = 0; i < addresses.Length; i++) { if (timeoutHelper.RemainingTime() == TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( CreateTimeoutException(uri, timeoutHelper.OriginalTimeout, addresses, invalidAddressCount, lastException)); } DateTime connectStartTime = DateTime.UtcNow; try { socketConnection = CreateConnection(addresses[i], port); lastException = null; break; } catch (SocketException socketException) { invalidAddressCount++; lastException = socketException; } } if (socketConnection == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new EndpointNotFoundException(SR.Format(SR.NoIPEndpointsFoundForHost, uri.Host))); } if (lastException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( SocketConnectionInitiator.ConvertConnectException(lastException, uri, timeoutHelper.ElapsedTime(), lastException)); } return socketConnection; } public async Task<IConnection> ConnectAsync(Uri uri, TimeSpan timeout) { int port = uri.Port; IPAddress[] addresses = await SocketConnectionInitiator.GetIPAddressesAsync(uri); IConnection socketConnection = null; SocketException lastException = null; if (port == -1) { port = TcpUri.DefaultPort; } int invalidAddressCount = 0; TimeoutHelper timeoutHelper = new TimeoutHelper(timeout); for (int i = 0; i < addresses.Length; i++) { if (timeoutHelper.RemainingTime() == TimeSpan.Zero) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( CreateTimeoutException(uri, timeoutHelper.OriginalTimeout, addresses, invalidAddressCount, lastException)); } DateTime connectStartTime = DateTime.UtcNow; try { socketConnection = await CreateConnectionAsync(addresses[i], port); lastException = null; break; } catch (SocketException socketException) { invalidAddressCount++; lastException = socketException; } } if (socketConnection == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( new EndpointNotFoundException(SR.Format(SR.NoIPEndpointsFoundForHost, uri.Host))); } if (lastException != null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( SocketConnectionInitiator.ConvertConnectException(lastException, uri, timeoutHelper.ElapsedTime(), lastException)); } return socketConnection; } } }
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ using Lucene.Net.Store; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using Console = Lucene.Net.Support.SystemConsole; namespace Lucene.Net.Util.Fst { public class TestFSTsMisc : LuceneTestCase { private MockDirectoryWrapper dir; public override void SetUp() { base.SetUp(); dir = NewMockDirectory(); dir.PreventDoubleWrite = false; } public override void TearDown() { // can be null if we force simpletext (funky, some kind of bug in test runner maybe) if (dir != null) dir.Dispose(); base.TearDown(); } [Test] public void TestRandomWords() { TestRandomWords(1000, LuceneTestCase.AtLeast(Random(), 2)); //TestRandomWords(100, 1); } private void TestRandomWords(int maxNumWords, int numIter) { Random random = new Random(Random().Next()); for (int iter = 0; iter < numIter; iter++) { if (VERBOSE) { Console.WriteLine("\nTEST: iter " + iter); } for (int inputMode = 0; inputMode < 2; inputMode++) { int numWords = random.nextInt(maxNumWords + 1); ISet<Int32sRef> termsSet = new HashSet<Int32sRef>(); Int32sRef[] terms = new Int32sRef[numWords]; while (termsSet.size() < numWords) { string term = FSTTester<object>.GetRandomString(random); termsSet.Add(FSTTester<object>.ToIntsRef(term, inputMode)); } DoTest(inputMode, termsSet.ToArray()); } } } private void DoTest(int inputMode, Int32sRef[] terms) { Array.Sort(terms); // Up to two positive ints, shared, generally but not // monotonically increasing { if (VERBOSE) { Console.WriteLine("TEST: now test UpToTwoPositiveIntOutputs"); } UpToTwoPositiveInt64Outputs outputs = UpToTwoPositiveInt64Outputs.GetSingleton(true); List<Lucene.Net.Util.Fst.FSTTester<object>.InputOutput<object>> pairs = new List<Lucene.Net.Util.Fst.FSTTester<object>.InputOutput<object>>(terms.Length); long lastOutput = 0; for (int idx = 0; idx < terms.Length; idx++) { // Sometimes go backwards long value = lastOutput + TestUtil.NextInt(Random(), -100, 1000); while (value < 0) { value = lastOutput + TestUtil.NextInt(Random(), -100, 1000); } object output; if (Random().nextInt(5) == 3) { long value2 = lastOutput + TestUtil.NextInt(Random(), -100, 1000); while (value2 < 0) { value2 = lastOutput + TestUtil.NextInt(Random(), -100, 1000); } List<long> values = new List<long>(); values.Add(value); values.Add(value2); output = values; } else { output = outputs.Get(value); } pairs.Add(new FSTTester<object>.InputOutput<object>(terms[idx], output)); } new FSTTesterHelper<object>(Random(), dir, inputMode, pairs, outputs, false).DoTest(false); // ListOfOutputs(PositiveIntOutputs), generally but not // monotonically increasing { if (VERBOSE) { Console.WriteLine("TEST: now test OneOrMoreOutputs"); } PositiveInt32Outputs _outputs = PositiveInt32Outputs.Singleton; ListOfOutputs<long?> outputs2 = new ListOfOutputs<long?>(_outputs); List<FSTTester<object>.InputOutput<object>> pairs2 = new List<FSTTester<object>.InputOutput<object>>(terms.Length); long lastOutput2 = 0; for (int idx = 0; idx < terms.Length; idx++) { int outputCount = TestUtil.NextInt(Random(), 1, 7); List<long?> values = new List<long?>(); for (int i = 0; i < outputCount; i++) { // Sometimes go backwards long value = lastOutput2 + TestUtil.NextInt(Random(), -100, 1000); while (value < 0) { value = lastOutput2 + TestUtil.NextInt(Random(), -100, 1000); } values.Add(value); lastOutput2 = value; } object output; if (values.size() == 1) { output = values[0]; } else { output = values; } pairs2.Add(new FSTTester<object>.InputOutput<object>(terms[idx], output)); } new FSTTester<object>(Random(), dir, inputMode, pairs2, outputs2, false).DoTest(false); } } } private class FSTTesterHelper<T> : FSTTester<T> { public FSTTesterHelper(Random random, Directory dir, int inputMode, List<InputOutput<T>> pairs, Outputs<T> outputs, bool doReverseLookup) : base(random, dir, inputMode, pairs, outputs, doReverseLookup) { } protected internal override bool OutputsEqual(T output1, T output2) { if (output1 is UpToTwoPositiveInt64Outputs.TwoInt64s && output2 is IEnumerable<long>) { UpToTwoPositiveInt64Outputs.TwoInt64s twoLongs1 = output1 as UpToTwoPositiveInt64Outputs.TwoInt64s; long[] list2 = (output2 as IEnumerable<long>).ToArray(); return (new long[] { twoLongs1.First, twoLongs1.Second }).SequenceEqual(list2); } else if (output2 is UpToTwoPositiveInt64Outputs.TwoInt64s && output1 is IEnumerable<long>) { long[] list1 = (output1 as IEnumerable<long>).ToArray(); UpToTwoPositiveInt64Outputs.TwoInt64s twoLongs2 = output2 as UpToTwoPositiveInt64Outputs.TwoInt64s; return (new long[] { twoLongs2.First, twoLongs2.Second }).SequenceEqual(list1); } return output1.Equals(output2); } } [Test] public void TestListOfOutputs() { PositiveInt32Outputs _outputs = PositiveInt32Outputs.Singleton; ListOfOutputs<long?> outputs = new ListOfOutputs<long?>(_outputs); Builder<object> builder = new Builder<object>(Lucene.Net.Util.Fst.FST.INPUT_TYPE.BYTE1, outputs); Int32sRef scratch = new Int32sRef(); // Add the same input more than once and the outputs // are merged: builder.Add(Util.ToInt32sRef(new BytesRef("a"), scratch), 1L); builder.Add(Util.ToInt32sRef(new BytesRef("a"), scratch), 3L); builder.Add(Util.ToInt32sRef(new BytesRef("a"), scratch), 0L); builder.Add(Util.ToInt32sRef(new BytesRef("b"), scratch), 17L); FST<object> fst = builder.Finish(); object output = Util.Get(fst, new BytesRef("a")); assertNotNull(output); IList<long?> outputList = outputs.AsList(output); assertEquals(3, outputList.size()); assertEquals(1L, outputList[0]); assertEquals(3L, outputList[1]); assertEquals(0L, outputList[2]); output = Util.Get(fst, new BytesRef("b")); assertNotNull(output); outputList = outputs.AsList(output); assertEquals(1, outputList.size()); assertEquals(17L, outputList[0]); } [Test] public void TestListOfOutputsEmptyString() { PositiveInt32Outputs _outputs = PositiveInt32Outputs.Singleton; ListOfOutputs<long?> outputs = new ListOfOutputs<long?>(_outputs); Builder<object> builder = new Builder<object>(FST.INPUT_TYPE.BYTE1, outputs); Int32sRef scratch = new Int32sRef(); builder.Add(scratch, 0L); builder.Add(scratch, 1L); builder.Add(scratch, 17L); builder.Add(scratch, 1L); builder.Add(Util.ToInt32sRef(new BytesRef("a"), scratch), 1L); builder.Add(Util.ToInt32sRef(new BytesRef("a"), scratch), 3L); builder.Add(Util.ToInt32sRef(new BytesRef("a"), scratch), 0L); builder.Add(Util.ToInt32sRef(new BytesRef("b"), scratch), 0L); FST<object> fst = builder.Finish(); object output = Util.Get(fst, new BytesRef("")); assertNotNull(output); IList<long?> outputList = outputs.AsList(output); assertEquals(4, outputList.size()); assertEquals(0L, outputList[0]); assertEquals(1L, outputList[1]); assertEquals(17L, outputList[2]); assertEquals(1L, outputList[3]); output = Util.Get(fst, new BytesRef("a")); assertNotNull(output); outputList = outputs.AsList(output); assertEquals(3, outputList.size()); assertEquals(1L, outputList[0]); assertEquals(3L, outputList[1]); assertEquals(0L, outputList[2]); output = Util.Get(fst, new BytesRef("b")); assertNotNull(output); outputList = outputs.AsList(output); assertEquals(1, outputList.size()); assertEquals(0L, outputList[0]); } } }
/* Copyright 2021 Jeffrey Sharp Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ using System.Security; namespace PSql; /// <summary> /// Top-level interface between PSql and PSql.Client. /// </summary> public class PSqlClient { static PSqlClient() { SniLoader.Load(); } /// <summary> /// Creates and opens a new <see cref="SqlConnection"/> instance /// using the specified connection string, logging server messages /// via the specified delegates. /// </summary> /// <param name="connectionString"> /// Gets the connection string used to create this connection. The /// connection string includes server name, database name, and other /// parameters that control the initial opening of the connection. /// </param> /// <param name="writeInformation"> /// Delegate that logs server informational messages. /// </param> /// <param name="writeWarning"> /// Delegate that logs server warning or error messages. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="connectionString"/>, /// <paramref name="writeInformation"/>, and/or /// <paramref name="writeWarning"/> is <see langword="null"/>. /// </exception> public SqlConnection Connect( string connectionString, Action<string> writeInformation, Action<string> writeWarning) { if (connectionString is null) throw new ArgumentNullException(nameof(connectionString)); if (writeInformation is null) throw new ArgumentNullException(nameof(writeInformation)); if (writeWarning is null) throw new ArgumentNullException(nameof(writeWarning)); return ConnectCore( new SqlConnection(connectionString), writeInformation, writeWarning ); } /// <summary> /// Creates and opens a new <see cref="SqlConnection"/> instance /// using the specified connection string and credential, logging /// server messages via the specified delegates. /// </summary> /// <param name="connectionString"> /// Gets the connection string used to create this connection. The /// connection string includes server name, database name, and other /// parameters that control the initial opening of the connection. /// </param> /// <param name="username"> /// The username to present for authentication. /// </param> /// <param name="password"> /// The password to present for authentication. /// </param> /// <param name="writeInformation"> /// Delegate that logs server informational messages. /// </param> /// <param name="writeWarning"> /// Delegate that logs server warning or error messages. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="connectionString"/>, /// <paramref name="username"/>, /// <paramref name="password"/>, /// <paramref name="writeInformation"/>, and/or /// <paramref name="writeWarning"/> is <see langword="null"/>. /// </exception> public SqlConnection Connect( string connectionString, string username, SecureString password, Action<string> writeInformation, Action<string> writeWarning) { if (connectionString is null) throw new ArgumentNullException(nameof(connectionString)); if (username is null) throw new ArgumentNullException(nameof(username)); if (password is null) throw new ArgumentNullException(nameof(password)); if (writeInformation is null) throw new ArgumentNullException(nameof(writeInformation)); if (writeWarning is null) throw new ArgumentNullException(nameof(writeWarning)); if (!password.IsReadOnly()) (password = password.Copy()).MakeReadOnly(); var credential = new SqlCredential(username, password); return ConnectCore( new SqlConnection(connectionString, credential), writeInformation, writeWarning ); } private SqlConnection ConnectCore( SqlConnection connection, Action<string> writeInformation, Action<string> writeWarning) { var info = null as ConnectionInfo; try { info = ConnectionInfo.Get(connection); SqlConnectionLogger.Use(connection, writeInformation, writeWarning); connection.Open(); return connection; } catch { if (info != null) info.IsDisconnecting = true; connection?.Dispose(); throw; } } /// <summary> /// Returns a value indicating whether errors have been logged on the /// specified connection. /// </summary> /// <param name="connection"> /// The connection to check. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="connection"/> is <see langword="null"/>. /// </exception> public bool HasErrors(SqlConnection connection) { return ConnectionInfo.Get(connection).HasErrors; } /// <summary> /// Clears any errors prevously logged on the specified connection. /// </summary> /// <param name="connection"> /// The connection for which to clear error state. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="connection"/> is <see langword="null"/>. /// </exception> public void ClearErrors(SqlConnection connection) { ConnectionInfo.Get(connection).HasErrors = false; } /// <summary> /// Indicates that the specified connection is expected to /// disconnect. /// </summary> /// <param name="connection"> /// The connection that is expected to disconnect. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="connection"/> is <see langword="null"/>. /// </exception> public void SetDisconnecting(SqlConnection connection) { ConnectionInfo.Get(connection).IsDisconnecting = true; } /// <summary> /// Executes the specified <see cref="SqlCommand"/> and projects /// results to objects using the specified delegates. /// </summary> /// <param name="command"> /// The command to execute. /// </param> /// <param name="createObject"> /// Delegate that creates a result object. /// </param> /// <param name="setProperty"> /// Delegate that sets a property on a result object. /// </param> /// <param name="useSqlTypes"> /// <see langword="false"/> to project fields using CLR types from the /// <see cref="System"/> namespace, such as <see cref="int"/>. /// <see langword="true"/> to project fields using SQL types from the /// <see cref="System.Data.SqlTypes"/> namespace, such as /// <see cref="System.Data.SqlTypes.SqlInt32"/>. /// </param> /// <returns> /// A sequence of objects created by executing /// <paramref name="command"/> /// and projecting each result row to an object using /// <paramref name="createObject"/>, /// <paramref name="setProperty"/>, and /// <paramref name="useSqlTypes"/>, /// in the order produced by the command. If the command produces no /// result rows, this method returns an empty sequence. /// </returns> /// <exception cref="ArgumentNullException"> /// <paramref name="command"/>, /// <paramref name="createObject"/>, and/or /// <paramref name="setProperty"/> is <see langword="null"/>. /// </exception> public IEnumerator<object> ExecuteAndProject( SqlCommand command, Func<object> createObject, Action<object, string, object?> setProperty, bool useSqlTypes = false) { if (command is null) throw new ArgumentNullException(nameof(command)); if (createObject is null) throw new ArgumentNullException(nameof(createObject)); if (setProperty is null) throw new ArgumentNullException(nameof(setProperty)); if (command.Connection.State == ConnectionState.Closed) command.Connection.Open(); var reader = command.ExecuteReader(); return new ObjectResultSet(reader, createObject, setProperty, useSqlTypes); } }
// Copyright (C) 2014 dot42 // // Original filename: Android.Telephony.Cdma.cs // // 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. #pragma warning disable 1717 namespace Android.Telephony.Cdma { /// <summary> /// <para>Represents the cell location on a CDMA phone. </para> /// </summary> /// <java-name> /// android/telephony/cdma/CdmaCellLocation /// </java-name> [Dot42.DexImport("android/telephony/cdma/CdmaCellLocation", AccessFlags = 33)] public partial class CdmaCellLocation : global::Android.Telephony.CellLocation /* scope: __dot42__ */ { /// <summary> /// <para>Empty constructor. Initializes the BID, SID, NID and base station latitude and longitude to invalid values. </para> /// </summary> [Dot42.DexImport("<init>", "()V", AccessFlags = 1)] public CdmaCellLocation() /* MethodBuilder.Create */ { } /// <summary> /// <para>Initialize the object from a bundle. </para> /// </summary> [Dot42.DexImport("<init>", "(Landroid/os/Bundle;)V", AccessFlags = 1)] public CdmaCellLocation(global::Android.Os.Bundle bundle) /* MethodBuilder.Create */ { } /// <summary> /// <para></para> /// </summary> /// <returns> /// <para>cdma base station identification number, -1 if unknown </para> /// </returns> /// <java-name> /// getBaseStationId /// </java-name> [Dot42.DexImport("getBaseStationId", "()I", AccessFlags = 1)] public virtual int GetBaseStationId() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Latitude is a decimal number as specified in 3GPP2 C.S0005-A v6.0. () It is represented in units of 0.25 seconds and ranges from -1296000 to 1296000, both values inclusive (corresponding to a range of -90 to +90 degrees). Integer.MAX_VALUE is considered invalid value.</para><para></para> /// </summary> /// <returns> /// <para>cdma base station latitude in units of 0.25 seconds, Integer.MAX_VALUE if unknown </para> /// </returns> /// <java-name> /// getBaseStationLatitude /// </java-name> [Dot42.DexImport("getBaseStationLatitude", "()I", AccessFlags = 1)] public virtual int GetBaseStationLatitude() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Longitude is a decimal number as specified in 3GPP2 C.S0005-A v6.0. () It is represented in units of 0.25 seconds and ranges from -2592000 to 2592000, both values inclusive (corresponding to a range of -180 to +180 degrees). Integer.MAX_VALUE is considered invalid value.</para><para></para> /// </summary> /// <returns> /// <para>cdma base station longitude in units of 0.25 seconds, Integer.MAX_VALUE if unknown </para> /// </returns> /// <java-name> /// getBaseStationLongitude /// </java-name> [Dot42.DexImport("getBaseStationLongitude", "()I", AccessFlags = 1)] public virtual int GetBaseStationLongitude() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para></para> /// </summary> /// <returns> /// <para>cdma system identification number, -1 if unknown </para> /// </returns> /// <java-name> /// getSystemId /// </java-name> [Dot42.DexImport("getSystemId", "()I", AccessFlags = 1)] public virtual int GetSystemId() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para></para> /// </summary> /// <returns> /// <para>cdma network identification number, -1 if unknown </para> /// </returns> /// <java-name> /// getNetworkId /// </java-name> [Dot42.DexImport("getNetworkId", "()I", AccessFlags = 1)] public virtual int GetNetworkId() /* MethodBuilder.Create */ { return default(int); } /// <summary> /// <para>Invalidate this object. The cell location data is set to invalid values. </para> /// </summary> /// <java-name> /// setStateInvalid /// </java-name> [Dot42.DexImport("setStateInvalid", "()V", AccessFlags = 1)] public virtual void SetStateInvalid() /* MethodBuilder.Create */ { } /// <summary> /// <para>Set the cell location data. </para> /// </summary> /// <java-name> /// setCellLocationData /// </java-name> [Dot42.DexImport("setCellLocationData", "(III)V", AccessFlags = 1)] public virtual void SetCellLocationData(int baseStationId, int baseStationLatitude, int baseStationLongitude) /* MethodBuilder.Create */ { } /// <summary> /// <para>Set the cell location data. </para> /// </summary> /// <java-name> /// setCellLocationData /// </java-name> [Dot42.DexImport("setCellLocationData", "(IIIII)V", AccessFlags = 1)] public virtual void SetCellLocationData(int baseStationId, int baseStationLatitude, int baseStationLongitude, int systemId, int networkId) /* MethodBuilder.Create */ { } /// <java-name> /// hashCode /// </java-name> [Dot42.DexImport("hashCode", "()I", AccessFlags = 1)] public override int GetHashCode() /* MethodBuilder.Create */ { return default(int); } /// <java-name> /// equals /// </java-name> [Dot42.DexImport("equals", "(Ljava/lang/Object;)Z", AccessFlags = 1)] public override bool Equals(object o) /* MethodBuilder.Create */ { return default(bool); } /// <java-name> /// toString /// </java-name> [Dot42.DexImport("toString", "()Ljava/lang/String;", AccessFlags = 1)] public override string ToString() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Fill the cell location data into the intent notifier Bundle based on service state</para><para></para> /// </summary> /// <java-name> /// fillInNotifierBundle /// </java-name> [Dot42.DexImport("fillInNotifierBundle", "(Landroid/os/Bundle;)V", AccessFlags = 1)] public virtual void FillInNotifierBundle(global::Android.Os.Bundle bundleToFill) /* MethodBuilder.Create */ { } /// <summary> /// <para></para> /// </summary> /// <returns> /// <para>cdma base station identification number, -1 if unknown </para> /// </returns> /// <java-name> /// getBaseStationId /// </java-name> public int BaseStationId { [Dot42.DexImport("getBaseStationId", "()I", AccessFlags = 1)] get{ return GetBaseStationId(); } } /// <summary> /// <para>Latitude is a decimal number as specified in 3GPP2 C.S0005-A v6.0. () It is represented in units of 0.25 seconds and ranges from -1296000 to 1296000, both values inclusive (corresponding to a range of -90 to +90 degrees). Integer.MAX_VALUE is considered invalid value.</para><para></para> /// </summary> /// <returns> /// <para>cdma base station latitude in units of 0.25 seconds, Integer.MAX_VALUE if unknown </para> /// </returns> /// <java-name> /// getBaseStationLatitude /// </java-name> public int BaseStationLatitude { [Dot42.DexImport("getBaseStationLatitude", "()I", AccessFlags = 1)] get{ return GetBaseStationLatitude(); } } /// <summary> /// <para>Longitude is a decimal number as specified in 3GPP2 C.S0005-A v6.0. () It is represented in units of 0.25 seconds and ranges from -2592000 to 2592000, both values inclusive (corresponding to a range of -180 to +180 degrees). Integer.MAX_VALUE is considered invalid value.</para><para></para> /// </summary> /// <returns> /// <para>cdma base station longitude in units of 0.25 seconds, Integer.MAX_VALUE if unknown </para> /// </returns> /// <java-name> /// getBaseStationLongitude /// </java-name> public int BaseStationLongitude { [Dot42.DexImport("getBaseStationLongitude", "()I", AccessFlags = 1)] get{ return GetBaseStationLongitude(); } } /// <summary> /// <para></para> /// </summary> /// <returns> /// <para>cdma system identification number, -1 if unknown </para> /// </returns> /// <java-name> /// getSystemId /// </java-name> public int SystemId { [Dot42.DexImport("getSystemId", "()I", AccessFlags = 1)] get{ return GetSystemId(); } } /// <summary> /// <para></para> /// </summary> /// <returns> /// <para>cdma network identification number, -1 if unknown </para> /// </returns> /// <java-name> /// getNetworkId /// </java-name> public int NetworkId { [Dot42.DexImport("getNetworkId", "()I", AccessFlags = 1)] get{ return GetNetworkId(); } } } }
/* * 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.HSSF.UserModel { using System; using System.Drawing; using System.Text; using System.Collections; using System.IO; using NPOI.DDF; using NPOI.Util; using NPOI.SS.UserModel; using NPOI.HSSF.Model; /// <summary> /// Represents a escher picture. Eg. A GIF, JPEG etc... /// @author Glen Stampoultzis /// @author Yegor Kozlov (yegor at apache.org) /// </summary> internal class HSSFPicture : HSSFSimpleShape , IPicture { /** * width of 1px in columns with default width in Units of 1/256 of a Char width */ private static float PX_DEFAULT = 32.00f; /** * width of 1px in columns with overridden width in Units of 1/256 of a Char width */ private static float PX_MODIFIED = 36.56f; /** * Height of 1px of a row */ private static int PX_ROW = 15; int pictureIndex; //HSSFPatriarch patriarch; /// <summary> /// Gets or sets the patriarch. /// </summary> /// <value>The patriarch.</value> public HSSFPatriarch Patriarch { get { return _patriarch; } set { _patriarch = value; } } private static POILogger log = POILogFactory.GetLogger(typeof(HSSFPicture)); /// <summary> /// Constructs a picture object. /// </summary> /// <param name="parent">The parent.</param> /// <param name="anchor">The anchor.</param> public HSSFPicture(HSSFShape parent, HSSFAnchor anchor) : base(parent, anchor) { this.ShapeType = (OBJECT_TYPE_PICTURE); } /// <summary> /// Gets or sets the index of the picture. /// </summary> /// <value>The index of the picture.</value> public int PictureIndex { get { return pictureIndex; } set { this.pictureIndex = value; } } /// <summary> /// Reset the image to the original size. /// </summary> public void Resize(double scale) { HSSFClientAnchor anchor = (HSSFClientAnchor)Anchor; anchor.AnchorType = 2; IClientAnchor pref = GetPreferredSize(scale); int row2 = anchor.Row1 + (pref.Row2 - pref.Row1); int col2 = anchor.Col1 + (pref.Col2 - pref.Col1); anchor.Col2 = col2; anchor.Dx1 = 0; anchor.Dx2 = pref.Dx2; anchor.Row2 = row2; anchor.Dy1 = 0; anchor.Dy2 = pref.Dy2; } /// <summary> /// Reset the image to the original size. /// </summary> public void Resize() { Resize(1.0); } /// <summary> /// Calculate the preferred size for this picture. /// </summary> /// <param name="scale">the amount by which image dimensions are multiplied relative to the original size.</param> /// <returns>HSSFClientAnchor with the preferred size for this image</returns> public HSSFClientAnchor GetPreferredSize(double scale) { HSSFClientAnchor anchor = (HSSFClientAnchor)Anchor; Size size = GetImageDimension(); double scaledWidth = size.Width * scale; double scaledHeight = size.Height * scale; float w = 0; //space in the leftmost cell w += GetColumnWidthInPixels(anchor.Col1) * (1 - (float)anchor.Dx1 / 1024); short col2 = (short)(anchor.Col1 + 1); int dx2 = 0; while (w < scaledWidth) { w += GetColumnWidthInPixels(col2++); } if (w > scaledWidth) { //calculate dx2, offset in the rightmost cell col2--; double cw = GetColumnWidthInPixels(col2); double delta = w - scaledWidth; dx2 = (int)((cw - delta) / cw * 1024); } anchor.Col2 = col2; anchor.Dx2 = dx2; float h = 0; h += (1 - (float)anchor.Dy1 / 256) * GetRowHeightInPixels(anchor.Row1); int row2 = anchor.Row1 + 1; int dy2 = 0; while (h < scaledHeight) { h += GetRowHeightInPixels(row2++); } if (h > scaledHeight) { row2--; double ch = GetRowHeightInPixels(row2); double delta = h - scaledHeight; dy2 = (int)((ch - delta) / ch * 256); } anchor.Row2 = row2; anchor.Dy2 = dy2; return anchor; } /// <summary> /// Calculate the preferred size for this picture. /// </summary> /// <returns>HSSFClientAnchor with the preferred size for this image</returns> public NPOI.SS.UserModel.IClientAnchor GetPreferredSize() { return GetPreferredSize(1.0); } /// <summary> /// Gets the column width in pixels. /// </summary> /// <param name="column">The column.</param> /// <returns></returns> private float GetColumnWidthInPixels(int column) { int cw = _patriarch._sheet.GetColumnWidth(column); float px = GetPixelWidth(column); return cw / px; } /// <summary> /// Gets the row height in pixels. /// </summary> /// <param name="i">The row</param> /// <returns></returns> private float GetRowHeightInPixels(int i) { IRow row = _patriarch._sheet.GetRow(i); float height; if (row != null) height = row.Height; else height = _patriarch._sheet.DefaultRowHeight; return height / PX_ROW; } /// <summary> /// Gets the width of the pixel. /// </summary> /// <param name="column">The column.</param> /// <returns></returns> private float GetPixelWidth(int column) { int def = _patriarch._sheet.DefaultColumnWidth * 256; int cw = _patriarch._sheet.GetColumnWidth(column); return cw == def ? PX_DEFAULT : PX_MODIFIED; } /// <summary> /// The metadata of PNG and JPEG can contain the width of a pixel in millimeters. /// Return the the "effective" dpi calculated as /// <c>25.4/HorizontalPixelSize</c> /// and /// <c>25.4/VerticalPixelSize</c> /// . Where 25.4 is the number of mm in inch. /// </summary> /// <param name="r">The image.</param> /// <returns>the resolution</returns> protected Size GetResolution(Image r) { //int hdpi = 96, vdpi = 96; //double mm2inch = 25.4; //NodeList lst; //Element node = (Element)r.GetImageMetadata(0).GetAsTree("javax_imageio_1.0"); //lst = node.GetElementsByTagName("HorizontalPixelSize"); //if (lst != null && lst.GetLength == 1) hdpi = (int)(mm2inch / Float.ParseFloat(((Element)lst.item(0)).GetAttribute("value"))); //lst = node.GetElementsByTagName("VerticalPixelSize"); //if (lst != null && lst.GetLength == 1) vdpi = (int)(mm2inch / Float.ParseFloat(((Element)lst.item(0)).GetAttribute("value"))); return new Size((int)r.HorizontalResolution, (int)r.VerticalResolution); } /// <summary> /// Return the dimension of this image /// </summary> /// <returns>image dimension</returns> public Size GetImageDimension() { EscherBSERecord bse = _patriarch._sheet.book.GetBSERecord(pictureIndex); byte[] data = bse.BlipRecord.PictureData; //int type = bse.BlipTypeWin32; using (MemoryStream ms = new MemoryStream(data)) { using (Image img = Image.FromStream(ms)) { return img.Size; } } } /** * Return picture data for this shape * * @return picture data for this shape */ public IPictureData PictureData { get { InternalWorkbook iwb = ((_patriarch._sheet.Workbook) as HSSFWorkbook).Workbook; EscherBlipRecord blipRecord = iwb.GetBSERecord(pictureIndex).BlipRecord; return new HSSFPictureData(blipRecord); } } } }
// // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System; using Mono.Cecil.Metadata; using Mono.Collections.Generic; namespace Mono.Cecil { public sealed class TypeDefinition : TypeReference, IMemberDefinition, ISecurityDeclarationProvider { uint attributes; TypeReference base_type; internal Range fields_range; internal Range methods_range; short packing_size = Mixin.NotResolvedMarker; int class_size = Mixin.NotResolvedMarker; Collection<TypeReference> interfaces; Collection<TypeDefinition> nested_types; Collection<MethodDefinition> methods; Collection<FieldDefinition> fields; Collection<EventDefinition> events; Collection<PropertyDefinition> properties; Collection<CustomAttribute> custom_attributes; Collection<SecurityDeclaration> security_declarations; public TypeAttributes Attributes { get { return (TypeAttributes) attributes; } set { attributes = (uint) value; } } public TypeReference BaseType { get { return base_type; } set { base_type = value; } } void ResolveLayout () { if (packing_size != Mixin.NotResolvedMarker || class_size != Mixin.NotResolvedMarker) return; if (!HasImage) { packing_size = Mixin.NoDataMarker; class_size = Mixin.NoDataMarker; return; } var row = Module.Read (this, (type, reader) => reader.ReadTypeLayout (type)); packing_size = row.Col1; class_size = row.Col2; } public bool HasLayoutInfo { get { if (packing_size >= 0 || class_size >= 0) return true; ResolveLayout (); return packing_size >= 0 || class_size >= 0; } } public short PackingSize { get { if (packing_size >= 0) return packing_size; ResolveLayout (); return packing_size >= 0 ? packing_size : (short) -1; } set { packing_size = value; } } public int ClassSize { get { if (class_size >= 0) return class_size; ResolveLayout (); return class_size >= 0 ? class_size : -1; } set { class_size = value; } } public bool HasInterfaces { get { if (interfaces != null) return interfaces.Count > 0; return HasImage && Module.Read (this, (type, reader) => reader.HasInterfaces (type)); } } public Collection<TypeReference> Interfaces { get { if (interfaces != null) return interfaces; if (HasImage) return Module.Read (ref interfaces, this, (type, reader) => reader.ReadInterfaces (type)); return interfaces = new Collection<TypeReference> (); } } public bool HasNestedTypes { get { if (nested_types != null) return nested_types.Count > 0; return HasImage && Module.Read (this, (type, reader) => reader.HasNestedTypes (type)); } } public Collection<TypeDefinition> NestedTypes { get { if (nested_types != null) return nested_types; if (HasImage) return Module.Read (ref nested_types, this, (type, reader) => reader.ReadNestedTypes (type)); return nested_types = new MemberDefinitionCollection<TypeDefinition> (this); } } public bool HasMethods { get { if (methods != null) return methods.Count > 0; return HasImage && methods_range.Length > 0; } } public Collection<MethodDefinition> Methods { get { if (methods != null) return methods; if (HasImage) return Module.Read (ref methods, this, (type, reader) => reader.ReadMethods (type)); return methods = new MemberDefinitionCollection<MethodDefinition> (this); } } public bool HasFields { get { if (fields != null) return fields.Count > 0; return HasImage && fields_range.Length > 0; } } public Collection<FieldDefinition> Fields { get { if (fields != null) return fields; if (HasImage) return Module.Read (ref fields, this, (type, reader) => reader.ReadFields (type)); return fields = new MemberDefinitionCollection<FieldDefinition> (this); } } public bool HasEvents { get { if (events != null) return events.Count > 0; return HasImage && Module.Read (this, (type, reader) => reader.HasEvents (type)); } } public Collection<EventDefinition> Events { get { if (events != null) return events; if (HasImage) return Module.Read (ref events, this, (type, reader) => reader.ReadEvents (type)); return events = new MemberDefinitionCollection<EventDefinition> (this); } } public bool HasProperties { get { if (properties != null) return properties.Count > 0; return HasImage && Module.Read (this, (type, reader) => reader.HasProperties (type)); } } public Collection<PropertyDefinition> Properties { get { if (properties != null) return properties; if (HasImage) return Module.Read (ref properties, this, (type, reader) => reader.ReadProperties (type)); return properties = new MemberDefinitionCollection<PropertyDefinition> (this); } } public bool HasSecurityDeclarations { get { if (security_declarations != null) return security_declarations.Count > 0; return this.GetHasSecurityDeclarations (Module); } } public Collection<SecurityDeclaration> SecurityDeclarations { get { return security_declarations ?? (this.GetSecurityDeclarations (ref security_declarations, Module)); } } public bool HasCustomAttributes { get { if (custom_attributes != null) return custom_attributes.Count > 0; return this.GetHasCustomAttributes (Module); } } public Collection<CustomAttribute> CustomAttributes { get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, Module)); } } public override bool HasGenericParameters { get { if (generic_parameters != null) return generic_parameters.Count > 0; return this.GetHasGenericParameters (Module); } } public override Collection<GenericParameter> GenericParameters { get { return generic_parameters ?? (this.GetGenericParameters (ref generic_parameters, Module)); } } #region TypeAttributes public bool IsNotPublic { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NotPublic); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NotPublic, value); } } public bool IsPublic { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.Public); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.Public, value); } } public bool IsNestedPublic { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPublic); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPublic, value); } } public bool IsNestedPrivate { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPrivate); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedPrivate, value); } } public bool IsNestedFamily { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamily); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamily, value); } } public bool IsNestedAssembly { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedAssembly); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedAssembly, value); } } public bool IsNestedFamilyAndAssembly { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamANDAssem); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamANDAssem, value); } } public bool IsNestedFamilyOrAssembly { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamORAssem); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.VisibilityMask, (uint) TypeAttributes.NestedFamORAssem, value); } } public bool IsAutoLayout { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.AutoLayout); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.AutoLayout, value); } } public bool IsSequentialLayout { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.SequentialLayout); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.SequentialLayout, value); } } public bool IsExplicitLayout { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.ExplicitLayout); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.LayoutMask, (uint) TypeAttributes.ExplicitLayout, value); } } public bool IsClass { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Class); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Class, value); } } public bool IsInterface { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Interface); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.ClassSemanticMask, (uint) TypeAttributes.Interface, value); } } public bool IsAbstract { get { return attributes.GetAttributes ((uint) TypeAttributes.Abstract); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Abstract, value); } } public bool IsSealed { get { return attributes.GetAttributes ((uint) TypeAttributes.Sealed); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Sealed, value); } } public bool IsSpecialName { get { return attributes.GetAttributes ((uint) TypeAttributes.SpecialName); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.SpecialName, value); } } public bool IsImport { get { return attributes.GetAttributes ((uint) TypeAttributes.Import); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Import, value); } } public bool IsSerializable { get { return attributes.GetAttributes ((uint) TypeAttributes.Serializable); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.Serializable, value); } } public bool IsWindowsRuntime { get { return attributes.GetAttributes ((uint) TypeAttributes.WindowsRuntime); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.WindowsRuntime, value); } } public bool IsAnsiClass { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AnsiClass); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AnsiClass, value); } } public bool IsUnicodeClass { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.UnicodeClass); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.UnicodeClass, value); } } public bool IsAutoClass { get { return attributes.GetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AutoClass); } set { attributes = attributes.SetMaskedAttributes ((uint) TypeAttributes.StringFormatMask, (uint) TypeAttributes.AutoClass, value); } } public bool IsBeforeFieldInit { get { return attributes.GetAttributes ((uint) TypeAttributes.BeforeFieldInit); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.BeforeFieldInit, value); } } public bool IsRuntimeSpecialName { get { return attributes.GetAttributes ((uint) TypeAttributes.RTSpecialName); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.RTSpecialName, value); } } public bool HasSecurity { get { return attributes.GetAttributes ((uint) TypeAttributes.HasSecurity); } set { attributes = attributes.SetAttributes ((uint) TypeAttributes.HasSecurity, value); } } #endregion public bool IsEnum { get { return base_type != null && base_type.IsTypeOf ("System", "Enum"); } } public override bool IsValueType { get { if (base_type == null) return false; return base_type.IsTypeOf ("System", "Enum") || (base_type.IsTypeOf ("System", "ValueType") && !this.IsTypeOf ("System", "Enum")); } } public override bool IsPrimitive { get { ElementType primitive_etype; return MetadataSystem.TryGetPrimitiveElementType (this, out primitive_etype); } } public override MetadataType MetadataType { get { ElementType primitive_etype; if (MetadataSystem.TryGetPrimitiveElementType (this, out primitive_etype)) return (MetadataType) primitive_etype; return base.MetadataType; } } public override bool IsDefinition { get { return true; } } public new TypeDefinition DeclaringType { get { return (TypeDefinition) base.DeclaringType; } set { base.DeclaringType = value; } } public TypeDefinition (string @namespace, string name, TypeAttributes attributes) : base (@namespace, name) { this.attributes = (uint) attributes; this.token = new MetadataToken (TokenType.TypeDef); } public TypeDefinition (string @namespace, string name, TypeAttributes attributes, TypeReference baseType) : this (@namespace, name, attributes) { this.BaseType = baseType; } protected override void ClearFullName () { base.ClearFullName (); if (!HasNestedTypes) return; var nested_types = this.NestedTypes; for (int i = 0; i < nested_types.Count; i++) nested_types [i].ClearFullName (); } public override TypeDefinition Resolve () { return this; } } static partial class Mixin { public static TypeReference GetEnumUnderlyingType (this TypeDefinition self) { var fields = self.Fields; for (int i = 0; i < fields.Count; i++) { var field = fields [i]; if (!field.IsStatic) return field.FieldType; } throw new ArgumentException (); } public static TypeDefinition GetNestedType (this TypeDefinition self, string fullname) { if (!self.HasNestedTypes) return null; var nested_types = self.NestedTypes; for (int i = 0; i < nested_types.Count; i++) { var nested_type = nested_types [i]; if (nested_type.TypeFullName () == fullname) return nested_type; } return null; } } }
using System; using System.Collections; using System.Diagnostics; using System.Runtime.InteropServices; using Microsoft.SPOT.Debugger; using WireProtocol = Microsoft.SPOT.Debugger.WireProtocol; using System.Collections.Generic; namespace Microsoft.SPOT.Debugger { public class CorDebugThread { CorDebugProcess m_process; CorDebugChain m_chain; uint m_id; bool m_fSuspended; bool m_fSuspendedSav; //for function eval, need to remember if this thread is suspended before suspending for function eval.. CorDebugValue m_currentException; CorDebugEval m_eval; bool m_fSuspendThreadEvents; CorDebugAppDomain m_initialAppDomain; bool m_fExited; //Doubly-linked list of virtual threads. The head of the list is the real thread //All other threads (at this point), should be the cause of a function eval CorDebugThread m_threadPrevious; CorDebugThread m_threadNext; public CorDebugThread (CorDebugProcess process, uint id, CorDebugEval eval) { m_process = process; m_id = id; m_fSuspended = false; m_eval = eval; } public CorDebugEval CurrentEval { get { return m_eval; } } public bool Exited { get { return m_fExited; } set { if (value) m_fExited = value; } } public bool SuspendThreadEvents { get { return m_fSuspendThreadEvents; } set { m_fSuspendThreadEvents = value; } } public void AttachVirtualThread (CorDebugThread thread) { CorDebugThread threadLast = this.GetLastCorDebugThread (); threadLast.m_threadNext = thread; thread.m_threadPrevious = threadLast; m_process.AddThread (thread); Debug.Assert (Process.IsExecutionPaused); threadLast.m_fSuspendedSav = threadLast.m_fSuspended; threadLast.IsSuspended = true; } public bool RemoveVirtualThread (CorDebugThread thread) { //can only remove last thread CorDebugThread threadLast = this.GetLastCorDebugThread (); Debug.Assert (threadLast.IsVirtualThread && !this.IsVirtualThread); if (threadLast != thread) return false; CorDebugThread threadNextToLast = threadLast.m_threadPrevious; threadNextToLast.m_threadNext = null; threadNextToLast.IsSuspended = threadNextToLast.m_fSuspendedSav; threadLast.m_threadPrevious = null; //Thread will be removed from process.m_alThreads when the ThreadTerminated breakpoint is hit return true; } public Engine Engine { [System.Diagnostics.DebuggerHidden] get { return m_process.Engine; } } public CorDebugProcess Process { [System.Diagnostics.DebuggerHidden] get { return m_process; } } public CorDebugAppDomain AppDomain { get { CorDebugAppDomain appDomain = m_initialAppDomain; if (!m_fExited) { CorDebugThread thread = GetLastCorDebugThread (); CorDebugFrame frame = thread.Chain.ActiveFrame; appDomain = frame.AppDomain; } return appDomain; } } public uint Id { [System.Diagnostics.DebuggerHidden] get { return m_id; } } public void StoppedOnException () { m_currentException = CorDebugValue.CreateValue (Engine.GetThreadException (m_id), this.AppDomain); } //This is the only thread that cpde knows about public CorDebugThread GetRealCorDebugThread () { CorDebugThread thread; for (thread = this; thread.m_threadPrevious != null; thread = thread.m_threadPrevious) { } return thread; } public CorDebugThread GetLastCorDebugThread () { CorDebugThread thread; for (thread = this; thread.m_threadNext != null; thread = thread.m_threadNext) { } return thread; } public CorDebugThread PreviousThread { get { return m_threadPrevious; } } public CorDebugThread NextThread { get { return m_threadNext; } } public bool IsVirtualThread { get { return m_eval != null; } } public bool IsLogicalThreadSuspended { get { return GetLastCorDebugThread ().IsSuspended; } } public bool IsSuspended { get { return m_fSuspended; } set { bool fSuspend = value; if (fSuspend && !IsSuspended) { this.Engine.SuspendThread (Id); } else if (!fSuspend && IsSuspended) { this.Engine.ResumeThread (Id); } m_fSuspended = fSuspend; } } public CorDebugChain Chain { get { if (m_chain == null) { WireProtocol.Commands.Debugging_Thread_Stack.Reply ts = this.Engine.GetThreadStack (m_id); if (ts != null) { m_fSuspended = (ts.m_flags & WireProtocol.Commands.Debugging_Thread_Stack.Reply.TH_F_Suspended) != 0; m_chain = new CorDebugChain (this, ts.m_data); if (m_initialAppDomain == null) { CorDebugFrame initialFrame = m_chain.GetFrameFromDepthTinyCLR (0); m_initialAppDomain = initialFrame.AppDomain; } } } return m_chain; } } public void RefreshChain () { if (m_chain != null) { m_chain.RefreshFrames (); } } public void ResumingExecution () { if (IsSuspended) { RefreshChain (); } else { m_chain = null; m_currentException = null; } } public CorDebugFrame ActiveFrame { get { Debug.Assert (!IsVirtualThread); return GetLastCorDebugThread ().Chain.ActiveFrame; } } public List<CorDebugChain> Chains { get { Debug.Assert (!IsVirtualThread); var chains = new List<CorDebugChain> (); for (CorDebugThread thread = this.GetLastCorDebugThread (); thread != null; thread = thread.m_threadPrevious) { CorDebugChain chain = thread.Chain; if (chain != null) { chains.Add (chain); } } return chains; } } public CorDebugValue CurrentException { get { return GetLastCorDebugThread ().m_currentException; } } } }
/* * Copyright (c) 2012 Calvin Rien * * Based on the JSON parser by Patrick van Bergen * http://techblog.procurios.nl/k/618/news/view/14605/14863/How-do-I-write-my-own-parser-for-JSON.html * * Simplified it so that it doesn't throw exceptions * and can be used in Unity iPhone with maximum code stripping. * * 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.IO; using System.Text; namespace MiniJSON { // Example usage: // // using UnityEngine; // using System.Collections; // using System.Collections.Generic; // using MiniJSON; // // public class MiniJSONTest : MonoBehaviour { // void Start () { // var jsonString = "{ \"array\": [1.44,2,3], " + // "\"object\": {\"key1\":\"value1\", \"key2\":256}, " + // "\"string\": \"The quick brown fox \\\"jumps\\\" over the lazy dog \", " + // "\"unicode\": \"\\u3041 Men\u00fa sesi\u00f3n\", " + // "\"int\": 65536, " + // "\"float\": 3.1415926, " + // "\"bool\": true, " + // "\"null\": null }"; // // var dict = Json.Deserialize(jsonString) as Dictionary<string,object>; // // Debug.Log("deserialized: " + dict.GetType()); // Debug.Log("dict['array'][0]: " + ((List<object>) dict["array"])[0]); // Debug.Log("dict['string']: " + (string) dict["string"]); // Debug.Log("dict['float']: " + (double) dict["float"]); // floats come out as doubles // Debug.Log("dict['int']: " + (long) dict["int"]); // ints come out as longs // Debug.Log("dict['unicode']: " + (string) dict["unicode"]); // // var str = Json.Serialize(dict); // // Debug.Log("serialized: " + str); // } // } /// <summary> /// This class encodes and decodes JSON strings. /// Spec. details, see http://www.json.org/ /// /// JSON uses Arrays and Objects. These correspond here to the datatypes IList and IDictionary. /// All numbers are parsed to doubles. /// </summary> public class Json { /// <summary> /// Parses the string json into a value /// </summary> /// <param name="json">A JSON string.</param> /// <returns>An List&lt;object&gt;, a Dictionary&lt;string, object&gt;, a double, an integer,a string, null, true, or false</returns> public static object Deserialize(string json) { // save the string for debug information if (json == null) return null; var parser = new Parser(json); return parser.Parse(); } class Parser { StringReader json; enum TOKEN { NONE, CURLY_OPEN, CURLY_CLOSE, SQUARED_OPEN, SQUARED_CLOSE, COLON, COMMA, STRING, NUMBER, TRUE, FALSE, NULL }; public Parser(string jsonData) { this.json = new StringReader(jsonData); } public object Parse() { return ParseValue(); } Dictionary<string, object> ParseObject() { Dictionary<string, object> table = new Dictionary<string, object>(); TOKEN token; // ditch opening brace json.Read(); // { while (true) { token = NextToken(); switch (token) { case TOKEN.NONE: return null; case TOKEN.COMMA: continue; case TOKEN.CURLY_CLOSE: return table; default: // name string name = ParseString(); if (name == null) { return null; } // : token = NextToken(); if (token != TOKEN.COLON) { return null; } // ditch the colon json.Read(); // value table[name] = ParseValue(); break; } } } List<object> ParseArray() { List<object> array = new List<object>(); TOKEN token; // ditch opening bracket json.Read(); // [ while (true) { token = NextToken(); if (token == TOKEN.NONE) { return null; } else if (token == TOKEN.COMMA) { continue; } else if (token == TOKEN.SQUARED_CLOSE) { break; } else { object value = ParseValue(); array.Add(value); } } return array; } object ParseValue() { switch (NextToken()) { case TOKEN.STRING: return ParseString(); case TOKEN.NUMBER: return ParseNumber(); case TOKEN.CURLY_OPEN: return ParseObject(); case TOKEN.SQUARED_OPEN: return ParseArray(); case TOKEN.TRUE: return true; case TOKEN.FALSE: return false; case TOKEN.NULL: return null; default: return null; } } string ParseString() { StringBuilder s = new StringBuilder(); char c; // ditch opening quote json.Read(); bool complete = false; while (true) { if (json.Peek() == -1) { break; } c = ReadChar(); if (c == '"') { complete = true; break; } else if (c == '\\') { if (json.Peek() == -1) { break; } c = ReadChar(); if (c == '"') { s.Append('"'); } else if (c == '\\') { s.Append('\\'); } else if (c == '/') { s.Append('/'); } else if (c == 'b') { s.Append('\b'); } else if (c == 'f') { s.Append('\f'); } else if (c == 'n') { s.Append('\n'); } else if (c == 'r') { s.Append('\r'); } else if (c == 't') { s.Append('\t'); } else if (c == 'u') { var hex = new StringBuilder(); for (int i=0; i< 4;i++) { hex.Append(ReadChar()); } s.Append((char) Convert.ToInt32(hex.ToString(), 16)); } } else { s.Append(c); } } if (!complete) { return null; } return s.ToString(); } object ParseNumber() { string number = NextWord(); if (number.IndexOf('.') == -1) { return Int64.Parse(number); } return Double.Parse(number); } void EatWhitespace() { while (" \t\n\r".IndexOf(PeekChar()) != -1) { json.Read(); if (json.Peek() == -1) break; } } char PeekChar() { return Convert.ToChar(json.Peek()); } char ReadChar() { return Convert.ToChar(json.Read()); } string NextWord() { StringBuilder word = new StringBuilder(); while (" \t\n\r{}[],:\"".IndexOf(PeekChar()) == -1) { word.Append(ReadChar()); if (json.Peek() == -1) break; } return word.ToString(); } TOKEN NextToken() { EatWhitespace(); if (json.Peek() == -1) { return TOKEN.NONE; } char c = PeekChar(); switch (c) { case '{': return TOKEN.CURLY_OPEN; case '}': json.Read(); return TOKEN.CURLY_CLOSE; case '[': return TOKEN.SQUARED_OPEN; case ']': json.Read(); return TOKEN.SQUARED_CLOSE; case ',': json.Read(); return TOKEN.COMMA; case '"': return TOKEN.STRING; case ':': return TOKEN.COLON; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case '-': return TOKEN.NUMBER; } string word = NextWord(); switch (word) { case "false": return TOKEN.FALSE; case "true": return TOKEN.TRUE; case "null": return TOKEN.NULL; } return TOKEN.NONE; } } /// <summary> /// Converts a IDictionary / IList object or a simple type (string, int, etc.) into a JSON string /// </summary> /// <param name="json">A Dictionary&lt;string, object&gt; / List&lt;object&gt;</param> /// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns> public static string Serialize(object obj) { var serializer = new Serializer(obj); return serializer.Serialize(); } class Serializer { StringBuilder builder; object obj; public Serializer(object obj) { this.obj = obj; builder = new StringBuilder(); } public string Serialize() { SerializeValue(obj); return builder.ToString(); } void SerializeValue(object value) { if (value == null) { builder.Append("null"); } else if (value is IDictionary) { SerializeObject((IDictionary)value); } else if (value is IList) { SerializeArray((IList)value); } else if (value is string) { SerializeString((string)value); } else if (value is Char) { SerializeString(((char)value).ToString()); } else if (value is bool) { builder.Append((bool)value ? "true" : "false"); } else { SerializeOther(value); } } void SerializeObject(IDictionary obj) { bool first = true; builder.Append('{'); foreach (object e in obj.Keys) { if (!first) { builder.Append(','); } SerializeString(e.ToString()); builder.Append(':'); SerializeValue(obj[e]); first = false; } builder.Append('}'); } void SerializeArray(IList anArray) { builder.Append('['); bool first = true; foreach (object obj in anArray) { if (!first) { builder.Append(','); } SerializeValue(obj); first = false; } builder.Append(']'); } void SerializeString(string str) { builder.Append('\"'); char[] charArray = str.ToCharArray(); foreach (var c in charArray) { if (c == '"') { builder.Append("\\\""); } else if (c == '\\') { builder.Append("\\\\"); } else if (c == '\b') { builder.Append("\\b"); } else if (c == '\f') { builder.Append("\\f"); } else if (c == '\n') { builder.Append("\\n"); } else if (c == '\r') { builder.Append("\\r"); } else if (c == '\t') { builder.Append("\\t"); } else { int codepoint = Convert.ToInt32(c); if ((codepoint >= 32) && (codepoint <= 126)) { builder.Append(c); } else { builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0')); } } } builder.Append('\"'); } void SerializeOther(object value) { if (value is float || value is int || value is uint || value is long || value is double || value is sbyte || value is byte || value is short || value is ushort || value is ulong || value is decimal) { builder.Append(value.ToString()); } else { SerializeString(value.ToString()); } } } } }
using Lucene.Net.Support; using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; namespace Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// Represents hits returned by /// <see cref="IndexSearcher.Search(Query,Filter,int)"/> and /// <see cref="IndexSearcher.Search(Query,int)"/>. /// </summary> public class TopDocs { /// <summary> /// The total number of hits for the query. </summary> public int TotalHits { get; set; } /// <summary> /// The top hits for the query. </summary> [WritableArray] [SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")] public ScoreDoc[] ScoreDocs { get; set; } /// <summary> /// Stores the maximum score value encountered, needed for normalizing. </summary> private float maxScore; /// <summary> /// Returns the maximum score value encountered. Note that in case /// scores are not tracked, this returns <see cref="float.NaN"/>. /// </summary> public virtual float MaxScore { get { return maxScore; } set { this.maxScore = value; } } /// <summary> /// Constructs a <see cref="TopDocs"/> with a default <c>maxScore=System.Single.NaN</c>. </summary> internal TopDocs(int totalHits, ScoreDoc[] scoreDocs) : this(totalHits, scoreDocs, float.NaN) { } public TopDocs(int totalHits, ScoreDoc[] scoreDocs, float maxScore) { this.TotalHits = totalHits; this.ScoreDocs = scoreDocs; this.maxScore = maxScore; } // Refers to one hit: private class ShardRef { // Which shard (index into shardHits[]): internal int ShardIndex { get; private set; } // Which hit within the shard: internal int HitIndex { get; set; } public ShardRef(int shardIndex) { this.ShardIndex = shardIndex; } public override string ToString() { return "ShardRef(shardIndex=" + ShardIndex + " hitIndex=" + HitIndex + ")"; } } // Specialized MergeSortQueue that just merges by // relevance score, descending: private class ScoreMergeSortQueue : Util.PriorityQueue<ShardRef> { internal readonly ScoreDoc[][] shardHits; public ScoreMergeSortQueue(TopDocs[] shardHits) : base(shardHits.Length) { this.shardHits = new ScoreDoc[shardHits.Length][]; for (int shardIDX = 0; shardIDX < shardHits.Length; shardIDX++) { this.shardHits[shardIDX] = shardHits[shardIDX].ScoreDocs; } } // Returns true if first is < second protected internal override bool LessThan(ShardRef first, ShardRef second) { Debug.Assert(first != second); float firstScore = shardHits[first.ShardIndex][first.HitIndex].Score; float secondScore = shardHits[second.ShardIndex][second.HitIndex].Score; if (firstScore < secondScore) { return false; } else if (firstScore > secondScore) { return true; } else { // Tie break: earlier shard wins if (first.ShardIndex < second.ShardIndex) { return true; } else if (first.ShardIndex > second.ShardIndex) { return false; } else { // Tie break in same shard: resolve however the // shard had resolved it: Debug.Assert(first.HitIndex != second.HitIndex); return first.HitIndex < second.HitIndex; } } } } private class MergeSortQueue : Util.PriorityQueue<ShardRef> { // These are really FieldDoc instances: internal readonly ScoreDoc[][] shardHits; internal readonly FieldComparer[] comparers; internal readonly int[] reverseMul; public MergeSortQueue(Sort sort, TopDocs[] shardHits) : base(shardHits.Length) { this.shardHits = new ScoreDoc[shardHits.Length][]; for (int shardIDX = 0; shardIDX < shardHits.Length; shardIDX++) { ScoreDoc[] shard = shardHits[shardIDX].ScoreDocs; //System.out.println(" init shardIdx=" + shardIDX + " hits=" + shard); if (shard != null) { this.shardHits[shardIDX] = shard; // Fail gracefully if API is misused: for (int hitIDX = 0; hitIDX < shard.Length; hitIDX++) { ScoreDoc sd = shard[hitIDX]; if (!(sd is FieldDoc)) { throw new System.ArgumentException("shard " + shardIDX + " was not sorted by the provided Sort (expected FieldDoc but got ScoreDoc)"); } FieldDoc fd = (FieldDoc)sd; if (fd.Fields == null) { throw new System.ArgumentException("shard " + shardIDX + " did not set sort field values (FieldDoc.fields is null); you must pass fillFields=true to IndexSearcher.search on each shard"); } } } } SortField[] sortFields = sort.GetSort(); comparers = new FieldComparer[sortFields.Length]; reverseMul = new int[sortFields.Length]; for (int compIDX = 0; compIDX < sortFields.Length; compIDX++) { SortField sortField = sortFields[compIDX]; comparers[compIDX] = sortField.GetComparer(1, compIDX); reverseMul[compIDX] = sortField.IsReverse ? -1 : 1; } } // Returns true if first is < second protected internal override bool LessThan(ShardRef first, ShardRef second) { Debug.Assert(first != second); FieldDoc firstFD = (FieldDoc)shardHits[first.ShardIndex][first.HitIndex]; FieldDoc secondFD = (FieldDoc)shardHits[second.ShardIndex][second.HitIndex]; //System.out.println(" lessThan:\n first=" + first + " doc=" + firstFD.doc + " score=" + firstFD.score + "\n second=" + second + " doc=" + secondFD.doc + " score=" + secondFD.score); for (int compIDX = 0; compIDX < comparers.Length; compIDX++) { FieldComparer comp = comparers[compIDX]; //System.out.println(" cmp idx=" + compIDX + " cmp1=" + firstFD.fields[compIDX] + " cmp2=" + secondFD.fields[compIDX] + " reverse=" + reverseMul[compIDX]); int cmp = reverseMul[compIDX] * comp.CompareValues(firstFD.Fields[compIDX], secondFD.Fields[compIDX]); if (cmp != 0) { //System.out.println(" return " + (cmp < 0)); return cmp < 0; } } // Tie break: earlier shard wins if (first.ShardIndex < second.ShardIndex) { //System.out.println(" return tb true"); return true; } else if (first.ShardIndex > second.ShardIndex) { //System.out.println(" return tb false"); return false; } else { // Tie break in same shard: resolve however the // shard had resolved it: //System.out.println(" return tb " + (first.hitIndex < second.hitIndex)); Debug.Assert(first.HitIndex != second.HitIndex); return first.HitIndex < second.HitIndex; } } } /// <summary> /// Returns a new <see cref="TopDocs"/>, containing <paramref name="topN"/> results across /// the provided <see cref="TopDocs"/>, sorting by the specified /// <see cref="Sort"/>. Each of the <see cref="TopDocs"/> must have been sorted by /// the same <see cref="Sort"/>, and sort field values must have been /// filled (ie, <c>fillFields=true</c> must be /// passed to /// <see cref="TopFieldCollector.Create(Sort, int, bool, bool, bool, bool)"/>. /// /// <para/>Pass <paramref name="sort"/>=null to merge sort by score descending. /// <para/> /// @lucene.experimental /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] public static TopDocs Merge(Sort sort, int topN, TopDocs[] shardHits) { return Merge(sort, 0, topN, shardHits); } /// <summary> /// Same as <see cref="Merge(Sort, int, TopDocs[])"/> but also slices the result at the same time based /// on the provided start and size. The return <c>TopDocs</c> will always have a scoreDocs with length of /// at most <see cref="Util.PriorityQueue{T}.Count"/>. /// </summary> [MethodImpl(MethodImplOptions.NoInlining)] public static TopDocs Merge(Sort sort, int start, int size, TopDocs[] shardHits) { Util.PriorityQueue<ShardRef> queue; if (sort == null) { queue = new ScoreMergeSortQueue(shardHits); } else { queue = new MergeSortQueue(sort, shardHits); } int totalHitCount = 0; int availHitCount = 0; float maxScore = float.MinValue; for (int shardIDX = 0; shardIDX < shardHits.Length; shardIDX++) { TopDocs shard = shardHits[shardIDX]; // totalHits can be non-zero even if no hits were // collected, when searchAfter was used: totalHitCount += shard.TotalHits; if (shard.ScoreDocs != null && shard.ScoreDocs.Length > 0) { availHitCount += shard.ScoreDocs.Length; queue.Add(new ShardRef(shardIDX)); maxScore = Math.Max(maxScore, shard.MaxScore); //System.out.println(" maxScore now " + maxScore + " vs " + shard.getMaxScore()); } } if (availHitCount == 0) { maxScore = float.NaN; } ScoreDoc[] hits; if (availHitCount <= start) { hits = new ScoreDoc[0]; } else { hits = new ScoreDoc[Math.Min(size, availHitCount - start)]; int requestedResultWindow = start + size; int numIterOnHits = Math.Min(availHitCount, requestedResultWindow); int hitUpto = 0; while (hitUpto < numIterOnHits) { Debug.Assert(queue.Count > 0); ShardRef @ref = queue.Pop(); ScoreDoc hit = shardHits[@ref.ShardIndex].ScoreDocs[@ref.HitIndex++]; hit.ShardIndex = @ref.ShardIndex; if (hitUpto >= start) { hits[hitUpto - start] = hit; } //System.out.println(" hitUpto=" + hitUpto); //System.out.println(" doc=" + hits[hitUpto].doc + " score=" + hits[hitUpto].score); hitUpto++; if (@ref.HitIndex < shardHits[@ref.ShardIndex].ScoreDocs.Length) { // Not done with this these TopDocs yet: queue.Add(@ref); } } } if (sort == null) { return new TopDocs(totalHitCount, hits, maxScore); } else { return new TopFieldDocs(totalHitCount, hits, sort.GetSort(), maxScore); } } } }
using System; using System.IO; namespace Python.Test { /// <summary> /// Supports units tests for method access. /// </summary> public class MethodTest { public MethodTest() { } public string PublicMethod() { return "public"; } public static string PublicStaticMethod() { return "public static"; } protected string ProtectedMethod() { return "protected"; } protected static string ProtectedStaticMethod() { return "protected static"; } internal string InternalMethod() { return "internal"; } internal static string InternalStaticMethod() { return "internal static"; } private string PrivateMethod() { return "private"; } private static string PrivateStaticMethod() { return "private static"; } /// <summary> /// Methods to support specific argument conversion unit tests /// </summary> public TypeCode TestEnumConversion(TypeCode v) { return v; } public FileAccess TestFlagsConversion(FileAccess v) { return v; } public Guid TestStructConversion(Guid v) { return v; } public Exception TestSubclassConversion(Exception v) { return v; } public Type[] TestNullArrayConversion(Type[] v) { return v; } public static string[] TestStringParamsArg(params string[] args) { return args; } public static object[] TestObjectParamsArg(params object[] args) { return args; } public static int[] TestValueParamsArg(params int[] args) { return args; } public static int[] TestOneArgWithParams(string s, params int[] args) { return args; } public static int[] TestTwoArgWithParams(string s, string x, params int[] args) { return args; } public static int[] TestOverloadedParams(string v, params int[] args) { return args; } public static int[] TestOverloadedParams(int v, int[] args) { return args; } public static string TestOverloadedNoObject(int i) { return "Got int"; } public static string TestOverloadedObject(int i) { return "Got int"; } public static string TestOverloadedObject(object o) { return "Got object"; } public static string TestOverloadedObjectTwo(int a, int b) { return "Got int-int"; } public static string TestOverloadedObjectTwo(string a, string b) { return "Got string-string"; } public static string TestOverloadedObjectTwo(string a, int b) { return "Got string-int"; } public static string TestOverloadedObjectTwo(string a, object b) { return "Got string-object"; } public static string TestOverloadedObjectTwo(int a, object b) { return "Got int-object"; } public static string TestOverloadedObjectTwo(object a, int b) { return "Got object-int"; } public static string TestOverloadedObjectTwo(object a, object b) { return "Got object-object"; } public static string TestOverloadedObjectTwo(int a, string b) { return "Got int-string"; } public static string TestOverloadedObjectThree(object a, int b) { return "Got object-int"; } public static string TestOverloadedObjectThree(int a, object b) { return "Got int-object"; } public static bool TestStringOutParams(string s, out string s1) { s1 = "output string"; return true; } public static bool TestStringRefParams(string s, ref string s1) { s1 = "output string"; return true; } public static bool TestNonParamsArrayInLastPlace(int i1, int[] i2) { return false; } public static bool TestNonParamsArrayInLastPlace(int i1, int i2, int i3) { return true; } public static bool TestValueOutParams(string s, out int i1) { i1 = 42; return true; } public static bool TestValueRefParams(string s, ref int i1) { i1 = 42; return true; } public static bool TestObjectOutParams(object o, out object o1) { o1 = new Exception("test"); return true; } public static bool TestObjectRefParams(object o, ref object o1) { o1 = new Exception("test"); return true; } public static bool TestStructOutParams(object o, out Guid o1) { o1 = Guid.NewGuid(); return true; } public static bool TestStructRefParams(object o, ref Guid o1) { o1 = Guid.NewGuid(); return true; } public static void TestVoidSingleOutParam(out int i) { i = 42; } public static void TestVoidSingleRefParam(ref int i) { i = 42; } public static int TestSingleDefaultParam(int i = 5) { return i; } public static int TestTwoDefaultParam(int i = 5, int j = 6) { return i + j; } public static int TestOneArgAndTwoDefaultParam(int z, int i = 5, int j = 6) { return i + j + z; } // overload selection test support public static bool Overloaded(bool v) { return v; } public static byte Overloaded(byte v) { return v; } public static sbyte Overloaded(sbyte v) { return v; } public static char Overloaded(char v) { return v; } public static short Overloaded(short v) { return v; } public static int Overloaded(int v) { return v; } public static long Overloaded(long v) { return v; } public static ushort Overloaded(ushort v) { return v; } public static uint Overloaded(uint v) { return v; } public static ulong Overloaded(ulong v) { return v; } public static float Overloaded(float v) { return v; } public static double Overloaded(double v) { return v; } public static decimal Overloaded(decimal v) { return v; } public static string Overloaded(string v) { return v; } public static ShortEnum Overloaded(ShortEnum v) { return v; } public static object Overloaded(object v) { return v; } public static InterfaceTest Overloaded(InterfaceTest v) { return v; } public static ISayHello1 Overloaded(ISayHello1 v) { return v; } public static bool[] Overloaded(bool[] v) { return v; } public static byte[] Overloaded(byte[] v) { return v; } public static sbyte[] Overloaded(sbyte[] v) { return v; } public static char[] Overloaded(char[] v) { return v; } public static short[] Overloaded(short[] v) { return v; } public static int[] Overloaded(int[] v) { return v; } public static long[] Overloaded(long[] v) { return v; } public static ushort[] Overloaded(ushort[] v) { return v; } public static uint[] Overloaded(uint[] v) { return v; } public static ulong[] Overloaded(ulong[] v) { return v; } public static float[] Overloaded(float[] v) { return v; } public static double[] Overloaded(double[] v) { return v; } public static decimal[] Overloaded(decimal[] v) { return v; } public static string[] Overloaded(string[] v) { return v; } public static ShortEnum[] Overloaded(ShortEnum[] v) { return v; } public static object[] Overloaded(object[] v) { return v; } public static InterfaceTest[] Overloaded(InterfaceTest[] v) { return v; } public static ISayHello1[] Overloaded(ISayHello1[] v) { return v; } public static GenericWrapper<bool> Overloaded(GenericWrapper<bool> v) { return v; } public static GenericWrapper<byte> Overloaded(GenericWrapper<byte> v) { return v; } public static GenericWrapper<sbyte> Overloaded(GenericWrapper<sbyte> v) { return v; } public static GenericWrapper<char> Overloaded(GenericWrapper<char> v) { return v; } public static GenericWrapper<short> Overloaded(GenericWrapper<short> v) { return v; } public static GenericWrapper<int> Overloaded(GenericWrapper<int> v) { return v; } public static GenericWrapper<long> Overloaded(GenericWrapper<long> v) { return v; } public static GenericWrapper<ushort> Overloaded(GenericWrapper<ushort> v) { return v; } public static GenericWrapper<uint> Overloaded(GenericWrapper<uint> v) { return v; } public static GenericWrapper<ulong> Overloaded(GenericWrapper<ulong> v) { return v; } public static GenericWrapper<float> Overloaded(GenericWrapper<float> v) { return v; } public static GenericWrapper<double> Overloaded(GenericWrapper<double> v) { return v; } public static GenericWrapper<decimal> Overloaded(GenericWrapper<decimal> v) { return v; } public static GenericWrapper<string> Overloaded(GenericWrapper<string> v) { return v; } public static GenericWrapper<ShortEnum> Overloaded(GenericWrapper<ShortEnum> v) { return v; } public static GenericWrapper<object> Overloaded(GenericWrapper<object> v) { return v; } public static GenericWrapper<InterfaceTest> Overloaded(GenericWrapper<InterfaceTest> v) { return v; } public static GenericWrapper<ISayHello1> Overloaded(GenericWrapper<ISayHello1> v) { return v; } public static GenericWrapper<bool>[] Overloaded(GenericWrapper<bool>[] v) { return v; } public static GenericWrapper<byte>[] Overloaded(GenericWrapper<byte>[] v) { return v; } public static GenericWrapper<sbyte>[] Overloaded(GenericWrapper<sbyte>[] v) { return v; } public static GenericWrapper<char>[] Overloaded(GenericWrapper<char>[] v) { return v; } public static GenericWrapper<short>[] Overloaded(GenericWrapper<short>[] v) { return v; } public static GenericWrapper<int>[] Overloaded(GenericWrapper<int>[] v) { return v; } public static GenericWrapper<long>[] Overloaded(GenericWrapper<long>[] v) { return v; } public static GenericWrapper<ushort>[] Overloaded(GenericWrapper<ushort>[] v) { return v; } public static GenericWrapper<uint>[] Overloaded(GenericWrapper<uint>[] v) { return v; } public static GenericWrapper<ulong>[] Overloaded(GenericWrapper<ulong>[] v) { return v; } public static GenericWrapper<float>[] Overloaded(GenericWrapper<float>[] v) { return v; } public static GenericWrapper<double>[] Overloaded(GenericWrapper<double>[] v) { return v; } public static GenericWrapper<decimal>[] Overloaded(GenericWrapper<decimal>[] v) { return v; } public static GenericWrapper<string>[] Overloaded(GenericWrapper<string>[] v) { return v; } public static GenericWrapper<ShortEnum>[] Overloaded(GenericWrapper<ShortEnum>[] v) { return v; } public static GenericWrapper<object>[] Overloaded(GenericWrapper<object>[] v) { return v; } public static GenericWrapper<InterfaceTest>[] Overloaded(GenericWrapper<InterfaceTest>[] v) { return v; } public static GenericWrapper<ISayHello1>[] Overloaded(GenericWrapper<ISayHello1>[] v) { return v; } public static int Overloaded(string s, int i, object[] o) { return o.Length; } public static int Overloaded(string s, int i) { return i; } public static int Overloaded(int i, string s) { return i; } public static string CaseSensitive() { return "CaseSensitive"; } public static string Casesensitive() { return "Casesensitive"; } } public class MethodTestSub : MethodTest { public MethodTestSub() : base() { } public string PublicMethod(string echo) { return echo; } } }
// Copyright (c) Umbraco. // See LICENSE for more details. using System.Collections.Generic; using System.Linq; using Microsoft.Extensions.DependencyInjection; using NUnit.Framework; using Umbraco.Cms.Core.Cache; using Umbraco.Cms.Core.DependencyInjection; using Umbraco.Cms.Core.Events; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Models.Membership; using Umbraco.Cms.Core.Notifications; using Umbraco.Cms.Core.Scoping; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Services.Implement; using Umbraco.Cms.Core.Sync; using Umbraco.Cms.Infrastructure.PublishedCache; using Umbraco.Cms.Infrastructure.Sync; using Umbraco.Cms.Tests.Common.Testing; using Umbraco.Cms.Tests.Integration.Testing; using Umbraco.Extensions; namespace Umbraco.Cms.Tests.Integration.Umbraco.Infrastructure.Scoping { [TestFixture] [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)] public class ScopedRepositoryTests : UmbracoIntegrationTest { private IUserService UserService => GetRequiredService<IUserService>(); private ILocalizationService LocalizationService => GetRequiredService<ILocalizationService>(); protected override AppCaches GetAppCaches() { // this is what's created core web runtime var result = new AppCaches( new DeepCloneAppCache(new ObjectCacheAppCache()), NoAppCache.Instance, new IsolatedCaches(type => new DeepCloneAppCache(new ObjectCacheAppCache()))); return result; } protected override void CustomTestSetup(IUmbracoBuilder builder) { builder.AddNuCache(); builder.Services.AddUnique<IServerMessenger, LocalServerMessenger>(); builder .AddNotificationHandler<DictionaryItemDeletedNotification, DistributedCacheBinder>() .AddNotificationHandler<DictionaryItemSavedNotification, DistributedCacheBinder>() .AddNotificationHandler<LanguageSavedNotification, DistributedCacheBinder>() .AddNotificationHandler<LanguageDeletedNotification, DistributedCacheBinder>() .AddNotificationHandler<UserSavedNotification, DistributedCacheBinder>() .AddNotificationHandler<LanguageDeletedNotification, DistributedCacheBinder>() .AddNotificationHandler<MemberGroupDeletedNotification, DistributedCacheBinder>() .AddNotificationHandler<MemberGroupSavedNotification, DistributedCacheBinder>(); builder.AddNotificationHandler<LanguageSavedNotification, PublishedSnapshotServiceEventHandler>(); } [TestCase(true)] [TestCase(false)] public void DefaultRepositoryCachePolicy(bool complete) { var scopeProvider = (ScopeProvider)ScopeProvider; var service = (UserService)UserService; IAppPolicyCache globalCache = AppCaches.IsolatedCaches.GetOrCreate(typeof(IUser)); var user = (IUser)new User(GlobalSettings, "name", "email", "username", "rawPassword"); service.Save(user); // User has been saved so the cache has been cleared of it var globalCached = (IUser)globalCache.Get(GetCacheIdKey<IUser>(user.Id), () => null); Assert.IsNull(globalCached); // Get user again to load it into the cache again, this also ensure we don't modify the one that's in the cache. user = service.GetUserById(user.Id); // global cache contains the entity globalCached = (IUser)globalCache.Get(GetCacheIdKey<IUser>(user.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(user.Id, globalCached.Id); Assert.AreEqual("name", globalCached.Name); Assert.IsNull(scopeProvider.AmbientScope); using (IScope scope = scopeProvider.CreateScope(repositoryCacheMode: RepositoryCacheMode.Scoped)) { Assert.IsInstanceOf<Scope>(scope); Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(scope, scopeProvider.AmbientScope); // scope has its own isolated cache IAppPolicyCache scopedCache = scope.IsolatedCaches.GetOrCreate(typeof(IUser)); Assert.AreNotSame(globalCache, scopedCache); user.Name = "changed"; service.Save(user); // scoped cache contains the "new" entity var scopeCached = (IUser)scopedCache.Get(GetCacheIdKey<IUser>(user.Id), () => null); Assert.IsNotNull(scopeCached); Assert.AreEqual(user.Id, scopeCached.Id); Assert.AreEqual("changed", scopeCached.Name); // global cache is unchanged globalCached = (IUser)globalCache.Get(GetCacheIdKey<IUser>(user.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(user.Id, globalCached.Id); Assert.AreEqual("name", globalCached.Name); if (complete) { scope.Complete(); } } Assert.IsNull(scopeProvider.AmbientScope); globalCached = (IUser)globalCache.Get(GetCacheIdKey<IUser>(user.Id), () => null); if (complete) { // global cache has been cleared Assert.IsNull(globalCached); } else { // global cache has *not* been cleared Assert.IsNotNull(globalCached); } // get again, updated if completed user = service.GetUserById(user.Id); Assert.AreEqual(complete ? "changed" : "name", user.Name); // global cache contains the entity again globalCached = (IUser)globalCache.Get(GetCacheIdKey<IUser>(user.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(user.Id, globalCached.Id); Assert.AreEqual(complete ? "changed" : "name", globalCached.Name); } [TestCase(true)] [TestCase(false)] public void FullDataSetRepositoryCachePolicy(bool complete) { var scopeProvider = (ScopeProvider)ScopeProvider; ILocalizationService service = LocalizationService; IAppPolicyCache globalCache = AppCaches.IsolatedCaches.GetOrCreate(typeof(ILanguage)); var lang = (ILanguage)new Language(GlobalSettings, "fr-FR"); service.Save(lang); // global cache has been flushed, reload var globalFullCached = (IEnumerable<ILanguage>)globalCache.Get(GetCacheTypeKey<ILanguage>(), () => null); Assert.IsNull(globalFullCached); ILanguage reload = service.GetLanguageById(lang.Id); // global cache contains the entity globalFullCached = (IEnumerable<ILanguage>)globalCache.Get(GetCacheTypeKey<ILanguage>(), () => null); Assert.IsNotNull(globalFullCached); ILanguage globalCached = globalFullCached.First(x => x.Id == lang.Id); Assert.IsNotNull(globalCached); Assert.AreEqual(lang.Id, globalCached.Id); Assert.AreEqual("fr-FR", globalCached.IsoCode); Assert.IsNull(scopeProvider.AmbientScope); using (IScope scope = scopeProvider.CreateScope(repositoryCacheMode: RepositoryCacheMode.Scoped)) { Assert.IsInstanceOf<Scope>(scope); Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(scope, scopeProvider.AmbientScope); // scope has its own isolated cache IAppPolicyCache scopedCache = scope.IsolatedCaches.GetOrCreate(typeof(ILanguage)); Assert.AreNotSame(globalCache, scopedCache); // Use IsMandatory of isocode to ensure publishedContent cache is not also rebuild lang.IsMandatory = true; service.Save(lang); // scoped cache has been flushed, reload var scopeFullCached = (IEnumerable<ILanguage>)scopedCache.Get(GetCacheTypeKey<ILanguage>(), () => null); Assert.IsNull(scopeFullCached); reload = service.GetLanguageById(lang.Id); // scoped cache contains the "new" entity scopeFullCached = (IEnumerable<ILanguage>)scopedCache.Get(GetCacheTypeKey<ILanguage>(), () => null); Assert.IsNotNull(scopeFullCached); ILanguage scopeCached = scopeFullCached.First(x => x.Id == lang.Id); Assert.IsNotNull(scopeCached); Assert.AreEqual(lang.Id, scopeCached.Id); Assert.AreEqual(true, scopeCached.IsMandatory); // global cache is unchanged globalFullCached = (IEnumerable<ILanguage>)globalCache.Get(GetCacheTypeKey<ILanguage>(), () => null); Assert.IsNotNull(globalFullCached); globalCached = globalFullCached.First(x => x.Id == lang.Id); Assert.IsNotNull(globalCached); Assert.AreEqual(lang.Id, globalCached.Id); Assert.AreEqual(false, globalCached.IsMandatory); if (complete) { scope.Complete(); } } Assert.IsNull(scopeProvider.AmbientScope); globalFullCached = (IEnumerable<ILanguage>)globalCache.Get(GetCacheTypeKey<ILanguage>(), () => null); if (complete) { // global cache has been cleared Assert.IsNull(globalFullCached); } else { // global cache has *not* been cleared Assert.IsNotNull(globalFullCached); } // get again, updated if completed lang = service.GetLanguageById(lang.Id); Assert.AreEqual(complete ? true : false, lang.IsMandatory); // global cache contains the entity again globalFullCached = (IEnumerable<ILanguage>)globalCache.Get(GetCacheTypeKey<ILanguage>(), () => null); Assert.IsNotNull(globalFullCached); globalCached = globalFullCached.First(x => x.Id == lang.Id); Assert.IsNotNull(globalCached); Assert.AreEqual(lang.Id, globalCached.Id); Assert.AreEqual(complete ? true : false, lang.IsMandatory); } [TestCase(true)] [TestCase(false)] public void SingleItemsOnlyRepositoryCachePolicy(bool complete) { var scopeProvider = (ScopeProvider)ScopeProvider; ILocalizationService service = LocalizationService; IAppPolicyCache globalCache = AppCaches.IsolatedCaches.GetOrCreate(typeof(IDictionaryItem)); var lang = (ILanguage)new Language(GlobalSettings, "fr-FR"); service.Save(lang); var item = (IDictionaryItem)new DictionaryItem("item-key"); item.Translations = new IDictionaryTranslation[] { new DictionaryTranslation(lang.Id, "item-value"), }; service.Save(item); // Refresh the cache manually because we can't unbind service.GetDictionaryItemById(item.Id); service.GetLanguageById(lang.Id); // global cache contains the entity var globalCached = (IDictionaryItem)globalCache.Get(GetCacheIdKey<IDictionaryItem>(item.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(item.Id, globalCached.Id); Assert.AreEqual("item-key", globalCached.ItemKey); Assert.IsNull(scopeProvider.AmbientScope); using (IScope scope = scopeProvider.CreateScope(repositoryCacheMode: RepositoryCacheMode.Scoped)) { Assert.IsInstanceOf<Scope>(scope); Assert.IsNotNull(scopeProvider.AmbientScope); Assert.AreSame(scope, scopeProvider.AmbientScope); // scope has its own isolated cache IAppPolicyCache scopedCache = scope.IsolatedCaches.GetOrCreate(typeof(IDictionaryItem)); Assert.AreNotSame(globalCache, scopedCache); item.ItemKey = "item-changed"; service.Save(item); // scoped cache contains the "new" entity var scopeCached = (IDictionaryItem)scopedCache.Get(GetCacheIdKey<IDictionaryItem>(item.Id), () => null); Assert.IsNotNull(scopeCached); Assert.AreEqual(item.Id, scopeCached.Id); Assert.AreEqual("item-changed", scopeCached.ItemKey); // global cache is unchanged globalCached = (IDictionaryItem)globalCache.Get(GetCacheIdKey<IDictionaryItem>(item.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(item.Id, globalCached.Id); Assert.AreEqual("item-key", globalCached.ItemKey); if (complete) { scope.Complete(); } } Assert.IsNull(scopeProvider.AmbientScope); globalCached = (IDictionaryItem)globalCache.Get(GetCacheIdKey<IDictionaryItem>(item.Id), () => null); if (complete) { // global cache has been cleared Assert.IsNull(globalCached); } else { // global cache has *not* been cleared Assert.IsNotNull(globalCached); } // get again, updated if completed item = service.GetDictionaryItemById(item.Id); Assert.AreEqual(complete ? "item-changed" : "item-key", item.ItemKey); // global cache contains the entity again globalCached = (IDictionaryItem)globalCache.Get(GetCacheIdKey<IDictionaryItem>(item.Id), () => null); Assert.IsNotNull(globalCached); Assert.AreEqual(item.Id, globalCached.Id); Assert.AreEqual(complete ? "item-changed" : "item-key", globalCached.ItemKey); } public static string GetCacheIdKey<T>(object id) => $"{GetCacheTypeKey<T>()}{id}"; public static string GetCacheTypeKey<T>() => $"uRepo_{typeof(T).Name}_"; public class PassiveEventDispatcher : QueuingEventDispatcherBase { public PassiveEventDispatcher() : base(false) { } protected override void ScopeExitCompleted() { // do nothing } } public class LocalServerMessenger : ServerMessengerBase { public LocalServerMessenger() : base(false) { } public override void SendMessages() { } public override void Sync() { } protected override void DeliverRemote(ICacheRefresher refresher, MessageType messageType, IEnumerable<object> ids = null, string json = null) { } } } }
namespace android.widget { [global::MonoJavaBridge.JavaClass()] public partial class VideoView : android.view.SurfaceView, android.widget.MediaController.MediaPlayerControl { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; static VideoView() { InitJNI(); } protected VideoView(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } internal static global::MonoJavaBridge.MethodId _start12368; public virtual void start() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.VideoView._start12368); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.VideoView.staticClass, global::android.widget.VideoView._start12368); } internal static global::MonoJavaBridge.MethodId _suspend12369; public virtual void suspend() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.VideoView._suspend12369); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.VideoView.staticClass, global::android.widget.VideoView._suspend12369); } internal static global::MonoJavaBridge.MethodId _resume12370; public virtual void resume() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.VideoView._resume12370); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.VideoView.staticClass, global::android.widget.VideoView._resume12370); } internal static global::MonoJavaBridge.MethodId _onKeyDown12371; public override bool onKeyDown(int arg0, android.view.KeyEvent arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.VideoView._onKeyDown12371, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.VideoView.staticClass, global::android.widget.VideoView._onKeyDown12371, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _onTouchEvent12372; public override bool onTouchEvent(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.VideoView._onTouchEvent12372, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.VideoView.staticClass, global::android.widget.VideoView._onTouchEvent12372, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onTrackballEvent12373; public override bool onTrackballEvent(android.view.MotionEvent arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.VideoView._onTrackballEvent12373, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.VideoView.staticClass, global::android.widget.VideoView._onTrackballEvent12373, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _onMeasure12374; protected override void onMeasure(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.VideoView._onMeasure12374, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.VideoView.staticClass, global::android.widget.VideoView._onMeasure12374, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _getDuration12375; public virtual int getDuration() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.VideoView._getDuration12375); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.VideoView.staticClass, global::android.widget.VideoView._getDuration12375); } internal static global::MonoJavaBridge.MethodId _pause12376; public virtual void pause() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.VideoView._pause12376); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.VideoView.staticClass, global::android.widget.VideoView._pause12376); } internal static global::MonoJavaBridge.MethodId _isPlaying12377; public virtual bool isPlaying() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.VideoView._isPlaying12377); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.VideoView.staticClass, global::android.widget.VideoView._isPlaying12377); } internal static global::MonoJavaBridge.MethodId _seekTo12378; public virtual void seekTo(int arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.VideoView._seekTo12378, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.VideoView.staticClass, global::android.widget.VideoView._seekTo12378, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getCurrentPosition12379; public virtual int getCurrentPosition() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.VideoView._getCurrentPosition12379); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.VideoView.staticClass, global::android.widget.VideoView._getCurrentPosition12379); } internal static global::MonoJavaBridge.MethodId _setOnPreparedListener12380; public virtual void setOnPreparedListener(android.media.MediaPlayer.OnPreparedListener arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.VideoView._setOnPreparedListener12380, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.VideoView.staticClass, global::android.widget.VideoView._setOnPreparedListener12380, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setOnCompletionListener12381; public virtual void setOnCompletionListener(android.media.MediaPlayer.OnCompletionListener arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.VideoView._setOnCompletionListener12381, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.VideoView.staticClass, global::android.widget.VideoView._setOnCompletionListener12381, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setOnErrorListener12382; public virtual void setOnErrorListener(android.media.MediaPlayer.OnErrorListener arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.VideoView._setOnErrorListener12382, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.VideoView.staticClass, global::android.widget.VideoView._setOnErrorListener12382, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _getBufferPercentage12383; public virtual int getBufferPercentage() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.VideoView._getBufferPercentage12383); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.VideoView.staticClass, global::android.widget.VideoView._getBufferPercentage12383); } internal static global::MonoJavaBridge.MethodId _canPause12384; public virtual bool canPause() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.VideoView._canPause12384); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.VideoView.staticClass, global::android.widget.VideoView._canPause12384); } internal static global::MonoJavaBridge.MethodId _canSeekBackward12385; public virtual bool canSeekBackward() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.VideoView._canSeekBackward12385); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.VideoView.staticClass, global::android.widget.VideoView._canSeekBackward12385); } internal static global::MonoJavaBridge.MethodId _canSeekForward12386; public virtual bool canSeekForward() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.VideoView._canSeekForward12386); else return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.VideoView.staticClass, global::android.widget.VideoView._canSeekForward12386); } internal static global::MonoJavaBridge.MethodId _resolveAdjustedSize12387; public virtual int resolveAdjustedSize(int arg0, int arg1) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) return @__env.CallIntMethod(this.JvmHandle, global::android.widget.VideoView._resolveAdjustedSize12387, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); else return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.VideoView.staticClass, global::android.widget.VideoView._resolveAdjustedSize12387, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } internal static global::MonoJavaBridge.MethodId _setVideoPath12388; public virtual void setVideoPath(java.lang.String arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.VideoView._setVideoPath12388, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.VideoView.staticClass, global::android.widget.VideoView._setVideoPath12388, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _setVideoURI12389; public virtual void setVideoURI(android.net.Uri arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.VideoView._setVideoURI12389, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.VideoView.staticClass, global::android.widget.VideoView._setVideoURI12389, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _stopPlayback12390; public virtual void stopPlayback() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.VideoView._stopPlayback12390); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.VideoView.staticClass, global::android.widget.VideoView._stopPlayback12390); } internal static global::MonoJavaBridge.MethodId _setMediaController12391; public virtual void setMediaController(android.widget.MediaController arg0) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (!IsClrObject) @__env.CallVoidMethod(this.JvmHandle, global::android.widget.VideoView._setMediaController12391, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); else @__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.VideoView.staticClass, global::android.widget.VideoView._setMediaController12391, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } internal static global::MonoJavaBridge.MethodId _VideoView12392; public VideoView(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.VideoView.staticClass, global::android.widget.VideoView._VideoView12392, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _VideoView12393; public VideoView(android.content.Context arg0, android.util.AttributeSet arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.VideoView.staticClass, global::android.widget.VideoView._VideoView12393, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); Init(@__env, handle); } internal static global::MonoJavaBridge.MethodId _VideoView12394; public VideoView(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.VideoView.staticClass, global::android.widget.VideoView._VideoView12394, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static void InitJNI() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::android.widget.VideoView.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/VideoView")); global::android.widget.VideoView._start12368 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "start", "()V"); global::android.widget.VideoView._suspend12369 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "suspend", "()V"); global::android.widget.VideoView._resume12370 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "resume", "()V"); global::android.widget.VideoView._onKeyDown12371 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "onKeyDown", "(ILandroid/view/KeyEvent;)Z"); global::android.widget.VideoView._onTouchEvent12372 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "onTouchEvent", "(Landroid/view/MotionEvent;)Z"); global::android.widget.VideoView._onTrackballEvent12373 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "onTrackballEvent", "(Landroid/view/MotionEvent;)Z"); global::android.widget.VideoView._onMeasure12374 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "onMeasure", "(II)V"); global::android.widget.VideoView._getDuration12375 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "getDuration", "()I"); global::android.widget.VideoView._pause12376 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "pause", "()V"); global::android.widget.VideoView._isPlaying12377 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "isPlaying", "()Z"); global::android.widget.VideoView._seekTo12378 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "seekTo", "(I)V"); global::android.widget.VideoView._getCurrentPosition12379 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "getCurrentPosition", "()I"); global::android.widget.VideoView._setOnPreparedListener12380 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "setOnPreparedListener", "(Landroid/media/MediaPlayer$OnPreparedListener;)V"); global::android.widget.VideoView._setOnCompletionListener12381 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "setOnCompletionListener", "(Landroid/media/MediaPlayer$OnCompletionListener;)V"); global::android.widget.VideoView._setOnErrorListener12382 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "setOnErrorListener", "(Landroid/media/MediaPlayer$OnErrorListener;)V"); global::android.widget.VideoView._getBufferPercentage12383 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "getBufferPercentage", "()I"); global::android.widget.VideoView._canPause12384 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "canPause", "()Z"); global::android.widget.VideoView._canSeekBackward12385 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "canSeekBackward", "()Z"); global::android.widget.VideoView._canSeekForward12386 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "canSeekForward", "()Z"); global::android.widget.VideoView._resolveAdjustedSize12387 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "resolveAdjustedSize", "(II)I"); global::android.widget.VideoView._setVideoPath12388 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "setVideoPath", "(Ljava/lang/String;)V"); global::android.widget.VideoView._setVideoURI12389 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "setVideoURI", "(Landroid/net/Uri;)V"); global::android.widget.VideoView._stopPlayback12390 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "stopPlayback", "()V"); global::android.widget.VideoView._setMediaController12391 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "setMediaController", "(Landroid/widget/MediaController;)V"); global::android.widget.VideoView._VideoView12392 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V"); global::android.widget.VideoView._VideoView12393 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;I)V"); global::android.widget.VideoView._VideoView12394 = @__env.GetMethodIDNoThrow(global::android.widget.VideoView.staticClass, "<init>", "(Landroid/content/Context;)V"); } } }
/* * This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson, * the work of Kim Sheffield and the fyiReporting project. * * Prior Copyrights: * _________________________________________________________ * |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others| * | (http://reportfu.org) | * ========================================================= * _________________________________________________________ * |Copyright (C) 2004-2008 fyiReporting Software, LLC | * |For additional information, email info@fyireporting.com | * |or visit the website www.fyiReporting.com. | * ========================================================= * * License: * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.Windows.Forms; using System.Globalization; using System.Net; using System.Xml; namespace Reporting.RdlDesign { /// <summary> /// Control for providing a designer image of RDL. Works directly off the RDL XML. /// </summary> internal class DesignRuler : UserControl, System.ComponentModel.ISupportInitialize { DesignCtl _Design = null; bool _Vertical = false; int _Offset = 0; // offset to start with (in pixels) bool _IsMetric; int _Intervals; // Background colors for gradient static readonly Color BEGINCOLOR = Color.White; static readonly Color ENDCOLOR = Color.FromArgb(30, Color.LightSkyBlue); static readonly Color GAPCOLOR = Color.FromArgb(30, Color.LightSkyBlue); internal DesignRuler() : base() { // force to double buffering for smoother drawing this.DoubleBuffered = true; //editor = e; //editor.TextChanged += new System.EventHandler(editor_TextChanged); //editor.Resize += new System.EventHandler(editor_Resize); //editor.VScroll += new System.EventHandler(editor_VScroll); RegionInfo rinfo = new RegionInfo(CultureInfo.CurrentCulture.LCID); _IsMetric = rinfo.IsMetric; _Intervals = _IsMetric ? 4 : 8; this.Paint += new PaintEventHandler(DesignRulerPaint); } internal DesignCtl Design { get { return _Design; } set { _Design = value; if (_Design == null) return; if (_Vertical) { _Design.VerticalScrollChanged += new System.EventHandler(ScrollChanged); // need to know when the various heights change as well _Design.HeightChanged += new DesignCtl.HeightEventHandler(HeightChanged); } else _Design.HorizontalScrollChanged += new System.EventHandler(ScrollChanged); } } public bool Vertical { get { return _Vertical; } set { _Vertical = value; } } public int Offset { get { return _Offset; } set { _Offset = value; } } private int ScrollPosition { get { if (_Design == null) return 0; return _Vertical ? _Design.VerticalScrollPosition : _Design.HorizontalScrollPosition; } } private void DesignRulerPaint(object sender, System.Windows.Forms.PaintEventArgs e) { if (_Vertical) Ruler_DrawVert(e.Graphics); else Ruler_DrawHorz(e.Graphics); } private void HeightChanged(object sender, HeightEventArgs e) { if (e.Node != null) { // Only need to invalidate when the Body, PageHeader or PageFooter change height XmlNode p = e.Node.ParentNode; if (p != null && (p.Name == "Body" || p.Name == "PageHeader" || p.Name == "PageFooter")) { this.Invalidate(); } } } private void ScrollChanged(object sender, System.EventArgs e) { this.Invalidate(); } private void Ruler_DrawHorz(Graphics g) { float xoff, yoff, xinc; StringFormat drawFormat=null; Font f = null; LinearGradientBrush lgb=null; try { drawFormat = new StringFormat(); drawFormat.FormatFlags |= StringFormatFlags.NoWrap; drawFormat.Alignment = StringAlignment.Near; float mod; yoff = this.Height/2 -2; mod = g.DpiX; if (_IsMetric) mod = mod / 2.54f; xinc = mod / _Intervals; float scroll = ScrollPosition; if (scroll == 0) xoff = 0; else xoff = scroll + (xinc - scroll % xinc); RectangleF rf; if (Offset > 0) // Fill in the left gap; if any { rf = new RectangleF(0, 0, Offset, this.Height); if (rf.IntersectsWith(g.ClipBounds)) { lgb = new LinearGradientBrush(rf, BEGINCOLOR, ENDCOLOR, LinearGradientMode.ForwardDiagonal); g.FillRectangle(lgb, rf); lgb.Dispose(); lgb = null; // g.FillRectangle(new SolidBrush(GAPCOLOR), rf); } } // Fill in the background for the entire ruler rf = new RectangleF(this.Offset, 0, this.Width, this.Height); if (rf.IntersectsWith(g.ClipBounds)) { lgb = new LinearGradientBrush(rf, BEGINCOLOR, ENDCOLOR, LinearGradientMode.Vertical); g.FillRectangle(lgb, rf); lgb.Dispose(); lgb = null; } else // nothing to draw return; f = new Font("Arial", 8, FontStyle.Regular); // Loop thru and draw the ruler while (xoff - scroll < this.Width-Offset) { // if (xoff % mod < .001f ) if (xoff % mod < .1f || Math.Abs((xoff % mod) - mod) < .1f) { if (xoff != 0) // Don't draw the zero { string l = string.Format("{0:0}", xoff / mod); SizeF sz = g.MeasureString(l, f); g.DrawString(l, f, Brushes.Black, //Offset + xoff - ((sz.Width) / 2) - scroll, yoff - ((sz.Height) / 2), drawFormat); //Josh: Add 0.5 to the int before converting so that it's not rounded down. Offset + xoff - ((int)(sz.Width + 0.5f) / 2) + 1 - scroll, yoff - ((int)(sz.Height + 0.5f) / 2), drawFormat); } g.DrawLine(Pens.Black, Offset + xoff - scroll, this.Height, Offset + xoff - scroll, this.Height - 2); } else { g.DrawLine(Pens.Black, Offset + xoff - scroll, yoff, Offset + xoff - scroll, yoff + 2); } xoff += xinc; } } finally { if (lgb != null) lgb.Dispose(); if (drawFormat != null) drawFormat.Dispose(); if (f != null) f.Dispose(); } } private void Ruler_DrawVert(Graphics g) { StringFormat df = null; Font f = null; SolidBrush sb = null; // brush for non-ruler portions of ruler SolidBrush bb = null; // brush for drawing the areas next to band separator try { g.PageUnit = GraphicsUnit.Point; // create some drawing resources df = new StringFormat(); df.FormatFlags |= StringFormatFlags.NoWrap; df.Alignment = StringAlignment.Near; f = new Font("Arial", 8, FontStyle.Regular); sb = new SolidBrush(GAPCOLOR); bb = new SolidBrush(Design.SepColor); // Go thru the regions float sp = Design.PointsY(this.ScrollPosition); // 1) Offset RectangleF rf; float off = 0; float offset = Design.PointsY(this.Offset); float width = Design.PointsX(this.Width); if (this.Offset > 0) { rf = new RectangleF(0, 0, width, offset); // scrolling doesn't affect offset if (rf.IntersectsWith(g.ClipBounds)) { LinearGradientBrush lgb = new LinearGradientBrush(rf, BEGINCOLOR, ENDCOLOR, LinearGradientMode.ForwardDiagonal); g.FillRectangle(lgb, rf); lgb.Dispose(); lgb = null; // g.FillRectangle(sb, rf); } off = offset; } // 2) PageHeader if (Design.PageHeaderHeight > 0) { Ruler_DrawVertPart(g, f, df, off, Design.PageHeaderHeight); off += Design.PageHeaderHeight; } // 3) PageHeader separator rf = new RectangleF(0, off-sp, width, Design.SepHeight); if (rf.IntersectsWith(g.ClipBounds)) g.FillRectangle(bb, rf); off += Design.SepHeight; // 4) Body if (Design.BodyHeight > 0) { Ruler_DrawVertPart(g, f, df, off, Design.BodyHeight); off += Design.BodyHeight; } // 5) Body separator rf = new RectangleF(0, off - sp, width, Design.SepHeight); if (rf.IntersectsWith(g.ClipBounds)) g.FillRectangle(bb, rf); off += Design.SepHeight; // 6) PageFooter if (Design.PageFooterHeight > 0) { Ruler_DrawVertPart(g, f, df, off, Design.PageFooterHeight); off += Design.PageFooterHeight; } // 7) PageFooter separator rf = new RectangleF(0, off - sp, width, Design.SepHeight); if (rf.IntersectsWith(g.ClipBounds)) g.FillRectangle(bb, rf); off += Design.SepHeight; // 8) The rest to end rf = new RectangleF(0, off - sp, width, Design.PointsY(this.Height) - (off - sp)); if (rf.IntersectsWith(g.ClipBounds)) g.FillRectangle(sb, rf); } finally { if (df != null) df.Dispose(); if (f != null) f.Dispose(); if (sb != null) sb.Dispose(); if (bb != null) bb.Dispose(); } } private void Ruler_DrawVertPart(Graphics g, Font f, StringFormat df, float offset, float height) { float xoff, yoff, yinc, sinc; float mod; xoff = Design.PointsX(this.Width / 2 - 2); if (_IsMetric) mod = Design.PointsY(g.DpiY / 2.54f); else mod = Design.PointsY(g.DpiY); yinc = mod / _Intervals; float scroll = Design.PointsY(ScrollPosition); sinc = yoff = 0; if (scroll > offset) sinc += (yinc - scroll % yinc); // Fill in the background for the entire ruler // RectangleF rf = new RectangleF(0, yoff + offset - scroll, this.Width, height); RectangleF rf = new RectangleF(0, offset - scroll, Design.PointsX(this.Width), height); if (rf.IntersectsWith(g.ClipBounds)) { LinearGradientBrush lgb = new LinearGradientBrush(rf, BEGINCOLOR, ENDCOLOR, LinearGradientMode.Horizontal); g.FillRectangle(lgb, rf); lgb.Dispose(); } else return; // nothing to draw // Loop thru and draw the ruler float width = Design.PointsX(this.Width); while (sinc + offset + yoff - scroll < (offset + height) - scroll && sinc + offset + yoff - scroll < g.ClipBounds.Bottom) { if (sinc + offset + yoff - scroll < g.ClipBounds.Top - 20) { // we don't need to do anything here } else if (yoff % mod < .1f || Math.Abs((yoff % mod) - mod) < .1f) { if (yoff != 0) // Don't draw the 0 { string l = string.Format("{0:0}", yoff / mod); SizeF sz = g.MeasureString(l, f); g.DrawString(l, f, Brushes.Black, xoff - (sz.Width / 2), sinc+offset + yoff - (sz.Height / 2) - scroll, df); } g.DrawLine(Pens.Black, width, sinc + offset + yoff - scroll, width - 2, sinc+offset + yoff - scroll); } else { g.DrawLine(Pens.Black, xoff, sinc + offset + yoff - scroll, xoff + 2, sinc+offset + yoff - scroll); } yoff += yinc; } } #region ISupportInitialize Members void System.ComponentModel.ISupportInitialize.BeginInit() { return; } void System.ComponentModel.ISupportInitialize.EndInit() { return; } #endregion } }
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Elastic.Transport; using Elastic.Transport.Products; using Elastic.Transport.Products.Elasticsearch; namespace Elastic.Clients.Elasticsearch { /// <inheritdoc cref="IElasticsearchClientSettings" /> public class ElasticsearchClientSettings : ElasticsearchClientSettingsBase<ElasticsearchClientSettings> { /// <summary> /// A delegate used to construct a serializer to serialize CLR types representing documents and other types related to /// documents. /// By default, the internal serializer will be used to serializer all types. /// </summary> public delegate SourceSerializer SourceSerializerFactory(Serializer builtIn, IElasticsearchClientSettings values); /// <summary> The default user agent for Elastic.Clients.Elasticsearch </summary> public static readonly UserAgent DefaultUserAgent = Elastic.Transport.UserAgent.Create("elasticsearch-net", typeof(IElasticsearchClientSettings)); /// <summary> /// Creates a new instance of connection settings, if <paramref name="uri" /> is not specified will default to /// connecting to http://localhost:9200 /// </summary> /// <param name="uri"></param> public ElasticsearchClientSettings(Uri? uri = null) : this( new SingleNodePool(uri ?? new Uri("http://localhost:9200"))) { } /// <summary> /// Sets up the client to communicate to Elastic Cloud using <paramref name="cloudId" />, /// <para><see cref="CloudNodePool" /> documentation for more information on how to obtain your Cloud Id</para> /// </summary> public ElasticsearchClientSettings(string cloudId, IAuthenticationHeader credentials) : this( new CloudNodePool(cloudId, credentials)) { } /// <summary> /// Instantiate connection settings using a <see cref="SingleNodePool" /> using the provided /// <see cref="InMemoryConnection" /> that never uses any IO. /// </summary> public ElasticsearchClientSettings(InMemoryConnection connection) : this(new SingleNodePool(new Uri("http://localhost:9200")), connection) { } public ElasticsearchClientSettings(NodePool nodePool) : this(nodePool, null, null) { } public ElasticsearchClientSettings(NodePool nodePool, SourceSerializerFactory sourceSerializer) : this(nodePool, null, sourceSerializer) { } public ElasticsearchClientSettings(NodePool nodePool, ITransportClient connection) : this(nodePool, connection, null) { } public ElasticsearchClientSettings(NodePool nodePool, ITransportClient connection, SourceSerializerFactory sourceSerializer) : this( nodePool, connection, sourceSerializer, null) { } public ElasticsearchClientSettings( NodePool nodePool, ITransportClient connection, SourceSerializerFactory sourceSerializer, IPropertyMappingProvider propertyMappingProvider) : base(nodePool, connection, sourceSerializer, propertyMappingProvider) { } } /// <inheritdoc cref="IElasticsearchClientSettings" /> [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public abstract class ElasticsearchClientSettingsBase<TConnectionSettings> : ConnectionConfigurationBase<TConnectionSettings>, IElasticsearchClientSettings where TConnectionSettings : ElasticsearchClientSettingsBase<TConnectionSettings>, IElasticsearchClientSettings { private readonly FluentDictionary<Type, string> _defaultIndices; private readonly FluentDictionary<Type, string> _defaultRelationNames; private readonly HashSet<Type> _disableIdInference = new(); private readonly FluentDictionary<Type, string> _idProperties = new(); private readonly Inferrer _inferrer; private readonly IPropertyMappingProvider _propertyMappingProvider; private readonly FluentDictionary<MemberInfo, IPropertyMapping> _propertyMappings = new(); private readonly FluentDictionary<Type, string> _routeProperties = new(); private readonly Serializer _sourceSerializer; private bool _experimentalEnableSerializeNullInferredValues; private ExperimentalSettings _experimentalSettings = new (); private bool _defaultDisableAllInference; private Func<string, string> _defaultFieldNameInferrer; private string _defaultIndex; protected ElasticsearchClientSettingsBase( NodePool nodePool, ITransportClient connection, ElasticsearchClientSettings.SourceSerializerFactory? sourceSerializerFactory, IPropertyMappingProvider propertyMappingProvider) : base(nodePool, connection, null, ElasticsearchClientProductRegistration.DefaultForElasticsearchClientsElasticsearch) { var defaultSerializer = new DefaultRequestResponseSerializer(this); var sourceSerializer = sourceSerializerFactory?.Invoke(defaultSerializer, this) ?? new DefaultSourceSerializer(this); // TODO - Is the second condition ever true? _propertyMappingProvider = propertyMappingProvider ?? sourceSerializer as IPropertyMappingProvider ?? new PropertyMappingProvider(); // TODO - Serializer implementations should directly call diagnostics to avoid wrapping //We wrap these in an internal proxy to facilitate serialization diagnostics //_sourceSerializer = new DiagnosticsSerializerProxy(sourceSerializer, "source"); _sourceSerializer = sourceSerializer; //UseThisRequestResponseSerializer = new DiagnosticsSerializerProxy(defaultSerializer); UseThisRequestResponseSerializer = defaultSerializer; _defaultFieldNameInferrer = p => p.ToCamelCase(); _defaultIndices = new FluentDictionary<Type, string>(); _defaultRelationNames = new FluentDictionary<Type, string>(); _inferrer = new Inferrer(this); UserAgent(ElasticsearchClientSettings.DefaultUserAgent); } public Serializer SourceSerializer { get; } bool IElasticsearchClientSettings.DefaultDisableIdInference => _defaultDisableAllInference; Func<string, string> IElasticsearchClientSettings.DefaultFieldNameInferrer => _defaultFieldNameInferrer; string IElasticsearchClientSettings.DefaultIndex => _defaultIndex; FluentDictionary<Type, string> IElasticsearchClientSettings.DefaultIndices => _defaultIndices; HashSet<Type> IElasticsearchClientSettings.DisableIdInference => _disableIdInference; FluentDictionary<Type, string> IElasticsearchClientSettings.DefaultRelationNames => _defaultRelationNames; FluentDictionary<Type, string> IElasticsearchClientSettings.IdProperties => _idProperties; Inferrer IElasticsearchClientSettings.Inferrer => _inferrer; IPropertyMappingProvider IElasticsearchClientSettings.PropertyMappingProvider => _propertyMappingProvider; FluentDictionary<MemberInfo, IPropertyMapping> IElasticsearchClientSettings.PropertyMappings => _propertyMappings; FluentDictionary<Type, string> IElasticsearchClientSettings.RouteProperties => _routeProperties; Serializer IElasticsearchClientSettings.SourceSerializer => _sourceSerializer; ExperimentalSettings IElasticsearchClientSettings.Experimental => _experimentalSettings; bool IElasticsearchClientSettings.ExperimentalEnableSerializeNullInferredValues => _experimentalEnableSerializeNullInferredValues; /// <summary> /// The default index to use for a request when no index has been explicitly specified /// and no default indices are specified for the given CLR type specified for the request. /// </summary> public TConnectionSettings DefaultIndex(string defaultIndex) => Assign(defaultIndex, (a, v) => a._defaultIndex = v); /// <summary> /// Specifies how field names are inferred from CLR property names. /// <para></para> /// By default, Elastic.Clients.Elasticsearch camel cases property names. /// </summary> /// <example> /// CLR property EmailAddress will be inferred as "emailAddress" Elasticsearch document field name /// </example> public TConnectionSettings DefaultFieldNameInferrer(Func<string, string> fieldNameInferrer) => Assign(fieldNameInferrer, (a, v) => a._defaultFieldNameInferrer = v); public TConnectionSettings ExperimentalEnableSerializeNullInferredValues(bool enabled = true) => Assign(enabled, (a, v) => a._experimentalEnableSerializeNullInferredValues = v); public TConnectionSettings Experimental(ExperimentalSettings settings) => Assign(settings, (a, v) => a._experimentalSettings = v); /// <summary> /// Disables automatic Id inference for given CLR types. /// <para></para> /// Elastic.Clients.Elasticsearch by default will use the value of a property named Id on a CLR type as the _id to send to Elasticsearch. Adding /// a type /// will disable this behaviour for that CLR type. If Id inference should be disabled for all CLR types, use /// <see cref="DefaultDisableIdInference" /> /// </summary> public TConnectionSettings DefaultDisableIdInference(bool disable = true) => Assign(disable, (a, v) => a._defaultDisableAllInference = v); private void MapIdPropertyFor<TDocument>(Expression<Func<TDocument, object>> objectPath) { objectPath.ThrowIfNull(nameof(objectPath)); var memberInfo = new MemberInfoResolver(objectPath); var fieldName = memberInfo.Members.Single().Name; if (_idProperties.TryGetValue(typeof(TDocument), out var idPropertyFieldName)) { if (idPropertyFieldName.Equals(fieldName)) return; throw new ArgumentException( $"Cannot map '{fieldName}' as the id property for type '{typeof(TDocument).Name}': it already has '{_idProperties[typeof(TDocument)]}' mapped."); } _idProperties.Add(typeof(TDocument), fieldName); } /// <inheritdoc cref="IElasticsearchClientSettings.RouteProperties" /> private void MapRoutePropertyFor<TDocument>(Expression<Func<TDocument, object>> objectPath) { objectPath.ThrowIfNull(nameof(objectPath)); var memberInfo = new MemberInfoResolver(objectPath); var fieldName = memberInfo.Members.Single().Name; if (_routeProperties.TryGetValue(typeof(TDocument), out var routePropertyFieldName)) { if (routePropertyFieldName.Equals(fieldName)) return; throw new ArgumentException( $"Cannot map '{fieldName}' as the route property for type '{typeof(TDocument).Name}': it already has '{_routeProperties[typeof(TDocument)]}' mapped."); } _routeProperties.Add(typeof(TDocument), fieldName); } private void ApplyPropertyMappings<TDocument>(IList<IClrPropertyMapping<TDocument>> mappings) where TDocument : class { foreach (var mapping in mappings) { var e = mapping.Property; var memberInfoResolver = new MemberInfoResolver(e); if (memberInfoResolver.Members.Count > 1) throw new ArgumentException($"{nameof(ApplyPropertyMappings)} can only map direct properties"); if (memberInfoResolver.Members.Count == 0) throw new ArgumentException($"Expression {e} does contain any member access"); var memberInfo = memberInfoResolver.Members[0]; if (_propertyMappings.TryGetValue(memberInfo, out var propertyMapping)) { var newName = mapping.NewName; var mappedAs = propertyMapping.Name; var typeName = typeof(TDocument).Name; if (mappedAs.IsNullOrEmpty() && newName.IsNullOrEmpty()) throw new ArgumentException($"Property mapping '{e}' on type is already ignored"); if (mappedAs.IsNullOrEmpty()) throw new ArgumentException( $"Property mapping '{e}' on type {typeName} can not be mapped to '{newName}' it already has an ignore mapping"); if (newName.IsNullOrEmpty()) throw new ArgumentException( $"Property mapping '{e}' on type {typeName} can not be ignored it already has a mapping to '{mappedAs}'"); throw new ArgumentException( $"Property mapping '{e}' on type {typeName} can not be mapped to '{newName}' already mapped as '{mappedAs}'"); } _propertyMappings[memberInfo] = mapping.ToPropertyMapping(); } } /// <summary> /// Specify how the mapping is inferred for a given CLR type. /// The mapping can infer the index, id and relation name for a given CLR type, as well as control /// serialization behaviour for CLR properties. /// </summary> public TConnectionSettings DefaultMappingFor<TDocument>( Action<ClrTypeMappingDescriptor<TDocument>> selector) where TDocument : class { var inferMapping = new ClrTypeMappingDescriptor<TDocument>(); selector(inferMapping); if (!inferMapping._indexName.IsNullOrEmpty()) _defaultIndices[inferMapping._clrType] = inferMapping._indexName; if (!inferMapping._relationName.IsNullOrEmpty()) _defaultRelationNames[inferMapping._clrType] = inferMapping._relationName; if (!string.IsNullOrWhiteSpace(inferMapping._idProperty)) _idProperties[inferMapping._clrType] = inferMapping._idProperty; if (inferMapping._idPropertyExpression != null) MapIdPropertyFor(inferMapping._idPropertyExpression); if (inferMapping._routingPropertyExpression != null) MapRoutePropertyFor(inferMapping._routingPropertyExpression); if (inferMapping._properties != null) ApplyPropertyMappings(inferMapping._properties); if (inferMapping._disableIdInference) _disableIdInference.Add(inferMapping._clrType); else _disableIdInference.Remove(inferMapping._clrType); return (TConnectionSettings)this; } /// <summary> /// Specify how the mapping is inferred for a given CLR type. /// The mapping can infer the index and relation name for a given CLR type. /// </summary> public TConnectionSettings DefaultMappingFor(Type documentType, Action<ClrTypeMappingDescriptor> selector) { var inferMapping = new ClrTypeMappingDescriptor(documentType); selector(inferMapping); if (!inferMapping._indexName.IsNullOrEmpty()) _defaultIndices[inferMapping._clrType] = inferMapping._indexName; if (!inferMapping._relationName.IsNullOrEmpty()) _defaultRelationNames[inferMapping._clrType] = inferMapping._relationName; if (!string.IsNullOrWhiteSpace(inferMapping._idProperty)) _idProperties[inferMapping._clrType] = inferMapping._idProperty; return (TConnectionSettings)this; } /// <summary> /// Specify how the mapping is inferred for a given CLR type. /// The mapping can infer the index and relation name for a given CLR type. /// </summary> public TConnectionSettings DefaultMappingFor(IEnumerable<ClrTypeMapping> typeMappings) { if (typeMappings == null) return (TConnectionSettings)this; foreach (var inferMapping in typeMappings) { if (!inferMapping.IndexName.IsNullOrEmpty()) _defaultIndices[inferMapping.ClrType] = inferMapping.IndexName; if (!inferMapping.RelationName.IsNullOrEmpty()) _defaultRelationNames[inferMapping.ClrType] = inferMapping.RelationName; } return (TConnectionSettings)this; } } /// <inheritdoc cref="ITransportClientConfigurationValues" /> public class ConnectionConfiguration : ConnectionConfigurationBase<ConnectionConfiguration> { /// <summary> /// The default user agent for Elasticsearch.Net /// </summary> public static readonly UserAgent DefaultUserAgent = Elastic.Transport.UserAgent.Create("elasticsearch-net", typeof(ITransportConfiguration)); public ConnectionConfiguration(Uri uri = null) : this(new SingleNodePool(uri ?? new Uri("http://localhost:9200"))) { } public ConnectionConfiguration(InMemoryConnection connection) : this(new SingleNodePool(new Uri("http://localhost:9200")), connection) { } /// <summary> /// Sets up the client to communicate to Elastic Cloud using <paramref name="cloudId" />, /// <para><see cref="CloudNodePool" /> documentation for more information on how to obtain your Cloud Id</para> /// </summary> public ConnectionConfiguration(string cloudId, IAuthenticationHeader credentials) : this( new CloudNodePool(cloudId, credentials)) { } public ConnectionConfiguration(NodePool nodePool) : this(nodePool, null, null) { } public ConnectionConfiguration(NodePool nodePool, ITransportClient connection) : this(nodePool, connection, null) { } public ConnectionConfiguration(NodePool nodePool, Serializer serializer) : this( nodePool, null, serializer) { } public ConnectionConfiguration(NodePool nodePool, ITransportClient connection, Serializer serializer) : base(nodePool, connection, serializer) { } } /// <inheritdoc cref="ITransportClientConfigurationValues" /> [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public abstract class ConnectionConfigurationBase<TConnectionConfiguration> : TransportConfigurationBase<TConnectionConfiguration>, ITransportClientConfigurationValues where TConnectionConfiguration : ConnectionConfigurationBase<TConnectionConfiguration>, ITransportClientConfigurationValues { private bool _includeServerStackTraceOnError; protected ConnectionConfigurationBase(NodePool nodePool, ITransportClient connection, Serializer? serializer, IProductRegistration registration = null) : base(nodePool, connection, serializer, registration ?? new ElasticsearchProductRegistration(typeof(IElasticsearchClient))) => UserAgent(ConnectionConfiguration.DefaultUserAgent); bool ITransportClientConfigurationValues.IncludeServerStackTraceOnError => _includeServerStackTraceOnError; public override TConnectionConfiguration EnableDebugMode(Action<IApiCallDetails> onRequestCompleted = null) => base.EnableDebugMode(onRequestCompleted) .PrettyJson() .IncludeServerStackTraceOnError(); /// <summary> /// Forces all requests to have ?pretty=true querystring parameter appended, /// causing Elasticsearch to return formatted JSON. /// Defaults to <c>false</c> /// </summary> public override TConnectionConfiguration PrettyJson(bool b = true) => base.PrettyJson(b).UpdateGlobalQueryString("pretty", "true", b); /// <summary> /// Forces all requests to have ?error_trace=true querystring parameter appended, /// causing Elasticsearch to return stack traces as part of serialized exceptions /// Defaults to <c>false</c> /// </summary> public TConnectionConfiguration IncludeServerStackTraceOnError(bool b = true) => Assign(b, (a, v) => { a._includeServerStackTraceOnError = true; const string key = "error_trace"; UpdateGlobalQueryString(key, "true", v); }); } public interface ITransportClientConfigurationValues : ITransportConfiguration { /// <summary> /// Forces all requests to have ?error_trace=true querystring parameter appended, /// causing Elasticsearch to return stack traces as part of serialized exceptions /// Defaults to <c>false</c> /// </summary> bool IncludeServerStackTraceOnError { get; } } }
#region PDFsharp - A .NET library for processing PDF // // Authors: // Stefan Lange // // Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // 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 // Based on code from here: // http://archive.msdn.microsoft.com/SilverlightMD5/Release/ProjectReleases.aspx?ReleaseId=2206 // // ************************************************************** // * Raw implementation of the MD5 hash algorithm // * from RFC 1321. // * // * Written By: Reid Borsuk and Jenny Zheng // * Copyright (c) Microsoft Corporation. All rights reserved. // ************************************************************** using System; using System.Diagnostics; #if !NETFX_CORE && !UWP using System.Security.Cryptography; #endif // ReSharper disable InconsistentNaming #if SILVERLIGHT || WINDOWS_PHONE || UWP || (GDI && DEBUG) namespace PdfSharp.Pdf.Security { #if UWP class HashAlgorithm { public int HashSizeValue { get; set; } public virtual void Initialize() { } protected virtual void HashCore(byte[] array, int ibStart, int cbSize) { } protected virtual byte[] HashFinal() { return null; } public byte[] HashValue { get; set; } public void TransformBlock(byte[] a, int b, int c, byte[] d, int e) { } public void TransformFinalBlock(byte[] a, int b, int c) { } public byte[] ComputeHash(byte[] a) { return null; } public byte[] Hash { get { return null; } } } #endif /// <summary> /// A managed implementation of the MD5 algorithm. /// Necessary because MD5 is not part of the framework in Silverlight and WP. /// </summary> class MD5Managed //#if !UWP : HashAlgorithm // TODO: WinRT has not even a HashAlgorithm base class. //#endif { // Intitial values as defined in RFC 1321. const uint A = 0x67452301; const uint B = 0xefcdab89; const uint C = 0x98badcfe; const uint D = 0x10325476; public MD5Managed() { HashSizeValue = 128; Initialize(); } public sealed override void Initialize() { _data = new byte[64]; _dataSize = 0; _totalLength = 0; _abcd = new MD5Core.ABCDStruct(); // Intitial values as defined in RFC 1321. _abcd.A = A; _abcd.B = B; _abcd.C = C; _abcd.D = D; } protected override void HashCore(byte[] array, int ibStart, int cbSize) { int startIndex = ibStart; int totalArrayLength = _dataSize + cbSize; if (totalArrayLength >= 64) { Array.Copy(array, startIndex, _data, _dataSize, 64 - _dataSize); // Process message of 64 bytes (512 bits) MD5Core.GetHashBlock(_data, ref _abcd, 0); startIndex += 64 - _dataSize; totalArrayLength -= 64; while (totalArrayLength >= 64) { Array.Copy(array, startIndex, _data, 0, 64); MD5Core.GetHashBlock(array, ref _abcd, startIndex); totalArrayLength -= 64; startIndex += 64; } _dataSize = totalArrayLength; Array.Copy(array, startIndex, _data, 0, totalArrayLength); } else { Array.Copy(array, startIndex, _data, _dataSize, cbSize); _dataSize = totalArrayLength; } _totalLength += cbSize; } protected override byte[] HashFinal() { HashValue = MD5Core.GetHashFinalBlock(_data, 0, _dataSize, _abcd, _totalLength * 8); return HashValue; } byte[] _data; MD5Core.ABCDStruct _abcd; Int64 _totalLength; int _dataSize; static class MD5Core { #if true public static byte[] GetHash(byte[] input) { if (null == input) throw new ArgumentNullException("input"); // Intitial values defined in RFC 1321. ABCDStruct abcd = new ABCDStruct(); abcd.A = A; abcd.B = B; abcd.C = C; abcd.D = D; // We pass in the input array by block, the final block of data must be handled specially for padding & length embeding. int startIndex = 0; while (startIndex <= input.Length - 64) { GetHashBlock(input, ref abcd, startIndex); startIndex += 64; } // The final data block. return GetHashFinalBlock(input, startIndex, input.Length - startIndex, abcd, (Int64)input.Length * 8); } #endif internal static byte[] GetHashFinalBlock(byte[] input, int ibStart, int cbSize, ABCDStruct abcd, Int64 len) { byte[] working = new byte[64]; byte[] length = BitConverter.GetBytes(len); // Padding is a single bit 1, followed by the number of 0s required to make size congruent to 448 modulo 512. Step 1 of RFC 1321 // The CLR ensures that our buffer is 0-assigned, we don't need to explicitly set it. This is why it ends up being quicker to just // use a temporary array rather then doing in-place assignment (5% for small inputs) Array.Copy(input, ibStart, working, 0, cbSize); working[cbSize] = 0x80; // We have enough room to store the length in this chunk. if (cbSize <= 56) { Array.Copy(length, 0, working, 56, 8); GetHashBlock(working, ref abcd, 0); } else // We need an aditional chunk to store the length. { GetHashBlock(working, ref abcd, 0); // Create an entirely new chunk due to the 0-assigned trick mentioned above, to avoid an extra function call clearing the array. working = new byte[64]; Array.Copy(length, 0, working, 56, 8); GetHashBlock(working, ref abcd, 0); } byte[] output = new byte[16]; Array.Copy(BitConverter.GetBytes(abcd.A), 0, output, 0, 4); Array.Copy(BitConverter.GetBytes(abcd.B), 0, output, 4, 4); Array.Copy(BitConverter.GetBytes(abcd.C), 0, output, 8, 4); Array.Copy(BitConverter.GetBytes(abcd.D), 0, output, 12, 4); return output; } internal static void GetHashBlock(byte[] input, ref ABCDStruct ABCDValue, int ibStart) { uint[] temp = Converter(input, ibStart); uint a = ABCDValue.A; uint b = ABCDValue.B; uint c = ABCDValue.C; uint d = ABCDValue.D; a = r1(a, b, c, d, temp[0], 7, 0xd76aa478); d = r1(d, a, b, c, temp[1], 12, 0xe8c7b756); c = r1(c, d, a, b, temp[2], 17, 0x242070db); b = r1(b, c, d, a, temp[3], 22, 0xc1bdceee); a = r1(a, b, c, d, temp[4], 7, 0xf57c0faf); d = r1(d, a, b, c, temp[5], 12, 0x4787c62a); c = r1(c, d, a, b, temp[6], 17, 0xa8304613); b = r1(b, c, d, a, temp[7], 22, 0xfd469501); a = r1(a, b, c, d, temp[8], 7, 0x698098d8); d = r1(d, a, b, c, temp[9], 12, 0x8b44f7af); c = r1(c, d, a, b, temp[10], 17, 0xffff5bb1); b = r1(b, c, d, a, temp[11], 22, 0x895cd7be); a = r1(a, b, c, d, temp[12], 7, 0x6b901122); d = r1(d, a, b, c, temp[13], 12, 0xfd987193); c = r1(c, d, a, b, temp[14], 17, 0xa679438e); b = r1(b, c, d, a, temp[15], 22, 0x49b40821); a = r2(a, b, c, d, temp[1], 5, 0xf61e2562); d = r2(d, a, b, c, temp[6], 9, 0xc040b340); c = r2(c, d, a, b, temp[11], 14, 0x265e5a51); b = r2(b, c, d, a, temp[0], 20, 0xe9b6c7aa); a = r2(a, b, c, d, temp[5], 5, 0xd62f105d); d = r2(d, a, b, c, temp[10], 9, 0x02441453); c = r2(c, d, a, b, temp[15], 14, 0xd8a1e681); b = r2(b, c, d, a, temp[4], 20, 0xe7d3fbc8); a = r2(a, b, c, d, temp[9], 5, 0x21e1cde6); d = r2(d, a, b, c, temp[14], 9, 0xc33707d6); c = r2(c, d, a, b, temp[3], 14, 0xf4d50d87); b = r2(b, c, d, a, temp[8], 20, 0x455a14ed); a = r2(a, b, c, d, temp[13], 5, 0xa9e3e905); d = r2(d, a, b, c, temp[2], 9, 0xfcefa3f8); c = r2(c, d, a, b, temp[7], 14, 0x676f02d9); b = r2(b, c, d, a, temp[12], 20, 0x8d2a4c8a); a = r3(a, b, c, d, temp[5], 4, 0xfffa3942); d = r3(d, a, b, c, temp[8], 11, 0x8771f681); c = r3(c, d, a, b, temp[11], 16, 0x6d9d6122); b = r3(b, c, d, a, temp[14], 23, 0xfde5380c); a = r3(a, b, c, d, temp[1], 4, 0xa4beea44); d = r3(d, a, b, c, temp[4], 11, 0x4bdecfa9); c = r3(c, d, a, b, temp[7], 16, 0xf6bb4b60); b = r3(b, c, d, a, temp[10], 23, 0xbebfbc70); a = r3(a, b, c, d, temp[13], 4, 0x289b7ec6); d = r3(d, a, b, c, temp[0], 11, 0xeaa127fa); c = r3(c, d, a, b, temp[3], 16, 0xd4ef3085); b = r3(b, c, d, a, temp[6], 23, 0x04881d05); a = r3(a, b, c, d, temp[9], 4, 0xd9d4d039); d = r3(d, a, b, c, temp[12], 11, 0xe6db99e5); c = r3(c, d, a, b, temp[15], 16, 0x1fa27cf8); b = r3(b, c, d, a, temp[2], 23, 0xc4ac5665); a = r4(a, b, c, d, temp[0], 6, 0xf4292244); d = r4(d, a, b, c, temp[7], 10, 0x432aff97); c = r4(c, d, a, b, temp[14], 15, 0xab9423a7); b = r4(b, c, d, a, temp[5], 21, 0xfc93a039); a = r4(a, b, c, d, temp[12], 6, 0x655b59c3); d = r4(d, a, b, c, temp[3], 10, 0x8f0ccc92); c = r4(c, d, a, b, temp[10], 15, 0xffeff47d); b = r4(b, c, d, a, temp[1], 21, 0x85845dd1); a = r4(a, b, c, d, temp[8], 6, 0x6fa87e4f); d = r4(d, a, b, c, temp[15], 10, 0xfe2ce6e0); c = r4(c, d, a, b, temp[6], 15, 0xa3014314); b = r4(b, c, d, a, temp[13], 21, 0x4e0811a1); a = r4(a, b, c, d, temp[4], 6, 0xf7537e82); d = r4(d, a, b, c, temp[11], 10, 0xbd3af235); c = r4(c, d, a, b, temp[2], 15, 0x2ad7d2bb); b = r4(b, c, d, a, temp[9], 21, 0xeb86d391); ABCDValue.A = unchecked(a + ABCDValue.A); ABCDValue.B = unchecked(b + ABCDValue.B); ABCDValue.C = unchecked(c + ABCDValue.C); ABCDValue.D = unchecked(d + ABCDValue.D); } // Manually unrolling these equations nets us a 20% performance improvement private static uint r1(uint a, uint b, uint c, uint d, uint x, int s, uint t) { // (b + LSR((a + F(b, c, d) + x + t), s)) // F(x, y, z) ((x & y) | ((x ^ 0xFFFFFFFF) & z)) return unchecked(b + LSR((a + ((b & c) | ((b ^ 0xFFFFFFFF) & d)) + x + t), s)); } private static uint r2(uint a, uint b, uint c, uint d, uint x, int s, uint t) { // (b + LSR((a + G(b, c, d) + x + t), s)) // G(x, y, z) ((x & z) | (y & (z ^ 0xFFFFFFFF))) return unchecked(b + LSR((a + ((b & d) | (c & (d ^ 0xFFFFFFFF))) + x + t), s)); } private static uint r3(uint a, uint b, uint c, uint d, uint x, int s, uint t) { // (b + LSR((a + H(b, c, d) + k + i), s)) // H(x, y, z) (x ^ y ^ z) return unchecked(b + LSR((a + (b ^ c ^ d) + x + t), s)); } private static uint r4(uint a, uint b, uint c, uint d, uint x, int s, uint t) { // (b + LSR((a + I(b, c, d) + k + i), s)) // I(x, y, z) (y ^ (x | (z ^ 0xFFFFFFFF))) return unchecked(b + LSR((a + (c ^ (b | (d ^ 0xFFFFFFFF))) + x + t), s)); } // Implementation of left rotate // s is an int instead of a uint becuase the CLR requires the argument passed to >>/<< is of // type int. Doing the demoting inside this function would add overhead. private static uint LSR(uint i, int s) { return (i << s) | (i >> (32 - s)); } // Convert input array into array of UInts. static uint[] Converter(byte[] input, int ibStart) { if (null == input) throw new ArgumentNullException("input"); uint[] result = new uint[16]; for (int idx = 0; idx < 16; idx++) { result[idx] = (uint)input[ibStart + idx * 4]; result[idx] += (uint)input[ibStart + idx * 4 + 1] << 8; result[idx] += (uint)input[ibStart + idx * 4 + 2] << 16; result[idx] += (uint)input[ibStart + idx * 4 + 3] << 24; Debug.Assert(result[idx] == (input[ibStart + idx * 4]) + ((uint)input[ibStart + idx * 4 + 1] << 8) + ((uint)input[ibStart + idx * 4 + 2] << 16) + ((uint)input[ibStart + idx * 4 + 3] << 24)); } return result; } // Simple struct for the (a,b,c,d) which is used to compute the mesage digest. public struct ABCDStruct { public uint A; public uint B; public uint C; public uint D; } } } #if GDI && DEBUG && true_ // See here for details: http://archive.msdn.microsoft.com/SilverlightMD5/WorkItem/View.aspx?WorkItemId=3 public static class TestMD5 { public static void Test() { Random rnd = new Random(); for (int i = 0; i < 10000; i++) { int count = rnd.Next(1000) + 1; Console.WriteLine(String.Format("{0}: {1}", i, count)); Test2(count); } } static void Test2(int count) { byte[] bytes = new byte[count]; for (int idx = 0; idx < count; idx += 16) Array.Copy(Guid.NewGuid().ToByteArray(), 0, bytes, idx, Math.Min(16, count - idx)); MD5 md5dotNet = new MD5CryptoServiceProvider(); md5dotNet.Initialize(); MD5Managed md5m = new MD5Managed(); md5m.Initialize(); byte[] result1 = md5dotNet.ComputeHash(bytes); byte[] result2 = md5m.ComputeHash(bytes); if (!CompareBytes(result1, result2)) { count.GetType(); //throw new Exception("Bug in MD5Managed..."); } } static bool CompareBytes(byte[] bytes1, byte[] bytes2) { for (int idx = 0; idx < bytes1.Length; idx++) { if (bytes1[idx] != bytes2[idx]) return false; } return true; } } #endif } #endif
using System; using System.Security; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; using MS.Internal.PresentationCore; using System.Collections.Specialized ; using System.Windows.Input; using System.Diagnostics; using MS.Internal; namespace System.Windows { /// <summary> /// The container for all state associated /// with a RoutedEvent /// </summary> /// <remarks> /// <see cref="RoutedEventArgs"/> /// constitutes the <para/> /// <see cref="RoutedEventArgs.RoutedEvent"/>, <para/> /// <see cref="RoutedEventArgs.Handled"/>, <para/> /// <see cref="RoutedEventArgs.Source"/> and <para/> /// <see cref="RoutedEventArgs.OriginalSource"/> <para/> /// <para/> /// /// Different <see cref="RoutedEventArgs"/> /// can be used with a single <see cref="RoutedEvent"/> <para/> /// <para/> /// /// The <see cref="RoutedEventArgs"/> is responsible /// for packaging the <see cref="RoutedEvent"/>, /// providing extra event state info, and invoking the /// handler associated with the RoutedEvent /// </remarks> public class RoutedEventArgs : EventArgs { #region Construction /// <summary> /// Constructor for <see cref="RoutedEventArgs"/> /// </summary> /// <remarks> /// All members take default values <para/> /// <para/> /// /// <see cref="RoutedEventArgs.RoutedEvent"/> /// defaults to null <para/> /// <see cref="RoutedEventArgs.Handled"/> defaults to /// false <para/> /// <see cref="Source"/> defaults to null <para/> /// <see cref="OriginalSource"/> also defaults to null /// <para/> /// </remarks> public RoutedEventArgs() { } /// <summary> /// Constructor for <see cref="RoutedEventArgs"/> /// </summary> /// <param name="routedEvent">The new value that the RoutedEvent Property is being set to </param> public RoutedEventArgs(RoutedEvent routedEvent) : this( routedEvent, null) { } /// <summary> /// Constructor for <see cref="RoutedEventArgs"/> /// </summary> /// <param name="source">The new value that the SourceProperty is being set to </param> /// <param name="routedEvent">The new value that the RoutedEvent Property is being set to </param> public RoutedEventArgs(RoutedEvent routedEvent, object source) { _routedEvent = routedEvent; _source = _originalSource = source; } #endregion Construction #region External API /// <summary> /// Returns the <see cref="RoutedEvent"/> associated /// with this <see cref="RoutedEventArgs"/> /// </summary> /// <remarks> /// The <see cref="RoutedEvent"/> cannot be null /// at any time /// </remarks> public RoutedEvent RoutedEvent { get {return _routedEvent;} set { if (UserInitiated && InvokingHandler) throw new InvalidOperationException(SR.Get(SRID.RoutedEventCannotChangeWhileRouting)); _routedEvent = value; } } /// <summary> /// Changes the RoutedEvent assocatied with these RoutedEventArgs /// </summary> /// <remarks> /// Only used internally. Added to support cracking generic MouseButtonDown/Up events /// into MouseLeft/RightButtonDown/Up events. /// </remarks> /// <param name="newRoutedEvent"> /// The new RoutedEvent to associate with these RoutedEventArgs /// </param> internal void OverrideRoutedEvent( RoutedEvent newRoutedEvent ) { _routedEvent = newRoutedEvent; } /// <summary> /// Returns a boolean flag indicating if or not this /// RoutedEvent has been handled this far in the route /// </summary> /// <remarks> /// Initially starts with a false value before routing /// has begun /// </remarks> ///<SecurityNote> /// Critical - _flags is critical due to UserInitiated value. /// PublicOK - in this function we're not setting UserInitiated - we're setting Handled. ///</SecurityNote> public bool Handled { [SecurityCritical ] get { return _flags[ HandledIndex ] ; } [SecurityCritical ] set { if (_routedEvent == null) { throw new InvalidOperationException(SR.Get(SRID.RoutedEventArgsMustHaveRoutedEvent)); } if( TraceRoutedEvent.IsEnabled ) { TraceRoutedEvent.TraceActivityItem( TraceRoutedEvent.HandleEvent, value, RoutedEvent.OwnerType.Name, RoutedEvent.Name, this ); } // Note: We need to allow the caller to change the handled value // from true to false. // // We are concerned about scenarios where a child element // listens to a high-level event (such as TextInput) while a // parent element listens tp a low-level event such as KeyDown. // In these scenarios, we want the parent to not respond to the // KeyDown event, in deference to the child. // // Internally we implement this by asking the parent to only // respond to KeyDown events if they have focus. This works // around the problem and is an example of an unofficial // protocol coordinating the two elements. // // But we imagine that there will be some cases we miss or // that third parties introduce. For these cases, we expect // that the application author may need to mark the KeyDown // as handled in the child, and then reset the event to // being unhandled after the parent, so that default processing // and promotion still occur. // // For more information see the following task: // 20284: Input promotion breaks down when lower level input is intercepted _flags[ HandledIndex ] = value; } } /// <summary> /// Returns Source object that raised the RoutedEvent /// </summary> public object Source { get {return _source;} set { if (InvokingHandler && UserInitiated) throw new InvalidOperationException(SR.Get(SRID.RoutedEventCannotChangeWhileRouting)); if (_routedEvent == null) { throw new InvalidOperationException(SR.Get(SRID.RoutedEventArgsMustHaveRoutedEvent)); } object source = value ; if (_source == null && _originalSource == null) { // Gets here when it is the first time that the source is set. // This implies that this is also the original source of the event _source = _originalSource = source; OnSetSource(source); } else if (_source != source) { // This is the actiaon taken at all other times when the // source is being set to a different value from what it was _source = source; OnSetSource(source); } } } /// <summary> /// Changes the Source assocatied with these RoutedEventArgs /// </summary> /// <remarks> /// Only used internally. Added to support cracking generic MouseButtonDown/Up events /// into MouseLeft/RightButtonDown/Up events. /// </remarks> /// <param name="source"> /// The new object to associate as the source of these RoutedEventArgs /// </param> internal void OverrideSource( object source ) { _source = source; } /// <summary> /// Returns OriginalSource object that raised the RoutedEvent /// </summary> /// <remarks> /// Always returns the OriginalSource object that raised the /// RoutedEvent unlike <see cref="RoutedEventArgs.Source"/> /// that may vary under specific scenarios <para/> /// This property acquires its value once before the event /// handlers are invoked and never changes then on /// </remarks> public object OriginalSource { get {return _originalSource;} } /// <summary> /// Invoked when the source of the event is set /// </summary> /// <remarks> /// Changing the source of an event can often /// require updating the data within the event. /// For this reason, the OnSource= method is /// protected virtual and is meant to be /// overridden by sub-classes of /// <see cref="RoutedEventArgs"/> <para/> /// Also see <see cref="RoutedEventArgs.Source"/> /// </remarks> /// <param name="source"> /// The new value that the SourceProperty is being set to /// </param> protected virtual void OnSetSource(object source) { } /// <summary> /// Invokes the generic handler with the /// appropriate arguments /// </summary> /// <remarks> /// Is meant to be overridden by sub-classes of /// <see cref="RoutedEventArgs"/> to provide /// more efficient invocation of their delegate /// </remarks> /// <param name="genericHandler"> /// Generic Handler to be invoked /// </param> /// <param name="genericTarget"> /// Target on whom the Handler will be invoked /// </param> protected virtual void InvokeEventHandler(Delegate genericHandler, object genericTarget) { if (genericHandler == null) { throw new ArgumentNullException("genericHandler"); } if (genericTarget == null) { throw new ArgumentNullException("genericTarget"); } if (_routedEvent == null) { throw new InvalidOperationException(SR.Get(SRID.RoutedEventArgsMustHaveRoutedEvent)); } InvokingHandler = true; try { if (genericHandler is RoutedEventHandler) { ((RoutedEventHandler)genericHandler)(genericTarget, this); } else { // Restricted Action - reflection permission required genericHandler.DynamicInvoke(new object[] {genericTarget, this}); } } finally { InvokingHandler = false; } } #endregion External API #region Operations // Calls the InvokeEventHandler protected // virtual method // // This method is needed because // delegates are invoked from // RoutedEventHandler which is not a // sub-class of RoutedEventArgs // and hence cannot invoke protected // method RoutedEventArgs.FireEventHandler internal void InvokeHandler(Delegate handler, object target) { InvokingHandler = true; try { InvokeEventHandler(handler, target); } finally { InvokingHandler = false; } } ///<SecurityNote> /// Critical - access critical information, if this is a user initiated command /// TreatAsSafe - checking user initiated bit considered safe. ///</SecurityNote> internal bool UserInitiated { [SecurityCritical, SecurityTreatAsSafe ] [FriendAccessAllowed] // Also used by Framework. get { if (_flags [UserInitiatedIndex]) { return SecurityHelper.CallerHasUserInitiatedRoutedEventPermission(); } return false; } } /// <SecurityNote> /// Critical - access critical information, if this is a user initiated command /// </SecurityNote> [SecurityCritical] internal void MarkAsUserInitiated() { _flags [ UserInitiatedIndex ] = true; } /// <SecurityNote> /// Critical - access critical information, if this is a user initiated command /// TreatAsSafe - clearing user initiated bit considered safe. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe ] internal void ClearUserInitiated() { _flags [ UserInitiatedIndex ] = false ; } ///<SecurityNote> /// Critical - _flags is critical due to UserInitiated value. /// TreatAsSafe - in this function we're not setting UserInitiated - we're setting InvokingHandler. ///</SecurityNote> private bool InvokingHandler { [SecurityCritical, SecurityTreatAsSafe ] get { return _flags[InvokingHandlerIndex]; } [SecurityCritical, SecurityTreatAsSafe ] set { _flags[InvokingHandlerIndex] = value; } } #endregion Operations #region Data private RoutedEvent _routedEvent; private object _source; private object _originalSource; ///<SecurityNote> /// Critical - the UserInitiated flag value is critical. ///</SecurityNote> [SecurityCritical] private BitVector32 _flags; private const int HandledIndex = 1; private const int UserInitiatedIndex = 2; private const int InvokingHandlerIndex = 4; #endregion Data } /// <summary> /// RoutedEventHandler Definition /// </summary> /// <ExternalAPI/> public delegate void RoutedEventHandler(object sender, RoutedEventArgs e); }
using System; using System.IO; using System.CodeDom; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Specialized; using System.Reflection; using Microsoft.Samples.CodeDomTestSuite; public class TryCatchTest : CodeDomTestTree { public override TestTypes TestType { get { return TestTypes.Everett; } } public override bool ShouldVerify { get { return true; } } public override bool ShouldCompile { get { return true; } } public override string Name { get { return "TryCatchTest"; } } public override string Description { get { return "Tests try/catch/finally statements."; } } public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) { // create a namespace CodeNamespace ns = new CodeNamespace ("NS"); ns.Imports.Add (new CodeNamespaceImport ("System")); cu.Namespaces.Add (ns); // create a class CodeTypeDeclaration class1 = new CodeTypeDeclaration (); class1.Name = "Test"; class1.IsClass = true; ns.Types.Add (class1); if (Supports (provider, GeneratorSupport.TryCatchStatements)) { // try catch statement with just finally // GENERATE (C#): // public static int FirstScenario(int a) { // try { // } // finally { // a = (a + 5); // } // return a; // } AddScenario ("CheckFirstScenario"); CodeMemberMethod cmm = new CodeMemberMethod (); cmm.Name = "FirstScenario"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression (typeof (int), "a"); cmm.Parameters.Add (param); CodeTryCatchFinallyStatement tcfstmt = new CodeTryCatchFinallyStatement (); tcfstmt.FinallyStatements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("a"), new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("a"), CodeBinaryOperatorType.Add, new CodePrimitiveExpression (5)))); cmm.Statements.Add (tcfstmt); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a"))); class1.Members.Add (cmm); // in VB (a = a/a) generates an warning if a is integer. Cast the expression just for VB language. CodeBinaryOperatorExpression cboExpression = new CodeBinaryOperatorExpression (new CodeArgumentReferenceExpression ("a"), CodeBinaryOperatorType.Divide, new CodeArgumentReferenceExpression ("a")); CodeAssignStatement assignStatement = null; if (provider is Microsoft.VisualBasic.VBCodeProvider) assignStatement = new CodeAssignStatement (new CodeArgumentReferenceExpression ("a"), new CodeCastExpression (typeof (int), cboExpression)); else assignStatement = new CodeAssignStatement (new CodeArgumentReferenceExpression ("a"), cboExpression); // try catch statement with just catch // GENERATE (C#): // public static int SecondScenario(int a, string exceptionMessage) { // try { // a = (a / a); // } // catch (System.Exception e) { // a = 3; // exceptionMessage = e.ToString(); // } // finally { // a = (a + 1); // } // return a; // } AddScenario ("CheckSecondScenario"); cmm = new CodeMemberMethod (); cmm.Name = "SecondScenario"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; param = new CodeParameterDeclarationExpression (typeof (int), "a"); cmm.Parameters.Add (param); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (String), "exceptionMessage")); tcfstmt = new CodeTryCatchFinallyStatement (); CodeCatchClause catchClause = new CodeCatchClause ("e"); tcfstmt.TryStatements.Add (assignStatement); catchClause.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("a"), new CodePrimitiveExpression (3))); catchClause.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("exceptionMessage"), new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("e"), "ToString"))); tcfstmt.CatchClauses.Add (catchClause); tcfstmt.FinallyStatements.Add (CDHelper.CreateIncrementByStatement (new CodeArgumentReferenceExpression ("a"), 1)); cmm.Statements.Add (tcfstmt); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a"))); class1.Members.Add (cmm); // try catch statement with multiple catches // GENERATE (C#): // public static int ThirdScenario(int a, string exceptionMessage) { // try { // a = (a / a); // } // catch (System.ArgumentNullException e) { // a = 10; // exceptionMessage = e.ToString(); // } // catch (System.DivideByZeroException f) { // exceptionMessage = f.ToString(); // a = 9; // } // return a; // } AddScenario ("CheckThirdScenario"); cmm = new CodeMemberMethod (); cmm.Name = "ThirdScenario"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; param = new CodeParameterDeclarationExpression (typeof (int), "a"); cmm.Parameters.Add (param); cmm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (String), "exceptionMessage")); tcfstmt = new CodeTryCatchFinallyStatement (); catchClause = new CodeCatchClause ("e", new CodeTypeReference (typeof (ArgumentNullException))); tcfstmt.TryStatements.Add (assignStatement); catchClause.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("a"), new CodePrimitiveExpression (9))); catchClause.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("exceptionMessage"), new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("e"), "ToString"))); tcfstmt.CatchClauses.Add (catchClause); // add a second catch clause catchClause = new CodeCatchClause ("f", new CodeTypeReference (typeof (Exception))); catchClause.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("exceptionMessage"), new CodeMethodInvokeExpression (new CodeVariableReferenceExpression ("f"), "ToString"))); catchClause.Statements.Add (new CodeAssignStatement (new CodeArgumentReferenceExpression ("a"), new CodePrimitiveExpression (9))); tcfstmt.CatchClauses.Add (catchClause); cmm.Statements.Add (tcfstmt); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a"))); class1.Members.Add (cmm); // catch throws exception // GENERATE (C#): // public static int FourthScenario(int a) { // try { // a = (a / a); // } // catch (System.Exception e) { // // Error handling // throw e; // } // return a; // } AddScenario ("CheckFourthScenario"); cmm = new CodeMemberMethod (); cmm.Name = "FourthScenario"; cmm.ReturnType = new CodeTypeReference (typeof (int)); cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static; param = new CodeParameterDeclarationExpression (typeof (int), "a"); cmm.Parameters.Add (param); tcfstmt = new CodeTryCatchFinallyStatement (); catchClause = new CodeCatchClause ("e"); tcfstmt.TryStatements.Add (assignStatement); catchClause.Statements.Add (new CodeCommentStatement ("Error handling")); catchClause.Statements.Add (new CodeThrowExceptionStatement (new CodeArgumentReferenceExpression ("e"))); tcfstmt.CatchClauses.Add (catchClause); cmm.Statements.Add (tcfstmt); cmm.Statements.Add (new CodeMethodReturnStatement (new CodeArgumentReferenceExpression ("a"))); class1.Members.Add (cmm); } } public override void VerifyAssembly (CodeDomProvider provider, Assembly asm) { if (Supports (provider, GeneratorSupport.TryCatchStatements)) { object genObject; Type genType; AddScenario ("InstantiateTest", "Find and instantiate Test."); if (!FindAndInstantiate ("NS.Test", asm, out genObject, out genType)) return; VerifyScenario ("InstantiateTest"); // verify method return value // verifying first scenario if (VerifyMethod (genType, genObject, "FirstScenario", new object[]{1}, 6) && VerifyMethod (genType, genObject, "FirstScenario", new object[]{10}, 15)) { VerifyScenario ("CheckFirstScenario"); } // verify second scenario return method if (VerifyMethod (genType, genObject, "SecondScenario", new object[]{0, "hi"}, 4) && VerifyMethod (genType, genObject, "SecondScenario", new object[]{10, "hi"}, 2)) { VerifyScenario ("CheckSecondScenario"); } // verify third scenario return method if (VerifyMethod (genType, genObject, "ThirdScenario", new object[]{0, "hi"}, 9)) { VerifyScenario ("CheckThirdScenario"); } // verify fourth scenario return method if (VerifyException (genType, genObject, "FourthScenario", new object[]{0}, new System.Reflection.TargetInvocationException (new DivideByZeroException ())) && VerifyMethod (genType, genObject, "FourthScenario", new object[]{10}, 1)) { VerifyScenario ("CheckFourthScenario"); } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V8.Resources { /// <summary>Resource name for the <c>DomainCategory</c> resource.</summary> public sealed partial class DomainCategoryName : gax::IResourceName, sys::IEquatable<DomainCategoryName> { /// <summary>The possible contents of <see cref="DomainCategoryName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c>. /// </summary> CustomerCampaignBase64CategoryLanguageCode = 1, } private static gax::PathTemplate s_customerCampaignBase64CategoryLanguageCode = new gax::PathTemplate("customers/{customer_id}/domainCategories/{campaign_id_base64_category_language_code}"); /// <summary>Creates a <see cref="DomainCategoryName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="DomainCategoryName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static DomainCategoryName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new DomainCategoryName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="DomainCategoryName"/> with the pattern /// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="base64CategoryId">The <c>Base64Category</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="languageCodeId">The <c>LanguageCode</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="DomainCategoryName"/> constructed from the provided ids.</returns> public static DomainCategoryName FromCustomerCampaignBase64CategoryLanguageCode(string customerId, string campaignId, string base64CategoryId, string languageCodeId) => new DomainCategoryName(ResourceNameType.CustomerCampaignBase64CategoryLanguageCode, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), base64CategoryId: gax::GaxPreconditions.CheckNotNullOrEmpty(base64CategoryId, nameof(base64CategoryId)), languageCodeId: gax::GaxPreconditions.CheckNotNullOrEmpty(languageCodeId, nameof(languageCodeId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="DomainCategoryName"/> with pattern /// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="base64CategoryId">The <c>Base64Category</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="languageCodeId">The <c>LanguageCode</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="DomainCategoryName"/> with pattern /// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c>. /// </returns> public static string Format(string customerId, string campaignId, string base64CategoryId, string languageCodeId) => FormatCustomerCampaignBase64CategoryLanguageCode(customerId, campaignId, base64CategoryId, languageCodeId); /// <summary> /// Formats the IDs into the string representation of this <see cref="DomainCategoryName"/> with pattern /// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="base64CategoryId">The <c>Base64Category</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="languageCodeId">The <c>LanguageCode</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="DomainCategoryName"/> with pattern /// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c>. /// </returns> public static string FormatCustomerCampaignBase64CategoryLanguageCode(string customerId, string campaignId, string base64CategoryId, string languageCodeId) => s_customerCampaignBase64CategoryLanguageCode.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(base64CategoryId, nameof(base64CategoryId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(languageCodeId, nameof(languageCodeId)))}"); /// <summary> /// Parses the given resource name string into a new <see cref="DomainCategoryName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="domainCategoryName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="DomainCategoryName"/> if successful.</returns> public static DomainCategoryName Parse(string domainCategoryName) => Parse(domainCategoryName, false); /// <summary> /// Parses the given resource name string into a new <see cref="DomainCategoryName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="domainCategoryName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="DomainCategoryName"/> if successful.</returns> public static DomainCategoryName Parse(string domainCategoryName, bool allowUnparsed) => TryParse(domainCategoryName, allowUnparsed, out DomainCategoryName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="DomainCategoryName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c> /// </description> /// </item> /// </list> /// </remarks> /// <param name="domainCategoryName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="DomainCategoryName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string domainCategoryName, out DomainCategoryName result) => TryParse(domainCategoryName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="DomainCategoryName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description> /// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c> /// </description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="domainCategoryName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="DomainCategoryName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string domainCategoryName, bool allowUnparsed, out DomainCategoryName result) { gax::GaxPreconditions.CheckNotNull(domainCategoryName, nameof(domainCategoryName)); gax::TemplatedResourceName resourceName; if (s_customerCampaignBase64CategoryLanguageCode.TryParseName(domainCategoryName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerCampaignBase64CategoryLanguageCode(resourceName[0], split1[0], split1[1], split1[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(domainCategoryName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private DomainCategoryName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string base64CategoryId = null, string campaignId = null, string customerId = null, string languageCodeId = null) { Type = type; UnparsedResource = unparsedResourceName; Base64CategoryId = base64CategoryId; CampaignId = campaignId; CustomerId = customerId; LanguageCodeId = languageCodeId; } /// <summary> /// Constructs a new instance of a <see cref="DomainCategoryName"/> class from the component parts of pattern /// <c>customers/{customer_id}/domainCategories/{campaign_id}~{base64_category}~{language_code}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="base64CategoryId">The <c>Base64Category</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="languageCodeId">The <c>LanguageCode</c> ID. Must not be <c>null</c> or empty.</param> public DomainCategoryName(string customerId, string campaignId, string base64CategoryId, string languageCodeId) : this(ResourceNameType.CustomerCampaignBase64CategoryLanguageCode, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), base64CategoryId: gax::GaxPreconditions.CheckNotNullOrEmpty(base64CategoryId, nameof(base64CategoryId)), languageCodeId: gax::GaxPreconditions.CheckNotNullOrEmpty(languageCodeId, nameof(languageCodeId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Base64Category</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string Base64CategoryId { get; } /// <summary> /// The <c>Campaign</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CampaignId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>LanguageCode</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string LanguageCodeId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerCampaignBase64CategoryLanguageCode: return s_customerCampaignBase64CategoryLanguageCode.Expand(CustomerId, $"{CampaignId}~{Base64CategoryId}~{LanguageCodeId}"); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as DomainCategoryName); /// <inheritdoc/> public bool Equals(DomainCategoryName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(DomainCategoryName a, DomainCategoryName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(DomainCategoryName a, DomainCategoryName b) => !(a == b); } public partial class DomainCategory { /// <summary> /// <see cref="DomainCategoryName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal DomainCategoryName ResourceNameAsDomainCategoryName { get => string.IsNullOrEmpty(ResourceName) ? null : DomainCategoryName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="CampaignName"/>-typed view over the <see cref="Campaign"/> resource name property. /// </summary> internal CampaignName CampaignAsCampaignName { get => string.IsNullOrEmpty(Campaign) ? null : CampaignName.Parse(Campaign, allowUnparsed: true); set => Campaign = value?.ToString() ?? ""; } } }
//--------------------------------------------------------------------------- // // <copyright file="Transform3DCollection.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // This file was generated, please do not edit it directly. // // Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information. // //--------------------------------------------------------------------------- using MS.Internal; using MS.Internal.Collections; using MS.Internal.PresentationCore; using MS.Utility; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Windows.Markup; using System.Windows.Media.Media3D.Converters; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using System.Security; using System.Security.Permissions; using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; using System.Windows.Media.Imaging; // These types are aliased to match the unamanaged names used in interop using BOOL = System.UInt32; using WORD = System.UInt16; using Float = System.Single; namespace System.Windows.Media.Media3D { /// <summary> /// A collection of Transform3D objects. /// </summary> public sealed partial class Transform3DCollection : Animatable, IList, IList<Transform3D> { //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Shadows inherited Clone() with a strongly typed /// version for convenience. /// </summary> public new Transform3DCollection Clone() { return (Transform3DCollection)base.Clone(); } /// <summary> /// Shadows inherited CloneCurrentValue() with a strongly typed /// version for convenience. /// </summary> public new Transform3DCollection CloneCurrentValue() { return (Transform3DCollection)base.CloneCurrentValue(); } #endregion Public Methods //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region IList<T> /// <summary> /// Adds "value" to the list /// </summary> public void Add(Transform3D value) { AddHelper(value); } /// <summary> /// Removes all elements from the list /// </summary> public void Clear() { WritePreamble(); // As part of Clear()'ing the collection, we will iterate it and call // OnFreezablePropertyChanged and OnRemove for each item. // However, OnRemove assumes that the item to be removed has already been // pulled from the underlying collection. To statisfy this condition, // we store the old collection and clear _collection before we call these methods. // As Clear() semantics do not include TrimToFit behavior, we create the new // collection storage at the same size as the previous. This is to provide // as close as possible the same perf characteristics as less complicated collections. FrugalStructList<Transform3D> oldCollection = _collection; _collection = new FrugalStructList<Transform3D>(_collection.Capacity); for (int i = oldCollection.Count - 1; i >= 0; i--) { OnFreezablePropertyChanged(/* oldValue = */ oldCollection[i], /* newValue = */ null); // Fire the OnRemove handlers for each item. We're not ensuring that // all OnRemove's get called if a resumable exception is thrown. // At this time, these call-outs are not public, so we do not handle exceptions. OnRemove( /* oldValue */ oldCollection[i]); } ++_version; WritePostscript(); } /// <summary> /// Determines if the list contains "value" /// </summary> public bool Contains(Transform3D value) { ReadPreamble(); return _collection.Contains(value); } /// <summary> /// Returns the index of "value" in the list /// </summary> public int IndexOf(Transform3D value) { ReadPreamble(); return _collection.IndexOf(value); } /// <summary> /// Inserts "value" into the list at the specified position /// </summary> public void Insert(int index, Transform3D value) { if (value == null) { throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull)); } WritePreamble(); OnFreezablePropertyChanged(/* oldValue = */ null, /* newValue = */ value); _collection.Insert(index, value); OnInsert(value); ++_version; WritePostscript(); } /// <summary> /// Removes "value" from the list /// </summary> public bool Remove(Transform3D value) { WritePreamble(); // By design collections "succeed silently" if you attempt to remove an item // not in the collection. Therefore we need to first verify the old value exists // before calling OnFreezablePropertyChanged. Since we already need to locate // the item in the collection we keep the index and use RemoveAt(...) to do // the work. (Windows OS #1016178) // We use the public IndexOf to guard our UIContext since OnFreezablePropertyChanged // is only called conditionally. IList.IndexOf returns -1 if the value is not found. int index = IndexOf(value); if (index >= 0) { Transform3D oldValue = _collection[index]; OnFreezablePropertyChanged(oldValue, null); _collection.RemoveAt(index); OnRemove(oldValue); ++_version; WritePostscript(); return true; } // Collection_Remove returns true, calls WritePostscript, // increments version, and does UpdateResource if it succeeds return false; } /// <summary> /// Removes the element at the specified index /// </summary> public void RemoveAt(int index) { RemoveAtWithoutFiringPublicEvents(index); // RemoveAtWithoutFiringPublicEvents incremented the version WritePostscript(); } /// <summary> /// Removes the element at the specified index without firing /// the public Changed event. /// The caller - typically a public method - is responsible for calling /// WritePostscript if appropriate. /// </summary> internal void RemoveAtWithoutFiringPublicEvents(int index) { WritePreamble(); Transform3D oldValue = _collection[ index ]; OnFreezablePropertyChanged(oldValue, null); _collection.RemoveAt(index); OnRemove(oldValue); ++_version; // No WritePostScript to avoid firing the Changed event. } /// <summary> /// Indexer for the collection /// </summary> public Transform3D this[int index] { get { ReadPreamble(); return _collection[index]; } set { if (value == null) { throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull)); } WritePreamble(); if (!Object.ReferenceEquals(_collection[ index ], value)) { Transform3D oldValue = _collection[ index ]; OnFreezablePropertyChanged(oldValue, value); _collection[ index ] = value; OnSet(oldValue, value); } ++_version; WritePostscript(); } } #endregion #region ICollection<T> /// <summary> /// The number of elements contained in the collection. /// </summary> public int Count { get { ReadPreamble(); return _collection.Count; } } /// <summary> /// Copies the elements of the collection into "array" starting at "index" /// </summary> public void CopyTo(Transform3D[] array, int index) { ReadPreamble(); if (array == null) { throw new ArgumentNullException("array"); } // This will not throw in the case that we are copying // from an empty collection. This is consistent with the // BCL Collection implementations. (Windows 1587365) if (index < 0 || (index + _collection.Count) > array.Length) { throw new ArgumentOutOfRangeException("index"); } _collection.CopyTo(array, index); } bool ICollection<Transform3D>.IsReadOnly { get { ReadPreamble(); return IsFrozen; } } #endregion #region IEnumerable<T> /// <summary> /// Returns an enumerator for the collection /// </summary> public Enumerator GetEnumerator() { ReadPreamble(); return new Enumerator(this); } IEnumerator<Transform3D> IEnumerable<Transform3D>.GetEnumerator() { return this.GetEnumerator(); } #endregion #region IList bool IList.IsReadOnly { get { return ((ICollection<Transform3D>)this).IsReadOnly; } } bool IList.IsFixedSize { get { ReadPreamble(); return IsFrozen; } } object IList.this[int index] { get { return this[index]; } set { // Forwards to typed implementation this[index] = Cast(value); } } int IList.Add(object value) { // Forward to typed helper return AddHelper(Cast(value)); } bool IList.Contains(object value) { return Contains(value as Transform3D); } int IList.IndexOf(object value) { return IndexOf(value as Transform3D); } void IList.Insert(int index, object value) { // Forward to IList<T> Insert Insert(index, Cast(value)); } void IList.Remove(object value) { Remove(value as Transform3D); } #endregion #region ICollection void ICollection.CopyTo(Array array, int index) { ReadPreamble(); if (array == null) { throw new ArgumentNullException("array"); } // This will not throw in the case that we are copying // from an empty collection. This is consistent with the // BCL Collection implementations. (Windows 1587365) if (index < 0 || (index + _collection.Count) > array.Length) { throw new ArgumentOutOfRangeException("index"); } if (array.Rank != 1) { throw new ArgumentException(SR.Get(SRID.Collection_BadRank)); } // Elsewhere in the collection we throw an AE when the type is // bad so we do it here as well to be consistent try { int count = _collection.Count; for (int i = 0; i < count; i++) { array.SetValue(_collection[i], index + i); } } catch (InvalidCastException e) { throw new ArgumentException(SR.Get(SRID.Collection_BadDestArray, this.GetType().Name), e); } } bool ICollection.IsSynchronized { get { ReadPreamble(); return IsFrozen || Dispatcher != null; } } object ICollection.SyncRoot { get { ReadPreamble(); return this; } } #endregion #region IEnumerable IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion #region Internal Helpers /// <summary> /// A frozen empty Transform3DCollection. /// </summary> internal static Transform3DCollection Empty { get { if (s_empty == null) { Transform3DCollection collection = new Transform3DCollection(); collection.Freeze(); s_empty = collection; } return s_empty; } } /// <summary> /// Helper to return read only access. /// </summary> internal Transform3D Internal_GetItem(int i) { return _collection[i]; } /// <summary> /// Freezable collections need to notify their contained Freezables /// about the change in the InheritanceContext /// </summary> internal override void OnInheritanceContextChangedCore(EventArgs args) { base.OnInheritanceContextChangedCore(args); for (int i=0; i<this.Count; i++) { DependencyObject inheritanceChild = _collection[i]; if (inheritanceChild!= null && inheritanceChild.InheritanceContext == this) { inheritanceChild.OnInheritanceContextChanged(args); } } } #endregion #region Private Helpers private Transform3D Cast(object value) { if( value == null ) { throw new System.ArgumentNullException("value"); } if (!(value is Transform3D)) { throw new System.ArgumentException(SR.Get(SRID.Collection_BadType, this.GetType().Name, value.GetType().Name, "Transform3D")); } return (Transform3D) value; } // IList.Add returns int and IList<T>.Add does not. This // is called by both Adds and IList<T>'s just ignores the // integer private int AddHelper(Transform3D value) { int index = AddWithoutFiringPublicEvents(value); // AddAtWithoutFiringPublicEvents incremented the version WritePostscript(); return index; } internal int AddWithoutFiringPublicEvents(Transform3D value) { int index = -1; if (value == null) { throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull)); } WritePreamble(); Transform3D newValue = value; OnFreezablePropertyChanged(/* oldValue = */ null, newValue); index = _collection.Add(newValue); OnInsert(newValue); ++_version; // No WritePostScript to avoid firing the Changed event. return index; } internal event ItemInsertedHandler ItemInserted; internal event ItemRemovedHandler ItemRemoved; private void OnInsert(object item) { if (ItemInserted != null) { ItemInserted(this, item); } } private void OnRemove(object oldValue) { if (ItemRemoved != null) { ItemRemoved(this, oldValue); } } private void OnSet(object oldValue, object newValue) { OnInsert(newValue); OnRemove(oldValue); } #endregion Private Helpers private static Transform3DCollection s_empty; #region Public Properties #endregion Public Properties //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> protected override Freezable CreateInstanceCore() { return new Transform3DCollection(); } /// <summary> /// Implementation of Freezable.CloneCore() /// </summary> protected override void CloneCore(Freezable source) { Transform3DCollection sourceTransform3DCollection = (Transform3DCollection) source; base.CloneCore(source); int count = sourceTransform3DCollection._collection.Count; _collection = new FrugalStructList<Transform3D>(count); for (int i = 0; i < count; i++) { Transform3D newValue = (Transform3D) sourceTransform3DCollection._collection[i].Clone(); OnFreezablePropertyChanged(/* oldValue = */ null, newValue); _collection.Add(newValue); OnInsert(newValue); } } /// <summary> /// Implementation of Freezable.CloneCurrentValueCore() /// </summary> protected override void CloneCurrentValueCore(Freezable source) { Transform3DCollection sourceTransform3DCollection = (Transform3DCollection) source; base.CloneCurrentValueCore(source); int count = sourceTransform3DCollection._collection.Count; _collection = new FrugalStructList<Transform3D>(count); for (int i = 0; i < count; i++) { Transform3D newValue = (Transform3D) sourceTransform3DCollection._collection[i].CloneCurrentValue(); OnFreezablePropertyChanged(/* oldValue = */ null, newValue); _collection.Add(newValue); OnInsert(newValue); } } /// <summary> /// Implementation of Freezable.GetAsFrozenCore() /// </summary> protected override void GetAsFrozenCore(Freezable source) { Transform3DCollection sourceTransform3DCollection = (Transform3DCollection) source; base.GetAsFrozenCore(source); int count = sourceTransform3DCollection._collection.Count; _collection = new FrugalStructList<Transform3D>(count); for (int i = 0; i < count; i++) { Transform3D newValue = (Transform3D) sourceTransform3DCollection._collection[i].GetAsFrozen(); OnFreezablePropertyChanged(/* oldValue = */ null, newValue); _collection.Add(newValue); OnInsert(newValue); } } /// <summary> /// Implementation of Freezable.GetCurrentValueAsFrozenCore() /// </summary> protected override void GetCurrentValueAsFrozenCore(Freezable source) { Transform3DCollection sourceTransform3DCollection = (Transform3DCollection) source; base.GetCurrentValueAsFrozenCore(source); int count = sourceTransform3DCollection._collection.Count; _collection = new FrugalStructList<Transform3D>(count); for (int i = 0; i < count; i++) { Transform3D newValue = (Transform3D) sourceTransform3DCollection._collection[i].GetCurrentValueAsFrozen(); OnFreezablePropertyChanged(/* oldValue = */ null, newValue); _collection.Add(newValue); OnInsert(newValue); } } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.FreezeCore">Freezable.FreezeCore</see>. /// </summary> protected override bool FreezeCore(bool isChecking) { bool canFreeze = base.FreezeCore(isChecking); int count = _collection.Count; for (int i = 0; i < count && canFreeze; i++) { canFreeze &= Freezable.Freeze(_collection[i], isChecking); } return canFreeze; } #endregion ProtectedMethods //------------------------------------------------------ // // Internal Methods // //------------------------------------------------------ #region Internal Methods #endregion Internal Methods //------------------------------------------------------ // // Internal Properties // //------------------------------------------------------ #region Internal Properties #endregion Internal Properties //------------------------------------------------------ // // Dependency Properties // //------------------------------------------------------ #region Dependency Properties #endregion Dependency Properties //------------------------------------------------------ // // Internal Fields // //------------------------------------------------------ #region Internal Fields internal FrugalStructList<Transform3D> _collection; internal uint _version = 0; #endregion Internal Fields #region Enumerator /// <summary> /// Enumerates the items in a Transform3DCollection /// </summary> public struct Enumerator : IEnumerator, IEnumerator<Transform3D> { #region Constructor internal Enumerator(Transform3DCollection list) { Debug.Assert(list != null, "list may not be null."); _list = list; _version = list._version; _index = -1; _current = default(Transform3D); } #endregion #region Methods void IDisposable.Dispose() { } /// <summary> /// Advances the enumerator to the next element of the collection. /// </summary> /// <returns> /// true if the enumerator was successfully advanced to the next element, /// false if the enumerator has passed the end of the collection. /// </returns> public bool MoveNext() { _list.ReadPreamble(); if (_version == _list._version) { if (_index > -2 && _index < _list._collection.Count - 1) { _current = _list._collection[++_index]; return true; } else { _index = -2; // -2 indicates "past the end" return false; } } else { throw new InvalidOperationException(SR.Get(SRID.Enumerator_CollectionChanged)); } } /// <summary> /// Sets the enumerator to its initial position, which is before the /// first element in the collection. /// </summary> public void Reset() { _list.ReadPreamble(); if (_version == _list._version) { _index = -1; } else { throw new InvalidOperationException(SR.Get(SRID.Enumerator_CollectionChanged)); } } #endregion #region Properties object IEnumerator.Current { get { return this.Current; } } /// <summary> /// Current element /// /// The behavior of IEnumerable&lt;T>.Current is undefined /// before the first MoveNext and after we have walked /// off the end of the list. However, the IEnumerable.Current /// contract requires that we throw exceptions /// </summary> public Transform3D Current { get { if (_index > -1) { return _current; } else if (_index == -1) { throw new InvalidOperationException(SR.Get(SRID.Enumerator_NotStarted)); } else { Debug.Assert(_index == -2, "expected -2, got " + _index + "\n"); throw new InvalidOperationException(SR.Get(SRID.Enumerator_ReachedEnd)); } } } #endregion #region Data private Transform3D _current; private Transform3DCollection _list; private uint _version; private int _index; #endregion } #endregion #region Constructors //------------------------------------------------------ // // Constructors // //------------------------------------------------------ /// <summary> /// Initializes a new instance that is empty. /// </summary> public Transform3DCollection() { _collection = new FrugalStructList<Transform3D>(); } /// <summary> /// Initializes a new instance that is empty and has the specified initial capacity. /// </summary> /// <param name="capacity"> int - The number of elements that the new list is initially capable of storing. </param> public Transform3DCollection(int capacity) { _collection = new FrugalStructList<Transform3D>(capacity); } /// <summary> /// Creates a Transform3DCollection with all of the same elements as collection /// </summary> public Transform3DCollection(IEnumerable<Transform3D> collection) { // The WritePreamble and WritePostscript aren't technically necessary // in the constructor as of 1/20/05 but they are put here in case // their behavior changes at a later date WritePreamble(); if (collection != null) { bool needsItemValidation = true; ICollection<Transform3D> icollectionOfT = collection as ICollection<Transform3D>; if (icollectionOfT != null) { _collection = new FrugalStructList<Transform3D>(icollectionOfT); } else { ICollection icollection = collection as ICollection; if (icollection != null) // an IC but not and IC<T> { _collection = new FrugalStructList<Transform3D>(icollection); } else // not a IC or IC<T> so fall back to the slower Add { _collection = new FrugalStructList<Transform3D>(); foreach (Transform3D item in collection) { if (item == null) { throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull)); } Transform3D newValue = item; OnFreezablePropertyChanged(/* oldValue = */ null, newValue); _collection.Add(newValue); OnInsert(newValue); } needsItemValidation = false; } } if (needsItemValidation) { foreach (Transform3D item in collection) { if (item == null) { throw new System.ArgumentException(SR.Get(SRID.Collection_NoNull)); } OnFreezablePropertyChanged(/* oldValue = */ null, item); OnInsert(item); } } WritePostscript(); } else { throw new ArgumentNullException("collection"); } } #endregion Constructors } }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System.Collections; using System.Runtime.CompilerServices; namespace System { [Serializable] [Clarity.ExportStub("System_AppDomain.cpp")] public abstract class Array : ICloneable, IList { [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern Array CreateInstance(Type elementType, int length); public static void Copy(Array sourceArray, Array destinationArray, int length) { Copy(sourceArray, 0, destinationArray, 0, length); } [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length); [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void Clear(Array array, int index, int length); public Object GetValue(int index) { return ((IList)this)[index]; } public extern int Length { [MethodImplAttribute(MethodImplOptions.InternalCall)] get; } int ICollection.Count { get { return this.Length; } } public Object SyncRoot { get { return this; } } public bool IsReadOnly { get { return false; } } public bool IsFixedSize { get { return true; } } public bool IsSynchronized { get { return false; } } extern Object IList.this[int index] { [MethodImplAttribute(MethodImplOptions.InternalCall)] get; [MethodImplAttribute(MethodImplOptions.InternalCall)] set; } int IList.Add(Object value) { throw new NotSupportedException(); } bool IList.Contains(Object value) { return Array.IndexOf(this, value) >= 0; } void IList.Clear() { Array.Clear(this, 0, this.Length); } int IList.IndexOf(Object value) { return Array.IndexOf(this, value); } void IList.Insert(int index, Object value) { throw new NotSupportedException(); } void IList.Remove(Object value) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } public Object Clone() { int length = this.Length; Array destArray = Array.CreateInstance(this.GetType().GetElementType(), length); Array.Copy(this, destArray, length); return destArray; } public static int BinarySearch(Array array, Object value, IComparer comparer) { return BinarySearch(array, 0, array.Length, value, comparer); } public static int BinarySearch(Array array, int index, int length, Object value, IComparer comparer) { int lo = index; int hi = index + length - 1; while (lo <= hi) { int i = (lo + hi) >> 1; int c; if (comparer == null) { try { var elementComparer = array.GetValue(i) as IComparable; c = elementComparer.CompareTo(value); } catch (Exception e) { throw new InvalidOperationException("Failed to compare two elements in the array", e); } } else { c = comparer.Compare(array.GetValue(i), value); } if (c == 0) return i; if (c < 0) { lo = i + 1; } else { hi = i - 1; } } return ~lo; } public void CopyTo(Array array, int index) { Array.Copy(this, 0, array, index, this.Length); } public IEnumerator GetEnumerator() { return new SZArrayEnumerator(this); } public static int IndexOf(Array array, Object value) { return IndexOf(array, value, 0, array.Length); } public static int IndexOf(Array array, Object value, int startIndex) { return IndexOf(array, value, startIndex, array.Length - startIndex); } public static int IndexOf(Array array, Object value, int startIndex, int count) { // Try calling a quick native method to handle primitive types. int retVal; if (TrySZIndexOf(array, startIndex, count, value, out retVal)) { return retVal; } int endIndex = startIndex + count; for (int i = startIndex; i < endIndex; i++) { Object obj = array.GetValue(i); if (Object.Equals(obj, value)) return i; } return -1; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern bool TrySZIndexOf(Array sourceArray, int sourceIndex, int count, Object value, out int retVal); // This is the underlying Enumerator for all of our array-based data structures (Array, ArrayList, Stack, and Queue) // It supports enumerating over an array, a part of an array, and also will wrap around when the endIndex // specified is larger than the size of the array (to support Queue's internal circular array) internal class SZArrayEnumerator : IEnumerator { private Array _array; private int _index; private int _endIndex; private int _startIndex; private int _arrayLength; internal SZArrayEnumerator(Array array) { _array = array; _arrayLength = _array.Length; _endIndex = _arrayLength; _startIndex = 0; _index = -1; } // By specifying the startIndex and endIndex, the enumerator will enumerate // only a subset of the array. Note that startIndex is inclusive, while // endIndex is NOT inclusive. // For example, if array is of size 5, // new SZArrayEnumerator(array, 0, 3) will enumerate through // array[0], array[1], array[2] // // This also supports an array acting as a circular data structure. // For example, if array is of size 5, // new SZArrayEnumerator(array, 4, 7) will enumerate through // array[4], array[0], array[1] internal SZArrayEnumerator(Array array, int startIndex, int endIndex) { _array = array; _arrayLength = _array.Length; _endIndex = endIndex; _startIndex = startIndex; _index = _startIndex - 1; } public bool MoveNext() { if (_index < _endIndex) { _index++; return (_index < _endIndex); } return false; } public Object Current { get { return _array.GetValue(_index % _arrayLength); } } public void Reset() { _index = _startIndex - 1; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Concurrent; using System.Diagnostics.Contracts; using System.Threading; using System.Threading.Tasks; namespace System.Runtime { public struct TimeoutHelper { public static readonly TimeSpan MaxWait = TimeSpan.FromMilliseconds(Int32.MaxValue); private static readonly CancellationToken s_precancelledToken = new CancellationToken(true); private bool _cancellationTokenInitialized; private bool _deadlineSet; private CancellationToken _cancellationToken; private DateTime _deadline; private TimeSpan _originalTimeout; public TimeoutHelper(TimeSpan timeout) { Contract.Assert(timeout >= TimeSpan.Zero, "timeout must be non-negative"); _cancellationTokenInitialized = false; _originalTimeout = timeout; _deadline = DateTime.MaxValue; _deadlineSet = (timeout == TimeSpan.MaxValue); } public CancellationToken GetCancellationToken() { return GetCancellationTokenAsync().Result; } public async Task<CancellationToken> GetCancellationTokenAsync() { if (!_cancellationTokenInitialized) { var timeout = RemainingTime(); if (timeout >= MaxWait || timeout == Timeout.InfiniteTimeSpan) { _cancellationToken = CancellationToken.None; } else if (timeout > TimeSpan.Zero) { _cancellationToken = await TimeoutTokenSource.FromTimeoutAsync((int)timeout.TotalMilliseconds); } else { _cancellationToken = s_precancelledToken; } _cancellationTokenInitialized = true; } return _cancellationToken; } public TimeSpan OriginalTimeout { get { return _originalTimeout; } } public static bool IsTooLarge(TimeSpan timeout) { return (timeout > TimeoutHelper.MaxWait) && (timeout != TimeSpan.MaxValue); } public static TimeSpan FromMilliseconds(int milliseconds) { if (milliseconds == Timeout.Infinite) { return TimeSpan.MaxValue; } else { return TimeSpan.FromMilliseconds(milliseconds); } } public static int ToMilliseconds(TimeSpan timeout) { if (timeout == TimeSpan.MaxValue) { return Timeout.Infinite; } else { long ticks = Ticks.FromTimeSpan(timeout); if (ticks / TimeSpan.TicksPerMillisecond > int.MaxValue) { return int.MaxValue; } return Ticks.ToMilliseconds(ticks); } } public static TimeSpan Min(TimeSpan val1, TimeSpan val2) { if (val1 > val2) { return val2; } else { return val1; } } public static TimeSpan Add(TimeSpan timeout1, TimeSpan timeout2) { return Ticks.ToTimeSpan(Ticks.Add(Ticks.FromTimeSpan(timeout1), Ticks.FromTimeSpan(timeout2))); } public static DateTime Add(DateTime time, TimeSpan timeout) { if (timeout >= TimeSpan.Zero && DateTime.MaxValue - time <= timeout) { return DateTime.MaxValue; } if (timeout <= TimeSpan.Zero && DateTime.MinValue - time >= timeout) { return DateTime.MinValue; } return time + timeout; } public static DateTime Subtract(DateTime time, TimeSpan timeout) { return Add(time, TimeSpan.Zero - timeout); } public static TimeSpan Divide(TimeSpan timeout, int factor) { if (timeout == TimeSpan.MaxValue) { return TimeSpan.MaxValue; } return Ticks.ToTimeSpan((Ticks.FromTimeSpan(timeout) / factor) + 1); } public TimeSpan RemainingTime() { if (!_deadlineSet) { this.SetDeadline(); return _originalTimeout; } else if (_deadline == DateTime.MaxValue) { return TimeSpan.MaxValue; } else { TimeSpan remaining = _deadline - DateTime.UtcNow; if (remaining <= TimeSpan.Zero) { return TimeSpan.Zero; } else { return remaining; } } } public TimeSpan ElapsedTime() { return _originalTimeout - this.RemainingTime(); } private void SetDeadline() { Contract.Assert(!_deadlineSet, "TimeoutHelper deadline set twice."); _deadline = DateTime.UtcNow + _originalTimeout; _deadlineSet = true; } public static void ThrowIfNegativeArgument(TimeSpan timeout) { ThrowIfNegativeArgument(timeout, "timeout"); } public static void ThrowIfNegativeArgument(TimeSpan timeout, string argumentName) { if (timeout < TimeSpan.Zero) { throw Fx.Exception.ArgumentOutOfRange(argumentName, timeout, InternalSR.TimeoutMustBeNonNegative(argumentName, timeout)); } } public static void ThrowIfNonPositiveArgument(TimeSpan timeout) { ThrowIfNonPositiveArgument(timeout, "timeout"); } public static void ThrowIfNonPositiveArgument(TimeSpan timeout, string argumentName) { if (timeout <= TimeSpan.Zero) { throw Fx.Exception.ArgumentOutOfRange(argumentName, timeout, InternalSR.TimeoutMustBePositive(argumentName, timeout)); } } public static bool WaitOne(WaitHandle waitHandle, TimeSpan timeout) { ThrowIfNegativeArgument(timeout); if (timeout == TimeSpan.MaxValue) { waitHandle.WaitOne(); return true; } else { // http://msdn.microsoft.com/en-us/library/85bbbxt9(v=vs.110).aspx // with exitContext was used in Desktop which is not supported in Net Native or CoreClr return waitHandle.WaitOne(timeout); } } internal static TimeoutException CreateEnterTimedOutException(TimeSpan timeout) { return new TimeoutException(string.Format(SRServiceModel.LockTimeoutExceptionMessage, timeout)); } } /// <summary> /// This class coalesces timeout tokens because cancelation tokens with timeouts are more expensive to expose. /// Disposing too many such tokens will cause thread contentions in high throughput scenario. /// /// Tokens with target cancelation time 15ms apart would resolve to the same instance. /// </summary> internal static class TimeoutTokenSource { /// <summary> /// These are constants use to calculate timeout coalescing, for more description see method FromTimeoutAsync /// </summary> private const int CoalescingFactor = 15; private const int GranularityFactor = 2000; private const int SegmentationFactor = CoalescingFactor * GranularityFactor; private static readonly ConcurrentDictionary<long, Task<CancellationToken>> s_tokenCache = new ConcurrentDictionary<long, Task<CancellationToken>>(); private static readonly Action<object> s_deregisterToken = (object state) => { var args = (Tuple<long, CancellationTokenSource>)state; Task<CancellationToken> ignored; try { s_tokenCache.TryRemove(args.Item1, out ignored); } finally { args.Item2.Dispose(); } }; public static CancellationToken FromTimeout(int millisecondsTimeout) { return FromTimeoutAsync(millisecondsTimeout).Result; } public static Task<CancellationToken> FromTimeoutAsync(int millisecondsTimeout) { // Note that CancellationTokenSource constructor requires input to be >= -1, // restricting millisecondsTimeout to be >= -1 would enforce that if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException("Invalid millisecondsTimeout value " + millisecondsTimeout); } // To prevent s_tokenCache growing too large, we have to adjust the granularity of the our coalesce depending // on the value of millisecondsTimeout. The coalescing span scales proportionally with millisecondsTimeout which // would garentee constant s_tokenCache size in the case where similar millisecondsTimeout values are accepted. // If the method is given a wildly different millisecondsTimeout values all the time, the dictionary would still // only grow logarithmically with respect to the range of the input values uint currentTime = (uint)Environment.TickCount; long targetTime = millisecondsTimeout + currentTime; // Formula for our coalescing span: // Divide millisecondsTimeout by SegmentationFactor and take the highest bit and then multiply CoalescingFactor back var segmentValue = millisecondsTimeout / SegmentationFactor; var coalescingSpanMs = CoalescingFactor; while (segmentValue > 0) { segmentValue >>= 1; coalescingSpanMs <<= 1; } targetTime = ((targetTime + (coalescingSpanMs - 1)) / coalescingSpanMs) * coalescingSpanMs; Task<CancellationToken> tokenTask; if (!s_tokenCache.TryGetValue(targetTime, out tokenTask)) { var tcs = new TaskCompletionSource<CancellationToken>(); // only a single thread may succeed adding its task into the cache if (s_tokenCache.TryAdd(targetTime, tcs.Task)) { // Since this thread was successful reserving a spot in the cache, it would be the only thread // that construct the CancellationTokenSource var tokenSource = new CancellationTokenSource((int)(targetTime - currentTime)); var token = tokenSource.Token; // Clean up cache when Token is canceled token.Register(s_deregisterToken, Tuple.Create(targetTime, tokenSource)); // set the result so other thread may observe the token, and return tcs.TrySetResult(token); tokenTask = tcs.Task; } else { // for threads that failed when calling TryAdd, there should be one already in the cache if (!s_tokenCache.TryGetValue(targetTime, out tokenTask)) { // In unlikely scenario the token was already cancelled and timed out, we would not find it in cache. // In this case we would simply create a non-coalsed token tokenTask = Task.FromResult(new CancellationTokenSource(millisecondsTimeout).Token); } } } return tokenTask; } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.ServiceModel.FederatedMessageSecurityOverHttp.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.ServiceModel { sealed public partial class FederatedMessageSecurityOverHttp { #region Methods and constructors public FederatedMessageSecurityOverHttp() { } public bool ShouldSerializeAlgorithmSuite() { Contract.Ensures(Contract.Result<bool>() == ((this.AlgorithmSuite == System.ServiceModel.Security.SecurityAlgorithmSuite.Default) == false)); return default(bool); } public bool ShouldSerializeClaimTypeRequirements() { Contract.Ensures(Contract.Result<bool>() == (this.ClaimTypeRequirements.Count > 0)); return default(bool); } public bool ShouldSerializeEstablishSecurityContext() { Contract.Ensures(Contract.Result<bool>() == (!this.EstablishSecurityContext)); return default(bool); } public bool ShouldSerializeIssuedKeyType() { Contract.Ensures(Contract.Result<bool>() == ((this.IssuedKeyType == ((System.IdentityModel.Tokens.SecurityKeyType)(0))) == false)); return default(bool); } public bool ShouldSerializeNegotiateServiceCredential() { Contract.Ensures(Contract.Result<bool>() == (!this.NegotiateServiceCredential)); return default(bool); } public bool ShouldSerializeTokenRequestParameters() { Contract.Ensures(Contract.Result<bool>() == (this.TokenRequestParameters.Count > 0)); return default(bool); } #endregion #region Properties and indexers public System.ServiceModel.Security.SecurityAlgorithmSuite AlgorithmSuite { get { return default(System.ServiceModel.Security.SecurityAlgorithmSuite); } set { } } public System.Collections.ObjectModel.Collection<System.ServiceModel.Security.Tokens.ClaimTypeRequirement> ClaimTypeRequirements { get { Contract.Ensures(Contract.Result<System.Collections.ObjectModel.Collection<System.ServiceModel.Security.Tokens.ClaimTypeRequirement>>() != null); return default(System.Collections.ObjectModel.Collection<System.ServiceModel.Security.Tokens.ClaimTypeRequirement>); } } public bool EstablishSecurityContext { get { return default(bool); } set { } } public System.IdentityModel.Tokens.SecurityKeyType IssuedKeyType { get { return default(System.IdentityModel.Tokens.SecurityKeyType); } set { } } public string IssuedTokenType { get { return default(string); } set { } } public EndpointAddress IssuerAddress { get { return default(EndpointAddress); } set { } } public System.ServiceModel.Channels.Binding IssuerBinding { get { return default(System.ServiceModel.Channels.Binding); } set { } } public EndpointAddress IssuerMetadataAddress { get { return default(EndpointAddress); } set { } } public bool NegotiateServiceCredential { get { return default(bool); } set { } } public System.Collections.ObjectModel.Collection<System.Xml.XmlElement> TokenRequestParameters { get { Contract.Ensures(Contract.Result<System.Collections.ObjectModel.Collection<System.Xml.XmlElement>>() != null); return default(System.Collections.ObjectModel.Collection<System.Xml.XmlElement>); } } #endregion } }
using Lucene.Net.Index; using Lucene.Net.Support; using System.Diagnostics; namespace Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Similarity = Lucene.Net.Search.Similarities.Similarity; internal sealed class ExactPhraseScorer : Scorer { private readonly int endMinus1; private const int CHUNK = 4096; private int gen; private readonly int[] counts = new int[CHUNK]; private readonly int[] gens = new int[CHUNK]; internal bool noDocs; private readonly long cost; private sealed class ChunkState { internal DocsAndPositionsEnum PosEnum { get; private set; } internal int Offset { get; private set; } internal bool UseAdvance { get; private set; } internal int PosUpto { get; set; } internal int PosLimit { get; set; } internal int Pos { get; set; } internal int LastPos { get; set; } public ChunkState(DocsAndPositionsEnum posEnum, int offset, bool useAdvance) { this.PosEnum = posEnum; this.Offset = offset; this.UseAdvance = useAdvance; } } private readonly ChunkState[] chunkStates; private int docID = -1; private int freq; private readonly Similarity.SimScorer docScorer; internal ExactPhraseScorer(Weight weight, PhraseQuery.PostingsAndFreq[] postings, Similarity.SimScorer docScorer) : base(weight) { this.docScorer = docScorer; chunkStates = new ChunkState[postings.Length]; endMinus1 = postings.Length - 1; // min(cost) cost = postings[0].postings.GetCost(); for (int i = 0; i < postings.Length; i++) { // Coarse optimization: advance(target) is fairly // costly, so, if the relative freq of the 2nd // rarest term is not that much (> 1/5th) rarer than // the first term, then we just use .nextDoc() when // ANDing. this buys ~15% gain for phrases where // freq of rarest 2 terms is close: bool useAdvance = postings[i].docFreq > 5 * postings[0].docFreq; chunkStates[i] = new ChunkState(postings[i].postings, -postings[i].position, useAdvance); if (i > 0 && postings[i].postings.NextDoc() == DocIdSetIterator.NO_MORE_DOCS) { noDocs = true; return; } } } public override int NextDoc() { while (true) { // first (rarest) term int doc = chunkStates[0].PosEnum.NextDoc(); if (doc == DocIdSetIterator.NO_MORE_DOCS) { docID = doc; return doc; } // not-first terms int i = 1; while (i < chunkStates.Length) { ChunkState cs = chunkStates[i]; int doc2 = cs.PosEnum.DocID; if (cs.UseAdvance) { if (doc2 < doc) { doc2 = cs.PosEnum.Advance(doc); } } else { int iter = 0; while (doc2 < doc) { // safety net -- fallback to .advance if we've // done too many .nextDocs if (++iter == 50) { doc2 = cs.PosEnum.Advance(doc); break; } else { doc2 = cs.PosEnum.NextDoc(); } } } if (doc2 > doc) { break; } i++; } if (i == chunkStates.Length) { // this doc has all the terms -- now test whether // phrase occurs docID = doc; freq = PhraseFreq(); if (freq != 0) { return docID; } } } } public override int Advance(int target) { // first term int doc = chunkStates[0].PosEnum.Advance(target); if (doc == DocIdSetIterator.NO_MORE_DOCS) { docID = DocIdSetIterator.NO_MORE_DOCS; return doc; } while (true) { // not-first terms int i = 1; while (i < chunkStates.Length) { int doc2 = chunkStates[i].PosEnum.DocID; if (doc2 < doc) { doc2 = chunkStates[i].PosEnum.Advance(doc); } if (doc2 > doc) { break; } i++; } if (i == chunkStates.Length) { // this doc has all the terms -- now test whether // phrase occurs docID = doc; freq = PhraseFreq(); if (freq != 0) { return docID; } } doc = chunkStates[0].PosEnum.NextDoc(); if (doc == DocIdSetIterator.NO_MORE_DOCS) { docID = doc; return doc; } } } public override string ToString() { return "ExactPhraseScorer(" + m_weight + ")"; } public override int Freq => freq; public override int DocID => docID; public override float GetScore() { return docScorer.Score(docID, freq); } private int PhraseFreq() { freq = 0; // init chunks for (int i = 0; i < chunkStates.Length; i++) { ChunkState cs = chunkStates[i]; cs.PosLimit = cs.PosEnum.Freq; cs.Pos = cs.Offset + cs.PosEnum.NextPosition(); cs.PosUpto = 1; cs.LastPos = -1; } int chunkStart = 0; int chunkEnd = CHUNK; // process chunk by chunk bool end = false; // TODO: we could fold in chunkStart into offset and // save one subtract per pos incr while (!end) { gen++; if (gen == 0) { // wraparound Arrays.Fill(gens, 0); gen++; } // first term { ChunkState cs = chunkStates[0]; while (cs.Pos < chunkEnd) { if (cs.Pos > cs.LastPos) { cs.LastPos = cs.Pos; int posIndex = cs.Pos - chunkStart; counts[posIndex] = 1; Debug.Assert(gens[posIndex] != gen); gens[posIndex] = gen; } if (cs.PosUpto == cs.PosLimit) { end = true; break; } cs.PosUpto++; cs.Pos = cs.Offset + cs.PosEnum.NextPosition(); } } // middle terms bool any = true; for (int t = 1; t < endMinus1; t++) { ChunkState cs = chunkStates[t]; any = false; while (cs.Pos < chunkEnd) { if (cs.Pos > cs.LastPos) { cs.LastPos = cs.Pos; int posIndex = cs.Pos - chunkStart; if (posIndex >= 0 && gens[posIndex] == gen && counts[posIndex] == t) { // viable counts[posIndex]++; any = true; } } if (cs.PosUpto == cs.PosLimit) { end = true; break; } cs.PosUpto++; cs.Pos = cs.Offset + cs.PosEnum.NextPosition(); } if (!any) { break; } } if (!any) { // petered out for this chunk chunkStart += CHUNK; chunkEnd += CHUNK; continue; } // last term { ChunkState cs = chunkStates[endMinus1]; while (cs.Pos < chunkEnd) { if (cs.Pos > cs.LastPos) { cs.LastPos = cs.Pos; int posIndex = cs.Pos - chunkStart; if (posIndex >= 0 && gens[posIndex] == gen && counts[posIndex] == endMinus1) { freq++; } } if (cs.PosUpto == cs.PosLimit) { end = true; break; } cs.PosUpto++; cs.Pos = cs.Offset + cs.PosEnum.NextPosition(); } } chunkStart += CHUNK; chunkEnd += CHUNK; } return freq; } public override long GetCost() { return cost; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace System.SpanTests { public static partial class SpanTests { [Fact] public static void ZeroLengthLastIndexOfAny_TwoByte() { var sp = new Span<int>(Array.Empty<int>()); int idx = sp.LastIndexOfAny(0, 0); Assert.Equal(-1, idx); } [Fact] public static void DefaultFilledLastIndexOfAny_TwoByte() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new int[length]; var span = new Span<int>(a); int[] targets = { default, 99 }; for (int i = 0; i < length; i++) { int index = rnd.Next(0, 2) == 0 ? 0 : 1; int target0 = targets[index]; int target1 = targets[(index + 1) % 2]; int idx = span.LastIndexOfAny(target0, target1); Assert.Equal(span.Length - 1, idx); } } } [Fact] public static void TestMatchLastIndexOfAny_TwoByte() { for (int length = 0; length < byte.MaxValue; length++) { var a = new int[length]; for (int i = 0; i < length; i++) { a[i] = i + 1; } var span = new Span<int>(a); for (int targetIndex = 0; targetIndex < length; targetIndex++) { int target0 = a[targetIndex]; int target1 = 0; int idx = span.LastIndexOfAny(target0, target1); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 1; targetIndex++) { int target0 = a[targetIndex]; int target1 = a[targetIndex + 1]; int idx = span.LastIndexOfAny(target0, target1); Assert.Equal(targetIndex + 1, idx); } for (int targetIndex = 0; targetIndex < length - 1; targetIndex++) { int target0 = 0; int target1 = a[targetIndex + 1]; int idx = span.LastIndexOfAny(target0, target1); Assert.Equal(targetIndex + 1, idx); } } } [Fact] public static void TestNoMatchLastIndexOfAny_TwoByte() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new int[length]; int target0 = rnd.Next(1, 256); int target1 = rnd.Next(1, 256); var span = new Span<int>(a); int idx = span.LastIndexOfAny(target0, target1); Assert.Equal(-1, idx); } } [Fact] public static void TestMultipleMatchLastIndexOfAny_TwoByte() { for (int length = 3; length < byte.MaxValue; length++) { var a = new int[length]; for (int i = 0; i < length; i++) { int val = i + 1; a[i] = val == 200 ? 201 : val; } a[length - 1] = 200; a[length - 2] = 200; a[length - 3] = 200; var span = new Span<int>(a); int idx = span.LastIndexOfAny(200, 200); Assert.Equal(length - 1, idx); } } [Fact] public static void MakeSureNoChecksGoOutOfRangeLastIndexOfAny_TwoByte() { for (int length = 1; length < byte.MaxValue; length++) { var a = new int[length + 2]; a[0] = 99; a[length + 1] = 98; var span = new Span<int>(a, 1, length - 1); int index = span.LastIndexOfAny(99, 98); Assert.Equal(-1, index); } for (int length = 1; length < byte.MaxValue; length++) { var a = new int[length + 2]; a[0] = 99; a[length + 1] = 99; var span = new Span<int>(a, 1, length - 1); int index = span.LastIndexOfAny(99, 99); Assert.Equal(-1, index); } } [Fact] public static void ZeroLengthIndexOf_ThreeByte() { var sp = new Span<int>(Array.Empty<int>()); int idx = sp.LastIndexOfAny(0, 0, 0); Assert.Equal(-1, idx); } [Fact] public static void DefaultFilledLastIndexOfAny_ThreeByte() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new int[length]; var span = new Span<int>(a); int[] targets = { default, 99, 98 }; for (int i = 0; i < length; i++) { int index = rnd.Next(0, 3); int target0 = targets[index]; int target1 = targets[(index + 1) % 2]; int target2 = targets[(index + 1) % 3]; int idx = span.LastIndexOfAny(target0, target1, target2); Assert.Equal(span.Length - 1, idx); } } } [Fact] public static void TestMatchLastIndexOfAny_ThreeByte() { for (int length = 0; length < byte.MaxValue; length++) { var a = new int[length]; for (int i = 0; i < length; i++) { a[i] = i + 1; } var span = new Span<int>(a); for (int targetIndex = 0; targetIndex < length; targetIndex++) { int target0 = a[targetIndex]; int target1 = 0; int target2 = 0; int idx = span.LastIndexOfAny(target0, target1, target2); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 2; targetIndex++) { int target0 = a[targetIndex]; int target1 = a[targetIndex + 1]; int target2 = a[targetIndex + 2]; int idx = span.LastIndexOfAny(target0, target1, target2); Assert.Equal(targetIndex + 2, idx); } for (int targetIndex = 0; targetIndex < length - 2; targetIndex++) { int target0 = 0; int target1 = 0; int target2 = a[targetIndex + 2]; int idx = span.LastIndexOfAny(target0, target1, target2); Assert.Equal(targetIndex + 2, idx); } } } [Fact] public static void TestNoMatchLastIndexOfAny_ThreeByte() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new int[length]; int target0 = rnd.Next(1, 256); int target1 = rnd.Next(1, 256); int target2 = rnd.Next(1, 256); var span = new Span<int>(a); int idx = span.LastIndexOfAny(target0, target1, target2); Assert.Equal(-1, idx); } } [Fact] public static void TestMultipleMatchLastIndexOfAny_ThreeByte() { for (int length = 4; length < byte.MaxValue; length++) { var a = new int[length]; for (int i = 0; i < length; i++) { int val = i + 1; a[i] = val == 200 ? 201 : val; } a[length - 1] = 200; a[length - 2] = 200; a[length - 3] = 200; a[length - 4] = 200; var span = new Span<int>(a); int idx = span.LastIndexOfAny(200, 200, 200); Assert.Equal(length - 1, idx); } } [Fact] public static void MakeSureNoChecksGoOutOfRangeLastIndexOfAny_ThreeByte() { for (int length = 1; length < byte.MaxValue; length++) { var a = new int[length + 2]; a[0] = 99; a[length + 1] = 98; var span = new Span<int>(a, 1, length - 1); int index = span.LastIndexOfAny(99, 98, 99); Assert.Equal(-1, index); } for (int length = 1; length < byte.MaxValue; length++) { var a = new int[length + 2]; a[0] = 99; a[length + 1] = 99; var span = new Span<int>(a, 1, length - 1); int index = span.LastIndexOfAny(99, 99, 99); Assert.Equal(-1, index); } } [Fact] public static void ZeroLengthLastIndexOfAny_ManyByte() { var sp = new Span<int>(Array.Empty<int>()); var values = new ReadOnlySpan<int>(new int[] { 0, 0, 0, 0 }); int idx = sp.LastIndexOfAny(values); Assert.Equal(-1, idx); values = new ReadOnlySpan<int>(new int[] { }); idx = sp.LastIndexOfAny(values); Assert.Equal(-1, idx); } [Fact] public static void DefaultFilledLastIndexOfAny_ManyByte() { for (int length = 0; length < byte.MaxValue; length++) { var a = new int[length]; var span = new Span<int>(a); var values = new ReadOnlySpan<int>(new int[] { default, 99, 98, 0 }); for (int i = 0; i < length; i++) { int idx = span.LastIndexOfAny(values); Assert.Equal(span.Length - 1, idx); } } } [Fact] public static void TestMatchLastIndexOfAny_ManyByte() { for (int length = 0; length < byte.MaxValue; length++) { var a = new int[length]; for (int i = 0; i < length; i++) { a[i] = i + 1; } var span = new Span<int>(a); for (int targetIndex = 0; targetIndex < length; targetIndex++) { var values = new ReadOnlySpan<int>(new int[] { a[targetIndex], 0, 0, 0 }); int idx = span.LastIndexOfAny(values); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 3; targetIndex++) { var values = new ReadOnlySpan<int>(new int[] { a[targetIndex], a[targetIndex + 1], a[targetIndex + 2], a[targetIndex + 3] }); int idx = span.LastIndexOfAny(values); Assert.Equal(targetIndex + 3, idx); } for (int targetIndex = 0; targetIndex < length - 3; targetIndex++) { var values = new ReadOnlySpan<int>(new int[] { 0, 0, 0, a[targetIndex + 3] }); int idx = span.LastIndexOfAny(values); Assert.Equal(targetIndex + 3, idx); } } } [Fact] public static void TestMatchValuesLargerLastIndexOfAny_ManyByte() { var rnd = new Random(42); for (int length = 2; length < byte.MaxValue; length++) { var a = new int[length]; int expectedIndex = length / 2; for (int i = 0; i < length; i++) { if (i == expectedIndex) { continue; } a[i] = 255; } var span = new Span<int>(a); var targets = new int[length * 2]; for (int i = 0; i < targets.Length; i++) { if (i == length + 1) { continue; } targets[i] = rnd.Next(1, 255); } var values = new ReadOnlySpan<int>(targets); int idx = span.LastIndexOfAny(values); Assert.Equal(expectedIndex, idx); } } [Fact] public static void TestNoMatchLastIndexOfAny_ManyByte() { var rnd = new Random(42); for (int length = 1; length < byte.MaxValue; length++) { var a = new int[length]; var targets = new int[length]; for (int i = 0; i < targets.Length; i++) { targets[i] = rnd.Next(1, 256); } var span = new Span<int>(a); var values = new ReadOnlySpan<int>(targets); int idx = span.LastIndexOfAny(values); Assert.Equal(-1, idx); } } [Fact] public static void TestNoMatchValuesLargerLastIndexOfAny_ManyByte() { var rnd = new Random(42); for (int length = 1; length < byte.MaxValue; length++) { var a = new int[length]; var targets = new int[length * 2]; for (int i = 0; i < targets.Length; i++) { targets[i] = rnd.Next(1, 256); } var span = new Span<int>(a); var values = new ReadOnlySpan<int>(targets); int idx = span.LastIndexOfAny(values); Assert.Equal(-1, idx); } } [Fact] public static void TestMultipleMatchLastIndexOfAny_ManyByte() { for (int length = 5; length < byte.MaxValue; length++) { var a = new int[length]; for (int i = 0; i < length; i++) { int val = i + 1; a[i] = val == 200 ? 201 : val; } a[length - 1] = 200; a[length - 2] = 200; a[length - 3] = 200; a[length - 4] = 200; a[length - 5] = 200; var span = new Span<int>(a); var values = new ReadOnlySpan<int>(new int[] { 200, 200, 200, 200, 200, 200, 200, 200, 200 }); int idx = span.LastIndexOfAny(values); Assert.Equal(length - 1, idx); } } [Fact] public static void MakeSureNoChecksGoOutOfRangeLastIndexOfAny_ManyByte() { for (int length = 1; length < byte.MaxValue; length++) { var a = new int[length + 2]; a[0] = 99; a[length + 1] = 98; var span = new Span<int>(a, 1, length - 1); var values = new ReadOnlySpan<int>(new int[] { 99, 98, 99, 98, 99, 98 }); int index = span.LastIndexOfAny(values); Assert.Equal(-1, index); } for (int length = 1; length < byte.MaxValue; length++) { var a = new int[length + 2]; a[0] = 99; a[length + 1] = 99; var span = new Span<int>(a, 1, length - 1); var values = new ReadOnlySpan<int>(new int[] { 99, 99, 99, 99, 99, 99 }); int index = span.LastIndexOfAny(values); Assert.Equal(-1, index); } } [Fact] public static void ZeroLengthLastIndexOfAny_String_TwoByte() { var sp = new Span<string>(Array.Empty<string>()); int idx = sp.LastIndexOfAny("0", "0"); Assert.Equal(-1, idx); } [Fact] public static void DefaultFilledLastIndexOfAny_String_TwoByte() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new string[length]; var span = new Span<string>(a); span.Fill(""); string[] targets = { "", "99" }; for (int i = 0; i < length; i++) { int index = rnd.Next(0, 2) == 0 ? 0 : 1; string target0 = targets[index]; string target1 = targets[(index + 1) % 2]; int idx = span.LastIndexOfAny(target0, target1); Assert.Equal(span.Length - 1, idx); } } } [Fact] public static void TestMatchLastIndexOfAny_String_TwoByte() { for (int length = 0; length < byte.MaxValue; length++) { var a = new string[length]; for (int i = 0; i < length; i++) { a[i] = (i + 1).ToString(); } var span = new Span<string>(a); for (int targetIndex = 0; targetIndex < length; targetIndex++) { string target0 = a[targetIndex]; string target1 = "0"; int idx = span.LastIndexOfAny(target0, target1); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 1; targetIndex++) { string target0 = a[targetIndex]; string target1 = a[targetIndex + 1]; int idx = span.LastIndexOfAny(target0, target1); Assert.Equal(targetIndex + 1, idx); } for (int targetIndex = 0; targetIndex < length - 1; targetIndex++) { string target0 = "0"; string target1 = a[targetIndex + 1]; int idx = span.LastIndexOfAny(target0, target1); Assert.Equal(targetIndex + 1, idx); } } } [Fact] public static void TestNoMatchLastIndexOfAny_String_TwoByte() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new string[length]; string target0 = rnd.Next(1, 256).ToString(); string target1 = rnd.Next(1, 256).ToString(); var span = new Span<string>(a); int idx = span.LastIndexOfAny(target0, target1); Assert.Equal(-1, idx); } } [Fact] public static void TestMultipleMatchLastIndexOfAny_String_TwoByte() { for (int length = 3; length < byte.MaxValue; length++) { var a = new string[length]; for (int i = 0; i < length; i++) { string val = (i + 1).ToString(); a[i] = val == "200" ? "201" : val; } a[length - 1] = "200"; a[length - 2] = "200"; a[length - 3] = "200"; var span = new Span<string>(a); int idx = span.LastIndexOfAny("200", "200"); Assert.Equal(length - 1, idx); } } [Fact] public static void MakeSureNoChecksGoOutOfRangeLastIndexOfAny_String_TwoByte() { for (int length = 1; length < byte.MaxValue; length++) { var a = new string[length + 2]; a[0] = "99"; a[length + 1] = "98"; var span = new Span<string>(a, 1, length - 1); int index = span.LastIndexOfAny("99", "98"); Assert.Equal(-1, index); } for (int length = 1; length < byte.MaxValue; length++) { var a = new string[length + 2]; a[0] = "99"; a[length + 1] = "99"; var span = new Span<string>(a, 1, length - 1); int index = span.LastIndexOfAny("99", "99"); Assert.Equal(-1, index); } } [Fact] public static void ZeroLengthIndexOf_String_ThreeByte() { var sp = new Span<string>(Array.Empty<string>()); int idx = sp.LastIndexOfAny("0", "0", "0"); Assert.Equal(-1, idx); } [Fact] public static void DefaultFilledLastIndexOfAny_String_ThreeByte() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new string[length]; var span = new Span<string>(a); span.Fill(""); string[] targets = { "", "99", "98" }; for (int i = 0; i < length; i++) { int index = rnd.Next(0, 3); string target0 = targets[index]; string target1 = targets[(index + 1) % 2]; string target2 = targets[(index + 1) % 3]; int idx = span.LastIndexOfAny(target0, target1, target2); Assert.Equal(span.Length - 1, idx); } } } [Fact] public static void TestMatchLastIndexOfAny_String_ThreeByte() { for (int length = 0; length < byte.MaxValue; length++) { var a = new string[length]; for (int i = 0; i < length; i++) { a[i] = (i + 1).ToString(); } var span = new Span<string>(a); for (int targetIndex = 0; targetIndex < length; targetIndex++) { string target0 = a[targetIndex]; string target1 = "0"; string target2 = "0"; int idx = span.LastIndexOfAny(target0, target1, target2); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 2; targetIndex++) { string target0 = a[targetIndex]; string target1 = a[targetIndex + 1]; string target2 = a[targetIndex + 2]; int idx = span.LastIndexOfAny(target0, target1, target2); Assert.Equal(targetIndex + 2, idx); } for (int targetIndex = 0; targetIndex < length - 2; targetIndex++) { string target0 = "0"; string target1 = "0"; string target2 = a[targetIndex + 2]; int idx = span.LastIndexOfAny(target0, target1, target2); Assert.Equal(targetIndex + 2, idx); } } } [Fact] public static void TestNoMatchLastIndexOfAny_String_ThreeByte() { var rnd = new Random(42); for (int length = 0; length < byte.MaxValue; length++) { var a = new string[length]; string target0 = rnd.Next(1, 256).ToString(); string target1 = rnd.Next(1, 256).ToString(); string target2 = rnd.Next(1, 256).ToString(); var span = new Span<string>(a); int idx = span.LastIndexOfAny(target0, target1, target2); Assert.Equal(-1, idx); } } [Fact] public static void TestMultipleMatchLastIndexOfAny_String_ThreeByte() { for (int length = 4; length < byte.MaxValue; length++) { var a = new string[length]; for (int i = 0; i < length; i++) { string val = (i + 1).ToString(); a[i] = val == "200" ? "201" : val; } a[length - 1] = "200"; a[length - 2] = "200"; a[length - 3] = "200"; a[length - 4] = "200"; var span = new Span<string>(a); int idx = span.LastIndexOfAny("200", "200", "200"); Assert.Equal(length - 1, idx); } } [Fact] public static void MakeSureNoChecksGoOutOfRangeLastIndexOfAny_String_ThreeByte() { for (int length = 1; length < byte.MaxValue; length++) { var a = new string[length + 2]; a[0] = "99"; a[length + 1] = "98"; var span = new Span<string>(a, 1, length - 1); int index = span.LastIndexOfAny("99", "98", "99"); Assert.Equal(-1, index); } for (int length = 1; length < byte.MaxValue; length++) { var a = new string[length + 2]; a[0] = "99"; a[length + 1] = "99"; var span = new Span<string>(a, 1, length - 1); int index = span.LastIndexOfAny("99", "99", "99"); Assert.Equal(-1, index); } } [Fact] public static void ZeroLengthLastIndexOfAny_String_ManyByte() { var sp = new Span<string>(Array.Empty<string>()); var values = new ReadOnlySpan<string>(new string[] { "0", "0", "0", "0" }); int idx = sp.LastIndexOfAny(values); Assert.Equal(-1, idx); values = new ReadOnlySpan<string>(new string[] { }); idx = sp.LastIndexOfAny(values); Assert.Equal(-1, idx); } [Fact] public static void DefaultFilledLastIndexOfAny_String_ManyByte() { for (int length = 0; length < byte.MaxValue; length++) { var a = new string[length]; var span = new Span<string>(a); span.Fill(""); var values = new ReadOnlySpan<string>(new string[] { "", "99", "98", "0" }); for (int i = 0; i < length; i++) { int idx = span.LastIndexOfAny(values); Assert.Equal(span.Length - 1, idx); } } } [Fact] public static void TestMatchLastIndexOfAny_String_ManyByte() { for (int length = 0; length < byte.MaxValue; length++) { var a = new string[length]; for (int i = 0; i < length; i++) { a[i] = (i + 1).ToString(); } var span = new Span<string>(a); for (int targetIndex = 0; targetIndex < length; targetIndex++) { var values = new ReadOnlySpan<string>(new string[] { a[targetIndex], "0", "0", "0" }); int idx = span.LastIndexOfAny(values); Assert.Equal(targetIndex, idx); } for (int targetIndex = 0; targetIndex < length - 3; targetIndex++) { var values = new ReadOnlySpan<string>(new string[] { a[targetIndex], a[targetIndex + 1], a[targetIndex + 2], a[targetIndex + 3] }); int idx = span.LastIndexOfAny(values); Assert.Equal(targetIndex + 3, idx); } for (int targetIndex = 0; targetIndex < length - 3; targetIndex++) { var values = new ReadOnlySpan<string>(new string[] { "0", "0", "0", a[targetIndex + 3] }); int idx = span.LastIndexOfAny(values); Assert.Equal(targetIndex + 3, idx); } } } [Fact] public static void TestMatchValuesLargerLastIndexOfAny_String_ManyByte() { var rnd = new Random(42); for (int length = 2; length < byte.MaxValue; length++) { var a = new string[length]; int expectedIndex = length / 2; for (int i = 0; i < length; i++) { if (i == expectedIndex) { a[i] = "val"; continue; } a[i] = "255"; } var span = new Span<string>(a); var targets = new string[length * 2]; for (int i = 0; i < targets.Length; i++) { if (i == length + 1) { targets[i] = "val"; continue; } targets[i] = rnd.Next(1, 255).ToString(); } var values = new ReadOnlySpan<string>(targets); int idx = span.LastIndexOfAny(values); Assert.Equal(expectedIndex, idx); } } [Fact] public static void TestNoMatchLastIndexOfAny_String_ManyByte() { var rnd = new Random(42); for (int length = 1; length < byte.MaxValue; length++) { var a = new string[length]; var targets = new string[length]; for (int i = 0; i < targets.Length; i++) { targets[i] = rnd.Next(1, 256).ToString(); } var span = new Span<string>(a); var values = new ReadOnlySpan<string>(targets); int idx = span.LastIndexOfAny(values); Assert.Equal(-1, idx); } } [Fact] public static void TestNoMatchValuesLargerLastIndexOfAny_String_ManyByte() { var rnd = new Random(42); for (int length = 1; length < byte.MaxValue; length++) { var a = new string[length]; var targets = new string[length * 2]; for (int i = 0; i < targets.Length; i++) { targets[i] = rnd.Next(1, 256).ToString(); } var span = new Span<string>(a); var values = new ReadOnlySpan<string>(targets); int idx = span.LastIndexOfAny(values); Assert.Equal(-1, idx); } } [Fact] public static void TestMultipleMatchLastIndexOfAny_String_ManyByte() { for (int length = 5; length < byte.MaxValue; length++) { var a = new string[length]; for (int i = 0; i < length; i++) { string val = (i + 1).ToString(); a[i] = val == "200" ? "201" : val; } a[length - 1] = "200"; a[length - 2] = "200"; a[length - 3] = "200"; a[length - 4] = "200"; a[length - 5] = "200"; var span = new Span<string>(a); var values = new ReadOnlySpan<string>(new string[] { "200", "200", "200", "200", "200", "200", "200", "200", "200" }); int idx = span.LastIndexOfAny(values); Assert.Equal(length - 1, idx); } } [Fact] public static void MakeSureNoChecksGoOutOfRangeLastIndexOfAny_String_ManyByte() { for (int length = 1; length < byte.MaxValue; length++) { var a = new string[length + 2]; a[0] = "99"; a[length + 1] = "98"; var span = new Span<string>(a, 1, length - 1); var values = new ReadOnlySpan<string>(new string[] { "99", "98", "99", "98", "99", "98" }); int index = span.LastIndexOfAny(values); Assert.Equal(-1, index); } for (int length = 1; length < byte.MaxValue; length++) { var a = new string[length + 2]; a[0] = "99"; a[length + 1] = "99"; var span = new Span<string>(a, 1, length - 1); var values = new ReadOnlySpan<string>(new string[] { "99", "99", "99", "99", "99", "99" }); int index = span.LastIndexOfAny(values); Assert.Equal(-1, index); } } [Theory] [MemberData(nameof(TestHelpers.LastIndexOfAnyNullSequenceData), MemberType = typeof(TestHelpers))] public static void LastIndexOfAnyNullSequence_String(string[] spanInput, string[] searchInput, int expected) { Span<string> theStrings = spanInput; Assert.Equal(expected, theStrings.LastIndexOfAny(searchInput)); Assert.Equal(expected, theStrings.LastIndexOfAny((ReadOnlySpan<string>)searchInput)); if (searchInput != null) { if (searchInput.Length >= 3) { Assert.Equal(expected, theStrings.LastIndexOfAny(searchInput[0], searchInput[1], searchInput[2])); } if (searchInput.Length >= 2) { Assert.Equal(expected, theStrings.LastIndexOfAny(searchInput[0], searchInput[1])); } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace DataTables.AspNet.Samples.WebApi2.BasicIntegration.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
/* * Copyright 2013 Splunk, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"): you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ namespace Splunk { using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using Newtonsoft.Json; /// <summary> /// The <see cref="ResultsReaderJson"/> class reads a results/event JSON /// stream one event at a time. /// </summary> public class ResultsReaderJson : ResultsReader { /// <summary> /// Helper object that will only be constructed if the reader is /// handling JSON format used by export. /// </summary> private ExportHelper exportHelper; /// <summary> /// Whether the "preview" flag is read. /// </summary> private bool previewFlagRead; /// <summary> /// Initializes a new instance of the <see cref="ResultsReaderJson"/> /// class. /// </summary> /// <param name="stream">The JSON stream to parse.</param> public ResultsReaderJson(Stream stream) : this(stream, false) { } /// <summary> /// Initializes a new instance of the <see cref="ResultsReaderJson"/> /// class. /// </summary> /// <param name="stream">The JSON stream to parse.</param> /// <param name="isInMultiReader"> /// Whether the reader is the underlying reader of a multi reader. /// </param> internal ResultsReaderJson(Stream stream, bool isInMultiReader) : base(stream, isInMultiReader) { StreamReader = new StreamReader(stream); if (this.IsExportStream || isInMultiReader) { this.exportHelper = new ExportHelper(this); } this.FinishInitialization(); } /// <summary> /// Gets the stream reader on the JSON stream to parse. /// </summary> internal StreamReader StreamReader { get; private set; } /// <summary> /// Gets or sets the JSON reader. /// </summary> private JsonTextReader JsonReader { get; set; } /// <summary> /// Gets a value indicating whether the results are /// a preview from an unfinished search. /// </summary> public override bool IsPreview { get { if (!this.previewFlagRead) { throw new InvalidOperationException( "isPreview() is not supported " + "with a stream from a Splunk 4.x server by this class. " + "Use the XML format and an XML result reader instead."); } return base.IsPreview; } protected set { base.IsPreview = value; } } /// <summary> /// Not supported. /// </summary> public override ICollection<string> Fields { // Unlike XML and CSV, JSON result streams do not provide field name // list before events. get { throw new InvalidOperationException( "Fields is not supported by this subclass."); } } /// <summary> /// Gets a value indicating whether the reader has been /// disposed. /// </summary> private bool IsDisposed { get { return this.StreamReader == null; } } /// <summary> /// Advances to the next set, skipping remaining event(s) /// if there are any in the current set. /// </summary> /// <returns>Returns false if the end is reached.</returns> internal override bool AdvanceStreamToNextSet() { return this.AdvanceIntoNextSetBeforeEvent(); } /// <summary> /// Advances to the next set, skipping remaining event(s) /// if there are any in the current set, and reads metadata before the /// first event in the next result set. /// </summary> /// <returns>Return false if the end is reached.</returns> internal bool AdvanceIntoNextSetBeforeEvent() { // If the end of stream has been reached, don't continue. if (this.IsDisposed) { return false; } // In Splunk 5.0 from the export endpoint, // each result is in its own top level object. // In Splunk 5.0 not from the export endpoint, the results are // an array at that object's key "results". // In Splunk 4.3, the // array was the top level returned. So if we find an object // at top level, we step into it until we find the right key, // then leave it in that state to iterate over. // // JSON single-reader depends on 'isExportStream' flag to function. // It does not support a stream from a file saved from // a stream from an export endpoint. // JSON multi-reader assumes export format thus does not support // a stream from none export endpoints. if (this.exportHelper != null) { /* * We're on Splunk 5 with a single-reader not from * an export endpoint * Below is an example of an input stream. * {"preview":true,"offset":0,"lastrow":true,"result":{"host":"Andy-PC","count":"62"}} * {"preview":true,"offset":0,"result":{"host":"Andy-PC","count":"1682"}} */ // Read into first result object of the cachedElement set. while (true) { bool endPassed = this.exportHelper.LastRow; this.exportHelper.SkipRestOfRow(); if (!this.exportHelper.ReadIntoRow()) { return false; } if (endPassed) { break; } } return true; } // Introduced in Splunk 5.0, the format of the JSON object // changed. Prior to 5.0, the array of events were a top level // JSON element. In 5.0 (not from Export), // the results are an array under the // key "results". // Note: Reading causes the side effect of setting the JSON node // information. this.JsonReader = new JsonTextReader(StreamReader); this.JsonReader.Read(); if (this.JsonReader.TokenType.Equals(JsonToken.StartObject)) { /* * We're on Splunk 5 with a single-reader not from * an export endpoint * Below is an example of an input stream. * {"preview":false,"init_offset":0,"messages":[{"type":"DEBUG","text":"base lispy: [ AND index::_internal ]"},{"type":"DEBUG","text":"search context: user=\"admin\", app=\"search\", bs-pathname=\"/Users/fross/splunks/splunk-5.0/etc\""}],"results":[{"sum(kb)":"14372242.758775","series":"twitter"},{"sum(kb)":"267802.333926","series":"splunkd"},{"sum(kb)":"5979.036338","series":"splunkd_access"}]} */ while (true) { if (!this.JsonReader.Read()) { this.Dispose(); return false; } if (this .JsonReader .TokenType .Equals(JsonToken.PropertyName)) { if (this.JsonReader.Value.Equals("preview")) { this.ReadPreviewFlag(); } if (this.JsonReader.Value.Equals("results")) { this.JsonReader.Read(); return true; } } } } else { /* Pre Splunk 5.0 * Below is an example of an input stream * [ * { * "sum(kb)":"14372242.758775", * "series":"twitter" * }, * { * "sum(kb)":"267802.333926", * "series":"splunkd" * }, * { * "sum(kb)":"5979.036338", * "series":"splunkd_access" * } * ] */ return true; } } /// <summary> /// Releases unmanaged resources. /// </summary> public override void Dispose() { if (this.IsDisposed) { return; } // The JSON reader is created after // constructor so the property could be // null. if (this.JsonReader != null) { ((IDisposable)this.JsonReader).Dispose(); } if (this.exportHelper != null) { this.exportHelper.Dispose(); } this.StreamReader.Close(); // Marking this reader as disposed. this.StreamReader = null; } /// <summary> /// Retrieves the enumerator for data returned from Splunk. /// </summary> /// <returns>A enumerator.</returns> internal override IEnumerable<Event> GetEventsFromCurrentSet() { while (true) { if (this.IsDisposed) { yield break; } if (this.exportHelper != null) { // If the last row has been passed and // AdvanceStreamToNextSet // has not been called, end the current set. if (this.exportHelper.LastRow && !this.exportHelper.InRow) { yield break; } this.exportHelper.ReadIntoRow(); } var returnData = this.ReadEvent(); if (this.exportHelper != null) { this.exportHelper.SkipRestOfRow(); } if (returnData == null) { // End the result reader. This is needed for Splunk 4.x this.Dispose(); yield break; } yield return returnData; } } /// <summary> /// Reads an event from the JSON reader. /// </summary> /// <returns> /// The event. A value of null indicates the end of stream, /// which is used by none --export cases. /// </returns> private Event ReadEvent() { string name = null; Event returnData = null; // Events are almost flat, so no need for a true general parser // solution. while (this.JsonReader.Read()) { if (returnData == null) { returnData = new Event(); } if (this.JsonReader.TokenType.Equals(JsonToken.StartObject)) { // skip } else if (this.JsonReader.TokenType.Equals(JsonToken.StartArray)) { var data = new List<string>(); while (this.JsonReader.Read()) { if (this .JsonReader .TokenType .Equals(JsonToken.EndArray)) { break; } if (this .JsonReader .TokenType .Equals(JsonToken.PropertyName)) { data.Add((string)this.JsonReader.Value); } } Debug.Assert(name != null, "Event field name is not set."); returnData.Add(name, new Event.FieldValue(data.ToArray())); } else if (this .JsonReader .TokenType .Equals(JsonToken.PropertyName)) { name = (string)this.JsonReader.Value; } else if (this.JsonReader.TokenType.Equals(JsonToken.String)) { Debug.Assert(name != null, "Event field name is not set."); returnData.Add(name, new Event.FieldValue((string)this.JsonReader.Value)); } else if (this.JsonReader.TokenType.Equals(JsonToken.EndObject)) { break; } else if (this.JsonReader.TokenType.Equals(JsonToken.EndArray)) { return null; // this is the end of the event set. } } return returnData; } /// <summary> /// Reads the preview flag value from the stream. /// </summary> private void ReadPreviewFlag() { this.JsonReader.Read(); this.IsPreview = (bool)this.JsonReader.Value; this.previewFlagRead = true; } /// <summary> /// Contains code only used for streams from the export endpoint. /// </summary> private class ExportHelper : IDisposable { /// <summary> /// The JSON reader. /// </summary> private readonly ResultsReaderJson resultsReader; /// <summary> /// The row being read. /// </summary> private StringReader currentRow; /// <summary> /// Initializes a new instance of the <see cref="ExportHelper" /> class. /// </summary> /// <param name="resultsReader">The result reader that is using this helper.</param> public ExportHelper(ResultsReaderJson resultsReader) { this.resultsReader = resultsReader; // Initial value must be true so that // the first row is treated as the start of a new set. this.LastRow = true; } /// <summary> /// Gets or sets the JSON reader, which is also used by /// the result reader itself. /// </summary> private JsonTextReader JsonReader { get { return this.resultsReader.JsonReader; } set { this.resultsReader.JsonReader = value; } } /// <summary> /// Gets a value indicating whether the row /// is the last in the current set. /// </summary> internal bool LastRow { get; private set; } /// <summary> /// Gets a value indicating whether the reader is in the middle /// or a row. /// </summary> public bool InRow { get; private set; } /// <summary> /// Reads metadata in the current row before event data. /// </summary> /// <returns>Returns false if the end of the stream is /// encountered.</returns> public bool ReadIntoRow() { if (this.InRow) { return true; } this.InRow = true; // Each row is a JSON object. Multiple such rows together is not // valid JSON format. JsonTestReader will fail on those. The JSON output format // is designed to use line breaks to seperate the rows. Below // we take one row and give it to a seperate JSON reader. var line = this.resultsReader.StreamReader.ReadLine(); if (line == null) { this.resultsReader.Dispose(); return false; } var stringReader = new StringReader(line); this.currentRow = stringReader; this.JsonReader = new JsonTextReader(this.currentRow); this.JsonReader.Read(); if (this.JsonReader.TokenType == JsonToken.StartArray) { throw new InvalidOperationException( "A stream from an export endpoint of " + "a Splunk 4.x server in the JSON output format " + "is not supported by this class. " + "Use the XML search output format, " + "and an XML result reader instead."); } // lastrow name and value pair does not appear if the row // is not the last in the set. this.LastRow = false; while (this.JsonReader.Read()) { if (this .JsonReader .TokenType .Equals(JsonToken.PropertyName)) { var name = (string)this.JsonReader.Value; if (name == "preview") { this.resultsReader.ReadPreviewFlag(); } else if (name == "lastrow") { this.JsonReader.Read(); this.LastRow = (bool)this.JsonReader.Value; } else if (name == "result") { return true; } else { this.JsonReader.Skip(); } } } return false; } /// <summary> /// Skips the rest of the current row. /// </summary> public void SkipRestOfRow() { if (!this.InRow) { return; } this.InRow = false; ((IDisposable)this.JsonReader).Dispose(); this.currentRow.Dispose(); } /// <summary> /// Releases resources, including unmanaged ones. /// </summary> public void Dispose() { ((IDisposable)this.JsonReader).Dispose(); this.currentRow.Dispose(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Cassandra; using Newtonsoft.Json; using Appleseed.Services.Base.Engine.Web.API.Models; namespace Appleseed.Services.Base.Engine.Web.API.Controllers { [Produces("application/json")] [Route("api/Config")] public class ConfigController : Controller { private string appConfigSource = "127.0.0.1"; private int appConfigSourcePort = 9042; private Config GetConfig(RowSet rowSet) { var engineJson = new Config(); var configList = new List<ConfigItem>(); foreach (var itemRow in rowSet) { var configItem = new ConfigItem(); configItem.config_name = (itemRow["config_name"] ?? "").ToString(); configItem.config_type = (itemRow["config_type"] ?? "").ToString(); configItem.config_values = (SortedDictionary<string, IDictionary<string, string>>)(itemRow["config_values"]); configList.Add(configItem); } engineJson.Engine = configList; return engineJson; } // GET: api/Config [HttpGet(Name = "Get Config")] public Config Get() { //var appConfigSource = ConfigurationManager.AppSettings["CassandraUrl"]; //var appConfigSourcePort = Convert.ToInt32(ConfigurationManager.AppSettings["CassandraPort"]); Cluster cluster = Cluster.Builder().WithPort(appConfigSourcePort).AddContactPoint(appConfigSource).Build(); Cassandra.ISession session = cluster.Connect("appleseed_search_engines"); var engineItems = session.Execute("select * from config"); var engineJson = GetConfig(engineItems); return engineJson; } // GET: api/Config/source [HttpGet("{type}", Name = "Get Config Type")] public Config Get(string type) { Cluster cluster = Cluster.Builder().WithPort(appConfigSourcePort).AddContactPoint(appConfigSource).Build(); Cassandra.ISession session = cluster.Connect("appleseed_search_engines"); var check = session.Prepare("select * from config where config_type = ?"); var checkStatement = check.Bind(type); var checkResults = session.Execute(checkStatement); var engineJson = GetConfig(checkResults); return engineJson; } // GET: api/Config/source/Data.XML [HttpGet("{type}/{name}", Name = "Get Config Type and Name")] public Config Get(string type, string name) { Cluster cluster = Cluster.Builder().WithPort(appConfigSourcePort).AddContactPoint(appConfigSource).Build(); Cassandra.ISession session = cluster.Connect("appleseed_search_engines"); var check = session.Prepare("select * from config where config_type = ? and config_name = ?"); var checkStatement = check.Bind(type, name); var checkResults = session.Execute(checkStatement); var engineJson = GetConfig(checkResults); return engineJson; } // POST: api/Config [HttpPost()] public IActionResult Post([FromBody] dynamic data) { if (data.config_type == null || data.config_name == null) { return BadRequest(); } Cluster cluster = Cluster.Builder().WithPort(appConfigSourcePort).AddContactPoint(appConfigSource).Build(); Cassandra.ISession session = cluster.Connect("appleseed_search_engines"); data = JsonConvert.SerializeObject(data); data = JsonConvert.DeserializeObject<ConfigItem>(data); var check = session.Prepare("select * from config where config_type = ? and config_name = ?"); var checkStatement = check.Bind(data.config_type, data.config_name); var checkResults = session.Execute(checkStatement); if (checkResults.GetAvailableWithoutFetching() > 0) { return BadRequest(); } var prep = session.Prepare("insert into config (config_type, config_name, config_values) values (?, ?, ?)"); var statement = prep.Bind(data.config_type, data.config_name, data.config_values); session.Execute(statement); return CreatedAtRoute("Get Config", data); } // POST: api/Config/source/Data.XML [HttpPost("{type}/{name}")] public IActionResult Post([FromBody] dynamic data, string type, string name) { Cluster cluster = Cluster.Builder().WithPort(appConfigSourcePort).AddContactPoint(appConfigSource).Build(); Cassandra.ISession session = cluster.Connect("appleseed_search_engines"); data.config_type = type; data.config_name = name; data = JsonConvert.SerializeObject(data); data = JsonConvert.DeserializeObject<ConfigItem>(data); var check = session.Prepare("select * from config where config_type = ? and config_name = ?"); var checkStatement = check.Bind(type, name); var checkResults = session.Execute(checkStatement); var results = checkResults.GetRows().ToList(); if (results.Count() == 0) { return BadRequest(); } var allValues = new SortedDictionary<string, IDictionary<string, string>>(); foreach (var dataValues in data.config_values) { foreach (var itemRow in results) { var itemValues = (SortedDictionary<string, IDictionary<string, string>>)(itemRow["config_values"]); foreach (var itemValue in itemValues) if (allValues.ContainsKey(itemValue.Key) == false) { allValues.Add(itemValue.Key, itemValue.Value); } if (itemValues.ContainsKey(dataValues.Key) == false) { allValues.Add(dataValues.Key, dataValues.Value); } else { return BadRequest(); } } } var prep = session.Prepare("insert into config (config_type, config_name, config_values) values (?, ?, ?)"); var statement = prep.Bind(type, name, allValues); session.Execute(statement); return CreatedAtRoute("Get Config", data); } // POST: api/Config/source/Data.XML/Contacts [HttpPost("{type}/{name}/{item}")] public IActionResult Post([FromBody] dynamic data, string type, string name, string item) { Cluster cluster = Cluster.Builder().WithPort(appConfigSourcePort).AddContactPoint(appConfigSource).Build(); Cassandra.ISession session = cluster.Connect("appleseed_search_engines"); var check = session.Prepare("select * from config where config_type = ? and config_name = ?"); var checkStatement = check.Bind(type, name); var checkResults = session.Execute(checkStatement); var results = checkResults.GetRows().ToList(); if (results.Count == 0) { return BadRequest(); } var allValues = new SortedDictionary<string, IDictionary<string, string>>(); foreach (var dataValues in data) { var itemValues = (SortedDictionary<string, IDictionary<string, string>>)(results.First()["config_values"]); foreach (var itemValue in itemValues) { if (allValues.ContainsKey(itemValue.Key) == false) { allValues.Add(itemValue.Key, itemValue.Value); } } if (itemValues.ContainsKey(item) == true) { if (itemValues[item].ContainsKey(dataValues.Name) == false) { allValues[item].Add(dataValues.Name, dataValues.Value.ToString()); } else { return BadRequest(); } } else { return BadRequest(); } } var prep = session.Prepare("insert into config (config_type, config_name, config_values) values (?, ?, ?)"); var statement = prep.Bind(type, name, allValues); session.Execute(statement); return CreatedAtRoute("Get Config", data); } // PUT: api/Config/source/Data.XML [HttpPut("{type}/{name}")] public IActionResult Put([FromBody] dynamic data, string type, string name) { Cluster cluster = Cluster.Builder().WithPort(appConfigSourcePort).AddContactPoint(appConfigSource).Build(); Cassandra.ISession session = cluster.Connect("appleseed_search_engines"); data.config_type = type; data.config_name = name; data = JsonConvert.SerializeObject(data); data = JsonConvert.DeserializeObject<ConfigItem>(data); var check = session.Prepare("select * from config where config_type = ? and config_name = ?"); var checkStatement = check.Bind(type, name); var checkResults = session.Execute(checkStatement); var results = checkResults.GetRows().ToList(); if (results.Count() == 0) { return BadRequest(); } var itemValues = (SortedDictionary<string, IDictionary<string, string>>)(results.First()["config_values"]); foreach (var dataValues in data.config_values) { foreach (var itemRow in results) { foreach (var itemValue in itemValues.ToList()) { if (itemValues.ContainsKey(dataValues.Key) == true) { itemValues[dataValues.Key] = dataValues.Value; } else { return BadRequest(); } } } } var prep = session.Prepare("insert into config (config_type, config_name, config_values) values (?, ?, ?)"); var statement = prep.Bind(type, name, itemValues); session.Execute(statement); return CreatedAtRoute("Get Config Type and Name", data); } // PUT: api/Config/source/Data.XML/Contacts [HttpPut("{type}/{name}/{item}")] public IActionResult Put([FromBody] dynamic data, string type, string name, string item) { Cluster cluster = Cluster.Builder().WithPort(appConfigSourcePort).AddContactPoint(appConfigSource).Build(); Cassandra.ISession session = cluster.Connect("appleseed_search_engines"); var check = session.Prepare("select * from config where config_type = ? and config_name = ?"); var checkStatement = check.Bind(type, name); var checkResults = session.Execute(checkStatement); var results = checkResults.GetRows().ToList(); if (results.Count() == 0) { return BadRequest(); } var itemValues = (SortedDictionary<string, IDictionary<string, string>>)(results.First()["config_values"]); foreach (var dataValues in data) { foreach (var itemValue in itemValues) { if (itemValues.ContainsKey(item) == true) { if (itemValues[item].ContainsKey(dataValues.Name) == true) { itemValues[item][dataValues.Name] = dataValues.Value.ToString(); } else { return BadRequest(); } } else { return BadRequest(); } } } var prep = session.Prepare("insert into config (config_type, config_name, config_values) values (?, ?, ?)"); var statement = prep.Bind(type, name, itemValues); session.Execute(statement); return CreatedAtRoute("Get Config Type and Name", data); } // PUT: api/Config/source/Data.XML/Contacts/indexPath [HttpPut("{type}/{name}/{item}/{valueKey}")] public IActionResult Put([FromBody] dynamic data, string type, string name, string item, string valueKey) { Cluster cluster = Cluster.Builder().WithPort(appConfigSourcePort).AddContactPoint(appConfigSource).Build(); Cassandra.ISession session = cluster.Connect("appleseed_search_engines"); var check = session.Prepare("select * from config where config_type = ? and config_name = ?"); var checkStatement = check.Bind(type, name); var checkResults = session.Execute(checkStatement); var results = checkResults.GetRows().ToList(); if (results.Count() == 0) { return BadRequest(); } var itemValues = (SortedDictionary<string, IDictionary<string, string>>)(results.First()["config_values"]); foreach (var itemValue in itemValues) { if (itemValues.ContainsKey(item) == true) { if (itemValues[item].ContainsKey(valueKey) == true) { itemValues[item][valueKey] = data.ToString(); } else { return BadRequest(); } } else { return BadRequest(); } } var prep = session.Prepare("insert into config (config_type, config_name, config_values) values (?, ?, ?)"); var statement = prep.Bind(type, name, itemValues); session.Execute(statement); return CreatedAtRoute("Get Config Type and Name", data); } // DELETE: api/Config/source [HttpDelete("{type}")] public IActionResult Delete(string type) { Cluster cluster = Cluster.Builder().WithPort(appConfigSourcePort).AddContactPoint(appConfigSource).Build(); Cassandra.ISession session = cluster.Connect("appleseed_search_engines"); var check = session.Prepare("select * from config where config_type = ?"); var checkStatement = check.Bind(type); var checkResults = session.Execute(checkStatement); var results = checkResults.GetRows().ToList(); if (results.Count() == 0) { return BadRequest(); } var prep = session.Prepare("delete from config where config_type = ?"); var statement = prep.Bind(type); session.Execute(statement); return Ok(); } // DELETE: api/Config/source/Data.XML [HttpDelete("{type}/{name}")] public IActionResult Delete(string type, string name) { Cluster cluster = Cluster.Builder().WithPort(appConfigSourcePort).AddContactPoint(appConfigSource).Build(); Cassandra.ISession session = cluster.Connect("appleseed_search_engines"); var check = session.Prepare("select * from config where config_type = ? and config_name = ?"); var checkStatement = check.Bind(type, name); var checkResults = session.Execute(checkStatement); var results = checkResults.GetRows().ToList(); if (results.Count() == 0) { return BadRequest(); } var prep = session.Prepare("delete from config where config_type = ? and config_name = ?"); var statement = prep.Bind(type, name); session.Execute(statement); return Ok(); } // DELETE: api/Config/source/Data.XML [HttpDelete("{type}/{name}/{item}")] public IActionResult Delete(string type, string name, string item) { Cluster cluster = Cluster.Builder().WithPort(appConfigSourcePort).AddContactPoint(appConfigSource).Build(); Cassandra.ISession session = cluster.Connect("appleseed_search_engines"); var check = session.Prepare("select * from config where config_type = ? and config_name = ?"); var checkStatement = check.Bind(type, name); var checkResults = session.Execute(checkStatement); var results = checkResults.GetRows().ToList(); if (results.Count() == 0) { return BadRequest(); } var itemValues = (SortedDictionary<string, IDictionary<string, string>>)(results.First()["config_values"]); if (itemValues.ContainsKey(item) == true) { itemValues.Remove(item); } else { return BadRequest(); } var prep = session.Prepare("insert into config (config_type, config_name, config_values) values (?, ?, ?)"); var statement = prep.Bind(type, name, itemValues); session.Execute(statement); return Ok(); } // DELETE: api/Config/source/Data.XML/indexPath [HttpDelete("{type}/{name}/{item}/{valueKey}")] public IActionResult Delete(string type, string name, string item, string valueKey) { Cluster cluster = Cluster.Builder().WithPort(appConfigSourcePort).AddContactPoint(appConfigSource).Build(); Cassandra.ISession session = cluster.Connect("appleseed_search_engines"); var check = session.Prepare("select * from config where config_type = ? and config_name = ?"); var checkStatement = check.Bind(type, name); var checkResults = session.Execute(checkStatement); var results = checkResults.GetRows().ToList(); if (results.Count() == 0) { return BadRequest(); } var itemValues = (SortedDictionary<string, IDictionary<string, string>>)(results.First()["config_values"]); if (itemValues.ContainsKey(item) == true) { if (itemValues[item].ContainsKey(valueKey) == true) { itemValues[item].Remove(valueKey); } else { return BadRequest(); } } else { return BadRequest(); } var prep = session.Prepare("insert into config (config_type, config_name, config_values) values (?, ?, ?)"); var statement = prep.Bind(type, name, itemValues); session.Execute(statement); return Ok(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using GitVersion.Logging; using LibGit2Sharp; namespace GitVersion.Extensions { public static class RepositoryExtensions { public static string GetRepositoryDirectory(this IRepository repository, bool omitGitPostFix = true) { var gitDirectory = repository.Info.Path; gitDirectory = gitDirectory.TrimEnd(Path.DirectorySeparatorChar); if (omitGitPostFix && gitDirectory.EndsWith(".git")) { gitDirectory = gitDirectory.Substring(0, gitDirectory.Length - ".git".Length); gitDirectory = gitDirectory.TrimEnd(Path.DirectorySeparatorChar); } return gitDirectory; } public static Branch FindBranch(this IRepository repository, string branchName) { return repository.Branches.FirstOrDefault(x => x.NameWithoutRemote() == branchName); } public static void DumpGraph(this IRepository repository, Action<string> writer = null, int? maxCommits = null) { LibGitExtensions.DumpGraph(repository.Info.Path, writer, maxCommits); } public static void EnsureLocalBranchExistsForCurrentBranch(this IRepository repo, ILog log, Remote remote, string currentBranch) { if (string.IsNullOrEmpty(currentBranch)) return; var isRef = currentBranch.Contains("refs"); var isBranch = currentBranch.Contains("refs/heads"); var localCanonicalName = !isRef ? "refs/heads/" + currentBranch : isBranch ? currentBranch : currentBranch.Replace("refs/", "refs/heads/"); var repoTip = repo.Head.Tip; // We currently have the rep.Head of the *default* branch, now we need to look up the right one var originCanonicalName = $"{remote.Name}/{currentBranch}"; var originBranch = repo.Branches[originCanonicalName]; if (originBranch != null) { repoTip = originBranch.Tip; } var repoTipId = repoTip.Id; if (repo.Branches.All(b => b.CanonicalName != localCanonicalName)) { log.Info(isBranch ? $"Creating local branch {localCanonicalName}" : $"Creating local branch {localCanonicalName} pointing at {repoTipId}"); repo.Refs.Add(localCanonicalName, repoTipId); } else { log.Info(isBranch ? $"Updating local branch {localCanonicalName} to point at {repoTip.Sha}" : $"Updating local branch {localCanonicalName} to match ref {currentBranch}"); repo.Refs.UpdateTarget(repo.Refs[localCanonicalName], repoTipId); } Commands.Checkout(repo, localCanonicalName); } public static void AddMissingRefSpecs(this IRepository repo, ILog log, Remote remote) { if (remote.FetchRefSpecs.Any(r => r.Source == "refs/heads/*")) return; var allBranchesFetchRefSpec = $"+refs/heads/*:refs/remotes/{remote.Name}/*"; log.Info($"Adding refspec: {allBranchesFetchRefSpec}"); repo.Network.Remotes.Update(remote.Name, r => r.FetchRefSpecs.Add(allBranchesFetchRefSpec)); } public static void CreateFakeBranchPointingAtThePullRequestTip(this IRepository repo, ILog log, AuthenticationInfo authentication) { var remote = repo.Network.Remotes.Single(); log.Info("Fetching remote refs to see if there is a pull request ref"); var remoteTips = (string.IsNullOrEmpty(authentication.Username) ? repo.GetRemoteTipsForAnonymousUser(remote) : repo.GetRemoteTipsUsingUsernamePasswordCredentials(remote, authentication.Username, authentication.Password)) .ToList(); log.Info($"Remote Refs:{System.Environment.NewLine}" + string.Join(System.Environment.NewLine, remoteTips.Select(r => r.CanonicalName))); var headTipSha = repo.Head.Tip.Sha; var refs = remoteTips.Where(r => r.TargetIdentifier == headTipSha).ToList(); if (refs.Count == 0) { var message = $"Couldn't find any remote tips from remote '{remote.Url}' pointing at the commit '{headTipSha}'."; throw new WarningException(message); } if (refs.Count > 1) { var names = string.Join(", ", refs.Select(r => r.CanonicalName)); var message = $"Found more than one remote tip from remote '{remote.Url}' pointing at the commit '{headTipSha}'. Unable to determine which one to use ({names})."; throw new WarningException(message); } var reference = refs[0]; var canonicalName = reference.CanonicalName; log.Info($"Found remote tip '{canonicalName}' pointing at the commit '{headTipSha}'."); if (canonicalName.StartsWith("refs/tags")) { log.Info($"Checking out tag '{canonicalName}'"); Commands.Checkout(repo, reference.Target.Sha); return; } if (!canonicalName.StartsWith("refs/pull/") && !canonicalName.StartsWith("refs/pull-requests/")) { var message = $"Remote tip '{canonicalName}' from remote '{remote.Url}' doesn't look like a valid pull request."; throw new WarningException(message); } var fakeBranchName = canonicalName.Replace("refs/pull/", "refs/heads/pull/").Replace("refs/pull-requests/", "refs/heads/pull-requests/"); log.Info($"Creating fake local branch '{fakeBranchName}'."); repo.Refs.Add(fakeBranchName, new ObjectId(headTipSha)); log.Info($"Checking local branch '{fakeBranchName}' out."); Commands.Checkout(repo, fakeBranchName); } public static void CreateOrUpdateLocalBranchesFromRemoteTrackingOnes(this IRepository repo, ILog log, string remoteName) { var prefix = $"refs/remotes/{remoteName}/"; var remoteHeadCanonicalName = $"{prefix}HEAD"; foreach (var remoteTrackingReference in repo.Refs.FromGlob(prefix + "*").Where(r => r.CanonicalName != remoteHeadCanonicalName)) { var remoteTrackingReferenceName = remoteTrackingReference.CanonicalName; var branchName = remoteTrackingReferenceName.Substring(prefix.Length); var localCanonicalName = "refs/heads/" + branchName; // We do not want to touch our current branch if (branchName == repo.Head.FriendlyName) continue; if (repo.Refs.Any(x => x.CanonicalName == localCanonicalName)) { var localRef = repo.Refs[localCanonicalName]; var remotedirectReference = remoteTrackingReference.ResolveToDirectReference(); if (localRef.ResolveToDirectReference().TargetIdentifier == remotedirectReference.TargetIdentifier) { log.Info($"Skipping update of '{remoteTrackingReference.CanonicalName}' as it already matches the remote ref."); continue; } var remoteRefTipId = remotedirectReference.Target.Id; log.Info($"Updating local ref '{localRef.CanonicalName}' to point at {remoteRefTipId}."); repo.Refs.UpdateTarget(localRef, remoteRefTipId); continue; } log.Info($"Creating local branch from remote tracking '{remoteTrackingReference.CanonicalName}'."); repo.Refs.Add(localCanonicalName, new ObjectId(remoteTrackingReference.ResolveToDirectReference().TargetIdentifier), true); var branch = repo.Branches[branchName]; repo.Branches.Update(branch, b => b.TrackedBranch = remoteTrackingReferenceName); } } public static Remote EnsureOnlyOneRemoteIsDefined(this IRepository repo, ILog log) { var remotes = repo.Network.Remotes; var howMany = remotes.Count(); if (howMany == 1) { var remote = remotes.Single(); log.Info($"One remote found ({remote.Name} -> '{remote.Url}')."); return remote; } var message = $"{howMany} remote(s) have been detected. When being run on a build server, the Git repository is expected to bear one (and no more than one) remote."; throw new WarningException(message); } private static IEnumerable<DirectReference> GetRemoteTipsUsingUsernamePasswordCredentials(this IRepository repository, Remote remote, string username, string password) { return repository.Network.ListReferences(remote, (url, fromUrl, types) => new UsernamePasswordCredentials { Username = username, Password = password ?? string.Empty }).Select(r => r.ResolveToDirectReference()); } private static IEnumerable<DirectReference> GetRemoteTipsForAnonymousUser(this IRepository repository, Remote remote) { return repository.Network.ListReferences(remote).Select(r => r.ResolveToDirectReference()); } } }
using EpisodeInformer.Core.Rss; using EpisodeInformer.Core.Threading; using EpisodeInformer.Data; using EpisodeInformer.LocalClasses; using System; using System.ComponentModel; using System.Drawing; using System.Windows.Forms; namespace EpisodeInformer { public partial class frmAEDFeed : Form { private RssFeed currentFeed; public FeedManagerMode FormMode { get; private set; } public FeedAEDAction ActionTook { get; private set; } public frmAEDFeed() { this.InitializeComponent(); this.FormMode = FeedManagerMode.ADD; this.ActionTook = FeedAEDAction.UNTOUCHED; this.currentFeed = new RssFeed(); this.LoadFeeds(); this.SetMode(); } public frmAEDFeed(RssFeed feed) { this.InitializeComponent(); this.ActionTook = FeedAEDAction.UNTOUCHED; this.currentFeed = feed; this.SetMode(); this.cmbURL.Items.Add((object)this.currentFeed.URL); this.cmbURL.SelectedIndex = this.cmbURL.Items.IndexOf((object)this.currentFeed.URL); this.cmbURL.Text = this.currentFeed.URL; } private void frmAEDFeed_Load(object sender, EventArgs e) { ThreadingHelper.SetUIDispatcher(); this.currentFeed.HeaderReadFinished += new delFeedHeaderRead(this.currentFeed_HeaderReadFinished); } private void btnAE_Click(object sender, EventArgs e) { if (this.FormMode == FeedManagerMode.ADD) { if (this.IsFieldsFilled()) { this.currentFeed.URL = this.cmbURL.Text; this.currentFeed.Title = this.txtTitle.Text; this.currentFeed.Description = this.txtDes.Text; RssDBAction.AddFeed(this.currentFeed); this.ActionTook = FeedAEDAction.ADDED; this.cmbURL.Items.Clear(); this.LoadFeeds(); this.cmbURL.Text = ""; this.LockControlForValidation(false); int num = (int)MessageBox.Show("Feed added to your feed list.", "Feed Added", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } else { int num1 = (int)MessageBox.Show("Please check URL, Title and Description fields are filled.", "Empty Fields", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } else if (this.IsFieldsFilled()) { this.currentFeed.URL = this.cmbURL.Text; this.currentFeed.Title = this.txtTitle.Text; this.currentFeed.Description = this.txtDes.Text; RssDBAction.UpdateFeed(this.currentFeed); this.ActionTook = FeedAEDAction.EDITED; this.cmbURL.Items.Clear(); this.LoadFeeds(); this.cmbURL.Text = ""; this.LockControlForValidation(false); int num2 = (int)MessageBox.Show("Feed information updated.", "Feed Updated", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); } else { int num3 = (int)MessageBox.Show("Please check URL, Title and Description fields are filled.", "Empty Fields", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } private void btnDelete_Click(object sender, EventArgs e) { if (this.cmbURL.SelectedIndex == -1 || MessageBox.Show("Delete rss feed '" + this.cmbURL.Text + "' from you feed list?", "Delete feed", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes) return; this.currentFeed.URL = this.cmbURL.Text; RssDBAction.DeleteFeed(this.currentFeed); int num = (int)MessageBox.Show("Feed deleted from feed list.", "Feed Deleted", MessageBoxButtons.OK, MessageBoxIcon.Asterisk); this.ActionTook = FeedAEDAction.DELETED; this.cmbURL.Items.Clear(); this.LoadFeeds(); this.cmbURL.Text = ""; this.LockControlForValidation(false); } private void btnClose_Click(object sender, EventArgs e) { this.Close(); } private void lnkLReadHeader_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { if (this.cmbURL.Text.Length > 0) { this.currentFeed.URL = this.cmbURL.Text; this.currentFeed.ReadFeedHeaderAsync(); this.lblStatus.Text = string.Format("Reading header of '{0}' rss feed.", (object)this.cmbURL.Text); } else { int num = (int)MessageBox.Show("You forgot to enter the feed's URL", "Missing url", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } private void cmbURL_TextUpdate(object sender, EventArgs e) { this.LockControlForValidation(false); this.FormMode = FeedManagerMode.ADD; this.SetMode(); } private void cmbURL_SelectedIndexChanged(object sender, EventArgs e) { if (this.cmbURL.SelectedIndex != -1) { this.LockControlForValidation(true); this.txtTitle.Text = this.currentFeed.Title; this.txtDes.Text = this.currentFeed.Description; this.SetMode(); } else { this.currentFeed.Title = (string)null; this.currentFeed.Description = (string)null; this.LockControlForValidation(false); this.FormMode = FeedManagerMode.ADD; this.SetMode(); } } private void currentFeed_HeaderReadFinished(object sender, RssHeaderStatus status) { if (status == RssHeaderStatus.DONE) { this.lblStatus.Text = "Done reading header."; this.txtTitle.Text = this.currentFeed.Title; this.txtDes.Text = this.currentFeed.Description; this.LockControlForValidation(true); } else if (status == RssHeaderStatus.ERROR) { this.txtTitle.Text = ""; this.txtDes.Text = ""; int num = (int)MessageBox.Show("Could retrive feed header. Please check the URL and your Internet connection and try again", "Feed Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); this.lblStatus.Text = "Waiting"; this.LockControlForValidation(false); } else { if (status != RssHeaderStatus.INVALID) return; this.txtTitle.Text = ""; this.txtDes.Text = ""; int num = (int)MessageBox.Show("This Rss feed is not currently compatible.", "Compatibility issue", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); this.lblStatus.Text = "Waiting"; this.LockControlForValidation(false); } } private void LoadFeeds() { foreach (RssFeed rssFeed in RssDBQuery.GetAllFeeds()) this.cmbURL.Items.Add((object)rssFeed.URL); } private void SetMode() { if (this.FormMode != FeedManagerMode.ADD) return; this.btnAE.Text = "ADD"; this.btnDelete.Enabled = false; } private void SetFieldValuesForCurFeed() { this.cmbURL.Text = this.currentFeed.URL; this.txtTitle.Text = this.currentFeed.Title; this.txtDes.Text = this.currentFeed.Description; } private void LockControlForValidation(bool enabled) { this.txtTitle.Enabled = enabled; this.txtDes.Enabled = enabled; if (enabled) return; this.txtDes.Text = ""; this.txtTitle.Text = ""; } public bool IsFieldsFilled() { return this.txtTitle.Text.Trim().Length > 0 && this.txtDes.Text.Trim().Length > 0 && this.cmbURL.Text.Trim().Length > 0; } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils { using System; using System.Collections.Generic; /// <summary> /// Represents a range of bytes in a stream. /// </summary> /// <remarks>This is normally used to represent regions of a SparseStream that /// are actually stored in the underlying storage medium (rather than implied /// zero bytes). Extents are stored as a zero-based byte offset (from the /// beginning of the stream), and a byte length</remarks> public sealed class StreamExtent : IEquatable<StreamExtent>, IComparable<StreamExtent> { private long _start; private long _length; /// <summary> /// Initializes a new instance of the StreamExtent class. /// </summary> /// <param name="start">The start of the extent</param> /// <param name="length">The length of the extent</param> public StreamExtent(long start, long length) { _start = start; _length = length; } /// <summary> /// Gets the start of the extent (in bytes). /// </summary> public long Start { get { return _start; } } /// <summary> /// Gets the start of the extent (in bytes). /// </summary> public long Length { get { return _length; } } /// <summary> /// Calculates the union of a list of extents with another extent. /// </summary> /// <param name="extents">The list of extents</param> /// <param name="other">The other extent</param> /// <returns>The union of the extents.</returns> public static IEnumerable<StreamExtent> Union(IEnumerable<StreamExtent> extents, StreamExtent other) { List<StreamExtent> otherList = new List<StreamExtent>(); otherList.Add(other); return Union(extents, otherList); } /// <summary> /// Calculates the union of the extents of multiple streams. /// </summary> /// <param name="streams">The stream extents</param> /// <returns>The union of the extents from multiple streams.</returns> /// <remarks>A typical use of this method is to calculate the combined set of /// stored extents from a number of overlayed sparse streams.</remarks> public static IEnumerable<StreamExtent> Union(params IEnumerable<StreamExtent>[] streams) { long extentStart = long.MaxValue; long extentEnd = 0; // Initialize enumerations and find first stored byte position IEnumerator<StreamExtent>[] enums = new IEnumerator<StreamExtent>[streams.Length]; bool[] streamsValid = new bool[streams.Length]; int validStreamsRemaining = 0; for (int i = 0; i < streams.Length; ++i) { enums[i] = streams[i].GetEnumerator(); streamsValid[i] = enums[i].MoveNext(); if (streamsValid[i]) { ++validStreamsRemaining; if (enums[i].Current.Start < extentStart) { extentStart = enums[i].Current.Start; extentEnd = enums[i].Current.Start + enums[i].Current.Length; } } } while (validStreamsRemaining > 0) { // Find the end of this extent bool foundIntersection; do { foundIntersection = false; validStreamsRemaining = 0; for (int i = 0; i < streams.Length; ++i) { while (streamsValid[i] && enums[i].Current.Start + enums[i].Current.Length <= extentEnd) { streamsValid[i] = enums[i].MoveNext(); } if (streamsValid[i]) { ++validStreamsRemaining; } if (streamsValid[i] && enums[i].Current.Start <= extentEnd) { extentEnd = enums[i].Current.Start + enums[i].Current.Length; foundIntersection = true; streamsValid[i] = enums[i].MoveNext(); } } } while (foundIntersection && validStreamsRemaining > 0); // Return the discovered extent yield return new StreamExtent(extentStart, extentEnd - extentStart); // Find the next extent start point extentStart = long.MaxValue; validStreamsRemaining = 0; for (int i = 0; i < streams.Length; ++i) { if (streamsValid[i]) { ++validStreamsRemaining; if (enums[i].Current.Start < extentStart) { extentStart = enums[i].Current.Start; extentEnd = enums[i].Current.Start + enums[i].Current.Length; } } } } } /// <summary> /// Calculates the intersection of the extents of a stream with another extent. /// </summary> /// <param name="extents">The stream extents</param> /// <param name="other">The extent to intersect</param> /// <returns>The intersection of the extents.</returns> public static IEnumerable<StreamExtent> Intersect(IEnumerable<StreamExtent> extents, StreamExtent other) { List<StreamExtent> otherList = new List<StreamExtent>(1); otherList.Add(other); return Intersect(extents, otherList); } /// <summary> /// Calculates the intersection of the extents of multiple streams. /// </summary> /// <param name="streams">The stream extents</param> /// <returns>The intersection of the extents from multiple streams.</returns> /// <remarks>A typical use of this method is to calculate the extents in a /// region of a stream..</remarks> public static IEnumerable<StreamExtent> Intersect(params IEnumerable<StreamExtent>[] streams) { long extentStart = long.MinValue; long extentEnd = long.MaxValue; IEnumerator<StreamExtent>[] enums = new IEnumerator<StreamExtent>[streams.Length]; for (int i = 0; i < streams.Length; ++i) { enums[i] = streams[i].GetEnumerator(); if (!enums[i].MoveNext()) { // Gone past end of one stream (in practice was empty), so no intersections yield break; } } int overlapsFound = 0; while (true) { // We keep cycling round the streams, until we get streams.Length continuous overlaps for (int i = 0; i < streams.Length; ++i) { // Move stream on past all extents that are earlier than our candidate start point while (enums[i].Current.Length == 0 || enums[i].Current.Start + enums[i].Current.Length <= extentStart) { if (!enums[i].MoveNext()) { // Gone past end of this stream, no more intersections possible yield break; } } // If this stream has an extent that spans over the candidate start point if (enums[i].Current.Start <= extentStart) { extentEnd = Math.Min(extentEnd, enums[i].Current.Start + enums[i].Current.Length); overlapsFound++; } else { extentStart = enums[i].Current.Start; extentEnd = extentStart + enums[i].Current.Length; overlapsFound = 1; } // We've just done a complete loop of all streams, they overlapped this start position // and we've cut the extent's end down to the shortest run. if (overlapsFound == streams.Length) { yield return new StreamExtent(extentStart, extentEnd - extentStart); extentStart = extentEnd; extentEnd = long.MaxValue; overlapsFound = 0; } } } } /// <summary> /// Calculates the subtraction of the extents of a stream by another extent. /// </summary> /// <param name="extents">The stream extents</param> /// <param name="other">The extent to subtract</param> /// <returns>The subtraction of <c>other</c> from <c>extents</c>.</returns> public static IEnumerable<StreamExtent> Subtract(IEnumerable<StreamExtent> extents, StreamExtent other) { return Subtract(extents, new StreamExtent[] { other }); } /// <summary> /// Calculates the subtraction of the extents of a stream by another stream. /// </summary> /// <param name="a">The stream extents to subtract from</param> /// <param name="b">The stream extents to subtract</param> /// <returns>The subtraction of the extents of b from a.</returns> public static IEnumerable<StreamExtent> Subtract(IEnumerable<StreamExtent> a, IEnumerable<StreamExtent> b) { return Intersect(a, Invert(b)); } /// <summary> /// Calculates the inverse of the extents of a stream. /// </summary> /// <param name="extents">The stream extents to inverse</param> /// <returns>The inverted extents</returns> /// <remarks> /// This method assumes a logical stream addressable from <c>0</c> to <c>long.MaxValue</c>, and is undefined /// should any stream extent start at less than 0. To constrain the extents to a specific range, use the /// <c>Intersect</c> method. /// </remarks> public static IEnumerable<StreamExtent> Invert(IEnumerable<StreamExtent> extents) { StreamExtent last = new StreamExtent(0, 0); foreach (StreamExtent extent in extents) { // Skip over any 'noise' if (extent.Length == 0) { continue; } long lastEnd = last.Start + last.Length; if (lastEnd < extent.Start) { yield return new StreamExtent(lastEnd, extent.Start - lastEnd); } last = extent; } long finalEnd = last.Start + last.Length; if (finalEnd < long.MaxValue) { yield return new StreamExtent(finalEnd, long.MaxValue - finalEnd); } } /// <summary> /// Offsets the extents of a stream. /// </summary> /// <param name="stream">The stream extents</param> /// <param name="delta">The amount to offset the extents by</param> /// <returns>The stream extents, offset by delta.</returns> public static IEnumerable<StreamExtent> Offset(IEnumerable<StreamExtent> stream, long delta) { foreach (StreamExtent extent in stream) { yield return new StreamExtent(extent.Start + delta, extent.Length); } } /// <summary> /// Returns the number of blocks containing stream data. /// </summary> /// <param name="stream">The stream extents</param> /// <param name="blockSize">The size of each block</param> /// <returns>The number of blocks containing stream data</returns> /// <remarks>This method logically divides the stream into blocks of a specified /// size, then indicates how many of those blocks contain actual stream data.</remarks> public static long BlockCount(IEnumerable<StreamExtent> stream, long blockSize) { long totalBlocks = 0; long lastBlock = -1; foreach (var extent in stream) { if (extent.Length > 0) { long extentStartBlock = extent.Start / blockSize; long extentNextBlock = Utilities.Ceil(extent.Start + extent.Length, blockSize); long extentNumBlocks = extentNextBlock - extentStartBlock; if (extentStartBlock == lastBlock) { extentNumBlocks--; } lastBlock = extentNextBlock - 1; totalBlocks += extentNumBlocks; } } return totalBlocks; } /// <summary> /// Returns all of the blocks containing stream data. /// </summary> /// <param name="stream">The stream extents</param> /// <param name="blockSize">The size of each block</param> /// <returns>Ranges of blocks, as block indexes</returns> /// <remarks>This method logically divides the stream into blocks of a specified /// size, then indicates ranges of blocks that contain stream data.</remarks> public static IEnumerable<Range<long, long>> Blocks(IEnumerable<StreamExtent> stream, long blockSize) { long? rangeStart = null; long rangeLength = 0; foreach (var extent in stream) { if (extent.Length > 0) { long extentStartBlock = extent.Start / blockSize; long extentNextBlock = Utilities.Ceil(extent.Start + extent.Length, blockSize); if (rangeStart != null && extentStartBlock > rangeStart + rangeLength) { // This extent is non-contiguous (in terms of blocks), so write out the last range and start new yield return new Range<long, long>((long)rangeStart, rangeLength); rangeStart = extentStartBlock; } else if (rangeStart == null) { // First extent, so start first range rangeStart = extentStartBlock; } // Set the length of the current range, based on the end of this extent rangeLength = extentNextBlock - (long)rangeStart; } } // Final range (if any ranges at all) hasn't been returned yet, so do that now if (rangeStart != null) { yield return new Range<long, long>((long)rangeStart, rangeLength); } } /// <summary> /// The equality operator. /// </summary> /// <param name="a">The first extent to compare</param> /// <param name="b">The second extent to compare</param> /// <returns>Whether the two extents are equal</returns> public static bool operator ==(StreamExtent a, StreamExtent b) { if (Object.ReferenceEquals(a, null)) { return Object.ReferenceEquals(b, null); } else { return a.Equals(b); } } /// <summary> /// The inequality operator. /// </summary> /// <param name="a">The first extent to compare</param> /// <param name="b">The second extent to compare</param> /// <returns>Whether the two extents are different</returns> public static bool operator !=(StreamExtent a, StreamExtent b) { return !(a == b); } /// <summary> /// The less-than operator. /// </summary> /// <param name="a">The first extent to compare</param> /// <param name="b">The second extent to compare</param> /// <returns>Whether a is less than b</returns> public static bool operator <(StreamExtent a, StreamExtent b) { return a.CompareTo(b) < 0; } /// <summary> /// The greater-than operator. /// </summary> /// <param name="a">The first extent to compare</param> /// <param name="b">The second extent to compare</param> /// <returns>Whether a is greather than b</returns> public static bool operator >(StreamExtent a, StreamExtent b) { return a.CompareTo(b) > 0; } /// <summary> /// Indicates if this StreamExtent is equal to another. /// </summary> /// <param name="other">The extent to compare</param> /// <returns><c>true</c> if the extents are equal, else <c>false</c></returns> public bool Equals(StreamExtent other) { if (other == null) { return false; } else { return _start == other._start && _length == other._length; } } /// <summary> /// Returns a string representation of the extent as [start:+length]. /// </summary> /// <returns>The string representation</returns> public override string ToString() { return "[" + _start + ":+" + _length + "]"; } /// <summary> /// Indicates if this stream extent is equal to another object. /// </summary> /// <param name="obj">The object to test</param> /// <returns><c>true</c> if <c>obj</c> is equivalent, else <c>false</c></returns> public override bool Equals(object obj) { return Equals(obj as StreamExtent); } /// <summary> /// Gets a hash code for this extent. /// </summary> /// <returns>The extent's hash code.</returns> public override int GetHashCode() { return _start.GetHashCode() ^ _length.GetHashCode(); } /// <summary> /// Compares this stream extent to another. /// </summary> /// <param name="other">The extent to compare.</param> /// <returns>Value greater than zero if this extent starts after /// <c>other</c>, zero if they start at the same position, else /// a value less than zero.</returns> public int CompareTo(StreamExtent other) { if (_start > other._start) { return 1; } else if (_start == other._start) { return 0; } else { return -1; } } } }
using System; using NSubstitute; using NUnit.Framework; using NUnit.Framework.SyntaxHelpers; using SineSignal.Ottoman.Specs.Framework; using SineSignal.Ottoman.Serialization; namespace SineSignal.Ottoman.Specs.Serialization.JsonReaderSpecs { public class ReadingObjectsSpecs { public class When_reading_a_json_string_that_contains_an_object_with_a_single_member : ConcernFor<JsonReader> { private string input; protected override void Given() { input = "{\"name1\":true}"; } public override JsonReader CreateSystemUnderTest() { return new JsonReader(input); } public class And_when_calling_read_once : When_reading_a_json_string_that_contains_an_object_with_a_single_member { protected override void When() { Sut.Read(); } [Test] public void Should_set_current_token_to_object_start() { Assert.That(Sut.CurrentToken, Is.EqualTo(JsonToken.ObjectStart)); } } public class And_when_calling_read_twice : When_reading_a_json_string_that_contains_an_object_with_a_single_member { protected override void When() { Sut.Read(); Sut.Read(); } [Test] public void Should_set_current_token_to_member_name() { Assert.That(Sut.CurrentToken, Is.EqualTo(JsonToken.MemberName)); } [Test] public void Should_set_current_token_value_to_name1() { Assert.That(Sut.CurrentTokenValue, Is.EqualTo("name1")); } } public class And_when_calling_read_three_times : When_reading_a_json_string_that_contains_an_object_with_a_single_member { protected override void When() { for (int index = 1; index <= 3; index++) { Sut.Read(); } } [Test] public void Should_set_current_token_to_json_boolean() { Assert.That(Sut.CurrentToken, Is.EqualTo(JsonToken.Boolean)); } [Test] public void Should_set_current_token_value_to_true() { Assert.That(Sut.CurrentTokenValue, Is.True); } } public class And_when_calling_read_four_times : When_reading_a_json_string_that_contains_an_object_with_a_single_member { protected override void When() { for (int index = 1; index <= 4; index++) { Sut.Read(); } } [Test] public void Should_set_current_token_to_object_end() { Assert.That(Sut.CurrentToken, Is.EqualTo(JsonToken.ObjectEnd)); } } public class And_when_calling_read_five_times : When_reading_a_json_string_that_contains_an_object_with_a_single_member { protected override void When() { for (int index = 1; index <= 5; index++) { Sut.Read(); } } [Test] public void Should_set_end_of_json_to_true() { Assert.That(Sut.EndOfJson, Is.True); } } } public class When_reading_a_json_string_that_contains_an_object_with_two_members_and_comments : ConcernFor<JsonReader> { private string input; protected override void Given() { input = @" { // This is a single-line comment ""name1"" : ""One"", /** * This is a multi-line another comment **/ ""name2"": ""Two"" }"; } public override JsonReader CreateSystemUnderTest() { var jsonReader = new JsonReader(input); jsonReader.AllowComments = true; return jsonReader; } public class And_when_calling_read_twice : When_reading_a_json_string_that_contains_an_object_with_two_members_and_comments { protected override void When() { Sut.Read(); Sut.Read(); } [Test] public void Should_set_current_token_to_member_name() { Assert.That(Sut.CurrentToken, Is.EqualTo(JsonToken.MemberName)); } [Test] public void Should_set_current_token_value_to_name1() { Assert.That(Sut.CurrentTokenValue, Is.EqualTo("name1")); } } public class And_when_calling_read_three_times : When_reading_a_json_string_that_contains_an_object_with_two_members_and_comments { protected override void When() { for (int index = 1; index <= 3; index++) { Sut.Read(); } } [Test] public void Should_set_current_token_to_json_string() { Assert.That(Sut.CurrentToken, Is.EqualTo(JsonToken.String)); } [Test] public void Should_set_current_token_value_to_One() { Assert.That(Sut.CurrentTokenValue, Is.EqualTo("One")); } } public class And_when_calling_read_four_times : When_reading_a_json_string_that_contains_an_object_with_two_members_and_comments { protected override void When() { for (int index = 1; index <= 4; index++) { Sut.Read(); } } [Test] public void Should_set_current_token_to_member_name() { Assert.That(Sut.CurrentToken, Is.EqualTo(JsonToken.MemberName)); } [Test] public void Should_set_current_token_value_to_name2() { Assert.That(Sut.CurrentTokenValue, Is.EqualTo("name2")); } } public class And_when_calling_read_five_times : When_reading_a_json_string_that_contains_an_object_with_two_members_and_comments { protected override void When() { for (int index = 1; index <= 5; index++) { Sut.Read(); } } [Test] public void Should_set_current_token_to_json_string() { Assert.That(Sut.CurrentToken, Is.EqualTo(JsonToken.String)); } [Test] public void Should_set_current_token_value_to_Two() { Assert.That(Sut.CurrentTokenValue, Is.EqualTo("Two")); } } public class And_when_calling_read_seven_times : When_reading_a_json_string_that_contains_an_object_with_two_members_and_comments { protected override void When() { for (int index = 1; index <= 7; index++) { Sut.Read(); } } [Test] public void Should_set_end_of_json_to_true() { Assert.That(Sut.EndOfJson, Is.True); } } } public class When_reading_a_json_string_with_nested_objects : ConcernFor<JsonReader> { private string input; private int objectCount; protected override void Given() { input = "{ \"name1\" : { \"name2\": { \"name3\": true } } }"; objectCount = 0; } public override JsonReader CreateSystemUnderTest() { return new JsonReader(input); } protected override void When() { while (Sut.Read()) { if (Sut.CurrentToken == JsonToken.ObjectStart) { objectCount++; } } } [Test] public void Should_count_three_objects() { Assert.That(objectCount, Is.EqualTo(3)); } } public class When_reading_a_json_string_that_contains_an_object_with_the_wrong_closing_token : ConcernFor<JsonReader> { private string input; private JsonException expectedException; protected override void Given() { input = "{ \"name1\" : [ \"name2\", \"name3\", \"name4\" ] ]"; } public override JsonReader CreateSystemUnderTest() { return new JsonReader(input); } protected override void When() { try { while (Sut.Read()); } catch (JsonException e) { expectedException = e; } } [Test] public void Should_throw_a_json_exception() { Assert.That(expectedException, Is.TypeOf(typeof(JsonException))); } [Test] public void Should_set_message_to_Invalid_token_93_in_input_string() { Assert.That(expectedException.Message, Is.EqualTo("Invalid token '93' in input string")); } } public class When_reading_a_json_string_that_contains_an_object_with_no_closing_token : ConcernFor<JsonReader> { private string input; private JsonException expectedException; protected override void Given() { input = "{ \"name1\" : true "; } public override JsonReader CreateSystemUnderTest() { return new JsonReader(input); } protected override void When() { try { while (Sut.Read()); } catch (JsonException e) { expectedException = e; } } [Test] public void Should_throw_a_json_exception() { Assert.That(expectedException, Is.TypeOf(typeof(JsonException))); } [Test] public void Should_set_message_to_Input_does_not_evaluate_to_proper_JSON_text() { Assert.That(expectedException.Message, Is.EqualTo("Input doesn't evaluate to proper JSON text")); } } public class When_reading_a_json_string_that_contains_an_object_without_a_member_name : ConcernFor<JsonReader> { private string input; private JsonException expectedException; protected override void Given() { input = "{ {\"name1\": true} }"; } public override JsonReader CreateSystemUnderTest() { return new JsonReader(input); } protected override void When() { try { while (Sut.Read()); } catch (JsonException e) { expectedException = e; } } [Test] public void Should_throw_a_json_exception() { Assert.That(expectedException, Is.TypeOf(typeof(JsonException))); } [Test] public void Should_set_message_to_Invalid_token_123_in_input_string() { Assert.That(expectedException.Message, Is.EqualTo("Invalid token '123' in input string")); } } } }
namespace PrimerProForms { partial class FormPSTable { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormPSTable)); this.tbCount = new System.Windows.Forms.TextBox(); this.labOf = new System.Windows.Forms.Label(); this.tbCurrent = new System.Windows.Forms.TextBox(); this.tbCode = new System.Windows.Forms.TextBox(); this.labCode = new System.Windows.Forms.Label(); this.tbFind = new System.Windows.Forms.TextBox(); this.btnFind = new System.Windows.Forms.Button(); this.btnExit = new System.Windows.Forms.Button(); this.btnSave = new System.Windows.Forms.Button(); this.btnPrevious = new System.Windows.Forms.Button(); this.btnDelete = new System.Windows.Forms.Button(); this.btnAdd = new System.Windows.Forms.Button(); this.btnNext = new System.Windows.Forms.Button(); this.labDesc = new System.Windows.Forms.Label(); this.tbDesc = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // tbCount // this.tbCount.BorderStyle = System.Windows.Forms.BorderStyle.None; this.tbCount.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.tbCount.Location = new System.Drawing.Point(254, 40); this.tbCount.Name = "tbCount"; this.tbCount.ReadOnly = true; this.tbCount.Size = new System.Drawing.Size(36, 17); this.tbCount.TabIndex = 4; this.tbCount.TabStop = false; this.tbCount.Text = "???"; this.tbCount.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // labOf // this.labOf.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labOf.Location = new System.Drawing.Point(227, 40); this.labOf.Name = "labOf"; this.labOf.Size = new System.Drawing.Size(27, 25); this.labOf.TabIndex = 3; this.labOf.Text = "of"; this.labOf.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // tbCurrent // this.tbCurrent.BorderStyle = System.Windows.Forms.BorderStyle.None; this.tbCurrent.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.tbCurrent.Location = new System.Drawing.Point(182, 40); this.tbCurrent.Name = "tbCurrent"; this.tbCurrent.ReadOnly = true; this.tbCurrent.Size = new System.Drawing.Size(36, 17); this.tbCurrent.TabIndex = 2; this.tbCurrent.TabStop = false; this.tbCurrent.Text = "???"; this.tbCurrent.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // tbCode // this.tbCode.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.tbCode.Location = new System.Drawing.Point(110, 40); this.tbCode.Name = "tbCode"; this.tbCode.Size = new System.Drawing.Size(64, 24); this.tbCode.TabIndex = 1; // // labCode // this.labCode.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.labCode.Location = new System.Drawing.Point(40, 40); this.labCode.Name = "labCode"; this.labCode.Size = new System.Drawing.Size(56, 26); this.labCode.TabIndex = 0; this.labCode.Text = "Code"; // // tbFind // this.tbFind.Font = new System.Drawing.Font("Microsoft Sans Serif", 10.2F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.tbFind.Location = new System.Drawing.Point(330, 200); this.tbFind.Name = "tbFind"; this.tbFind.Size = new System.Drawing.Size(100, 27); this.tbFind.TabIndex = 11; // // btnFind // this.btnFind.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnFind.Location = new System.Drawing.Point(439, 197); this.btnFind.Name = "btnFind"; this.btnFind.Size = new System.Drawing.Size(100, 32); this.btnFind.TabIndex = 12; this.btnFind.Text = "&Find"; this.btnFind.Click += new System.EventHandler(this.btnFind_Click); // // btnExit // this.btnExit.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnExit.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnExit.Location = new System.Drawing.Point(439, 240); this.btnExit.Name = "btnExit"; this.btnExit.Size = new System.Drawing.Size(100, 32); this.btnExit.TabIndex = 14; this.btnExit.Text = "E&xit"; this.btnExit.Click += new System.EventHandler(this.btnExit_Click); // // btnSave // this.btnSave.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnSave.Location = new System.Drawing.Point(330, 240); this.btnSave.Name = "btnSave"; this.btnSave.Size = new System.Drawing.Size(100, 32); this.btnSave.TabIndex = 13; this.btnSave.Text = "&Save"; this.btnSave.Click += new System.EventHandler(this.btnSave_Click); // // btnPrevious // this.btnPrevious.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnPrevious.Location = new System.Drawing.Point(330, 40); this.btnPrevious.Name = "btnPrevious"; this.btnPrevious.Size = new System.Drawing.Size(100, 32); this.btnPrevious.TabIndex = 7; this.btnPrevious.Text = "&Previous"; this.btnPrevious.Click += new System.EventHandler(this.btnPrevious_Click); // // btnDelete // this.btnDelete.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnDelete.Location = new System.Drawing.Point(330, 160); this.btnDelete.Name = "btnDelete"; this.btnDelete.Size = new System.Drawing.Size(100, 32); this.btnDelete.TabIndex = 10; this.btnDelete.Text = "&Delete"; this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click); // // btnAdd // this.btnAdd.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnAdd.Location = new System.Drawing.Point(330, 120); this.btnAdd.Name = "btnAdd"; this.btnAdd.Size = new System.Drawing.Size(100, 32); this.btnAdd.TabIndex = 9; this.btnAdd.Text = "&Add"; this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click); // // btnNext // this.btnNext.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.btnNext.Location = new System.Drawing.Point(330, 80); this.btnNext.Name = "btnNext"; this.btnNext.Size = new System.Drawing.Size(100, 32); this.btnNext.TabIndex = 8; this.btnNext.Text = "&Next"; this.btnNext.Click += new System.EventHandler(this.btnNext_Click); // // labDesc // this.labDesc.AutoEllipsis = true; this.labDesc.AutoSize = true; this.labDesc.Location = new System.Drawing.Point(40, 100); this.labDesc.Name = "labDesc"; this.labDesc.Size = new System.Drawing.Size(83, 18); this.labDesc.TabIndex = 5; this.labDesc.Text = "Description"; // // tbDesc // this.tbDesc.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.tbDesc.Location = new System.Drawing.Point(43, 131); this.tbDesc.Name = "tbDesc"; this.tbDesc.Size = new System.Drawing.Size(247, 24); this.tbDesc.TabIndex = 6; // // FormPSTable // this.AcceptButton = this.btnSave; this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 18F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.btnExit; this.ClientSize = new System.Drawing.Size(551, 298); this.Controls.Add(this.tbDesc); this.Controls.Add(this.labDesc); this.Controls.Add(this.tbFind); this.Controls.Add(this.btnFind); this.Controls.Add(this.btnExit); this.Controls.Add(this.btnSave); this.Controls.Add(this.btnPrevious); this.Controls.Add(this.btnDelete); this.Controls.Add(this.btnAdd); this.Controls.Add(this.btnNext); this.Controls.Add(this.tbCount); this.Controls.Add(this.labOf); this.Controls.Add(this.tbCurrent); this.Controls.Add(this.tbCode); this.Controls.Add(this.labCode); this.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "FormPSTable"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Update Parts of Speech"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox tbCount; private System.Windows.Forms.Label labOf; private System.Windows.Forms.TextBox tbCurrent; private System.Windows.Forms.TextBox tbCode; private System.Windows.Forms.TextBox tbFind; private System.Windows.Forms.Button btnFind; private System.Windows.Forms.Button btnExit; private System.Windows.Forms.Button btnSave; private System.Windows.Forms.Button btnPrevious; private System.Windows.Forms.Button btnDelete; private System.Windows.Forms.Button btnAdd; private System.Windows.Forms.Button btnNext; private System.Windows.Forms.Label labDesc; private System.Windows.Forms.TextBox tbDesc; protected System.Windows.Forms.Label labCode; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Network.Fluent { using ApplicationGatewayFrontend.Definition; using ApplicationGatewayFrontend.UpdateDefinition; using Models; using ResourceManager.Fluent; using ResourceManager.Fluent.Core; using ResourceManager.Fluent.Core.ChildResourceActions; /// <summary> /// Implementation for ApplicationGatewayFrontend. /// </summary> ///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50Lm5ldHdvcmsuaW1wbGVtZW50YXRpb24uQXBwbGljYXRpb25HYXRld2F5RnJvbnRlbmRJbXBs internal partial class ApplicationGatewayFrontendImpl : ChildResource<ApplicationGatewayFrontendIPConfigurationInner, ApplicationGatewayImpl, IApplicationGateway>, IApplicationGatewayFrontend, IDefinition<ApplicationGateway.Definition.IWithListener>, IUpdateDefinition<ApplicationGateway.Update.IUpdate>, ApplicationGatewayFrontend.Update.IUpdate { ///GENMHASH:6C169A817DC3F6F4927C26EB324FD8B5:C0847EA0CDA78F6D91EFD239C70F0FA7 internal ApplicationGatewayFrontendImpl(ApplicationGatewayFrontendIPConfigurationInner inner, ApplicationGatewayImpl parent) : base(inner, parent) { } #region Actions ///GENMHASH:166583FE514624A3D800151836CD57C1:CC312A186A3A88FA6CF6445A4520AE59 public IPublicIPAddress GetPublicIPAddress() { string pipId = PublicIPAddressId(); if (pipId == null) { return null; } else { return Parent.Manager.PublicIPAddresses.GetById(pipId); } } ///GENMHASH:077EB7776EFFBFAA141C1696E75EF7B3:FE436520410AAD95E2287867567BC278 public ApplicationGatewayImpl Attach() { return Parent.WithFrontend(this); } ///GENMHASH:777AE9B7CB4EA1B471FA1957A07DF81F:447635D831A0A80A464ADA6413BED58F public ISubnet GetSubnet() { return Parent.Manager.GetAssociatedSubnet(Inner.Subnet); } #endregion #region Accessors ///GENMHASH:6A7F875381DF37D9F784810F1A3E35BE:C4BB293D7BE83843DB9F85EA7205F9BB public bool IsPrivate() { return (Inner.Subnet != null); } ///GENMHASH:3E38805ED0E7BA3CAEE31311D032A21C:61C1065B307679F3800C701AE0D87070 public override string Name() { return Inner.Name; } ///GENMHASH:5EF934D4E2CF202DF23C026435D9F6D6:E2FB3C470570EB032EC48D6BFD6A7AFF public string PublicIPAddressId() { if (Inner.PublicIPAddress != null) { return Inner.PublicIPAddress.Id; } else { return null; } } ///GENMHASH:2911D7234EA1C2B2AC65B607D78B6E4A:38017BCE9C42CC6C34351378D14F8A09 public bool IsPublic() { return (Inner.PublicIPAddress != null); } ApplicationGateway.Update.IUpdate ISettable<ApplicationGateway.Update.IUpdate>.Parent() { return Parent; } ///GENMHASH:1C444C90348D7064AB23705C542DDF18:7C10C7860B6E28E6D17CB999015864B9 public string NetworkId() { var subnetRef = Inner.Subnet; if (subnetRef != null) { return ResourceUtils.ParentResourcePathFromResourceId(subnetRef.Id); } else { return null; } } ///GENMHASH:C57133CD301470A479B3BA07CD283E86:AF6B5F15AE40A0AA08ADA331F3C75492 public string SubnetName() { var subnetRef = Inner.Subnet; if (subnetRef != null) { return ResourceUtils.NameFromResourceId(subnetRef.Id); } else { return null; } } ///GENMHASH:F4EEE08685E447AE7D2A8F7252EC223A:516B6A004CB15A757AC222DE49CEC6EC public string PrivateIPAddress() { return Inner.PrivateIPAddress; } ///GENMHASH:FCB784E90DCC27EAC6AD4B4C988E2752:925E8594616C741FD699EF2269B3D731 public IPAllocationMethod PrivateIPAllocationMethod() { return Inner.PrivateIPAllocationMethod; } #endregion #region Withers ///GENMHASH:5647899224D30C7B5E1FDCD2D9AAB1DB:F08EFDCC8A8286B3C9226D19B2EA7889 public ApplicationGatewayFrontendImpl WithExistingSubnet(INetwork network, string subnetName) { return WithExistingSubnet(network.Id, subnetName); } ///GENMHASH:E8683B20FED733D23930E96CCD1EB0A2:D46E32F223224E6AB5C12C956BB18C94 public ApplicationGatewayFrontendImpl WithExistingSubnet(string parentNetworkResourceId, string subnetName) { var subnetRef = new SubResource() { Id = parentNetworkResourceId + "/subnets/" + subnetName }; Inner.Subnet = subnetRef; // Ensure this frontend is not public WithoutPublicIPAddress(); return this; } ///GENMHASH:BE684C4F4845D0C09A9399569DFB7A42:096D95C5168036459198B2B1F15EC515 public ApplicationGatewayFrontendImpl WithExistingPublicIPAddress(IPublicIPAddress pip) { return WithExistingPublicIPAddress(pip.Id); } ///GENMHASH:3C078CA3D79C59C878B566E6BDD55B86:5185A4691911407C18CF3290890D0252 public ApplicationGatewayFrontendImpl WithExistingPublicIPAddress(string resourceId) { var pipRef = new SubResource() { Id = resourceId }; Inner.PublicIPAddress = pipRef; // Ensure no conflicting public and private settings WithoutSubnet(); return this; } ///GENMHASH:A280AFBA3926E1E20A16C1DA07F8C6A3:144D0CF08C876F0017D38A9B294CEBC7 public ApplicationGatewayFrontendImpl WithoutSubnet() { Inner.Subnet = null; Inner.PrivateIPAddress = null; Inner.PrivateIPAllocationMethod = null; return this; } ///GENMHASH:26224359DA104EABE1EDF7F491D110F7:381025C979BFBD1E8A2299FD1136F281 public ApplicationGatewayFrontendImpl WithPrivateIPAddressDynamic() { Inner.PrivateIPAddress = null; Inner.PrivateIPAllocationMethod = IPAllocationMethod.Dynamic; return this; } ///GENMHASH:9946B3475EBD5468D4462F188EEE86C2:9952D5FC5D28D16082887464EAAE7D3C public ApplicationGatewayFrontendImpl WithPrivateIPAddressStatic(string ipAddress) { Inner.PrivateIPAddress = ipAddress; Inner.PrivateIPAllocationMethod = IPAllocationMethod.Static; return this; } ///GENMHASH:C4684C8A47F80967DA864E1AB75147B5:2AADFAA8967336A82263A3FD701F270A public ApplicationGatewayFrontendImpl WithoutPublicIPAddress() { Inner.PublicIPAddress = null; return this; } #endregion } }
/* * Note to JL: Refactored extension methods * * [The "BSD licence"] * Copyright (c) 2005-2008 Terence Parr * All rights reserved. * * Conversion to C#: * Copyright (c) 2008-2009 Sam Harwell, Pixel Mine, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Antlr.Runtime.Debug { using Antlr.Runtime.JavaExtensions; using BaseTree = Antlr.Runtime.Tree.BaseTree; using Console = System.Console; using Exception = System.Exception; using IOException = System.IO.IOException; using ITree = Antlr.Runtime.Tree.ITree; using Socket = System.Net.Sockets.Socket; using SocketException = System.Net.Sockets.SocketException; using TextReader = System.IO.TextReader; using TextWriter = System.IO.TextWriter; public class RemoteDebugEventSocketListener { const int MAX_EVENT_ELEMENTS = 8; IDebugEventListener listener; string machine; int port; Socket channel = null; TextWriter @out; TextReader @in; string @event; /** <summary>Version of ANTLR (dictates events)</summary> */ public string version; public string grammarFileName; /** <summary> * Track the last token index we saw during a consume. If same, then * set a flag that we have a problem. * </summary> */ int previousTokenIndex = -1; bool tokenIndexesInvalid = false; public class ProxyToken : IToken { int index; int type; int channel; int line; int charPos; string text; public ProxyToken(int index) { this.index = index; } public ProxyToken(int index, int type, int channel, int line, int charPos, string text) { this.index = index; this.type = type; this.channel = channel; this.line = line; this.charPos = charPos; this.text = text; } #region IToken Members public string Text { get { return text; } set { text = value; } } public int Type { get { return type; } set { type = value; } } public int Line { get { return line; } set { line = value; } } public int CharPositionInLine { get { return charPos; } set { charPos = value; } } public int Channel { get { return channel; } set { channel = value; } } public int StartIndex { get { return -1; } set { } } public int StopIndex { get { return -1; } set { } } public int TokenIndex { get { return index; } set { index = value; } } public ICharStream InputStream { get { return null; } set { } } #endregion public override string ToString() { string channelStr = ""; if (channel != TokenChannels.Default) { channelStr = ",channel=" + channel; } return "[" + Text + "/<" + type + ">" + channelStr + "," + line + ":" + CharPositionInLine + ",@" + index + "]"; } } public class ProxyTree : BaseTree { public int ID; int type; int line = 0; public int charPos = -1; public int tokenIndex = -1; string text; public ProxyTree(int ID, int type, int line, int charPos, int tokenIndex, string text) { this.ID = ID; this.type = type; this.line = line; this.charPos = charPos; this.tokenIndex = tokenIndex; this.text = text; } public ProxyTree(int ID) { this.ID = ID; } #region Properties public override string Text { get { return text; } set { } } public override int TokenStartIndex { get { return tokenIndex; } set { } } public override int TokenStopIndex { get { return 0; } set { } } public override int Type { get { return type; } set { } } #endregion public override ITree DupNode() { return null; } public override string ToString() { return "fix this"; } } public RemoteDebugEventSocketListener(IDebugEventListener listener, string machine, int port) { this.listener = listener; this.machine = machine; this.port = port; if (!OpenConnection()) { throw new SocketException(); } } protected virtual void EventHandler() { try { Handshake(); @event = @in.ReadLine(); while (@event != null) { Dispatch(@event); Ack(); @event = @in.ReadLine(); } } catch (Exception e) { Console.Error.WriteLine(e); ExceptionExtensions.PrintStackTrace(e, Console.Error); } finally { CloseConnection(); } } protected virtual bool OpenConnection() { bool success = false; try { throw new System.NotImplementedException(); //channel = new Socket( machine, port ); //channel.setTcpNoDelay( true ); //OutputStream os = channel.getOutputStream(); //OutputStreamWriter osw = new OutputStreamWriter( os, "UTF8" ); //@out = new PrintWriter( new BufferedWriter( osw ) ); //InputStream @is = channel.getInputStream(); //InputStreamReader isr = new InputStreamReader( @is, "UTF8" ); //@in = new BufferedReader( isr ); //success = true; } catch (Exception e) { Console.Error.WriteLine(e); } return success; } protected virtual void CloseConnection() { try { @in.Close(); @in = null; @out.Close(); @out = null; channel.Close(); channel = null; } catch (Exception e) { Console.Error.WriteLine(e); ExceptionExtensions.PrintStackTrace(e, Console.Error); } finally { if (@in != null) { try { @in.Close(); } catch (IOException ioe) { Console.Error.WriteLine(ioe); } } if (@out != null) { @out.Close(); } if (channel != null) { try { channel.Close(); } catch (IOException ioe) { Console.Error.WriteLine(ioe); } } } } protected virtual void Handshake() { string antlrLine = @in.ReadLine(); string[] antlrElements = GetEventElements(antlrLine); version = antlrElements[1]; string grammarLine = @in.ReadLine(); string[] grammarElements = GetEventElements(grammarLine); grammarFileName = grammarElements[1]; Ack(); listener.Commence(); // inform listener after handshake } protected virtual void Ack() { @out.WriteLine("ack"); @out.Flush(); } protected virtual void Dispatch(string line) { //JSystem.@out.println( "event: " + line ); string[] elements = GetEventElements(line); if (elements == null || elements[0] == null) { Console.Error.WriteLine("unknown debug event: " + line); return; } if (elements[0].Equals("enterRule")) { listener.EnterRule(elements[1], elements[2]); } else if (elements[0].Equals("exitRule")) { listener.ExitRule(elements[1], elements[2]); } else if (elements[0].Equals("enterAlt")) { listener.EnterAlt(int.Parse(elements[1])); } else if (elements[0].Equals("enterSubRule")) { listener.EnterSubRule(int.Parse(elements[1])); } else if (elements[0].Equals("exitSubRule")) { listener.ExitSubRule(int.Parse(elements[1])); } else if (elements[0].Equals("enterDecision")) { listener.EnterDecision(int.Parse(elements[1]), elements[2].Equals("true")); } else if (elements[0].Equals("exitDecision")) { listener.ExitDecision(int.Parse(elements[1])); } else if (elements[0].Equals("location")) { listener.Location(int.Parse(elements[1]), int.Parse(elements[2])); } else if (elements[0].Equals("consumeToken")) { ProxyToken t = DeserializeToken(elements, 1); if (t.TokenIndex == previousTokenIndex) { tokenIndexesInvalid = true; } previousTokenIndex = t.TokenIndex; listener.ConsumeToken(t); } else if (elements[0].Equals("consumeHiddenToken")) { ProxyToken t = DeserializeToken(elements, 1); if (t.TokenIndex == previousTokenIndex) { tokenIndexesInvalid = true; } previousTokenIndex = t.TokenIndex; listener.ConsumeHiddenToken(t); } else if (elements[0].Equals("LT")) { IToken t = DeserializeToken(elements, 2); listener.LT(int.Parse(elements[1]), t); } else if (elements[0].Equals("mark")) { listener.Mark(int.Parse(elements[1])); } else if (elements[0].Equals("rewind")) { if (elements[1] != null) { listener.Rewind(int.Parse(elements[1])); } else { listener.Rewind(); } } else if (elements[0].Equals("beginBacktrack")) { listener.BeginBacktrack(int.Parse(elements[1])); } else if (elements[0].Equals("endBacktrack")) { int level = int.Parse(elements[1]); int successI = int.Parse(elements[2]); listener.EndBacktrack(level, successI == DebugEventListenerConstants.True); } else if (elements[0].Equals("exception")) { #if true throw new System.NotImplementedException(); #else string excName = elements[1]; string indexS = elements[2]; string lineS = elements[3]; string posS = elements[4]; Class excClass = null; try { excClass = Class.forName( excName ); RecognitionException e = (RecognitionException)excClass.newInstance(); e.index = int.Parse( indexS ); e.line = int.Parse( lineS ); e.charPositionInLine = int.Parse( posS ); listener.recognitionException( e ); } catch ( ClassNotFoundException cnfe ) { Console.Error.println( "can't find class " + cnfe ); cnfe.printStackTrace( Console.Error ); } catch ( InstantiationException ie ) { Console.Error.println( "can't instantiate class " + ie ); ie.printStackTrace( Console.Error ); } catch ( IllegalAccessException iae ) { Console.Error.println( "can't access class " + iae ); iae.printStackTrace( Console.Error ); } #endif } else if (elements[0].Equals("beginResync")) { listener.BeginResync(); } else if (elements[0].Equals("endResync")) { listener.EndResync(); } else if (elements[0].Equals("terminate")) { listener.Terminate(); } else if (elements[0].Equals("semanticPredicate")) { bool result = bool.Parse(elements[1]); string predicateText = elements[2]; predicateText = UnEscapeNewlines(predicateText); listener.SemanticPredicate(result, predicateText); } else if (elements[0].Equals("consumeNode")) { ProxyTree node = DeserializeNode(elements, 1); listener.ConsumeNode(node); } else if (elements[0].Equals("LN")) { int i = int.Parse(elements[1]); ProxyTree node = DeserializeNode(elements, 2); listener.LT(i, node); } else if (elements[0].Equals("createNodeFromTokenElements")) { int ID = int.Parse(elements[1]); int type = int.Parse(elements[2]); string text = elements[3]; text = UnEscapeNewlines(text); ProxyTree node = new ProxyTree(ID, type, -1, -1, -1, text); listener.CreateNode(node); } else if (elements[0].Equals("createNode")) { int ID = int.Parse(elements[1]); int tokenIndex = int.Parse(elements[2]); // create dummy node/token filled with ID, tokenIndex ProxyTree node = new ProxyTree(ID); ProxyToken token = new ProxyToken(tokenIndex); listener.CreateNode(node, token); } else if (elements[0].Equals("nilNode")) { int ID = int.Parse(elements[1]); ProxyTree node = new ProxyTree(ID); listener.NilNode(node); } else if (elements[0].Equals("errorNode")) { // TODO: do we need a special tree here? int ID = int.Parse(elements[1]); int type = int.Parse(elements[2]); string text = elements[3]; text = UnEscapeNewlines(text); ProxyTree node = new ProxyTree(ID, type, -1, -1, -1, text); listener.ErrorNode(node); } else if (elements[0].Equals("becomeRoot")) { int newRootID = int.Parse(elements[1]); int oldRootID = int.Parse(elements[2]); ProxyTree newRoot = new ProxyTree(newRootID); ProxyTree oldRoot = new ProxyTree(oldRootID); listener.BecomeRoot(newRoot, oldRoot); } else if (elements[0].Equals("addChild")) { int rootID = int.Parse(elements[1]); int childID = int.Parse(elements[2]); ProxyTree root = new ProxyTree(rootID); ProxyTree child = new ProxyTree(childID); listener.AddChild(root, child); } else if (elements[0].Equals("setTokenBoundaries")) { int ID = int.Parse(elements[1]); ProxyTree node = new ProxyTree(ID); listener.SetTokenBoundaries( node, int.Parse(elements[2]), int.Parse(elements[3])); } else { Console.Error.WriteLine("unknown debug event: " + line); } } protected virtual ProxyTree DeserializeNode(string[] elements, int offset) { int ID = int.Parse(elements[offset + 0]); int type = int.Parse(elements[offset + 1]); int tokenLine = int.Parse(elements[offset + 2]); int charPositionInLine = int.Parse(elements[offset + 3]); int tokenIndex = int.Parse(elements[offset + 4]); string text = elements[offset + 5]; text = UnEscapeNewlines(text); return new ProxyTree(ID, type, tokenLine, charPositionInLine, tokenIndex, text); } protected virtual ProxyToken DeserializeToken(string[] elements, int offset) { string indexS = elements[offset + 0]; string typeS = elements[offset + 1]; string channelS = elements[offset + 2]; string lineS = elements[offset + 3]; string posS = elements[offset + 4]; string text = elements[offset + 5]; text = UnEscapeNewlines(text); int index = int.Parse(indexS); ProxyToken t = new ProxyToken(index, int.Parse(typeS), int.Parse(channelS), int.Parse(lineS), int.Parse(posS), text); return t; } /** <summary>Create a thread to listen to the remote running recognizer</summary> */ public virtual void Start() { System.Threading.Thread t = new System.Threading.Thread(Run); t.Start(); } public virtual void Run() { EventHandler(); } #region Misc public virtual string[] GetEventElements(string @event) { if (@event == null) { return null; } string[] elements = new string[MAX_EVENT_ELEMENTS]; string str = null; // a string element if present (must be last) try { int firstQuoteIndex = @event.IndexOf('"'); if (firstQuoteIndex >= 0) { // treat specially; has a string argument like "a comment\n // Note that the string is terminated by \n not end quote. // Easier to parse that way. string eventWithoutString = @event.Substring(0, firstQuoteIndex); str = @event.Substring(firstQuoteIndex + 1); @event = eventWithoutString; } StringTokenizer st = new StringTokenizer(@event, "\t", false); int i = 0; while (st.hasMoreTokens()) { if (i >= MAX_EVENT_ELEMENTS) { // ErrorManager.internalError("event has more than "+MAX_EVENT_ELEMENTS+" args: "+event); return elements; } elements[i] = st.nextToken(); i++; } if (str != null) { elements[i] = str; } } catch (Exception e) { ExceptionExtensions.PrintStackTrace(e, Console.Error); } return elements; } protected virtual string UnEscapeNewlines(string txt) { // this unescape is slow but easy to understand txt = StringExtensions.replaceAll(txt, "%0A", "\n"); // unescape \n txt = StringExtensions.replaceAll(txt, "%0D", "\r"); // unescape \r txt = StringExtensions.replaceAll(txt, "%25", "%"); // undo escaped escape chars return txt; } public virtual bool TokenIndexesAreInvalid() { return false; //return tokenIndexesInvalid; } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System.Collections.Generic; using System.Reflection; using System.Threading; namespace OpenSim.Region.CoreModules.Agent.AssetTransaction { /// <summary> /// Manage asset transactions for a single agent. /// </summary> public class AgentAssetTransactions { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // Fields private bool m_dumpAssetsToFile; private Scene m_Scene; private ReaderWriterLock m_UploaderRwLock = new ReaderWriterLock(); private Dictionary<UUID, AssetXferUploader> XferUploaders = new Dictionary<UUID, AssetXferUploader>(); // Methods public AgentAssetTransactions(UUID agentID, Scene scene, bool dumpAssetsToFile) { m_Scene = scene; m_dumpAssetsToFile = dumpAssetsToFile; } /// <summary> /// Return the xfer uploader for the given transaction. /// </summary> /// <remarks> /// If an uploader does not already exist for this transaction then it is created, otherwise the existing /// uploader is returned. /// </remarks> /// <param name="transactionID"></param> /// <returns>The asset xfer uploader</returns> public AssetXferUploader RequestXferUploader(UUID transactionID) { AssetXferUploader uploader; m_UploaderRwLock.AcquireReaderLock(-1); try { if (!XferUploaders.ContainsKey(transactionID)) { LockCookie lc = m_UploaderRwLock.UpgradeToWriterLock(-1); try { uploader = new AssetXferUploader(this, m_Scene, transactionID, m_dumpAssetsToFile); // m_log.DebugFormat( // "[AGENT ASSETS TRANSACTIONS]: Adding asset xfer uploader {0} since it didn't previously exist", transactionID); XferUploaders.Add(transactionID, uploader); } finally { m_UploaderRwLock.DowngradeFromWriterLock(ref lc); } } else { uploader = XferUploaders[transactionID]; } } finally { m_UploaderRwLock.ReleaseReaderLock(); } return uploader; } public void HandleXfer(ulong xferID, uint packetID, byte[] data) { AssetXferUploader foundUploader = null; m_UploaderRwLock.AcquireReaderLock(-1); try { foreach (AssetXferUploader uploader in XferUploaders.Values) { // m_log.DebugFormat( // "[AGENT ASSETS TRANSACTIONS]: In HandleXfer, inspect xfer upload with xfer id {0}", // uploader.XferID); if (uploader.XferID == xferID) { foundUploader = uploader; break; } } } finally { m_UploaderRwLock.ReleaseReaderLock(); } if (foundUploader != null) { // m_log.DebugFormat( // "[AGENT ASSETS TRANSACTIONS]: Found xfer uploader for xfer id {0}, packet id {1}, data length {2}", // xferID, packetID, data.Length); foundUploader.HandleXferPacket(xferID, packetID, data); } else { // Check if the xfer is a terrain xfer IEstateModule estateModule = m_Scene.RequestModuleInterface<IEstateModule>(); if (estateModule != null) { if (estateModule.IsTerrainXfer(xferID)) return; } m_log.ErrorFormat( "[AGENT ASSET TRANSACTIONS]: Could not find uploader for xfer id {0}, packet id {1}, data length {2}", xferID, packetID, data.Length); } } public bool RemoveXferUploader(UUID transactionID) { m_UploaderRwLock.AcquireWriterLock(-1); try { bool removed = XferUploaders.Remove(transactionID); if (!removed) m_log.WarnFormat( "[AGENT ASSET TRANSACTIONS]: Received request to remove xfer uploader with transaction ID {0} but none found", transactionID); // else // m_log.DebugFormat( // "[AGENT ASSET TRANSACTIONS]: Removed xfer uploader with transaction ID {0}", transactionID); return removed; } finally { m_UploaderRwLock.ReleaseWriterLock(); } } public void RequestCreateInventoryItem(IClientAPI remoteClient, UUID transactionID, UUID folderID, uint callbackID, string description, string name, sbyte invType, sbyte type, byte wearableType, uint nextOwnerMask) { AssetXferUploader uploader = RequestXferUploader(transactionID); uploader.RequestCreateInventoryItem( remoteClient, folderID, callbackID, description, name, invType, type, wearableType, nextOwnerMask); } public void RequestUpdateTaskInventoryItem(IClientAPI remoteClient, SceneObjectPart part, UUID transactionID, TaskInventoryItem item) { AssetXferUploader uploader = RequestXferUploader(transactionID); uploader.RequestUpdateTaskInventoryItem(remoteClient, item); } public void RequestUpdateInventoryItem(IClientAPI remoteClient, UUID transactionID, InventoryItemBase item) { AssetXferUploader uploader = RequestXferUploader(transactionID); uploader.RequestUpdateInventoryItem(remoteClient, item); } } }
// 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.Security; using System.Threading; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Text { [Serializable] public abstract class EncoderFallback { // disable csharp compiler warning #0414: field assigned unused value #pragma warning disable 0414 internal bool bIsMicrosoftBestFitFallback = false; #pragma warning restore 0414 private static volatile EncoderFallback replacementFallback; // Default fallback, uses no best fit & "?" private static volatile EncoderFallback exceptionFallback; // Private object for locking instead of locking on a public type for SQL reliability work. private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if (s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } } // Get each of our generic fallbacks. public static EncoderFallback ReplacementFallback { get { if (replacementFallback == null) lock (InternalSyncObject) if (replacementFallback == null) replacementFallback = new EncoderReplacementFallback(); return replacementFallback; } } public static EncoderFallback ExceptionFallback { get { if (exceptionFallback == null) lock (InternalSyncObject) if (exceptionFallback == null) exceptionFallback = new EncoderExceptionFallback(); return exceptionFallback; } } // Fallback // // Return the appropriate unicode string alternative to the character that need to fall back. // Most implimentations will be: // return new MyCustomEncoderFallbackBuffer(this); public abstract EncoderFallbackBuffer CreateFallbackBuffer(); // Maximum number of characters that this instance of this fallback could return public abstract int MaxCharCount { get; } } public abstract class EncoderFallbackBuffer { // Most implementations will probably need an implemenation-specific constructor // Public methods that cannot be overriden that let us do our fallback thing // These wrap the internal methods so that we can check for people doing stuff that is incorrect public abstract bool Fallback(char charUnknown, int index); public abstract bool Fallback(char charUnknownHigh, char charUnknownLow, int index); // Get next character public abstract char GetNextChar(); // Back up a character public abstract bool MovePrevious(); // How many chars left in this fallback? public abstract int Remaining { get; } // Not sure if this should be public or not. // Clear the buffer public virtual void Reset() { while (GetNextChar() != (char)0) ; } // Internal items to help us figure out what we're doing as far as error messages, etc. // These help us with our performance and messages internally internal unsafe char* charStart; internal unsafe char* charEnd; internal EncoderNLS encoder; internal bool setEncoder; internal bool bUsedEncoder; internal bool bFallingBack = false; internal int iRecursionCount = 0; private const int iMaxRecursion = 250; // Internal Reset // For example, what if someone fails a conversion and wants to reset one of our fallback buffers? internal unsafe void InternalReset() { charStart = null; bFallingBack = false; iRecursionCount = 0; Reset(); } // Set the above values // This can't be part of the constructor because EncoderFallbacks would have to know how to impliment these. internal unsafe void InternalInitialize(char* charStart, char* charEnd, EncoderNLS encoder, bool setEncoder) { this.charStart = charStart; this.charEnd = charEnd; this.encoder = encoder; this.setEncoder = setEncoder; this.bUsedEncoder = false; this.bFallingBack = false; this.iRecursionCount = 0; } internal char InternalGetNextChar() { char ch = GetNextChar(); bFallingBack = (ch != 0); if (ch == 0) iRecursionCount = 0; return ch; } // Fallback the current character using the remaining buffer and encoder if necessary // This can only be called by our encodings (other have to use the public fallback methods), so // we can use our EncoderNLS here too. // setEncoder is true if we're calling from a GetBytes method, false if we're calling from a GetByteCount // // Note that this could also change the contents of this.encoder, which is the same // object that the caller is using, so the caller could mess up the encoder for us // if they aren't careful. internal unsafe virtual bool InternalFallback(char ch, ref char* chars) { // Shouldn't have null charStart Debug.Assert(charStart != null, "[EncoderFallback.InternalFallbackBuffer]Fallback buffer is not initialized"); // Get our index, remember chars was preincremented to point at next char, so have to -1 int index = (int)(chars - charStart) - 1; // See if it was a high surrogate if (Char.IsHighSurrogate(ch)) { // See if there's a low surrogate to go with it if (chars >= this.charEnd) { // Nothing left in input buffer // No input, return 0 if mustflush is false if (this.encoder != null && !this.encoder.MustFlush) { // Done, nothing to fallback if (this.setEncoder) { bUsedEncoder = true; this.encoder.charLeftOver = ch; } bFallingBack = false; return false; } } else { // Might have a low surrogate char cNext = *chars; if (Char.IsLowSurrogate(cNext)) { // If already falling back then fail if (bFallingBack && iRecursionCount++ > iMaxRecursion) ThrowLastCharRecursive(Char.ConvertToUtf32(ch, cNext)); // Next is a surrogate, add it as surrogate pair, and increment chars chars++; bFallingBack = Fallback(ch, cNext, index); return bFallingBack; } // Next isn't a low surrogate, just fallback the high surrogate } } // If already falling back then fail if (bFallingBack && iRecursionCount++ > iMaxRecursion) ThrowLastCharRecursive((int)ch); // Fall back our char bFallingBack = Fallback(ch, index); return bFallingBack; } // private helper methods internal void ThrowLastCharRecursive(int charRecursive) { // Throw it, using our complete character throw new ArgumentException( Environment.GetResourceString("Argument_RecursiveFallback", charRecursive), "chars"); } } }
/******************************************************************** * * PropertyBag.cs * -------------- * Derived from PropertyBag.cs by Tony Allowatt * CodeProject: http://www.codeproject.com/cs/miscctrl/bending_property.asp * Last Update: 04/05/2005 * ********************************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing.Design; using System.Reflection; using CslaGenerator.Attributes; using CslaGenerator.Metadata; namespace CslaGenerator.Util.PropertyBags { /// <summary> /// Represents a collection of custom properties that can be selected into a /// PropertyGrid to provide functionality beyond that of the simple reflection /// normally used to query an object's properties. /// </summary> public class AssociativeEntityPropertyBag : ICustomTypeDescriptor { #region PropertySpecCollection class definition /// <summary> /// Encapsulates a collection of PropertySpec objects. /// </summary> [Serializable] public class PropertySpecCollection : IList { private readonly ArrayList _innerArray; /// <summary> /// Initializes a new instance of the PropertySpecCollection class. /// </summary> public PropertySpecCollection() { _innerArray = new ArrayList(); } /// <summary> /// Gets or sets the element at the specified index. /// In C#, this property is the indexer for the PropertySpecCollection class. /// </summary> /// <param name="index">The zero-based index of the element to get or set.</param> /// <value> /// The element at the specified index. /// </value> public PropertySpec this[int index] { get { return (PropertySpec) _innerArray[index]; } set { _innerArray[index] = value; } } #region IList Members /// <summary> /// Gets the number of elements in the PropertySpecCollection. /// </summary> /// <value> /// The number of elements contained in the PropertySpecCollection. /// </value> public int Count { get { return _innerArray.Count; } } /// <summary> /// Gets a value indicating whether the PropertySpecCollection has a fixed size. /// </summary> /// <value> /// true if the PropertySpecCollection has a fixed size; otherwise, false. /// </value> public bool IsFixedSize { get { return false; } } /// <summary> /// Gets a value indicating whether the PropertySpecCollection is read-only. /// </summary> public bool IsReadOnly { get { return false; } } /// <summary> /// Gets a value indicating whether access to the collection is synchronized (thread-safe). /// </summary> /// <value> /// true if access to the PropertySpecCollection is synchronized (thread-safe); otherwise, false. /// </value> public bool IsSynchronized { get { return false; } } /// <summary> /// Gets an object that can be used to synchronize access to the collection. /// </summary> /// <value> /// An object that can be used to synchronize access to the collection. /// </value> object ICollection.SyncRoot { get { return null; } } /// <summary> /// Removes all elements from the PropertySpecCollection. /// </summary> public void Clear() { _innerArray.Clear(); } /// <summary> /// Returns an enumerator that can iterate through the PropertySpecCollection. /// </summary> /// <returns>An IEnumerator for the entire PropertySpecCollection.</returns> public IEnumerator GetEnumerator() { return _innerArray.GetEnumerator(); } /// <summary> /// Removes the object at the specified index of the PropertySpecCollection. /// </summary> /// <param name="index">The zero-based index of the element to remove.</param> public void RemoveAt(int index) { _innerArray.RemoveAt(index); } #endregion /// <summary> /// Adds a PropertySpec to the end of the PropertySpecCollection. /// </summary> /// <param name="value">The PropertySpec to be added to the end of the PropertySpecCollection.</param> /// <returns>The PropertySpecCollection index at which the value has been added.</returns> public int Add(PropertySpec value) { int index = _innerArray.Add(value); return index; } /// <summary> /// Adds the elements of an array of PropertySpec objects to the end of the PropertySpecCollection. /// </summary> /// <param name="array">The PropertySpec array whose elements should be added to the end of the /// PropertySpecCollection.</param> public void AddRange(PropertySpec[] array) { _innerArray.AddRange(array); } /// <summary> /// Determines whether a PropertySpec is in the PropertySpecCollection. /// </summary> /// <param name="item">The PropertySpec to locate in the PropertySpecCollection. The element to locate /// can be a null reference (Nothing in Visual Basic).</param> /// <returns>true if item is found in the PropertySpecCollection; otherwise, false.</returns> public bool Contains(PropertySpec item) { return _innerArray.Contains(item); } /// <summary> /// Determines whether a PropertySpec with the specified name is in the PropertySpecCollection. /// </summary> /// <param name="name">The name of the PropertySpec to locate in the PropertySpecCollection.</param> /// <returns>true if item is found in the PropertySpecCollection; otherwise, false.</returns> public bool Contains(string name) { foreach (PropertySpec spec in _innerArray) if (spec.Name == name) return true; return false; } /// <summary> /// Copies the entire PropertySpecCollection to a compatible one-dimensional Array, starting at the /// beginning of the target array. /// </summary> /// <param name="array">The one-dimensional Array that is the destination of the elements copied /// from PropertySpecCollection. The Array must have zero-based indexing.</param> public void CopyTo(PropertySpec[] array) { _innerArray.CopyTo(array); } /// <summary> /// Copies the PropertySpecCollection or a portion of it to a one-dimensional array. /// </summary> /// <param name="array">The one-dimensional Array that is the destination of the elements copied /// from the collection.</param> /// <param name="index">The zero-based index in array at which copying begins.</param> public void CopyTo(PropertySpec[] array, int index) { _innerArray.CopyTo(array, index); } /// <summary> /// Searches for the specified PropertySpec and returns the zero-based index of the first /// occurrence within the entire PropertySpecCollection. /// </summary> /// <param name="value">The PropertySpec to locate in the PropertySpecCollection.</param> /// <returns>The zero-based index of the first occurrence of value within the entire PropertySpecCollection, /// if found; otherwise, -1.</returns> public int IndexOf(PropertySpec value) { return _innerArray.IndexOf(value); } /// <summary> /// Searches for the PropertySpec with the specified name and returns the zero-based index of /// the first occurrence within the entire PropertySpecCollection. /// </summary> /// <param name="name">The name of the PropertySpec to locate in the PropertySpecCollection.</param> /// <returns>The zero-based index of the first occurrence of value within the entire PropertySpecCollection, /// if found; otherwise, -1.</returns> public int IndexOf(string name) { int i = 0; foreach (PropertySpec spec in _innerArray) { //if (spec.Name == name) if (spec.TargetProperty == name) return i; i++; } return -1; } /// <summary> /// Inserts a PropertySpec object into the PropertySpecCollection at the specified index. /// </summary> /// <param name="index">The zero-based index at which value should be inserted.</param> /// <param name="value">The PropertySpec to insert.</param> public void Insert(int index, PropertySpec value) { _innerArray.Insert(index, value); } /// <summary> /// Removes the first occurrence of a specific object from the PropertySpecCollection. /// </summary> /// <param name="obj">The PropertySpec to remove from the PropertySpecCollection.</param> public void Remove(PropertySpec obj) { _innerArray.Remove(obj); } /// <summary> /// Removes the property with the specified name from the PropertySpecCollection. /// </summary> /// <param name="name">The name of the PropertySpec to remove from the PropertySpecCollection.</param> public void Remove(string name) { int index = IndexOf(name); RemoveAt(index); } /// <summary> /// Copies the elements of the PropertySpecCollection to a new PropertySpec array. /// </summary> /// <returns>A PropertySpec array containing copies of the elements of the PropertySpecCollection.</returns> public PropertySpec[] ToArray() { return (PropertySpec[]) _innerArray.ToArray(typeof (PropertySpec)); } #region Explicit interface implementations for ICollection and IList /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> void ICollection.CopyTo(Array array, int index) { CopyTo((PropertySpec[]) array, index); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> int IList.Add(object value) { return Add((PropertySpec) value); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> bool IList.Contains(object obj) { return Contains((PropertySpec) obj); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> object IList.this[int index] { get { return this[index]; } set { this[index] = (PropertySpec) value; } } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> int IList.IndexOf(object obj) { return IndexOf((PropertySpec) obj); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> void IList.Insert(int index, object value) { Insert(index, (PropertySpec) value); } /// <summary> /// This member supports the .NET Framework infrastructure and is not intended to be used directly from your code. /// </summary> void IList.Remove(object value) { Remove((PropertySpec) value); } #endregion } #endregion #region PropertySpecDescriptor class definition private class PropertySpecDescriptor : PropertyDescriptor { private readonly AssociativeEntityPropertyBag _bag; private readonly PropertySpec _item; public PropertySpecDescriptor(PropertySpec item, AssociativeEntityPropertyBag bag, string name, Attribute[] attrs) : base(name, attrs) { _bag = bag; _item = item; } public override Type ComponentType { get { return _item.GetType(); } } public override bool IsReadOnly { get { return (Attributes.Matches(ReadOnlyAttribute.Yes)); } } public override Type PropertyType { get { return Type.GetType(_item.TypeName); } } public override bool CanResetValue(object component) { if (_item.DefaultValue == null) return false; return !GetValue(component).Equals(_item.DefaultValue); } public override object GetValue(object component) { // Have the property bag raise an event to get the current value // of the property. var e = new PropertySpecEventArgs(_item, null); _bag.OnGetValue(e); return e.Value; } public override void ResetValue(object component) { SetValue(component, _item.DefaultValue); } public override void SetValue(object component, object value) { // Have the property bag raise an event to set the current value // of the property. var e = new PropertySpecEventArgs(_item, value); _bag.OnSetValue(e); } public override bool ShouldSerializeValue(object component) { object val = GetValue(component); if (_item.DefaultValue == null && val == null) return false; return !val.Equals(_item.DefaultValue); } } #endregion #region Properties and Events private readonly PropertySpecCollection _properties; private string _defaultProperty; private AssociativeEntity[] _selectedObject; /// <summary> /// Initializes a new instance of the AssociativeEntityPropertyBag class. /// </summary> public AssociativeEntityPropertyBag() { _defaultProperty = null; _properties = new PropertySpecCollection(); } public AssociativeEntityPropertyBag(AssociativeEntity obj) : this(new[] {obj}) { } public AssociativeEntityPropertyBag(AssociativeEntity[] obj) { _defaultProperty = "ObjectName"; _properties = new PropertySpecCollection(); _selectedObject = obj; InitPropertyBag(); } /// <summary> /// Gets or sets the name of the default property in the collection. /// </summary> public string DefaultProperty { get { return _defaultProperty; } set { _defaultProperty = value; } } /// <summary> /// Gets or sets the name of the default property in the collection. /// </summary> public AssociativeEntity[] SelectedObject { get { return _selectedObject; } set { _selectedObject = value; InitPropertyBag(); } } /// <summary> /// Gets the collection of properties contained within this AssociativeEntityPropertyBag. /// </summary> public PropertySpecCollection Properties { get { return _properties; } } /// <summary> /// Occurs when a PropertyGrid requests the value of a property. /// </summary> public event PropertySpecEventHandler GetValue; /// <summary> /// Occurs when the user changes the value of a property in a PropertyGrid. /// </summary> public event PropertySpecEventHandler SetValue; /// <summary> /// Raises the GetValue event. /// </summary> /// <param name="e">A PropertySpecEventArgs that contains the event data.</param> protected virtual void OnGetValue(PropertySpecEventArgs e) { if (e.Value != null) GetValue(this, e); e.Value = GetProperty(e.Property.TargetObject, e.Property.TargetProperty, e.Property.DefaultValue); } /// <summary> /// Raises the SetValue event. /// </summary> /// <param name="e">A PropertySpecEventArgs that contains the event data.</param> protected virtual void OnSetValue(PropertySpecEventArgs e) { if (SetValue != null) SetValue(this, e); SetProperty(e.Property.TargetObject, e.Property.TargetProperty, e.Value); } #endregion #region Initialize Propertybag private void InitPropertyBag() { PropertyInfo propertyInfo; Type t = typeof(AssociativeEntity);// _selectedObject.GetType(); PropertyInfo[] props = t.GetProperties(); // Display information for all properties. for (int i = 0; i < props.Length; i++) { propertyInfo = props[i]; object[] myAttributes = propertyInfo.GetCustomAttributes(true); string category = ""; string description = ""; bool isreadonly = false; bool isbrowsable = true; object defaultvalue = null; string userfriendlyname = ""; string typeconverter = ""; string designertypename = ""; string helptopic = ""; bool bindable = true; string editor = ""; for (int n = 0; n < myAttributes.Length; n++) { var a = (Attribute) myAttributes[n]; switch (a.GetType().ToString()) { case "System.ComponentModel.CategoryAttribute": category = ((CategoryAttribute) a).Category; break; case "System.ComponentModel.DescriptionAttribute": description = ((DescriptionAttribute) a).Description; break; case "System.ComponentModel.ReadOnlyAttribute": isreadonly = ((ReadOnlyAttribute) a).IsReadOnly; break; case "System.ComponentModel.BrowsableAttribute": isbrowsable = ((BrowsableAttribute) a).Browsable; break; case "System.ComponentModel.DefaultValueAttribute": defaultvalue = ((DefaultValueAttribute) a).Value; break; case "CslaGenerator.Attributes.UserFriendlyNameAttribute": userfriendlyname = ((UserFriendlyNameAttribute) a).UserFriendlyName; break; case "CslaGenerator.Attributes.HelpTopicAttribute": helptopic = ((HelpTopicAttribute) a).HelpTopic; break; case "System.ComponentModel.TypeConverterAttribute": typeconverter = ((TypeConverterAttribute) a).ConverterTypeName; break; case "System.ComponentModel.DesignerAttribute": designertypename = ((DesignerAttribute) a).DesignerTypeName; break; case "System.ComponentModel.BindableAttribute": bindable = ((BindableAttribute) a).Bindable; break; case "System.ComponentModel.EditorAttribute": editor = ((EditorAttribute) a).EditorTypeName; break; } } // Set ReadOnly properties /*if (SelectedObject[0].LoadingScheme == LoadingScheme.ParentLoad && propertyInfo.Name == "LazyLoad") isreadonly = true;*/ userfriendlyname = userfriendlyname.Length > 0 ? userfriendlyname : propertyInfo.Name; var types = new List<string>(); foreach (AssociativeEntity obj in _selectedObject) { // if (!types.Contains(obj.RelationType.ToString())) types.Add(obj.RelationType.ToString()); // if (!types.Contains(obj.MainLoadingScheme.ToString())) types.Add(obj.MainLoadingScheme.ToString()); // if (!types.Contains(obj.SecondaryLoadingScheme.ToString())) types.Add(obj.SecondaryLoadingScheme.ToString()); } // here get rid of Parent bool isValidProperty = propertyInfo.Name != "Parent"; if (isValidProperty && IsBrowsable(types.ToArray(), propertyInfo.Name)) { // CR added missing parameters //this.Properties.Add(new PropertySpec(userfriendlyname,propertyInfo.PropertyType.AssemblyQualifiedName,category,description,defaultvalue, editor, typeconverter, _selectedObject, propertyInfo.Name,helptopic)); Properties.Add(new PropertySpec(userfriendlyname, propertyInfo.PropertyType.AssemblyQualifiedName, category, description, defaultvalue, editor, typeconverter, _selectedObject, propertyInfo.Name, helptopic, isreadonly, isbrowsable, designertypename, bindable)); } } } #endregion private readonly Dictionary<string, PropertyInfo> propertyInfoCache = new Dictionary<string, PropertyInfo>(); private PropertyInfo GetPropertyInfoCache(string propertyName) { if (!propertyInfoCache.ContainsKey(propertyName)) { propertyInfoCache.Add(propertyName, typeof (AssociativeEntity).GetProperty(propertyName)); } return propertyInfoCache[propertyName]; } private bool IsEnumerable(PropertyInfo prop) { if (prop.PropertyType == typeof (string)) return false; Type[] interfaces = prop.PropertyType.GetInterfaces(); foreach (Type typ in interfaces) if (typ.Name.Contains("IEnumerable")) return true; return false; } #region IsBrowsable map objectType:propertyName -> true | false private bool IsBrowsable(string[] objectType, string propertyName) { try { // is it non-root? var mainCslaObject = GeneratorController.Current.CurrentUnit.CslaObjects.Find(SelectedObject[0].MainObject); if (mainCslaObject.IsNotRootType()) if (propertyName == "MainLoadParameters" || propertyName == "SecondaryLoadParameters") return false; if (objectType[0] == "OneToMany" && (propertyName == "SecondaryObject" || propertyName == "SecondaryPropertyName" || propertyName == "SecondaryCollectionTypeName" || propertyName == "SecondaryItemTypeName" || propertyName == "SecondaryLazyLoad" || propertyName == "SecondaryLoadingScheme" || propertyName == "SecondaryLoadProperties" || propertyName == "SecondaryLoadParameters")) return false; if (objectType[1] == "ParentLoad" && (propertyName == "MainLoadProperties" || propertyName == "MainLazyLoad")) return false; if (objectType[2] == "ParentLoad" && (propertyName == "SecondaryLoadProperties" || propertyName == "SecondaryLazyLoad")) return false; if (_selectedObject.Length > 1 && IsEnumerable(GetPropertyInfoCache(propertyName))) return false; return true; } catch //(Exception e) { //Debug.WriteLine(objectType + ":" + propertyName); return true; } } #endregion #region Reflection functions private object GetField(Type t, string name, object target) { object obj = null; Type tx; //FieldInfo[] fields; //fields = target.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); //fields = target.GetType().GetFields(BindingFlags.Public); tx = target.GetType(); obj = tx.InvokeMember(name, BindingFlags.Default | BindingFlags.GetField, null, target, new object[] {}); return obj; } private object SetField(Type t, string name, object value, object target) { object obj; obj = t.InvokeMember(name, BindingFlags.Default | BindingFlags.SetField, null, target, new[] {value}); return obj; } private bool SetProperty(object obj, string propertyName, object val) { try { // get a reference to the PropertyInfo, exit if no property with that name PropertyInfo propertyInfo = typeof (AssociativeEntity).GetProperty(propertyName); if (propertyInfo == null) return false; // convert the value to the expected type val = Convert.ChangeType(val, propertyInfo.PropertyType); // attempt the assignment foreach (AssociativeEntity bo in (AssociativeEntity[]) obj) propertyInfo.SetValue(bo, val, null); return true; } catch { return false; } } private object GetProperty(object obj, string propertyName, object defaultValue) { try { PropertyInfo propertyInfo = GetPropertyInfoCache(propertyName); if (!(propertyInfo == null)) { var objs = (AssociativeEntity[]) obj; var valueList = new ArrayList(); foreach (AssociativeEntity bo in objs) { object value = propertyInfo.GetValue(bo, null); if (!valueList.Contains(value)) { valueList.Add(value); } } switch (valueList.Count) { case 1: return valueList[0]; default: return string.Empty; } } } catch (Exception ex) { Console.WriteLine(ex.Message); } // if property doesn't exist or throws return defaultValue; } #endregion #region ICustomTypeDescriptor explicit interface definitions // Most of the functions required by the ICustomTypeDescriptor are // merely pssed on to the default TypeDescriptor for this type, // which will do something appropriate. The exceptions are noted // below. AttributeCollection ICustomTypeDescriptor.GetAttributes() { return TypeDescriptor.GetAttributes(this, true); } string ICustomTypeDescriptor.GetClassName() { return TypeDescriptor.GetClassName(this, true); } string ICustomTypeDescriptor.GetComponentName() { return TypeDescriptor.GetComponentName(this, true); } TypeConverter ICustomTypeDescriptor.GetConverter() { return TypeDescriptor.GetConverter(this, true); } EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() { return TypeDescriptor.GetDefaultEvent(this, true); } PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() { // This function searches the property list for the property // with the same name as the DefaultProperty specified, and // returns a property descriptor for it. If no property is // found that matches DefaultProperty, a null reference is // returned instead. PropertySpec propertySpec = null; if (_defaultProperty != null) { int index = _properties.IndexOf(_defaultProperty); propertySpec = _properties[index]; } if (propertySpec != null) return new PropertySpecDescriptor(propertySpec, this, propertySpec.Name, null); return null; } object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { return TypeDescriptor.GetEditor(this, editorBaseType, true); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { return TypeDescriptor.GetEvents(this, true); } EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) { return TypeDescriptor.GetEvents(this, attributes, true); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { return ((ICustomTypeDescriptor) this).GetProperties(new Attribute[0]); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { // Rather than passing this function on to the default TypeDescriptor, // which would return the actual properties of AssociativeEntityPropertyBag, I construct // a list here that contains property descriptors for the elements of the // Properties list in the bag. var props = new ArrayList(); foreach (PropertySpec property in _properties) { var attrs = new ArrayList(); // If a category, description, editor, or type converter are specified // in the PropertySpec, create attributes to define that relationship. if (property.Category != null) attrs.Add(new CategoryAttribute(property.Category)); if (property.Description != null) attrs.Add(new DescriptionAttribute(property.Description)); if (property.EditorTypeName != null) attrs.Add(new EditorAttribute(property.EditorTypeName, typeof (UITypeEditor))); if (property.ConverterTypeName != null) attrs.Add(new TypeConverterAttribute(property.ConverterTypeName)); // Additionally, append the custom attributes associated with the // PropertySpec, if any. if (property.Attributes != null) attrs.AddRange(property.Attributes); if (property.DefaultValue != null) attrs.Add(new DefaultValueAttribute(property.DefaultValue)); attrs.Add(new BrowsableAttribute(property.Browsable)); attrs.Add(new ReadOnlyAttribute(property.ReadOnly)); attrs.Add(new BindableAttribute(property.Bindable)); var attrArray = (Attribute[]) attrs.ToArray(typeof (Attribute)); // Create a new property descriptor for the property item, and add // it to the list. var pd = new PropertySpecDescriptor(property, this, property.Name, attrArray); props.Add(pd); } // Convert the list of PropertyDescriptors to a collection that the // ICustomTypeDescriptor can use, and return it. var propArray = (PropertyDescriptor[]) props.ToArray( typeof (PropertyDescriptor)); return new PropertyDescriptorCollection(propArray); } object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { return this; } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; //using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using WebTrackr.Areas.HelpPage.ModelDescriptions; using WebTrackr.Areas.HelpPage.Models; namespace WebTrackr.Areas.HelpPage { /// <summary> /// Help Page Configuration Extenstion Methods /// </summary> public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; var modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { var apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; var apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { var apiModel = new HelpPageApiModel { ApiDescription = apiDescription, }; var modelGenerator = config.GetModelDescriptionGenerator(); var sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { var apiDescription = apiModel.ApiDescription; foreach (var apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { var parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (var uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { var uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation { Documentation = "Required" }); } var defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { //Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. var modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { var parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { var apiDescription = apiModel.ApiDescription; foreach (var apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { // ReSharper disable once PossibleNullReferenceException var parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { var parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { var response = apiModel.ApiDescription.ResponseDescription; var responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { var sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { var modelGenerator = new ModelDescriptionGenerator(config); var apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (var api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { var invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
#region License /* The MIT License Copyright (c) 2008 Sky Morey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System.Web.Routing; using System.Collections.Generic; using System.Reflection; #if !MVC2 using HtmlHelperKludge = System.Web.Mvc.HtmlHelper; #endif namespace System.Web.Mvc.Html { /// <summary> /// FormExtensionsEx /// </summary> public static class FormExtensionsEx { private static readonly PropertyInfo _formIdGeneratorPropertyInfo = typeof(ViewContext).GetProperty("FormIdGenerator", BindingFlags.NonPublic | BindingFlags.Instance); /// <summary> /// Begins the form ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <returns></returns> public static MvcForm BeginFormEx(this HtmlHelper htmlHelper) { var rawUrl = htmlHelper.ViewContext.HttpContext.Request.RawUrl; return FormHelper(htmlHelper, rawUrl, FormMethod.Post, new RouteValueDictionary()); } /// <summary> /// Begins the form ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="routeValues">The route values.</param> /// <returns></returns> public static MvcForm BeginFormEx(this HtmlHelper htmlHelper, object routeValues) { return BeginFormEx(htmlHelper, null, null, new RouteValueDictionary(routeValues), FormMethod.Post, new RouteValueDictionary()); } /// <summary> /// Begins the form ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="routeValues">The route values.</param> /// <returns></returns> public static MvcForm BeginFormEx(this HtmlHelper htmlHelper, RouteValueDictionary routeValues) { return BeginFormEx(htmlHelper, null, null, routeValues, FormMethod.Post, new RouteValueDictionary()); } /// <summary> /// Begins the form ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="actionName">Name of the action.</param> /// <param name="controllerName">Name of the controller.</param> /// <returns></returns> public static MvcForm BeginFormEx(this HtmlHelper htmlHelper, string actionName, string controllerName) { return BeginFormEx(htmlHelper, actionName, controllerName, new RouteValueDictionary(), FormMethod.Post, new RouteValueDictionary()); } /// <summary> /// Begins the form ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="actionName">Name of the action.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="routeValues">The route values.</param> /// <returns></returns> public static MvcForm BeginFormEx(this HtmlHelper htmlHelper, string actionName, string controllerName, object routeValues) { return BeginFormEx(htmlHelper, actionName, controllerName, new RouteValueDictionary(routeValues), FormMethod.Post, new RouteValueDictionary()); } /// <summary> /// Begins the form ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="actionName">Name of the action.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="method">The method.</param> /// <returns></returns> public static MvcForm BeginFormEx(this HtmlHelper htmlHelper, string actionName, string controllerName, FormMethod method) { return BeginFormEx(htmlHelper, actionName, controllerName, new RouteValueDictionary(), method, new RouteValueDictionary()); } /// <summary> /// Begins the form ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="actionName">Name of the action.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="routeValues">The route values.</param> /// <returns></returns> public static MvcForm BeginFormEx(this HtmlHelper htmlHelper, string actionName, string controllerName, RouteValueDictionary routeValues) { return BeginFormEx(htmlHelper, actionName, controllerName, routeValues, FormMethod.Post, new RouteValueDictionary()); } /// <summary> /// Begins the form ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="actionName">Name of the action.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="routeValues">The route values.</param> /// <param name="method">The method.</param> /// <returns></returns> public static MvcForm BeginFormEx(this HtmlHelper htmlHelper, string actionName, string controllerName, object routeValues, FormMethod method) { return BeginFormEx(htmlHelper, actionName, controllerName, new RouteValueDictionary(routeValues), method, new RouteValueDictionary()); } /// <summary> /// Begins the form ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="actionName">Name of the action.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="method">The method.</param> /// <param name="htmlAttributes">The HTML attributes.</param> /// <returns></returns> public static MvcForm BeginFormEx(this HtmlHelper htmlHelper, string actionName, string controllerName, FormMethod method, IDictionary<string, object> htmlAttributes) { return BeginFormEx(htmlHelper, actionName, controllerName, new RouteValueDictionary(), method, htmlAttributes); } /// <summary> /// Begins the form ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="actionName">Name of the action.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="method">The method.</param> /// <param name="htmlAttributes">The HTML attributes.</param> /// <returns></returns> public static MvcForm BeginFormEx(this HtmlHelper htmlHelper, string actionName, string controllerName, FormMethod method, object htmlAttributes) { return BeginFormEx(htmlHelper, actionName, controllerName, new RouteValueDictionary(), method, HtmlHelperKludge.AnonymousObjectToHtmlAttributes(htmlAttributes)); } /// <summary> /// Begins the form ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="actionName">Name of the action.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="routeValues">The route values.</param> /// <param name="method">The method.</param> /// <returns></returns> public static MvcForm BeginFormEx(this HtmlHelper htmlHelper, string actionName, string controllerName, RouteValueDictionary routeValues, FormMethod method) { return BeginFormEx(htmlHelper, actionName, controllerName, routeValues, method, new RouteValueDictionary()); } /// <summary> /// Begins the form ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="actionName">Name of the action.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="routeValues">The route values.</param> /// <param name="method">The method.</param> /// <param name="htmlAttributes">The HTML attributes.</param> /// <returns></returns> public static MvcForm BeginFormEx(this HtmlHelper htmlHelper, string actionName, string controllerName, object routeValues, FormMethod method, object htmlAttributes) { return BeginFormEx(htmlHelper, actionName, controllerName, new RouteValueDictionary(routeValues), method, HtmlHelperKludge.AnonymousObjectToHtmlAttributes(htmlAttributes)); } /// <summary> /// Begins the form ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="actionName">Name of the action.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="routeValues">The route values.</param> /// <param name="method">The method.</param> /// <param name="htmlAttributes">The HTML attributes.</param> /// <returns></returns> public static MvcForm BeginFormEx(this HtmlHelper htmlHelper, string actionName, string controllerName, RouteValueDictionary routeValues, FormMethod method, IDictionary<string, object> htmlAttributes) { IDynamicNode node; var formAction = UrlHelperEx.GenerateUrl(out node, null, actionName, controllerName, routeValues, htmlHelper.RouteCollection, htmlHelper.ViewContext.RequestContext, true); return FormHelper(htmlHelper, formAction, method, htmlAttributes); } /// <summary> /// Begins the route form ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="routeValues">The route values.</param> /// <returns></returns> public static MvcForm BeginRouteFormEx(this HtmlHelper htmlHelper, object routeValues) { return BeginRouteFormEx(htmlHelper, null, new RouteValueDictionary(routeValues), FormMethod.Post, new RouteValueDictionary()); } /// <summary> /// Begins the route form ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="routeName">Name of the route.</param> /// <returns></returns> public static MvcForm BeginRouteFormEx(this HtmlHelper htmlHelper, string routeName) { return BeginRouteFormEx(htmlHelper, routeName, new RouteValueDictionary(), FormMethod.Post, new RouteValueDictionary()); } /// <summary> /// Begins the route form ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="routeValues">The route values.</param> /// <returns></returns> public static MvcForm BeginRouteFormEx(this HtmlHelper htmlHelper, RouteValueDictionary routeValues) { return BeginRouteFormEx(htmlHelper, null, routeValues, FormMethod.Post, new RouteValueDictionary()); } /// <summary> /// Begins the route form ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="routeName">Name of the route.</param> /// <param name="routeValues">The route values.</param> /// <returns></returns> public static MvcForm BeginRouteFormEx(this HtmlHelper htmlHelper, string routeName, object routeValues) { return BeginRouteFormEx(htmlHelper, routeName, new RouteValueDictionary(routeValues), FormMethod.Post, new RouteValueDictionary()); } /// <summary> /// Begins the route form ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="routeName">Name of the route.</param> /// <param name="method">The method.</param> /// <returns></returns> public static MvcForm BeginRouteFormEx(this HtmlHelper htmlHelper, string routeName, FormMethod method) { return BeginRouteFormEx(htmlHelper, routeName, new RouteValueDictionary(), method, new RouteValueDictionary()); } /// <summary> /// Begins the route form ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="routeName">Name of the route.</param> /// <param name="routeValues">The route values.</param> /// <returns></returns> public static MvcForm BeginRouteFormEx(this HtmlHelper htmlHelper, string routeName, RouteValueDictionary routeValues) { return BeginRouteFormEx(htmlHelper, routeName, routeValues, FormMethod.Post, new RouteValueDictionary()); } /// <summary> /// Begins the route form ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="routeName">Name of the route.</param> /// <param name="routeValues">The route values.</param> /// <param name="method">The method.</param> /// <returns></returns> public static MvcForm BeginRouteFormEx(this HtmlHelper htmlHelper, string routeName, object routeValues, FormMethod method) { return BeginRouteFormEx(htmlHelper, routeName, new RouteValueDictionary(routeValues), method, new RouteValueDictionary()); } /// <summary> /// Begins the route form ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="routeName">Name of the route.</param> /// <param name="method">The method.</param> /// <param name="htmlAttributes">The HTML attributes.</param> /// <returns></returns> public static MvcForm BeginRouteFormEx(this HtmlHelper htmlHelper, string routeName, FormMethod method, IDictionary<string, object> htmlAttributes) { return BeginRouteFormEx(htmlHelper, routeName, new RouteValueDictionary(), method, htmlAttributes); } /// <summary> /// Begins the route form ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="routeName">Name of the route.</param> /// <param name="method">The method.</param> /// <param name="htmlAttributes">The HTML attributes.</param> /// <returns></returns> public static MvcForm BeginRouteFormEx(this HtmlHelper htmlHelper, string routeName, FormMethod method, object htmlAttributes) { return BeginRouteFormEx(htmlHelper, routeName, new RouteValueDictionary(), method, HtmlHelperKludge.AnonymousObjectToHtmlAttributes(htmlAttributes)); } /// <summary> /// Begins the route form ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="routeName">Name of the route.</param> /// <param name="routeValues">The route values.</param> /// <param name="method">The method.</param> /// <returns></returns> public static MvcForm BeginRouteFormEx(this HtmlHelper htmlHelper, string routeName, RouteValueDictionary routeValues, FormMethod method) { return BeginRouteFormEx(htmlHelper, routeName, routeValues, method, new RouteValueDictionary()); } /// <summary> /// Begins the route form ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="routeName">Name of the route.</param> /// <param name="routeValues">The route values.</param> /// <param name="method">The method.</param> /// <param name="htmlAttributes">The HTML attributes.</param> /// <returns></returns> public static MvcForm BeginRouteFormEx(this HtmlHelper htmlHelper, string routeName, object routeValues, FormMethod method, object htmlAttributes) { return BeginRouteFormEx(htmlHelper, routeName, new RouteValueDictionary(routeValues), method, HtmlHelperKludge.AnonymousObjectToHtmlAttributes(htmlAttributes)); } /// <summary> /// Begins the route form ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> /// <param name="routeName">Name of the route.</param> /// <param name="routeValues">The route values.</param> /// <param name="method">The method.</param> /// <param name="htmlAttributes">The HTML attributes.</param> /// <returns></returns> public static MvcForm BeginRouteFormEx(this HtmlHelper htmlHelper, string routeName, RouteValueDictionary routeValues, FormMethod method, IDictionary<string, object> htmlAttributes) { IDynamicNode node; var formAction = UrlHelperEx.GenerateUrl(out node, routeName, null, null, routeValues, htmlHelper.RouteCollection, htmlHelper.ViewContext.RequestContext, false); return FormHelper(htmlHelper, formAction, method, htmlAttributes); } /// <summary> /// Ends the form ex. /// </summary> /// <param name="htmlHelper">The HTML helper.</param> public static void EndFormEx(this HtmlHelper htmlHelper) { htmlHelper.ViewContext.Writer.Write("</form>"); htmlHelper.ViewContext.OutputClientValidation(); htmlHelper.ViewContext.FormContext = null; //:kludge } private static MvcForm FormHelper(HtmlHelper htmlHelper, string formAction, FormMethod method, IDictionary<string, object> htmlAttributes) { var builder = new TagBuilder("form"); builder.MergeAttributes<string, object>(htmlAttributes); builder.MergeAttribute("action", formAction); builder.MergeAttribute("method", HtmlHelper.GetFormMethodString(method), true); #if !MVC2 var flag = (htmlHelper.ViewContext.ClientValidationEnabled && !htmlHelper.ViewContext.UnobtrusiveJavaScriptEnabled); #else var flag = htmlHelper.ViewContext.ClientValidationEnabled; #endif if (flag) builder.GenerateId(((Func<string>)_formIdGeneratorPropertyInfo.GetValue(htmlHelper.ViewContext, null))()); htmlHelper.ViewContext.Writer.Write(builder.ToString(TagRenderMode.StartTag)); var form = new MvcForm(htmlHelper.ViewContext); if (flag) htmlHelper.ViewContext.FormContext.FormId = builder.Attributes["id"]; return form; } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using LExpression = System.Linq.Expressions.Expression; namespace Pidgin { public static partial class Parser<TToken> { /// <summary> /// Creates a parser that parses and returns a literal sequence of tokens /// </summary> /// <param name="tokens">A sequence of tokens</param> /// <returns>A parser that parses a literal sequence of tokens</returns> public static Parser<TToken, TToken[]> Sequence(params TToken[] tokens) { if (tokens == null) { throw new ArgumentNullException(nameof(tokens)); } return Sequence<TToken[]>(tokens); } /// <summary> /// Creates a parser that parses and returns a literal sequence of tokens. /// The input enumerable is enumerated and copied to a list. /// </summary> /// <typeparam name="TEnumerable">The type of tokens to parse</typeparam> /// <param name="tokens">A sequence of tokens</param> /// <returns>A parser that parses a literal sequence of tokens</returns> public static Parser<TToken, TEnumerable> Sequence<TEnumerable>(TEnumerable tokens) where TEnumerable : IEnumerable<TToken> { if (tokens == null) { throw new ArgumentNullException(nameof(tokens)); } return SequenceTokenParser<TToken, TEnumerable>.Create(tokens); } /// <summary> /// Creates a parser that applies a sequence of parsers and collects the results. /// This parser fails if any of its constituent parsers fail /// </summary> /// <typeparam name="T">The return type of the parsers</typeparam> /// <param name="parsers">A sequence of parsers</param> /// <returns>A parser that applies a sequence of parsers and collects the results</returns> public static Parser<TToken, IEnumerable<T>> Sequence<T>(params Parser<TToken, T>[] parsers) { return Sequence(parsers.AsEnumerable()); } /// <summary> /// Creates a parser that applies a sequence of parsers and collects the results. /// This parser fails if any of its constituent parsers fail /// </summary> /// <typeparam name="T">The return type of the parsers</typeparam> /// <param name="parsers">A sequence of parsers</param> /// <returns>A parser that applies a sequence of parsers and collects the results</returns> public static Parser<TToken, IEnumerable<T>> Sequence<T>(IEnumerable<Parser<TToken, T>> parsers) { if (parsers == null) { throw new ArgumentNullException(nameof(parsers)); } var parsersArray = parsers.ToArray(); if (parsersArray.Length == 1) { return parsersArray[0].Select(x => new[] { x }.AsEnumerable()); } return new SequenceParser<TToken, T>(parsersArray); } } internal sealed class SequenceParser<TToken, T> : Parser<TToken, IEnumerable<T>> { private readonly Parser<TToken, T>[] _parsers; public SequenceParser(Parser<TToken, T>[] parsers) { _parsers = parsers; } public sealed override bool TryParse(ref ParseState<TToken> state, ref PooledList<Expected<TToken>> expecteds, [MaybeNullWhen(false)] out IEnumerable<T> result) { var ts = new T[_parsers.Length]; for (var i = 0; i < _parsers.Length; i++) { var p = _parsers[i]; var success = p.TryParse(ref state, ref expecteds, out ts[i]!); if (!success) { result = null; return false; } } result = ts; return true; } } internal static class SequenceTokenParser<TToken, TEnumerable> where TEnumerable : IEnumerable<TToken> { private static readonly Func<TEnumerable, Parser<TToken, TEnumerable>>? _createParser; public static Parser<TToken, TEnumerable> Create(TEnumerable tokens) { if (_createParser != null) { return _createParser(tokens); } return new SequenceTokenParserSlow<TToken, TEnumerable>(tokens); } static SequenceTokenParser() { var ttoken = typeof(TToken).GetTypeInfo(); var equatable = typeof(IEquatable<TToken>).GetTypeInfo(); if (ttoken.IsValueType && equatable.IsAssignableFrom(ttoken)) { var ctor = typeof(SequenceTokenParserFast<,>) .MakeGenericType(typeof(TToken), typeof(TEnumerable)) .GetTypeInfo() .DeclaredConstructors .Single(); var param = LExpression.Parameter(typeof(TEnumerable)); var create = LExpression.New(ctor, param); _createParser = LExpression.Lambda<Func<TEnumerable, Parser<TToken, TEnumerable>>>(create, param).Compile(); } } } internal sealed class SequenceTokenParserFast<TToken, TEnumerable> : Parser<TToken, TEnumerable> where TToken : struct, IEquatable<TToken> where TEnumerable : IEnumerable<TToken> { private readonly TEnumerable _value; private readonly ImmutableArray<TToken> _valueTokens; public SequenceTokenParserFast(TEnumerable value) { _value = value; _valueTokens = value.ToImmutableArray(); } public sealed override bool TryParse(ref ParseState<TToken> state, ref PooledList<Expected<TToken>> expecteds, [MaybeNullWhen(false)] out TEnumerable result) { var span = state.LookAhead(_valueTokens.Length); // span.Length <= _valueTokens.Length var errorPos = -1; for (var i = 0; i < span.Length; i++) { if (!span[i].Equals(_valueTokens[i])) { errorPos = i; break; } } if (errorPos != -1) { // strings didn't match state.Advance(errorPos); state.SetError( Maybe.Just(span[errorPos]), false, state.Location, null ); expecteds.Add(new Expected<TToken>(_valueTokens)); result = default; return false; } if (span.Length < _valueTokens.Length) { // strings matched but reached EOF state.Advance(span.Length); state.SetError( Maybe.Nothing<TToken>(), true, state.Location, null ); expecteds.Add(new Expected<TToken>(_valueTokens)); result = default; return false; } // OK state.Advance(_valueTokens.Length); result = _value; return true; } } internal sealed class SequenceTokenParserSlow<TToken, TEnumerable> : Parser<TToken, TEnumerable> where TEnumerable : IEnumerable<TToken> { private readonly TEnumerable _value; private readonly ImmutableArray<TToken> _valueTokens; public SequenceTokenParserSlow(TEnumerable value) { _value = value; _valueTokens = value.ToImmutableArray(); } public sealed override bool TryParse(ref ParseState<TToken> state, ref PooledList<Expected<TToken>> expecteds, [MaybeNullWhen(false)] out TEnumerable result) { var span = state.LookAhead(_valueTokens.Length); // span.Length <= _valueTokens.Length var errorPos = -1; for (var i = 0; i < span.Length; i++) { if (!EqualityComparer<TToken>.Default.Equals(span[i], _valueTokens[i])) { errorPos = i; break; } } if (errorPos != -1) { // strings didn't match state.Advance(errorPos); state.SetError(Maybe.Just(span[errorPos]), false, state.Location, null); expecteds.Add(new Expected<TToken>(_valueTokens)); result = default; return false; } if (span.Length < _valueTokens.Length) { // strings matched but reached EOF state.Advance(span.Length); state.SetError(Maybe.Nothing<TToken>(), true, state.Location, null); expecteds.Add(new Expected<TToken>(_valueTokens)); result = default; return false; } // OK state.Advance(_valueTokens.Length); result = _value; return true; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; using System; using System.Xml; namespace XMLTests.ReaderWriter.ReadContentTests { public class IntegerElementContentTests { [Fact] public static void ReadElementContentAsInt1() { var reader = Utils.CreateFragmentReader(@"<doc a='b'>9999</doc>"); reader.PositionOnElementNonEmptyNoDoctype("doc"); Assert.Equal(new DateTime(9999, 1, 1, 0, 0, 0), reader.ReadElementContentAs(typeof(DateTime), null)); } [Fact] public static void ReadElementContentAsInt10() { var reader = Utils.CreateFragmentReader("<Root>-4<!-- Comment inbetween-->4</Root>"); reader.PositionOnElement("Root"); Assert.Equal(-44, reader.ReadElementContentAsInt()); } [Fact] public static void ReadElementContentAsInt11() { var reader = Utils.CreateFragmentReader("<Root> -<!-- Comment inbetween-->000<?a?>455 </Root>"); reader.PositionOnElement("Root"); Assert.Equal(-455, reader.ReadElementContentAsInt()); } [Fact] public static void ReadElementContentAsInt12() { var reader = Utils.CreateFragmentReader("<Root> -45.5 </Root>"); reader.PositionOnElement("Root"); Assert.Throws<XmlException>(() => reader.ReadElementContentAsInt()); } [Fact] public static void ReadElementContentAsInt13() { var reader = Utils.CreateFragmentReader("<Root> -45.5 </Root>"); reader.PositionOnElement("Root"); reader.Read(); Assert.Throws<XmlException>(() => reader.ReadContentAsInt()); } [Fact] public static void ReadElementContentAsInt14() { var reader = Utils.CreateFragmentReader("<Root a=' 4.678'/>"); reader.PositionOnElement("Root"); reader.MoveToAttribute("a"); Assert.Throws<XmlException>(() => reader.ReadContentAsInt()); } [Fact] public static void ReadElementContentAsInt15() { var reader = Utils.CreateFragmentReader("<Root> -<![CDATA[0]]>0<!-- Comment inbetween-->5<?a?> </Root>"); reader.PositionOnElement("Root"); Assert.Equal(-5, reader.ReadElementContentAs(typeof(int), null)); } [Fact] public static void ReadElementContentAsInt16() { var reader = Utils.CreateFragmentReader("<Root> <!-- Comment inbetween-->0<?a?>00<![CDATA[1]]></Root>"); reader.PositionOnElement("Root"); Assert.Equal(1, reader.ReadElementContentAs(typeof(int), null)); } [Fact] public static void ReadElementContentAsInt17() { var reader = Utils.CreateFragmentReader("<Root><![CDATA[0]]> <!-- Comment inbetween--> </Root>"); reader.PositionOnElement("Root"); Assert.Equal(0, reader.ReadElementContentAs(typeof(int), null)); } [Fact] public static void ReadElementContentAsInt18() { var reader = Utils.CreateFragmentReader("<Root> 9<![CDATA[9]]>99<?a?>9<!-- Comment inbetween--><![CDATA[9]]> </Root>"); reader.PositionOnElement("Root"); Assert.Equal(999999, reader.ReadElementContentAs(typeof(int), null)); } [Fact] public static void ReadElementContentAsInt19() { var reader = Utils.CreateFragmentReader("<Root>-4<!-- Comment inbetween-->4</Root>"); reader.PositionOnElement("Root"); Assert.Equal(-44, reader.ReadElementContentAs(typeof(int), null)); } [Fact] public static void ReadElementContentAsInt2() { var reader = Utils.CreateFragmentReader(@"<doc a='b'>0001z</doc>"); reader.PositionOnElementNonEmptyNoDoctype("doc"); Assert.Equal(new DateTime(1, 1, 1, 0, 0, 0, 0).Add(new TimeSpan(0, 0, 0)), reader.ReadElementContentAs(typeof(DateTime), null)); } [Fact] public static void ReadElementContentAsInt20() { var reader = Utils.CreateFragmentReader("<Root> -<!-- Comment inbetween-->000<?a?>455 </Root>"); reader.PositionOnElement("Root"); Assert.Equal(-455, reader.ReadElementContentAs(typeof(int), null)); } [Fact] public static void ReadElementContentAsInt21() { var reader = Utils.CreateFragmentReader("<Root> -45.5 </Root>"); reader.PositionOnElement("Root"); Assert.Throws<XmlException>(() => reader.ReadElementContentAs(typeof(int), null)); } [Fact] public static void ReadElementContentAsInt22() { var reader = Utils.CreateFragmentReader("<Root> -45.5 </Root>"); reader.PositionOnElement("Root"); reader.Read(); Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(int), null)); } [Fact] public static void ReadElementContentAsInt23() { var reader = Utils.CreateFragmentReader(@"<doc a='b'>9999</doc>"); reader.PositionOnElementNonEmptyNoDoctype("doc"); Assert.Equal(new DateTimeOffset(9999, 1, 1, 0, 0, 0, TimeZoneInfo.Local.GetUtcOffset(new DateTime(9999, 1, 1))).ToString(), reader.ReadElementContentAs(typeof(DateTimeOffset), null).ToString()); } [Fact] public static void ReadElementContentAsInt24() { var reader = Utils.CreateFragmentReader(@"<doc a='b'>0001z</doc>"); reader.PositionOnElementNonEmptyNoDoctype("doc"); Assert.Equal(new DateTimeOffset(1, 1, 1, 0, 0, 0, TimeSpan.FromHours(0)).ToString(), reader.ReadElementContentAs(typeof(DateTimeOffset), null).ToString()); } [Fact] public static void ReadElementContentAsInt3() { var reader = Utils.CreateFragmentReader(@"<doc a='b'>0001z</doc>"); reader.PositionOnElementNonEmptyNoDoctype("doc"); Assert.Equal(new DateTimeOffset(new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)), reader.ReadElementContentAs(typeof(DateTimeOffset), null)); } [Fact] public static void ReadElementContentAsInt4() { var reader = Utils.CreateFragmentReader(@"<doc a='b'>9999</doc>"); reader.PositionOnElementNonEmptyNoDoctype("doc"); Assert.Equal(new DateTimeOffset(new DateTime(9999, 1, 1, 0, 0, 0, DateTimeKind.Local)), reader.ReadElementContentAs(typeof(DateTimeOffset), null)); } [Fact] public static void ReadElementContentAsInt5() { var reader = Utils.CreateFragmentReader("<Root a=' 4.678'/>"); reader.PositionOnElement("Root"); reader.MoveToAttribute("a"); Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(int), null)); } [Fact] public static void ReadElementContentAsInt6() { var reader = Utils.CreateFragmentReader("<Root> -<![CDATA[0]]>0<!-- Comment inbetween-->5<?a?> </Root>"); reader.PositionOnElement("Root"); Assert.Equal(-5, reader.ReadElementContentAsInt()); } [Fact] public static void ReadElementContentAsInt7() { var reader = Utils.CreateFragmentReader("<Root> <!-- Comment inbetween-->0<?a?>00<![CDATA[1]]></Root>"); reader.PositionOnElement("Root"); Assert.Equal(1, reader.ReadElementContentAsInt()); } [Fact] public static void ReadElementContentAsInt8() { var reader = Utils.CreateFragmentReader("<Root><![CDATA[0]]> <!-- Comment inbetween--> </Root>"); reader.PositionOnElement("Root"); Assert.Equal(0, reader.ReadElementContentAsInt()); } [Fact] public static void ReadElementContentAsInt9() { var reader = Utils.CreateFragmentReader("<Root> 9<![CDATA[9]]>99<?a?>9<!-- Comment inbetween--><![CDATA[9]]> </Root>"); reader.PositionOnElement("Root"); Assert.Equal(999999, reader.ReadElementContentAsInt()); } } }
// // Copyright (C) DataStax Inc. // // 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 NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Net; using Cassandra.IntegrationTests.SimulacronAPI; using Cassandra.IntegrationTests.TestBase; using Cassandra.IntegrationTests.TestClusterManagement; using Cassandra.IntegrationTests.TestClusterManagement.Simulacron; using Cassandra.Tests; namespace Cassandra.IntegrationTests.Core { [TestFixture, Category(TestCategory.Short)] public class ExceptionsTests : TestGlobals { private ISession _session; private string _keyspace; private string _table; private static SimulacronCluster _simulacronCluster; [SetUp] public void RestartCluster() { _simulacronCluster = SimulacronCluster.CreateNew(new SimulacronOptions()); var contactPoint = _simulacronCluster.InitialContactPoint; var builder = ClusterBuilder() .AddContactPoint(contactPoint); var cluster = builder.Build(); _session = cluster.Connect(); _keyspace = TestUtils.GetUniqueKeyspaceName().ToLowerInvariant(); _table = TestUtils.GetUniqueTableName().ToLowerInvariant(); } [TearDown] public void TearDown() { _session.Cluster.Shutdown(); _simulacronCluster.Dispose(); } /// <summary> /// Tests the AlreadyExistsException. Create a keyspace twice and a table twice. /// Catch and test all the exception methods. /// </summary> [Test] public void AlreadyExistsException() { var cql = string.Format(TestUtils.CreateKeyspaceSimpleFormat, _keyspace, 1); _simulacronCluster.PrimeFluent(b => b.WhenQuery(cql).ThenAlreadyExists(_keyspace, "")); var ex = Assert.Throws<AlreadyExistsException>(() => _session.Execute(cql)); Assert.AreEqual(ex.Keyspace, _keyspace); Assert.AreEqual(ex.Table, null); Assert.AreEqual(ex.WasTableCreation, false); var cqlTable = string.Format(TestUtils.CreateTableSimpleFormat, _table); _simulacronCluster.PrimeFluent(b => b.WhenQuery(cqlTable).ThenAlreadyExists(_keyspace, _table)); var e = Assert.Throws<AlreadyExistsException>(() => _session.Execute(cqlTable)); Assert.AreEqual(e.Keyspace, _keyspace); Assert.AreEqual(e.Table, _table); Assert.AreEqual(e.WasTableCreation, true); } /// <summary> /// Tests the NoHostAvailableException. by attempting to build a cluster using /// the IP address "255.255.255.255" and test all available exception methods. /// </summary> [Test] public void NoHostAvailableException() { const string ipAddress = "255.255.255.255"; var errorsHashMap = new Dictionary<IPAddress, Exception> {{IPAddress.Parse(ipAddress), null}}; try { ClusterBuilder().AddContactPoint(ipAddress).Build(); } catch (NoHostAvailableException e) { Assert.AreEqual(e.Message, $"All host tried for query are in error (tried: {ipAddress})"); Assert.AreEqual(e.Errors.Keys.ToArray(), errorsHashMap.Keys.ToArray()); } } /// <summary> /// Tests the ReadTimeoutException. Create a 3 node cluster and write out a /// single key at CL.ALL. Then forcibly kill single node and attempt a read of /// the key at CL.ALL. Catch and test all available exception methods. /// </summary> [Test] public void ReadTimeoutException() { var cql = string.Format(TestUtils.SELECT_ALL_FORMAT, _table); _simulacronCluster.PrimeFluent(b => b.WhenQuery(cql).ThenReadTimeout(5, 1, 2, true)); var ex = Assert.Throws<ReadTimeoutException>(() => _session.Execute(new SimpleStatement(cql).SetConsistencyLevel(ConsistencyLevel.All))); Assert.AreEqual(ex.ConsistencyLevel, ConsistencyLevel.All); Assert.AreEqual(ex.ReceivedAcknowledgements, 1); Assert.AreEqual(ex.RequiredAcknowledgements, 2); Assert.AreEqual(ex.WasDataRetrieved, true); } /// <summary> /// Tests SyntaxError. Tests basic message and copy abilities. /// </summary> [Test] public void SyntaxError() { const string errorMessage = "Test Message"; try { throw new SyntaxError(errorMessage); } catch (SyntaxError e) { Assert.AreEqual(e.Message, errorMessage); } } /// <summary> /// Tests TraceRetrievalException. Tests basic message. /// </summary> [Test] public void TraceRetrievalException() { const string errorMessage = "Test Message"; try { throw new TraceRetrievalException(errorMessage); } catch (TraceRetrievalException e) { Assert.AreEqual(e.Message, errorMessage); } } /// <summary> /// Tests TruncateException. Tests basic message and copy abilities. /// </summary> [Test] public void TruncateException() { const string errorMessage = "Test Message"; try { throw new TruncateException(errorMessage); } catch (TruncateException e) { Assert.AreEqual(e.Message, errorMessage); } } /// <summary> /// Tests UnauthorizedException. Tests basic message and copy abilities. /// </summary> [Test] public void UnauthorizedException() { const string errorMessage = "Test Message"; try { throw new UnauthorizedException(errorMessage); } catch (UnauthorizedException e) { Assert.AreEqual(e.Message, errorMessage); } } /// <summary> /// Tests the UnavailableException. Create a 3 node cluster and write out a /// single key at CL.ALL. Then kill single node, wait for gossip to propogate the /// new state, and attempt to read and write the same key at CL.ALL. Catch and /// test all available exception methods. /// </summary> [Test] public void UnavailableException() { var cql = string.Format(TestUtils.SELECT_ALL_FORMAT, _table); _simulacronCluster.PrimeFluent(b => b.WhenQuery(cql).ThenUnavailable("unavailable", 5, 2, 1)); var ex = Assert.Throws<UnavailableException>(() => _session.Execute(new SimpleStatement(cql).SetConsistencyLevel(ConsistencyLevel.All))); Assert.AreEqual(ex.Consistency, ConsistencyLevel.All); Assert.AreEqual(ex.RequiredReplicas, 2); Assert.AreEqual(ex.AliveReplicas, 1); } /// <summary> /// Tests the WriteTimeoutException. Create a 3 node cluster and write out a /// single key at CL.ALL. Then forcibly kill single node and attempt to write the /// same key at CL.ALL. Catch and test all available exception methods. /// </summary> [Test] public void WriteTimeoutException() { var cql = string.Format(TestUtils.SELECT_ALL_FORMAT, _table); _simulacronCluster.PrimeFluent(b => b.WhenQuery(cql).ThenWriteTimeout("write_timeout", 5, 1, 2, "SIMPLE")); var ex = Assert.Throws<WriteTimeoutException>(() => _session.Execute(new SimpleStatement(cql).SetConsistencyLevel(ConsistencyLevel.All))); Assert.AreEqual(ex.ConsistencyLevel, ConsistencyLevel.All); Assert.AreEqual(1, ex.ReceivedAcknowledgements); Assert.AreEqual(2, ex.RequiredAcknowledgements); Assert.AreEqual(ex.WriteType, "SIMPLE"); } [Test] public void PreserveStackTraceTest() { _simulacronCluster.PrimeFluent(b => b.WhenQuery("SELECT WILL FAIL").ThenSyntaxError("syntax_error")); var ex = Assert.Throws<SyntaxError>(() => _session.Execute("SELECT WILL FAIL")); #if !NETFRAMEWORK StringAssert.Contains(nameof(PreserveStackTraceTest), ex.StackTrace); StringAssert.Contains(nameof(ExceptionsTests), ex.StackTrace); #endif StringAssert.Contains("Cassandra.Session.Execute", ex.StackTrace); } [Test] public void RowSetIteratedTwice() { var cql = string.Format(TestUtils.SELECT_ALL_FORMAT, _table); _simulacronCluster .PrimeFluent(b => b.WhenQuery(cql).ThenRowsSuccess( new[] { ("id", DataType.Uuid), ("value", DataType.Varchar) }, rows => rows.WithRow(Guid.NewGuid(), "value"))); var rowset = _session.Execute(new SimpleStatement(cql)).GetRows(); Assert.NotNull(rowset); //Linq Count iterates Assert.AreEqual(1, rowset.Count()); Assert.AreEqual(0, rowset.Count()); } [Test] public void RowSetPagingAfterSessionDispose() { var cql = string.Format(TestUtils.SELECT_ALL_FORMAT, _table); _simulacronCluster .PrimeFluent(b => b.WhenQuery(cql).ThenRowsSuccess( new[] { ("id", DataType.Uuid), ("value", DataType.Varchar) }, rows => rows.WithRow(Guid.NewGuid(), "value"))); var rs = _session.Execute(new SimpleStatement(string.Format(TestUtils.SELECT_ALL_FORMAT, _table)).SetPageSize(1)); if (TestClusterManager.CheckCassandraVersion(false, new Version(2, 0), Comparison.LessThan)) { //Paging should be ignored in 1.x //But setting the page size should work Assert.AreEqual(2, rs.InnerQueueCount); return; } Assert.AreEqual(1, rs.InnerQueueCount); _session.Dispose(); //It should not fail, just do nothing rs.FetchMoreResults(); Assert.AreEqual(1, rs.InnerQueueCount); } [Test] [TestCassandraVersion(2, 2)] public void WriteFailureExceptionTest() { var cql = string.Format(TestUtils.SELECT_ALL_FORMAT, _table); _simulacronCluster .PrimeFluent(b => b.WhenQuery(cql).ThenWriteFailure( 5, 1, 2, "write_failure", new Dictionary<string, int> { { "127.0.0.1", 0 } }, "SIMPLE")); var ex = Assert.Throws<WriteFailureException>(() => _session.Execute(new SimpleStatement(cql).SetConsistencyLevel(ConsistencyLevel.All))); Assert.AreEqual(ex.ConsistencyLevel, ConsistencyLevel.All); Assert.AreEqual(1, ex.ReceivedAcknowledgements); Assert.AreEqual(2, ex.RequiredAcknowledgements); Assert.AreEqual(ex.WriteType, "SIMPLE"); } [Test] [TestCase(ConsistencyLevel.LocalQuorum, 2, 5, true, "LocalQuorum (5 response(s) were required but only 2 replica(s) responded, 1 failed)")] [TestCase(ConsistencyLevel.LocalQuorum, 1, 2, true, "LocalQuorum (2 response(s) were required but only 1 replica(s) responded, 1 failed)")] [TestCase(ConsistencyLevel.LocalOne, 1, 0, false, "LocalOne (the replica queried for data didn't respond)")] [TestCase(ConsistencyLevel.LocalQuorum, 3, 3, true, "LocalQuorum (failure while waiting for repair of inconsistent replica)")] public void ReadFailureExceptionTest(ConsistencyLevel consistencyLevel, int received, int required, bool dataPresent, string expectedMessageEnd) { const string baseMessage = "Server failure during read query at consistency "; const string cql = "SELECT * FROM ks1.table_for_read_failure_test"; _simulacronCluster .PrimeFluent(b => b.WhenQuery(cql).ThenReadFailure( (int) consistencyLevel, received, required, "read_failure", new Dictionary<string, int> { { "127.0.0.1", 0 } }, dataPresent)); var ex = Assert.Throws<ReadFailureException>(() => _session.Execute(new SimpleStatement(cql).SetConsistencyLevel(consistencyLevel))); Assert.AreEqual(consistencyLevel, ex.ConsistencyLevel); Assert.AreEqual(received, ex.ReceivedAcknowledgements); Assert.AreEqual(required, ex.RequiredAcknowledgements); Assert.AreEqual(baseMessage + expectedMessageEnd, ex.Message); } [Test] [TestCassandraVersion(2, 2)] public void FunctionFailureExceptionTest() { const string cql = "SELECT ks_func.div(v1,v2) FROM ks_func.tbl1 where id = 1"; _simulacronCluster .PrimeFluent(b => b.WhenQuery(cql).ThenFunctionFailure( "ks_func", "div", new[] { "text" }, "function_failure")); Assert.Throws<FunctionFailureException>(() => _session.Execute(cql)); } } }
/* Copyright 2012 Michael Edwards 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. */ //-CRE- using System.Collections.Generic; using System.IO; using System.Text; using Glass.Mapper.Sc.Configuration; using Glass.Mapper.Sc.DataMappers; using NUnit.Framework; using Sitecore.Data; using Sitecore.FakeDb; namespace Glass.Mapper.Sc.FakeDb.DataMappers { public class SitecoreFieldStreamMapperFixture { #region Method - GetField [Test] public void GetField_FieldContainsData_StreamIsReturned() { //Assign var templateId = ID.NewID; var targetId = ID.NewID; var fieldName = "Field"; using (Db database = new Db { new DbTemplate(templateId) { {fieldName, ""} }, new Sitecore.FakeDb.DbItem("Target", targetId, templateId), }) { var fieldValue = ""; var item = database.GetItem("/sitecore/content/Target"); var field = item.Fields[fieldName]; string expected = "hello world"; var stream = new MemoryStream(Encoding.UTF8.GetBytes(expected)); var mapper = new SitecoreFieldStreamMapper(); using (new ItemEditing(item, true)) { field.SetBlobStream(stream); } //Act var result = mapper.GetField(field, null, null) as Stream; //Assert var reader = new StreamReader(result); var resultStr = reader.ReadToEnd(); Assert.AreEqual(expected, resultStr); } } //TODO: This requires a FakeDb fix [Test] public void GetField_FieldContainsDataTestConnectionLimit_StreamIsReturned() { //Assign var templateId = ID.NewID; var targetId = ID.NewID; var fieldName = "Field"; using (Db database = new Db { new DbTemplate(templateId) { {fieldName, ""} }, new Sitecore.FakeDb.DbItem("Target", targetId, templateId), }) { var fieldValue = ""; var item = database.GetItem("/sitecore/content/Target"); var field = item.Fields[fieldName]; string expected = "hello world"; var stream = new MemoryStream(Encoding.UTF8.GetBytes(expected)); var mapper = new SitecoreFieldStreamMapper(); using (new ItemEditing(item, true)) { field.SetBlobStream(stream); } //Act var results = new List<Stream>(); for (int i = 0; i < 1000; i++) { var result = mapper.GetField(field, null, null) as Stream; if(result == null) continue; results.Add(result); } //Assert Assert.AreEqual(1000, results.Count); } } #endregion #region Method - SetField [Test] public void SetField_StreamPassed_FieldContainsStream() { //Assign var templateId = ID.NewID; var targetId = ID.NewID; var fieldName = "Field"; using (Db database = new Db { new DbTemplate(templateId) { {fieldName, ""} }, new Sitecore.FakeDb.DbItem("Target", targetId, templateId), }) { var fieldValue = ""; var item = database.GetItem("/sitecore/content/Target"); var field = item.Fields[fieldName]; string expected = "hello world"; var stream = new MemoryStream(Encoding.UTF8.GetBytes(expected)); var mapper = new SitecoreFieldStreamMapper(); using (new ItemEditing(item, true)) { field.SetBlobStream(new MemoryStream()); } //Act using (new ItemEditing(item, true)) { mapper.SetField(field, stream, null, null); } //Assert var stream1 = field.GetBlobStream(); stream1.Seek(0, SeekOrigin.Begin); var reader = new StreamReader(stream1); var resultStr = reader.ReadToEnd(); Assert.AreEqual(expected, resultStr); } } [Test] public void SetField_NullPassed_NoExceptionThrown() { //Assign var templateId = ID.NewID; var targetId = ID.NewID; var fieldName = "Field"; using (Db database = new Db { new DbTemplate(templateId) { {fieldName, ""} }, new Sitecore.FakeDb.DbItem("Target", targetId, templateId), }) { var fieldValue = ""; var item = database.GetItem("/sitecore/content/Target"); var field = item.Fields[fieldName]; string expected = "hello world"; Stream stream = null; var mapper = new SitecoreFieldStreamMapper(); using (new ItemEditing(item, true)) { field.SetBlobStream(new MemoryStream()); } //Act using (new ItemEditing(item, true)) { mapper.SetField(field, stream, null, null); } //Assert var outStream = field.GetBlobStream(); Assert.AreEqual(0,outStream.Length); } } #endregion #region Method - CanHandle [Test] public void CanHandle_StreamType_ReturnsTrue() { //Assign var mapper = new SitecoreFieldStreamMapper(); var config = new SitecoreFieldConfiguration(); config.PropertyInfo = typeof (StubClass).GetProperty("Stream"); //Act var result = mapper.CanHandle(config, null); //Assert Assert.IsTrue(result); } #endregion #region Stubs public class StubClass { public Stream Stream { get; set; } } #endregion } }
using System; using System.Collections.Generic; using DarkMultiPlayerCommon; namespace DarkMultiPlayer { public class PlayerStatusWorker { public bool workerEnabled; private static PlayerStatusWorker singleton; private Queue<PlayerStatus> addStatusQueue = new Queue<PlayerStatus>(); private Queue<string> removeStatusQueue = new Queue<string>(); public PlayerStatus myPlayerStatus; private PlayerStatus lastPlayerStatus = new PlayerStatus(); public List<PlayerStatus> playerStatusList = new List<PlayerStatus>(); private const float PLAYER_STATUS_CHECK_INTERVAL = .2f; private const float PLAYER_STATUS_SEND_THROTTLE = 1f; private float lastPlayerStatusSend = 0f; private float lastPlayerStatusCheck = 0f; public PlayerStatusWorker() { myPlayerStatus = new PlayerStatus(); myPlayerStatus.playerName = Settings.fetch.playerName; myPlayerStatus.statusText = "Syncing"; } public static PlayerStatusWorker fetch { get { return singleton; } } private void Update() { if (workerEnabled) { if ((UnityEngine.Time.realtimeSinceStartup - lastPlayerStatusCheck) > PLAYER_STATUS_CHECK_INTERVAL) { lastPlayerStatusCheck = UnityEngine.Time.realtimeSinceStartup; myPlayerStatus.vesselText = ""; myPlayerStatus.statusText = ""; if (HighLogic.LoadedSceneIsFlight) { //Send vessel+status update if (FlightGlobals.ActiveVessel != null) { if (!VesselWorker.fetch.isSpectating) { myPlayerStatus.vesselText = FlightGlobals.ActiveVessel.vesselName; string bodyName = FlightGlobals.ActiveVessel.mainBody.bodyName; switch (FlightGlobals.ActiveVessel.situation) { case (Vessel.Situations.DOCKED): myPlayerStatus.statusText = "Docked above " + bodyName; break; case (Vessel.Situations.ESCAPING): if (FlightGlobals.ActiveVessel.orbit.timeToPe < 0) { myPlayerStatus.statusText = "Escaping " + bodyName; } else { myPlayerStatus.statusText = "Encountering " + bodyName; } break; case (Vessel.Situations.FLYING): if (!VesselWorker.fetch.isInSafetyBubble(FlightGlobals.fetch.activeVessel.GetWorldPos3D(), FlightGlobals.fetch.activeVessel.mainBody)) { myPlayerStatus.statusText = "Flying above " + bodyName; } else { myPlayerStatus.statusText = "Flying in safety bubble"; } break; case (Vessel.Situations.LANDED): if (!VesselWorker.fetch.isInSafetyBubble(FlightGlobals.fetch.activeVessel.GetWorldPos3D(), FlightGlobals.fetch.activeVessel.mainBody)) { myPlayerStatus.statusText = "Landed on " + bodyName; } else { myPlayerStatus.statusText = "Landed in safety bubble"; } break; case (Vessel.Situations.ORBITING): myPlayerStatus.statusText = "Orbiting " + bodyName; break; case (Vessel.Situations.PRELAUNCH): if (!VesselWorker.fetch.isInSafetyBubble(FlightGlobals.fetch.activeVessel.GetWorldPos3D(), FlightGlobals.fetch.activeVessel.mainBody)) { myPlayerStatus.statusText = "Launching from " + bodyName; } else { myPlayerStatus.statusText = "Launching from safety bubble"; } break; case (Vessel.Situations.SPLASHED): myPlayerStatus.statusText = "Splashed on " + bodyName; break; case (Vessel.Situations.SUB_ORBITAL): if (FlightGlobals.ActiveVessel.verticalSpeed > 0) { myPlayerStatus.statusText = "Ascending from " + bodyName; } else { myPlayerStatus.statusText = "Descending to " + bodyName; } break; } } else { if (LockSystem.fetch.LockExists("control-" + FlightGlobals.ActiveVessel.id.ToString())) { if (LockSystem.fetch.LockIsOurs("control-" + FlightGlobals.ActiveVessel.id.ToString())) { myPlayerStatus.statusText = "Waiting for vessel control"; } else { myPlayerStatus.statusText = "Spectating " + LockSystem.fetch.LockOwner("control-" + FlightGlobals.ActiveVessel.id.ToString()); } } else { myPlayerStatus.statusText = "Spectating future updates"; } } } else { myPlayerStatus.statusText = "Loading"; } } else { //Send status update switch (HighLogic.LoadedScene) { case (GameScenes.EDITOR): myPlayerStatus.statusText = "Building"; if (EditorDriver.editorFacility == EditorFacility.VAB) { myPlayerStatus.statusText = "Building in VAB"; } if (EditorDriver.editorFacility == EditorFacility.SPH) { myPlayerStatus.statusText = "Building in SPH"; } break; case (GameScenes.SPACECENTER): myPlayerStatus.statusText = "At Space Center"; break; case (GameScenes.TRACKSTATION): myPlayerStatus.statusText = "At Tracking Station"; break; case (GameScenes.LOADING): myPlayerStatus.statusText = "Loading"; break; } } } bool statusDifferent = false; statusDifferent = statusDifferent || (myPlayerStatus.vesselText != lastPlayerStatus.vesselText); statusDifferent = statusDifferent || (myPlayerStatus.statusText != lastPlayerStatus.statusText); if (statusDifferent && ((UnityEngine.Time.realtimeSinceStartup - lastPlayerStatusSend) > PLAYER_STATUS_SEND_THROTTLE)) { lastPlayerStatusSend = UnityEngine.Time.realtimeSinceStartup; lastPlayerStatus.vesselText = myPlayerStatus.vesselText; lastPlayerStatus.statusText = myPlayerStatus.statusText; NetworkWorker.fetch.SendPlayerStatus(myPlayerStatus); } while (addStatusQueue.Count > 0) { PlayerStatus newStatusEntry = addStatusQueue.Dequeue(); bool found = false; foreach (PlayerStatus playerStatusEntry in playerStatusList) { if (playerStatusEntry.playerName == newStatusEntry.playerName) { found = true; playerStatusEntry.vesselText = newStatusEntry.vesselText; playerStatusEntry.statusText = newStatusEntry.statusText; } } if (!found) { playerStatusList.Add(newStatusEntry); DarkLog.Debug("Added " + newStatusEntry.playerName + " to status list"); } } while (removeStatusQueue.Count > 0) { string removeStatusString = removeStatusQueue.Dequeue(); PlayerStatus removeStatus = null; foreach (PlayerStatus currentStatus in playerStatusList) { if (currentStatus.playerName == removeStatusString) { removeStatus = currentStatus; } } if (removeStatus != null) { playerStatusList.Remove(removeStatus); DarkLog.Debug("Removed " + removeStatusString + " from status list"); } else { DarkLog.Debug("Cannot remove non-existant player " + removeStatusString); } } } } public void AddPlayerStatus(PlayerStatus playerStatus) { addStatusQueue.Enqueue(playerStatus); } public void RemovePlayerStatus(string playerName) { removeStatusQueue.Enqueue(playerName); } public PlayerStatus GetPlayerStatus(string playerName) { PlayerStatus returnStatus = null; foreach (PlayerStatus ps in playerStatusList) { if (ps.playerName == playerName) { returnStatus = ps; break; } } return returnStatus; } public static void Reset() { lock (Client.eventLock) { if (singleton != null) { singleton.workerEnabled = false; Client.updateEvent.Remove(singleton.Update); } singleton = new PlayerStatusWorker(); Client.updateEvent.Add(singleton.Update); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.ResourceManager { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; /// <summary> /// ResourcesOperations operations. /// </summary> public partial interface IResourcesOperations { /// <summary> /// Move resources from one resource group to another. The resources /// being moved should all be in the same resource group. /// </summary> /// <param name='sourceResourceGroupName'> /// Source resource group name. /// </param> /// <param name='parameters'> /// move resources' parameters. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> MoveResourcesWithHttpMessagesAsync(string sourceResourceGroupName, ResourcesMoveInfo parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Move resources from one resource group to another. The resources /// being moved should all be in the same resource group. /// </summary> /// <param name='sourceResourceGroupName'> /// Source resource group name. /// </param> /// <param name='parameters'> /// move resources' parameters. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> BeginMoveResourcesWithHttpMessagesAsync(string sourceResourceGroupName, ResourcesMoveInfo parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get all of the resources under a subscription. /// </summary> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<GenericResource>>> ListWithHttpMessagesAsync(ODataQuery<GenericResourceFilter> odataQuery = default(ODataQuery<GenericResourceFilter>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Checks whether resource exists. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='resourceProviderNamespace'> /// Resource identity. /// </param> /// <param name='parentResourcePath'> /// Resource identity. /// </param> /// <param name='resourceType'> /// Resource identity. /// </param> /// <param name='resourceName'> /// Resource identity. /// </param> /// <param name='apiVersion'> /// Api version to use. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<bool>> CheckExistenceWithHttpMessagesAsync(string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string apiVersion, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a resource. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='resourceProviderNamespace'> /// Resource identity. /// </param> /// <param name='parentResourcePath'> /// Resource identity. /// </param> /// <param name='resourceType'> /// Resource identity. /// </param> /// <param name='resourceName'> /// Resource identity. /// </param> /// <param name='apiVersion'> /// Api version to use. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string apiVersion, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Create a resource. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='resourceProviderNamespace'> /// Resource identity. /// </param> /// <param name='parentResourcePath'> /// Resource identity. /// </param> /// <param name='resourceType'> /// Resource identity. /// </param> /// <param name='resourceName'> /// Resource identity. /// </param> /// <param name='apiVersion'> /// Api version to use. /// </param> /// <param name='parameters'> /// Create or update resource parameters. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<GenericResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string apiVersion, GenericResource parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns a resource belonging to a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='resourceProviderNamespace'> /// Resource identity. /// </param> /// <param name='parentResourcePath'> /// Resource identity. /// </param> /// <param name='resourceType'> /// Resource identity. /// </param> /// <param name='resourceName'> /// Resource identity. /// </param> /// <param name='apiVersion'> /// Api version to use. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<GenericResource>> GetWithHttpMessagesAsync(string resourceGroupName, string resourceProviderNamespace, string parentResourcePath, string resourceType, string resourceName, string apiVersion, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Checks whether resource exists. /// </summary> /// <param name='resourceId'> /// The fully qualified Id of the resource, including the resource /// name and resource type. For example, /// /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite /// </param> /// <param name='apiVersion'> /// Api version to use. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<bool>> CheckExistenceByIdWithHttpMessagesAsync(string resourceId, string apiVersion, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a resource. /// </summary> /// <param name='resourceId'> /// The fully qualified Id of the resource, including the resource /// name and resource type. For example, /// /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite /// </param> /// <param name='apiVersion'> /// Api version to use. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse> DeleteByIdWithHttpMessagesAsync(string resourceId, string apiVersion, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Create a resource. /// </summary> /// <param name='resourceId'> /// The fully qualified Id of the resource, including the resource /// name and resource type. For example, /// /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite /// </param> /// <param name='apiVersion'> /// Api version to use. /// </param> /// <param name='parameters'> /// Create or update resource parameters. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<GenericResource>> CreateOrUpdateByIdWithHttpMessagesAsync(string resourceId, string apiVersion, GenericResource parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets a resource. /// </summary> /// <param name='resourceId'> /// The fully qualified Id of the resource, including the resource /// name and resource type. For example, /// /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/myGroup/Microsoft.Web/sites/mySite /// </param> /// <param name='apiVersion'> /// Api version to use. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<GenericResource>> GetByIdWithHttpMessagesAsync(string resourceId, string apiVersion, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get all of the resources under a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<GenericResource>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Threading; using System.Collections.Generic; using System.Collections.ObjectModel; using Microsoft.Protocols.TestTools.StackSdk.Security.Sspi; namespace Microsoft.Protocols.TestTools.StackSdk.Networking.Rpce { /// <summary> /// RpceClientTransport provides transport layer support /// for RPC bind and methods calls.<para/> /// This RPC transport class does support: /// RPC over TCP/IP, RPC over Named Pipes, NDR, PDU fragment, security provider, /// authentication level, verification trailer and call timeout.<para/> /// It does not support: /// RPC over other transport layers, partially-bound binding handle, /// data representation other than IEEE little endian ASCII, /// NDR64, security context multiplexing, concurrent multiplexing, /// callback, and keeping connection open on orphaned. /// </summary> public class RpceClientTransport : IDisposable { // RPCE client private RpceClient rpceClient; // The lock for response private object responseLock = new object(); // RPCE thread to receive the response from server private Thread receiveThread; // List of outstanding call id private Collection<uint> outstandingCallIds; /// <summary> /// Initialize an instance of RpceClientTransport. /// </summary> public RpceClientTransport() { rpceClient = new RpceClient(); outstandingCallIds = new Collection<uint>(); receiveThread = null; } /// <summary> /// Gets RPC client handle. /// </summary> public virtual IntPtr Handle { get { return rpceClient.Handle; } } /// <summary> /// Gets RPC transport context. /// </summary> public virtual RpceClientContext Context { get { return rpceClient.Context; } } /// <summary> /// Let SMB transport execute a transaction over the named pipe for synchronous RPCs /// </summary> public void UseTransactionForNamedPipe(bool useTransactionForNamedPipe) { rpceClient.Context.UseTransactionForNamedPipe = useTransactionForNamedPipe; } /// <summary> /// Connect and bind to a RPCE remote host. /// </summary> /// <param name="protocolSequence"> /// A protocol sequence.<para/> /// Support ncacn_ip_tcp and ncacn_np only. /// </param> /// <param name="networkAddress"> /// A network address of RPCE remote host. /// </param> /// <param name="endpoint"> /// An endpoint that its format and content /// are associated with the protocol sequence. /// </param> /// <param name="transportCredential"> /// If connect by SMB/SMB2, it's the security credential /// used by underlayer transport (SMB/SMB2). /// If connect by TCP, this parameter is ignored. /// </param> /// <param name="interfaceId"> /// A Guid of interface_id that is binding to. /// </param> /// <param name="interfaceMajorVersion"> /// interface_major_ver that is binding to. /// </param> /// <param name="interfaceMinorVersion"> /// interface_minor_ver that is binding to. /// </param> /// <param name="securityContext"> /// A security provider. If setting to null, indicate the default authentication type NTLM is selected. /// </param> /// <param name="connectSecurityContext"> /// A security provider for connect authentication. If setting to null, indicate the default authentication type NTLM is selected. /// </param> /// <param name="authenticationLevel"> /// An authentication level. /// </param> /// <param name="supportsHeaderSign"> /// Indicates whether client supports header sign or not. /// </param> /// <param name="timeout"> /// Timeout period. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when protSeq, networkAddr or endpoint is null. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown when receive error from server. /// </exception> public virtual void Bind( string protocolSequence, string networkAddress, string endpoint, AccountCredential transportCredential, Guid interfaceId, ushort interfaceMajorVersion, ushort interfaceMinorVersion, ClientSecurityContext securityContext, ClientSecurityContext connectSecurityContext, RpceAuthenticationLevel authenticationLevel, bool supportsHeaderSign, TimeSpan timeout) { if (protocolSequence == null) { throw new ArgumentNullException("protocolSequence"); } if (networkAddress == null) { throw new ArgumentNullException("networkAddress"); } if (endpoint == null) { throw new ArgumentNullException("endpoint"); } // RPC over named-pipe does not support asynchronous call in this library. // http://msdn.microsoft.com/en-us/library/windows/desktop/aa373551(v=vs.85).aspx rpceClient.Context.IsAsynchronous = (string.Compare(protocolSequence, RpceUtility.RPC_OVER_NAMED_PIPE_PROTOCOL_SEQUENCE, true) != 0); rpceClient.Connect(protocolSequence, networkAddress, endpoint, transportCredential, timeout, connectSecurityContext == null ? SecurityPackageType.Ntlm : connectSecurityContext.PackageType); rpceClient.SetAuthInfo(securityContext, authenticationLevel, rpceClient.Context.AuthenticationContextId); RpceCoBindPdu bindPdu = rpceClient.CreateCoBindPdu( //read from context, donot hardcode. rpceClient.Context.RpcVersionMinor, // default is rpc vers 5.0 supportsHeaderSign ? RpceCoPfcFlags.PFC_SUPPORT_HEADER_SIGN : RpceCoPfcFlags.None, rpceClient.ComputeNextCallId(), // call id, default is 1 rpceClient.Context.MaxTransmitFragmentSize, // max xmit frag rpceClient.Context.MaxReceiveFragmentSize, // max recv frag rpceClient.Context.AssociateGroupId, // assoc group id, default 0 interfaceId, interfaceMajorVersion, interfaceMinorVersion, rpceClient.Context.NdrVersion, // default is NDR (rpceClient.Context.BindTimeFeatureNegotiationBitmask != RpceBindTimeFeatureNegotiationBitmask.None) // default is None ? (RpceBindTimeFeatureNegotiationBitmask?)rpceClient.Context.BindTimeFeatureNegotiationBitmask : null); FragmentAndSendPdu(bindPdu); RpcePdu receivedPdu = ReceiveAndReassemblePdu(timeout); if (receivedPdu is RpceCoBindAckPdu) { if (rpceClient.Context.NdrVersion == RpceNdrVersion.None) { throw new InvalidOperationException("Neither NDR nor NDR64 is supported."); } } else { RpceCoBindNakPdu bindNakPdu = receivedPdu as RpceCoBindNakPdu; if (bindNakPdu != null) { throw new InvalidOperationException(bindNakPdu.provider_reject_reason.ToString()); } else { throw new InvalidOperationException( string.Format("Unexpected packet type received - {0}.", receivedPdu.GetType().Name)); } } while (rpceClient.Context.SecurityContext != null && rpceClient.Context.SecurityContext.NeedContinueProcessing) { RpceCoAlterContextPdu alterContextPdu = rpceClient.CreateCoAlterContextPdu(); FragmentAndSendPdu(alterContextPdu); receivedPdu = ReceiveAndReassemblePdu(timeout); RpceCoFaultPdu faultPdu = receivedPdu as RpceCoFaultPdu; if (faultPdu != null) { throw new InvalidOperationException(faultPdu.status.ToString()); } if (!(receivedPdu is RpceCoAlterContextRespPdu)) { throw new InvalidOperationException("Expect alter_context_pdu, but received others."); } } if (rpceClient.Context.SecurityContext != null && rpceClient.Context.SecurityContext.Token != null && rpceClient.Context.SecurityContext.Token.Length != 0) { RpceCoAuth3Pdu auth3Pdu = rpceClient.CreateCoAuth3Pdu(); FragmentAndSendPdu(auth3Pdu); // no expected response from server rpceClient.Context.OutstandingCalls.Remove(auth3Pdu.call_id); } if (rpceClient.Context.IsAsynchronous) { // Start the receiving thread to receive the response from server. receiveThread = new Thread(new ThreadStart(EventLoop)); receiveThread.IsBackground = true; receiveThread.Start(); } } /// <summary> /// Connect and bind to a RPCE remote host. /// </summary> /// <param name="protocolSequence"> /// A protocol sequence.<para/> /// Support ncacn_ip_tcp and ncacn_np only. /// </param> /// <param name="networkAddress"> /// A network address of RPCE remote host. /// </param> /// <param name="endpoint"> /// An endpoint that its format and content /// are associated with the protocol sequence. /// </param> /// <param name="transportCredential"> /// If connect by SMB/SMB2, it's the security credential /// used by underlayer transport (SMB/SMB2). /// If connect by TCP, this parameter is ignored. /// </param> /// <param name="interfaceId"> /// A Guid of interface_id that is binding to. /// </param> /// <param name="interfaceMajorVersion"> /// interface_major_ver that is binding to. /// </param> /// <param name="interfaceMinorVersion"> /// interface_minor_ver that is binding to. /// </param> /// <param name="securityContext"> /// A security provider. If setting to null, indicate the default authentication type NTLM is selected. /// </param> /// <param name="authenticationLevel"> /// An authentication level. /// </param> /// <param name="supportsHeaderSign"> /// Indicates whether client supports header sign or not. /// </param> /// <param name="timeout"> /// Timeout period. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when protSeq, networkAddr or endpoint is null. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown when receive error from server. /// </exception> public virtual void Bind( string protocolSequence, string networkAddress, string endpoint, AccountCredential transportCredential, Guid interfaceId, ushort interfaceMajorVersion, ushort interfaceMinorVersion, ClientSecurityContext securityContext, RpceAuthenticationLevel authenticationLevel, bool supportsHeaderSign, TimeSpan timeout) { Bind(protocolSequence, networkAddress, endpoint, transportCredential, interfaceId, interfaceMajorVersion, interfaceMinorVersion, securityContext, securityContext, authenticationLevel, supportsHeaderSign, timeout); } /// <summary> /// Synchronously call a RPCE method. /// </summary> /// <param name="opnum"> /// The opnum of a method. /// </param> /// <param name="requestStub"> /// A byte array of the request stub of a method.<para/> /// RpceStubEncoder can be used to NDR marshal parameters to a byte array. /// </param> /// <param name="timeout"> /// Timeout period. /// </param> /// <param name="responseStub"> /// A byte array of the response stub of a method.<para/> /// RpceStubDecoder can be used to NDR un-marshal parameters to a byte array. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when requestStub is null. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown when receive error from server or RPC connection has not been established. /// </exception> public virtual void Call( ushort opnum, byte[] requestStub, TimeSpan timeout, out byte[] responseStub) { uint callId; SendRequest(opnum, requestStub, out callId); RecvResponse(callId, timeout, out responseStub); } /// <summary> /// Send request to RPCE server. /// </summary> /// <param name="opnum"> /// The opnum of a method. /// </param> /// <param name="requestStub"> /// A byte array of the request stub of a method.<para/> /// RpceStubEncoder can be used to NDR marshal parameters to a byte array. /// </param> /// <param name="callId"> /// The identifier of this call. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when requestStub is null. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown when receive error from server or RPC connection has not been established. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown when this transport has been used as an synchronous transport. /// </exception> public virtual void SendRequest( ushort opnum, byte[] requestStub, out uint callId) { if (requestStub == null) { throw new ArgumentNullException("requestStub"); } if (rpceClient.IsDisposed) { throw new InvalidOperationException("RPC connection has not been established."); } RpceCoRequestPdu requestPdu = rpceClient.CreateCoRequestPdu( opnum, requestStub); if (rpceClient.Context.AuthenticationType == RpceAuthenticationType.RPC_C_AUTHN_WINNT && rpceClient.Context.AuthenticationLevel == RpceAuthenticationLevel.RPC_C_AUTHN_LEVEL_PKT_INTEGRITY) { verification_trailer_t verificationTrailer = requestPdu.CreateVerificationTrailer( SEC_VT_COMMAND.SEC_VT_COMMAND_BITMASK_1, SEC_VT_COMMAND.SEC_VT_COMMAND_HEADER2, SEC_VT_COMMAND.SEC_VT_COMMAND_PCONTEXT | SEC_VT_COMMAND.SEC_VT_COMMAND_END); requestPdu.AppendVerificationTrailerToStub(verificationTrailer); } FragmentAndSendPdu(requestPdu); lock (responseLock) { callId = requestPdu.call_id; outstandingCallIds.Add(callId); } } /// <summary> /// Receive response from RPCE server. /// </summary> /// <param name="callId"> /// The identifier of this call. /// </param> /// <param name="timeout"> /// Timeout period. /// </param> /// <param name="responseStub"> /// A byte array of the response stub of a method. /// RpceStubDecoder can be used to NDR un-marshal parameters to a byte array. /// </param> /// <exception cref="ArgumentException"> /// Thrown when callId is invalid. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown when receive error from server or RPC connection has not been established. /// </exception> /// <exception cref="RpceDisconnectedException"> /// Thrown when the connection is disconnected. /// </exception> /// <exception cref="TimeoutException"> /// Thrown when timeout to expect the response of the async call. /// </exception> public virtual void RecvResponse( uint callId, TimeSpan timeout, out byte[] responseStub) { if (rpceClient.IsDisposed) { throw new InvalidOperationException("RPC connection has not been established."); } lock (responseLock) { if (!outstandingCallIds.Contains(callId)) { throw new ArgumentException("Invalid call id."); } } if (rpceClient.Context.IsAsynchronous) { TimeSpan leftTime = timeout; DateTime expiratedTime = DateTime.Now + timeout; while (leftTime.CompareTo(new TimeSpan(0)) > 0) { lock (responseLock) { // Handle the events added in receiving thread. while (rpceClient.Context.Events.Count > 0) { if (rpceClient.Context.Events[0] is RpcePdu) { RpcePdu rpcePdu = rpceClient.Context.Events[0] as RpcePdu; uint id = ParseRpcePdu(rpcePdu); rpceClient.Context.ReceivedPdus.Add(id, rpcePdu); rpceClient.Context.Events.RemoveAt(0); } else { throw rpceClient.Context.Events[0] as Exception; } } RpcePdu receivedPdu; if (rpceClient.Context.ReceivedPdus.TryGetValue(callId, out receivedPdu)) { rpceClient.Context.ReceivedPdus.Remove(callId); outstandingCallIds.Remove(callId); HandleRpcePdu(receivedPdu, out responseStub); return; } } System.Threading.Thread.Sleep(10); leftTime = expiratedTime - DateTime.Now; } throw new TimeoutException(string.Format("RecvResponse timeout to expect the response of the call. call_id: {0}", callId)); } else { RpcePdu receivedPdu = ReceiveAndReassemblePdu(timeout); ParseRpcePdu(receivedPdu); HandleRpcePdu(receivedPdu, out responseStub); } } /// <summary> /// RPCE unbind and disconnect. /// </summary> /// <param name="timeout"> /// Timeout period. /// </param> /// <exception cref="InvalidOperationException"> /// Thrown when RPC has not been bind. /// </exception> public virtual void Unbind(TimeSpan timeout) { if (rpceClient.IsDisposed) { throw new InvalidOperationException("RPC connection has not been established."); } rpceClient.Disconnect(timeout); if (receiveThread != null) { if (!receiveThread.Join(new TimeSpan(0, 0, 10))) { receiveThread.Abort(); } receiveThread = null; } } /// <summary> /// Fragment and send PDU. /// </summary> /// <param name="pdu">PDU</param> private void FragmentAndSendPdu(RpceCoPdu pdu) { if (pdu.PTYPE == RpcePacketType.Bind || pdu.PTYPE == RpcePacketType.BindAck || pdu.PTYPE == RpcePacketType.AlterContext || pdu.PTYPE == RpcePacketType.AlterContextResp || pdu.PTYPE == RpcePacketType.Auth3) { pdu.InitializeAuthenticationToken(); pdu.SetLength(); foreach (RpceCoPdu fragPdu in RpceUtility.FragmentPdu(rpceClient.Context, pdu)) { rpceClient.SendPdu(fragPdu); } } else { foreach (RpceCoPdu fragPdu in RpceUtility.FragmentPdu(rpceClient.Context, pdu)) { fragPdu.InitializeAuthenticationToken(); rpceClient.SendPdu(fragPdu); } } } /// <summary> /// Receive and reassemble PDU. /// </summary> /// <param name="timeout">timeout</param> /// <returns>PDU</returns> private RpcePdu ReceiveAndReassemblePdu(TimeSpan timeout) { RpcePdu receivedPdu = rpceClient.ExpectPdu(timeout); RpceCoPdu receivedCoPdu = receivedPdu as RpceCoPdu; if (receivedCoPdu == null) { return receivedPdu; } List<RpceCoPdu> pduList = new List<RpceCoPdu>(); pduList.Add(receivedCoPdu); while ((receivedCoPdu.pfc_flags & RpceCoPfcFlags.PFC_LAST_FRAG) == 0) { receivedPdu = rpceClient.ExpectPdu(timeout); receivedCoPdu = receivedPdu as RpceCoPdu; if (receivedCoPdu == null) { throw new InvalidOperationException("CL PDU received inside a connection."); } pduList.Add(receivedCoPdu); } return RpceUtility.ReassemblePdu(rpceClient.Context, pduList.ToArray()); } /// <summary> /// Loop for asychronous receive response. /// </summary> private void EventLoop() { while (!rpceClient.IsDisposed) { try { RpcePdu receivedPdu; receivedPdu = ReceiveAndReassemblePdu(new TimeSpan(1, 0, 0)); if (receivedPdu is RpceCoShutdownPdu) { throw new RpceDisconnectedException("The connection is disconnected by server."); } lock (responseLock) { rpceClient.Context.Events.Add(receivedPdu); } } catch (TimeoutException) { continue; } catch (RpceDisconnectedException e) { if (!rpceClient.IsDisposed && rpceClient.Context != null && rpceClient.Context.Events != null) { rpceClient.Context.Events.Add(e); } return; } catch (Exception e) { if (!rpceClient.IsDisposed && rpceClient.Context != null && rpceClient.Context.Events != null) { rpceClient.Context.Events.Add(e); } continue; } } } /// <summary> /// Parse the identifier of the call from the received pdu from server. /// </summary> /// <param name="rpcePdu"> /// Received pdu received from server. /// </param> /// <exception cref="RpceDisconnectedException"> /// Thrown when receive shutdown PDU. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown when receive error from server. /// </exception> /// <returns>Return the identifier of the call if success, otherwise throw an exception.</returns> private uint ParseRpcePdu(RpcePdu rpcePdu) { if (rpcePdu is RpceCoResponsePdu) { return (rpcePdu as RpceCoResponsePdu).call_id; } else if (rpcePdu is RpceCoFaultPdu) { return (rpcePdu as RpceCoFaultPdu).call_id; } if (rpcePdu is RpceCoShutdownPdu) { throw new RpceDisconnectedException("Shutdown PDU received"); } throw new InvalidOperationException( string.Format("Unexpected packet type received - {0}.", rpcePdu.GetType().Name)); } /// <summary> /// Handle the received pdu from server. /// </summary> /// <param name="rpcePdu"> /// Received pdu received from server. /// </param> /// <param name="responseStub"> /// A byte array of the response stub of a method. /// RpceStubDecoder can be used to NDR un-marshal parameters to a byte array. /// </param> /// <exception cref="InvalidOperationException"> /// Thrown when receive error from server or RPC connection has not been established. /// </exception> private void HandleRpcePdu(RpcePdu rpcePdu, out byte[] responseStub) { if (rpcePdu is RpceCoResponsePdu) { responseStub = (rpcePdu as RpceCoResponsePdu).stub; } else if (rpcePdu is RpceCoFaultPdu) { throw new InvalidOperationException((rpcePdu as RpceCoFaultPdu).status.ToString()); } else { throw new InvalidOperationException(rpcePdu.GetType().ToString()); } } #region IDisposable Members /// <summary> /// Dispose method. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Dispose method. /// </summary> /// <param name="disposing"> /// True to release both managed and unmanaged resources.<para/> /// False to release unmanaged resources only. /// </param> protected virtual void Dispose(bool disposing) { if (disposing) { try { receiveThread.Abort(); } catch { } // Release managed resources. if (!rpceClient.IsDisposed) { rpceClient.Dispose(); } } // Release unmanaged resources. } /// <summary> /// finalizer /// </summary> ~RpceClientTransport() { Dispose(false); } #endregion } }
using System; using System.Windows.Forms; using System.Drawing; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; namespace WeifenLuo.WinFormsUI.Docking { public delegate string GetPersistStringCallback(); public class DockContentHandler : IDisposable, IDockDragSource { public DockContentHandler(Form form) : this(form, null) { } public DockContentHandler(Form form, GetPersistStringCallback getPersistStringCallback) { if (!(form is IDockContent)) throw new ArgumentException(Strings.DockContent_Constructor_InvalidForm, "form"); m_form = form; m_getPersistStringCallback = getPersistStringCallback; m_events = new EventHandlerList(); Form.Disposed +=new EventHandler(Form_Disposed); Form.TextChanged += new EventHandler(Form_TextChanged); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { DockPanel = null; if (m_autoHideTab != null) m_autoHideTab.Dispose(); if (m_tab != null) m_tab.Dispose(); Form.Disposed -= new EventHandler(Form_Disposed); Form.TextChanged -= new EventHandler(Form_TextChanged); m_events.Dispose(); } } private Form m_form; public Form Form { get { return m_form; } } public IDockContent Content { get { return Form as IDockContent; } } private IDockContent m_previousActive = null; public IDockContent PreviousActive { get { return m_previousActive; } internal set { m_previousActive = value; } } private IDockContent m_nextActive = null; public IDockContent NextActive { get { return m_nextActive; } internal set { m_nextActive = value; } } private EventHandlerList m_events; private EventHandlerList Events { get { return m_events; } } private bool m_allowEndUserDocking = true; public bool AllowEndUserDocking { get { return m_allowEndUserDocking; } set { m_allowEndUserDocking = value; } } private double m_autoHidePortion = 0.25; public double AutoHidePortion { get { return m_autoHidePortion; } set { if (value <= 0) throw(new ArgumentOutOfRangeException(Strings.DockContentHandler_AutoHidePortion_OutOfRange)); if (m_autoHidePortion == value) return; m_autoHidePortion = value; if (DockPanel == null) return; if (DockPanel.ActiveAutoHideContent == Content) DockPanel.PerformLayout(); } } private bool m_closeButton = true; public bool CloseButton { get { return m_closeButton; } set { if (m_closeButton == value) return; m_closeButton = value; if (IsActiveContentHandler) Pane.RefreshChanges(); } } private bool m_closeButtonVisible = true; /// <summary> /// Determines whether the close button is visible on the content /// </summary> public bool CloseButtonVisible { get { return m_closeButtonVisible; } set { if (m_closeButtonVisible == value) return; m_closeButtonVisible = value; if (IsActiveContentHandler) Pane.RefreshChanges(); } } private bool IsActiveContentHandler { get { return Pane != null && Pane.ActiveContent != null && Pane.ActiveContent.DockHandler == this; } } private DockState DefaultDockState { get { if (ShowHint != DockState.Unknown && ShowHint != DockState.Hidden) return ShowHint; if ((DockAreas & DockAreas.Document) != 0) return DockState.Document; if ((DockAreas & DockAreas.DockRight) != 0) return DockState.DockRight; if ((DockAreas & DockAreas.DockLeft) != 0) return DockState.DockLeft; if ((DockAreas & DockAreas.DockBottom) != 0) return DockState.DockBottom; if ((DockAreas & DockAreas.DockTop) != 0) return DockState.DockTop; return DockState.Unknown; } } private DockState DefaultShowState { get { if (ShowHint != DockState.Unknown) return ShowHint; if ((DockAreas & DockAreas.Document) != 0) return DockState.Document; if ((DockAreas & DockAreas.DockRight) != 0) return DockState.DockRight; if ((DockAreas & DockAreas.DockLeft) != 0) return DockState.DockLeft; if ((DockAreas & DockAreas.DockBottom) != 0) return DockState.DockBottom; if ((DockAreas & DockAreas.DockTop) != 0) return DockState.DockTop; if ((DockAreas & DockAreas.Float) != 0) return DockState.Float; return DockState.Unknown; } } private DockAreas m_allowedAreas = DockAreas.DockLeft | DockAreas.DockRight | DockAreas.DockTop | DockAreas.DockBottom | DockAreas.Document | DockAreas.Float; public DockAreas DockAreas { get { return m_allowedAreas; } set { if (m_allowedAreas == value) return; if (!DockHelper.IsDockStateValid(DockState, value)) throw(new InvalidOperationException(Strings.DockContentHandler_DockAreas_InvalidValue)); m_allowedAreas = value; if (!DockHelper.IsDockStateValid(ShowHint, m_allowedAreas)) ShowHint = DockState.Unknown; } } private DockState m_dockState = DockState.Unknown; public DockState DockState { get { return m_dockState; } set { if (m_dockState == value) return; DockPanel.SuspendLayout(true); if (value == DockState.Hidden) IsHidden = true; else SetDockState(false, value, Pane); DockPanel.ResumeLayout(true, true); } } private DockPanel m_dockPanel = null; public DockPanel DockPanel { get { return m_dockPanel; } set { if (m_dockPanel == value) return; Pane = null; if (m_dockPanel != null) m_dockPanel.RemoveContent(Content); if (m_tab != null) { m_tab.Dispose(); m_tab = null; } if (m_autoHideTab != null) { m_autoHideTab.Dispose(); m_autoHideTab = null; } m_dockPanel = value; if (m_dockPanel != null) { m_dockPanel.AddContent(Content); Form.TopLevel = false; Form.FormBorderStyle = FormBorderStyle.None; Form.ShowInTaskbar = false; Form.WindowState = FormWindowState.Normal; if (Win32Helper.IsRunningOnMono) return; NativeMethods.SetWindowPos(Form.Handle, IntPtr.Zero, 0, 0, 0, 0, Win32.FlagsSetWindowPos.SWP_NOACTIVATE | Win32.FlagsSetWindowPos.SWP_NOMOVE | Win32.FlagsSetWindowPos.SWP_NOSIZE | Win32.FlagsSetWindowPos.SWP_NOZORDER | Win32.FlagsSetWindowPos.SWP_NOOWNERZORDER | Win32.FlagsSetWindowPos.SWP_FRAMECHANGED); } } } public Icon Icon { get { return Form.Icon; } } public DockPane Pane { get { return IsFloat ? FloatPane : PanelPane; } set { if (Pane == value) return; DockPanel.SuspendLayout(true); DockPane oldPane = Pane; SuspendSetDockState(); FloatPane = (value == null ? null : (value.IsFloat ? value : FloatPane)); PanelPane = (value == null ? null : (value.IsFloat ? PanelPane : value)); ResumeSetDockState(IsHidden, value != null ? value.DockState : DockState.Unknown, oldPane); DockPanel.ResumeLayout(true, true); } } private bool m_isHidden = true; public bool IsHidden { get { return m_isHidden; } set { if (m_isHidden == value) return; SetDockState(value, VisibleState, Pane); } } private string m_tabText = null; public string TabText { get { return m_tabText == null || m_tabText == "" ? Form.Text : m_tabText; } set { if (m_tabText == value) return; m_tabText = value; if (Pane != null) Pane.RefreshChanges(); } } private DockState m_visibleState = DockState.Unknown; public DockState VisibleState { get { return m_visibleState; } set { if (m_visibleState == value) return; SetDockState(IsHidden, value, Pane); } } private bool m_isFloat = false; public bool IsFloat { get { return m_isFloat; } set { if (m_isFloat == value) return; DockState visibleState = CheckDockState(value); if (visibleState == DockState.Unknown) throw new InvalidOperationException(Strings.DockContentHandler_IsFloat_InvalidValue); SetDockState(IsHidden, visibleState, Pane); } } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] public DockState CheckDockState(bool isFloat) { DockState dockState; if (isFloat) { if (!IsDockStateValid(DockState.Float)) dockState = DockState.Unknown; else dockState = DockState.Float; } else { dockState = (PanelPane != null) ? PanelPane.DockState : DefaultDockState; if (dockState != DockState.Unknown && !IsDockStateValid(dockState)) dockState = DockState.Unknown; } return dockState; } private DockPane m_panelPane = null; public DockPane PanelPane { get { return m_panelPane; } set { if (m_panelPane == value) return; if (value != null) { if (value.IsFloat || value.DockPanel != DockPanel) throw new InvalidOperationException(Strings.DockContentHandler_DockPane_InvalidValue); } DockPane oldPane = Pane; if (m_panelPane != null) RemoveFromPane(m_panelPane); m_panelPane = value; if (m_panelPane != null) { m_panelPane.AddContent(Content); SetDockState(IsHidden, IsFloat ? DockState.Float : m_panelPane.DockState, oldPane); } else SetDockState(IsHidden, DockState.Unknown, oldPane); } } private void RemoveFromPane(DockPane pane) { pane.RemoveContent(Content); SetPane(null); if (pane.Contents.Count == 0) pane.Dispose(); } private DockPane m_floatPane = null; public DockPane FloatPane { get { return m_floatPane; } set { if (m_floatPane == value) return; if (value != null) { if (!value.IsFloat || value.DockPanel != DockPanel) throw new InvalidOperationException(Strings.DockContentHandler_FloatPane_InvalidValue); } DockPane oldPane = Pane; if (m_floatPane != null) RemoveFromPane(m_floatPane); m_floatPane = value; if (m_floatPane != null) { m_floatPane.AddContent(Content); SetDockState(IsHidden, IsFloat ? DockState.Float : VisibleState, oldPane); } else SetDockState(IsHidden, DockState.Unknown, oldPane); } } private int m_countSetDockState = 0; private void SuspendSetDockState() { m_countSetDockState ++; } private void ResumeSetDockState() { m_countSetDockState --; if (m_countSetDockState < 0) m_countSetDockState = 0; } internal bool IsSuspendSetDockState { get { return m_countSetDockState != 0; } } private void ResumeSetDockState(bool isHidden, DockState visibleState, DockPane oldPane) { ResumeSetDockState(); SetDockState(isHidden, visibleState, oldPane); } internal void SetDockState(bool isHidden, DockState visibleState, DockPane oldPane) { if (IsSuspendSetDockState) return; if (DockPanel == null && visibleState != DockState.Unknown) throw new InvalidOperationException(Strings.DockContentHandler_SetDockState_NullPanel); if (visibleState == DockState.Hidden || (visibleState != DockState.Unknown && !IsDockStateValid(visibleState))) throw new InvalidOperationException(Strings.DockContentHandler_SetDockState_InvalidState); DockPanel dockPanel = DockPanel; if (dockPanel != null) dockPanel.SuspendLayout(true); SuspendSetDockState(); DockState oldDockState = DockState; if (m_isHidden != isHidden || oldDockState == DockState.Unknown) { m_isHidden = isHidden; } m_visibleState = visibleState; m_dockState = isHidden ? DockState.Hidden : visibleState; if (visibleState == DockState.Unknown) Pane = null; else { m_isFloat = (m_visibleState == DockState.Float); if (Pane == null) Pane = DockPanel.DockPaneFactory.CreateDockPane(Content, visibleState, true); else if (Pane.DockState != visibleState) { if (Pane.Contents.Count == 1) Pane.SetDockState(visibleState); else Pane = DockPanel.DockPaneFactory.CreateDockPane(Content, visibleState, true); } } if (Form.ContainsFocus) { if (DockState == DockState.Hidden || DockState == DockState.Unknown) { if (!Win32Helper.IsRunningOnMono) { DockPanel.ContentFocusManager.GiveUpFocus(Content); } } } SetPaneAndVisible(Pane); if (oldPane != null && !oldPane.IsDisposed && oldDockState == oldPane.DockState) RefreshDockPane(oldPane); if (Pane != null && DockState == Pane.DockState) { if ((Pane != oldPane) || (Pane == oldPane && oldDockState != oldPane.DockState)) { // Avoid early refresh of hidden AutoHide panes if ((Pane.DockWindow == null || Pane.DockWindow.Visible || Pane.IsHidden) && !Pane.IsAutoHide) { RefreshDockPane(Pane); } } } if (oldDockState != DockState) { if (DockState == DockState.Hidden || DockState == DockState.Unknown || DockHelper.IsDockStateAutoHide(DockState)) { if (!Win32Helper.IsRunningOnMono) { DockPanel.ContentFocusManager.RemoveFromList(Content); } } else if (!Win32Helper.IsRunningOnMono) { DockPanel.ContentFocusManager.AddToList(Content); } ResetAutoHidePortion(oldDockState, DockState); OnDockStateChanged(EventArgs.Empty); } ResumeSetDockState(); if (dockPanel != null) dockPanel.ResumeLayout(true, true); } private void ResetAutoHidePortion(DockState oldState, DockState newState) { if (oldState == newState || DockHelper.ToggleAutoHideState(oldState) == newState) return; switch (newState) { case DockState.DockTop: case DockState.DockTopAutoHide: AutoHidePortion = DockPanel.DockTopPortion; break; case DockState.DockLeft: case DockState.DockLeftAutoHide: AutoHidePortion = DockPanel.DockLeftPortion; break; case DockState.DockBottom: case DockState.DockBottomAutoHide: AutoHidePortion = DockPanel.DockBottomPortion; break; case DockState.DockRight: case DockState.DockRightAutoHide: AutoHidePortion = DockPanel.DockRightPortion; break; } } private static void RefreshDockPane(DockPane pane) { pane.RefreshChanges(); pane.ValidateActiveContent(); } internal string PersistString { get { return GetPersistStringCallback == null ? Form.GetType().ToString() : GetPersistStringCallback(); } } private GetPersistStringCallback m_getPersistStringCallback = null; public GetPersistStringCallback GetPersistStringCallback { get { return m_getPersistStringCallback; } set { m_getPersistStringCallback = value; } } private bool m_hideOnClose = false; public bool HideOnClose { get { return m_hideOnClose; } set { m_hideOnClose = value; } } private DockState m_showHint = DockState.Unknown; public DockState ShowHint { get { return m_showHint; } set { if (!DockHelper.IsDockStateValid(value, DockAreas)) throw (new InvalidOperationException(Strings.DockContentHandler_ShowHint_InvalidValue)); if (m_showHint == value) return; m_showHint = value; } } private bool m_isActivated = false; public bool IsActivated { get { return m_isActivated; } internal set { if (m_isActivated == value) return; m_isActivated = value; } } public bool IsDockStateValid(DockState dockState) { if (DockPanel != null && dockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.SystemMdi) return false; else return DockHelper.IsDockStateValid(dockState, DockAreas); } private ContextMenu m_tabPageContextMenu = null; public ContextMenu TabPageContextMenu { get { return m_tabPageContextMenu; } set { m_tabPageContextMenu = value; } } private string m_toolTipText = null; public string ToolTipText { get { return m_toolTipText; } set { m_toolTipText = value; } } public void Activate() { if (DockPanel == null) Form.Activate(); else if (Pane == null) Show(DockPanel); else { IsHidden = false; Pane.ActiveContent = Content; if (DockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.SystemMdi) { Form.Activate(); return; } else if (DockHelper.IsDockStateAutoHide(DockState)) { if (DockPanel.ActiveAutoHideContent != Content) { DockPanel.ActiveAutoHideContent = null; return; } } if (Form.ContainsFocus) return; if (Win32Helper.IsRunningOnMono) return; DockPanel.ContentFocusManager.Activate(Content); } } public void GiveUpFocus() { if (!Win32Helper.IsRunningOnMono) DockPanel.ContentFocusManager.GiveUpFocus(Content); } private IntPtr m_activeWindowHandle = IntPtr.Zero; internal IntPtr ActiveWindowHandle { get { return m_activeWindowHandle; } set { m_activeWindowHandle = value; } } public void Hide() { IsHidden = true; } internal void SetPaneAndVisible(DockPane pane) { SetPane(pane); SetVisible(); } private void SetPane(DockPane pane) { if (pane != null && pane.DockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.DockingMdi) { if (Form.Parent is DockPane) SetParent(null); if (Form.MdiParent != DockPanel.ParentForm) { FlagClipWindow = true; Form.MdiParent = DockPanel.ParentForm; } } else { FlagClipWindow = true; if (Form.MdiParent != null) Form.MdiParent = null; if (Form.TopLevel) Form.TopLevel = false; SetParent(pane); } } internal void SetVisible() { bool visible; if (IsHidden) visible = false; else if (Pane != null && Pane.DockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.DockingMdi) visible = true; else if (Pane != null && Pane.ActiveContent == Content) visible = true; else if (Pane != null && Pane.ActiveContent != Content) visible = false; else visible = Form.Visible; if (Form.Visible != visible) Form.Visible = visible; } private void SetParent(Control value) { if (Form.Parent == value) return; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Workaround of .Net Framework bug: // Change the parent of a control with focus may result in the first // MDI child form get activated. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! bool bRestoreFocus = false; if (Form.ContainsFocus) { // Suggested as a fix for a memory leak by bugreports if (value == null && !IsFloat) { if (!Win32Helper.IsRunningOnMono) { DockPanel.ContentFocusManager.GiveUpFocus(this.Content); } } else { DockPanel.SaveFocus(); bRestoreFocus = true; } } // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Form.Parent = value; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Workaround of .Net Framework bug: // Change the parent of a control with focus may result in the first // MDI child form get activated. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if (bRestoreFocus) Activate(); // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! } public void Show() { if (DockPanel == null) Form.Show(); else Show(DockPanel); } public void Show(DockPanel dockPanel) { if (dockPanel == null) throw(new ArgumentNullException(Strings.DockContentHandler_Show_NullDockPanel)); if (DockState == DockState.Unknown) Show(dockPanel, DefaultShowState); else if (DockPanel != dockPanel) Show(dockPanel, DockState == DockState.Hidden ? m_visibleState : DockState); else Activate(); } public void Show(DockPanel dockPanel, DockState dockState) { if (dockPanel == null) throw(new ArgumentNullException(Strings.DockContentHandler_Show_NullDockPanel)); if (dockState == DockState.Unknown || dockState == DockState.Hidden) throw(new ArgumentException(Strings.DockContentHandler_Show_InvalidDockState)); dockPanel.SuspendLayout(true); DockPanel = dockPanel; if (dockState == DockState.Float) { if (FloatPane == null) Pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.Float, true); } else if (PanelPane == null) { DockPane paneExisting = null; foreach (DockPane pane in DockPanel.Panes) if (pane.DockState == dockState) { if (paneExisting == null || pane.IsActivated) paneExisting = pane; if (pane.IsActivated) break; } if (paneExisting == null) Pane = DockPanel.DockPaneFactory.CreateDockPane(Content, dockState, true); else Pane = paneExisting; } DockState = dockState; dockPanel.ResumeLayout(true, true); //we'll resume the layout before activating to ensure that the position Activate(); //and size of the form are finally processed before the form is shown } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters")] public void Show(DockPanel dockPanel, Rectangle floatWindowBounds) { if (dockPanel == null) throw(new ArgumentNullException(Strings.DockContentHandler_Show_NullDockPanel)); dockPanel.SuspendLayout(true); DockPanel = dockPanel; if (FloatPane == null) { IsHidden = true; // to reduce the screen flicker FloatPane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.Float, false); FloatPane.FloatWindow.StartPosition = FormStartPosition.Manual; } FloatPane.FloatWindow.Bounds = floatWindowBounds; Show(dockPanel, DockState.Float); Activate(); dockPanel.ResumeLayout(true, true); } public void Show(DockPane pane, IDockContent beforeContent) { if (pane == null) throw(new ArgumentNullException(Strings.DockContentHandler_Show_NullPane)); if (beforeContent != null && pane.Contents.IndexOf(beforeContent) == -1) throw(new ArgumentException(Strings.DockContentHandler_Show_InvalidBeforeContent)); pane.DockPanel.SuspendLayout(true); DockPanel = pane.DockPanel; Pane = pane; pane.SetContentIndex(Content, pane.Contents.IndexOf(beforeContent)); Show(); pane.DockPanel.ResumeLayout(true, true); } public void Show(DockPane previousPane, DockAlignment alignment, double proportion) { if (previousPane == null) throw(new ArgumentException(Strings.DockContentHandler_Show_InvalidPrevPane)); if (DockHelper.IsDockStateAutoHide(previousPane.DockState)) throw(new ArgumentException(Strings.DockContentHandler_Show_InvalidPrevPane)); previousPane.DockPanel.SuspendLayout(true); DockPanel = previousPane.DockPanel; DockPanel.DockPaneFactory.CreateDockPane(Content, previousPane, alignment, proportion, true); Show(); previousPane.DockPanel.ResumeLayout(true, true); } public void Close() { DockPanel dockPanel = DockPanel; if (dockPanel != null) dockPanel.SuspendLayout(true); Form.Close(); if (dockPanel != null) dockPanel.ResumeLayout(true, true); } private DockPaneStripBase.Tab m_tab = null; internal DockPaneStripBase.Tab GetTab(DockPaneStripBase dockPaneStrip) { if (m_tab == null) m_tab = dockPaneStrip.CreateTab(Content); return m_tab; } private IDisposable m_autoHideTab = null; internal IDisposable AutoHideTab { get { return m_autoHideTab; } set { m_autoHideTab = value; } } #region Events private static readonly object DockStateChangedEvent = new object(); public event EventHandler DockStateChanged { add { Events.AddHandler(DockStateChangedEvent, value); } remove { Events.RemoveHandler(DockStateChangedEvent, value); } } protected virtual void OnDockStateChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[DockStateChangedEvent]; if (handler != null) handler(this, e); } #endregion private void Form_Disposed(object sender, EventArgs e) { Dispose(); } private void Form_TextChanged(object sender, EventArgs e) { if (DockHelper.IsDockStateAutoHide(DockState)) DockPanel.RefreshAutoHideStrip(); else if (Pane != null) { if (Pane.FloatWindow != null) Pane.FloatWindow.SetText(); Pane.RefreshChanges(); } } private bool m_flagClipWindow = false; internal bool FlagClipWindow { get { return m_flagClipWindow; } set { if (m_flagClipWindow == value) return; m_flagClipWindow = value; if (m_flagClipWindow) Form.Region = new Region(Rectangle.Empty); else Form.Region = null; } } private ContextMenuStrip m_tabPageContextMenuStrip = null; public ContextMenuStrip TabPageContextMenuStrip { get { return m_tabPageContextMenuStrip; } set { m_tabPageContextMenuStrip = value; } } #region IDockDragSource Members Control IDragSource.DragControl { get { return Form; } } bool IDockDragSource.CanDockTo(DockPane pane) { if (!IsDockStateValid(pane.DockState)) return false; if (Pane == pane && pane.DisplayingContents.Count == 1) return false; return true; } Rectangle IDockDragSource.BeginDrag(Point ptMouse) { Size size; DockPane floatPane = this.FloatPane; if (DockState == DockState.Float || floatPane == null || floatPane.FloatWindow.NestedPanes.Count != 1) size = DockPanel.DefaultFloatWindowSize; else size = floatPane.FloatWindow.Size; Point location; Rectangle rectPane = Pane.ClientRectangle; if (DockState == DockState.Document) { if (Pane.DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) location = new Point(rectPane.Left, rectPane.Bottom - size.Height); else location = new Point(rectPane.Left, rectPane.Top); } else { location = new Point(rectPane.Left, rectPane.Bottom); location.Y -= size.Height; } location = Pane.PointToScreen(location); if (ptMouse.X > location.X + size.Width) location.X += ptMouse.X - (location.X + size.Width) + Measures.SplitterSize; return new Rectangle(location, size); } void IDockDragSource.EndDrag() { } public void FloatAt(Rectangle floatWindowBounds) { // TODO: where is the pane used? DockPane pane = DockPanel.DockPaneFactory.CreateDockPane(Content, floatWindowBounds, true); } public void DockTo(DockPane pane, DockStyle dockStyle, int contentIndex) { if (dockStyle == DockStyle.Fill) { bool samePane = (Pane == pane); if (!samePane) Pane = pane; int visiblePanes = 0; int convertedIndex = 0; while (visiblePanes <= contentIndex && convertedIndex < Pane.Contents.Count) { DockContent window = Pane.Contents[convertedIndex] as DockContent; if (window != null && !window.IsHidden) ++visiblePanes; ++convertedIndex; } contentIndex = Math.Min(Math.Max(0, convertedIndex-1), Pane.Contents.Count - 1); if (contentIndex == -1 || !samePane) pane.SetContentIndex(Content, contentIndex); else { DockContentCollection contents = pane.Contents; int oldIndex = contents.IndexOf(Content); int newIndex = contentIndex; if (oldIndex < newIndex) { newIndex += 1; if (newIndex > contents.Count -1) newIndex = -1; } pane.SetContentIndex(Content, newIndex); } } else { DockPane paneFrom = DockPanel.DockPaneFactory.CreateDockPane(Content, pane.DockState, true); INestedPanesContainer container = pane.NestedPanesContainer; if (dockStyle == DockStyle.Left) paneFrom.DockTo(container, pane, DockAlignment.Left, 0.5); else if (dockStyle == DockStyle.Right) paneFrom.DockTo(container, pane, DockAlignment.Right, 0.5); else if (dockStyle == DockStyle.Top) paneFrom.DockTo(container, pane, DockAlignment.Top, 0.5); else if (dockStyle == DockStyle.Bottom) paneFrom.DockTo(container, pane, DockAlignment.Bottom, 0.5); paneFrom.DockState = pane.DockState; } } public void DockTo(DockPanel panel, DockStyle dockStyle) { if (panel != DockPanel) throw new ArgumentException(Strings.IDockDragSource_DockTo_InvalidPanel, "panel"); DockPane pane; if (dockStyle == DockStyle.Top) pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.DockTop, true); else if (dockStyle == DockStyle.Bottom) pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.DockBottom, true); else if (dockStyle == DockStyle.Left) pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.DockLeft, true); else if (dockStyle == DockStyle.Right) pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.DockRight, true); else if (dockStyle == DockStyle.Fill) pane = DockPanel.DockPaneFactory.CreateDockPane(Content, DockState.Document, true); else return; } #endregion } }
/* Copyright Microsoft Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 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 2 License for the specific language governing permissions and limitations under the License. */ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using MileageStats.Domain.Models; using Xunit; namespace MileageStats.Domain.Tests { public class VehiclePhotoFixture { [Fact] public void WhenConstructed_ThenPopulated() { VehiclePhoto actual = new VehiclePhoto(); Assert.NotNull(actual); Assert.Equal(0, actual.VehiclePhotoId); Assert.Null(actual.Image); Assert.Null(actual.ImageMimeType); } [Fact] public void WehnVehiclePhotoIdSet_ThenValueUpdated() { VehiclePhoto target = new VehiclePhoto(); target.VehiclePhotoId = 4; int actual = target.VehiclePhotoId; Assert.Equal(4, actual); } [Fact] public void WhenImageSet_ThenValueUpdated() { VehiclePhoto target = new VehiclePhoto(); byte[] expected = new byte[] {1, 2, 3}; target.Image = expected; byte[] actual = target.Image; Assert.Equal(expected.Length, actual.Length); for (int i = 0; i < expected.Length; i++) { Assert.Equal(expected[i], actual[i]); } } [Fact] public void WhenImageSetToNull_ThenValueUpdated() { VehiclePhoto target = new VehiclePhoto(); target.Image = new byte[] {1, 2, 3}; target.Image = null; byte[] actual = target.Image; Assert.Null(actual); } [Fact] public void WhenImageSetToValidValue_ThenValidationPasses() { VehiclePhoto target = new VehiclePhoto(); target.ImageMimeType = "ImageMimeType"; target.Image = new byte[1]; var validationContext = new ValidationContext(target, null, null); var validationResults = new List<ValidationResult>(); bool actual = Validator.TryValidateObject(target, validationContext, validationResults, true); Assert.True(actual); Assert.Equal(0, validationResults.Count); } [Fact] public void WhenImageSetToNull_ThenValidationFails() { VehiclePhoto target = new VehiclePhoto(); target.ImageMimeType = "ImageMimeType"; target.Image = null; var validationContext = new ValidationContext(target, null, null); var validationResults = new List<ValidationResult>(); bool actual = Validator.TryValidateObject(target, validationContext, validationResults, true); Assert.False(actual); Assert.Equal(1, validationResults.Count); Assert.Equal(1, validationResults[0].MemberNames.Count()); Assert.Equal("Image", validationResults[0].MemberNames.First()); } [Fact] public void WhenImageMimeTypeSet_ThenValueUpdated() { VehiclePhoto target = new VehiclePhoto(); target.ImageMimeType = "ImageMimeType"; string actual = target.ImageMimeType; Assert.Equal("ImageMimeType", actual); } [Fact] public void WhenImageMimeTypeSetToNull_ThenUpdatesValue() { VehiclePhoto target = new VehiclePhoto(); target.ImageMimeType = "ImageMimeType"; target.ImageMimeType = null; string actual = target.ImageMimeType; Assert.Null(actual); } [Fact] public void WhenImageMimeTypeSetToValidValue_ThenValidationPasses() { VehiclePhoto target = new VehiclePhoto(); target.Image = new byte[1]; target.ImageMimeType = "ImageMimeType"; var validationContext = new ValidationContext(target, null, null); var validationResults = new List<ValidationResult>(); bool actual = Validator.TryValidateObject(target, validationContext, validationResults, true); Assert.True(actual); Assert.Equal(0, validationResults.Count); } [Fact] public void WhenImageMimeTypeSetToNull_ThenValidationFails() { VehiclePhoto target = new VehiclePhoto(); target.Image = new byte[1]; target.ImageMimeType = null; var validationContext = new ValidationContext(target, null, null); var validationResults = new List<ValidationResult>(); bool actual = Validator.TryValidateObject(target, validationContext, validationResults, true); Assert.False(actual); Assert.Equal(1, validationResults.Count); Assert.Equal(1, validationResults[0].MemberNames.Count()); Assert.Equal("ImageMimeType", validationResults[0].MemberNames.First()); } [Fact] public void WhenImageMimeTypeSetToEmpty_ThenValidationFails() { VehiclePhoto target = new VehiclePhoto(); target.Image = new byte[1]; target.ImageMimeType = string.Empty; var validationContext = new ValidationContext(target, null, null); var validationResults = new List<ValidationResult>(); bool actual = Validator.TryValidateObject(target, validationContext, validationResults, true); Assert.False(actual); Assert.Equal(1, validationResults.Count); Assert.Equal(1, validationResults[0].MemberNames.Count()); Assert.Equal("ImageMimeType", validationResults[0].MemberNames.First()); } [Fact] public void WhenImageMimeTypeSetTo101Characters_ThenValidationFails() { VehiclePhoto target = new VehiclePhoto(); target.Image = new byte[1]; target.ImageMimeType = new string('1', 101); var validationContext = new ValidationContext(target, null, null); var validationResults = new List<ValidationResult>(); bool actual = Validator.TryValidateObject(target, validationContext, validationResults, true); Assert.False(actual); Assert.Equal(1, validationResults.Count); Assert.Equal(1, validationResults[0].MemberNames.Count()); Assert.Equal("ImageMimeType", validationResults[0].MemberNames.First()); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Compute { using Microsoft.Rest.Azure; using Models; /// <summary> /// VirtualMachineScaleSetsOperations operations. /// </summary> public partial interface IVirtualMachineScaleSetsOperations { /// <summary> /// Allows you to create or update a virtual machine scale set by /// providing parameters or a path to pre-configured parameter file. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='name'> /// Parameters supplied to the Create Virtual Machine Scale Set /// operation. /// </param> /// <param name='parameters'> /// Parameters supplied to the Create Virtual Machine Scale Set /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<VirtualMachineScaleSet>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string name, VirtualMachineScaleSet parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Allows you to create or update a virtual machine scale set by /// providing parameters or a path to pre-configured parameter file. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='name'> /// Parameters supplied to the Create Virtual Machine Scale Set /// operation. /// </param> /// <param name='parameters'> /// Parameters supplied to the Create Virtual Machine Scale Set /// operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<VirtualMachineScaleSet>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string name, VirtualMachineScaleSet parameters, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Allows you to deallocate virtual machines in a virtual machine /// scale set. Shuts down the virtual machines and releases the /// compute resources. You are not billed for the compute resources /// that this virtual machine scale set uses. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='instanceIds'> /// the virtual machine scale set instance ids. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeallocateWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, System.Collections.Generic.IList<string> instanceIds = default(System.Collections.Generic.IList<string>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Allows you to deallocate virtual machines in a virtual machine /// scale set. Shuts down the virtual machines and releases the /// compute resources. You are not billed for the compute resources /// that this virtual machine scale set uses. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='instanceIds'> /// the virtual machine scale set instance ids. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> BeginDeallocateWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, System.Collections.Generic.IList<string> instanceIds = default(System.Collections.Generic.IList<string>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Allows you to delete a virtual machine scale set. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Allows you to delete a virtual machine scale set. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Display information about a virtual machine scale set. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<VirtualMachineScaleSet>> GetWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Allows you to delete virtual machines in a virtual machine scale /// set. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='instanceIds'> /// the virtual machine scale set instance ids. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> DeleteInstancesWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, System.Collections.Generic.IList<string> instanceIds, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Allows you to delete virtual machines in a virtual machine scale /// set. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='instanceIds'> /// the virtual machine scale set instance ids. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> BeginDeleteInstancesWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, System.Collections.Generic.IList<string> instanceIds, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Displays status of a virtual machine scale set instance. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<VirtualMachineScaleSetInstanceView>> GetInstanceViewWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Lists all virtual machine scale sets under a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<VirtualMachineScaleSet>>> ListWithHttpMessagesAsync(string resourceGroupName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Lists all Virtual Machine Scale Sets in the subscription. Use /// nextLink property in the response to get the next page of Virtual /// Machine Scale Sets. Do this till nextLink is not null to fetch /// all the Virtual Machine Scale Sets. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<VirtualMachineScaleSet>>> ListAllWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Displays available skus for your virtual machine scale set /// including the minimum and maximum vm instances allowed for a /// particular sku. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<VirtualMachineScaleSetSku>>> ListSkusWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Allows you to power off (stop) virtual machines in a virtual /// machine scale set. Note that resources are still attached and you /// are getting charged for the resources. Use deallocate to release /// resources. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='instanceIds'> /// the virtual machine scale set instance ids. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> PowerOffWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, System.Collections.Generic.IList<string> instanceIds = default(System.Collections.Generic.IList<string>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Allows you to power off (stop) virtual machines in a virtual /// machine scale set. Note that resources are still attached and you /// are getting charged for the resources. Use deallocate to release /// resources. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='instanceIds'> /// the virtual machine scale set instance ids. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> BeginPowerOffWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, System.Collections.Generic.IList<string> instanceIds = default(System.Collections.Generic.IList<string>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Allows you to restart virtual machines in a virtual machine scale /// set. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='instanceIds'> /// the virtual machine scale set instance ids. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> RestartWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, System.Collections.Generic.IList<string> instanceIds = default(System.Collections.Generic.IList<string>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Allows you to restart virtual machines in a virtual machine scale /// set. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='instanceIds'> /// the virtual machine scale set instance ids. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> BeginRestartWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, System.Collections.Generic.IList<string> instanceIds = default(System.Collections.Generic.IList<string>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Allows you to start virtual machines in a virtual machine scale /// set. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='instanceIds'> /// the virtual machine scale set instance ids. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> StartWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, System.Collections.Generic.IList<string> instanceIds = default(System.Collections.Generic.IList<string>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Allows you to start virtual machines in a virtual machine scale /// set. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='instanceIds'> /// the virtual machine scale set instance ids. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> BeginStartWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, System.Collections.Generic.IList<string> instanceIds = default(System.Collections.Generic.IList<string>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Allows you to manually upgrade virtual machines in a virtual /// machine scale set. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='instanceIds'> /// the virtual machine scale set instance ids. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> UpdateInstancesWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, System.Collections.Generic.IList<string> instanceIds, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Allows you to manually upgrade virtual machines in a virtual /// machine scale set. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='instanceIds'> /// the virtual machine scale set instance ids. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> BeginUpdateInstancesWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, System.Collections.Generic.IList<string> instanceIds, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Allows you to re-image(update the version of the installed /// operating system) virtual machines in a virtual machine scale set. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> ReimageWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Allows you to re-image(update the version of the installed /// operating system) virtual machines in a virtual machine scale set. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='vmScaleSetName'> /// The name of the virtual machine scale set. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse> BeginReimageWithHttpMessagesAsync(string resourceGroupName, string vmScaleSetName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Lists all virtual machine scale sets under a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<VirtualMachineScaleSet>>> ListNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Lists all Virtual Machine Scale Sets in the subscription. Use /// nextLink property in the response to get the next page of Virtual /// Machine Scale Sets. Do this till nextLink is not null to fetch /// all the Virtual Machine Scale Sets. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<VirtualMachineScaleSet>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Displays available skus for your virtual machine scale set /// including the minimum and maximum vm instances allowed for a /// particular sku. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<VirtualMachineScaleSetSku>>> ListSkusNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } }
// DeflaterEngine.cs // // Copyright (C) 2001 Mike Krueger // Copyright (C) 2004 John Reilly // // This file was translated from java, it was part of the GNU Classpath // Copyright (C) 2001 Free Software Foundation, Inc. // // 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. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; using ICSharpCode.SharpZipLib.Checksums; namespace ICSharpCode.SharpZipLib.Zip.Compression { /// <summary> /// Strategies for deflater /// </summary> public enum DeflateStrategy { /// <summary> /// The default strategy /// </summary> Default = 0, /// <summary> /// This strategy will only allow longer string repetitions. It is /// useful for random data with a small character set. /// </summary> Filtered = 1, /// <summary> /// This strategy will not look for string repetitions at all. It /// only encodes with Huffman trees (which means, that more common /// characters get a smaller encoding. /// </summary> HuffmanOnly = 2 } // DEFLATE ALGORITHM: // // The uncompressed stream is inserted into the window array. When // the window array is full the first half is thrown away and the // second half is copied to the beginning. // // The head array is a hash table. Three characters build a hash value // and they the value points to the corresponding index in window of // the last string with this hash. The prev array implements a // linked list of matches with the same hash: prev[index & WMASK] points // to the previous index with the same hash. // /// <summary> /// Low level compression engine for deflate algorithm which uses a 32K sliding window /// with secondary compression from Huffman/Shannon-Fano codes. /// </summary> public class DeflaterEngine : DeflaterConstants { #region Constants const int TooFar = 4096; #endregion #region Constructors /// <summary> /// Construct instance with pending buffer /// </summary> /// <param name="pending"> /// Pending buffer to use /// </param>> public DeflaterEngine(DeflaterPending pending) { this.pending = pending; huffman = new DeflaterHuffman(pending); adler = new Adler32(); window = new byte[2 * WSIZE]; head = new short[HASH_SIZE]; prev = new short[WSIZE]; // We start at index 1, to avoid an implementation deficiency, that // we cannot build a repeat pattern at index 0. blockStart = strstart = 1; } #endregion /// <summary> /// Deflate drives actual compression of data /// </summary> /// <param name="flush">True to flush input buffers</param> /// <param name="finish">Finish deflation with the current input.</param> /// <returns>Returns true if progress has been made.</returns> public bool Deflate(bool flush, bool finish) { bool progress; do { FillWindow(); bool canFlush = flush && (inputOff == inputEnd); #if DebugDeflation if (DeflaterConstants.DEBUGGING) { Console.WriteLine("window: [" + blockStart + "," + strstart + "," + lookahead + "], " + compressionFunction + "," + canFlush); } #endif switch (compressionFunction) { case DEFLATE_STORED: progress = DeflateStored(canFlush, finish); break; case DEFLATE_FAST: progress = DeflateFast(canFlush, finish); break; case DEFLATE_SLOW: progress = DeflateSlow(canFlush, finish); break; default: throw new InvalidOperationException("unknown compressionFunction"); } } while (pending.IsFlushed && progress); // repeat while we have no pending output and progress was made return progress; } /// <summary> /// Sets input data to be deflated. Should only be called when <code>NeedsInput()</code> /// returns true /// </summary> /// <param name="buffer">The buffer containing input data.</param> /// <param name="offset">The offset of the first byte of data.</param> /// <param name="count">The number of bytes of data to use as input.</param> public void SetInput(byte[] buffer, int offset, int count) { if ( buffer == null ) { throw new ArgumentNullException("buffer"); } if ( offset < 0 ) { throw new ArgumentOutOfRangeException("offset"); } if ( count < 0 ) { throw new ArgumentOutOfRangeException("count"); } if (inputOff < inputEnd) { throw new InvalidOperationException("Old input was not completely processed"); } int end = offset + count; /* We want to throw an ArrayIndexOutOfBoundsException early. The * check is very tricky: it also handles integer wrap around. */ if ((offset > end) || (end > buffer.Length) ) { throw new ArgumentOutOfRangeException("count"); } inputBuf = buffer; inputOff = offset; inputEnd = end; } /// <summary> /// Determines if more <see cref="SetInput">input</see> is needed. /// </summary> /// <returns>Return true if input is needed via <see cref="SetInput">SetInput</see></returns> public bool NeedsInput() { return (inputEnd == inputOff); } /// <summary> /// Set compression dictionary /// </summary> /// <param name="buffer">The buffer containing the dictionary data</param> /// <param name="offset">The offset in the buffer for the first byte of data</param> /// <param name="length">The length of the dictionary data.</param> public void SetDictionary(byte[] buffer, int offset, int length) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (strstart != 1) ) { throw new InvalidOperationException("strstart not 1"); } #endif adler.Update(buffer, offset, length); if (length < MIN_MATCH) { return; } if (length > MAX_DIST) { offset += length - MAX_DIST; length = MAX_DIST; } System.Array.Copy(buffer, offset, window, strstart, length); UpdateHash(); --length; while (--length > 0) { InsertString(); strstart++; } strstart += 2; blockStart = strstart; } /// <summary> /// Reset internal state /// </summary> public void Reset() { huffman.Reset(); adler.Reset(); blockStart = strstart = 1; lookahead = 0; totalIn = 0; prevAvailable = false; matchLen = MIN_MATCH - 1; for (int i = 0; i < HASH_SIZE; i++) { head[i] = 0; } for (int i = 0; i < WSIZE; i++) { prev[i] = 0; } } /// <summary> /// Reset Adler checksum /// </summary> public void ResetAdler() { adler.Reset(); } /// <summary> /// Get current value of Adler checksum /// </summary> public int Adler { get { return unchecked((int)adler.Value); } } /// <summary> /// Total data processed /// </summary> public long TotalIn { get { return totalIn; } } /// <summary> /// Get/set the <see cref="DeflateStrategy">deflate strategy</see> /// </summary> public DeflateStrategy Strategy { get { return strategy; } set { strategy = value; } } /// <summary> /// Set the deflate level (0-9) /// </summary> /// <param name="level">The value to set the level to.</param> public void SetLevel(int level) { if ( (level < 0) || (level > 9) ) { throw new ArgumentOutOfRangeException("level"); } goodLength = DeflaterConstants.GOOD_LENGTH[level]; max_lazy = DeflaterConstants.MAX_LAZY[level]; niceLength = DeflaterConstants.NICE_LENGTH[level]; max_chain = DeflaterConstants.MAX_CHAIN[level]; if (DeflaterConstants.COMPR_FUNC[level] != compressionFunction) { #if DebugDeflation if (DeflaterConstants.DEBUGGING) { Console.WriteLine("Change from " + compressionFunction + " to " + DeflaterConstants.COMPR_FUNC[level]); } #endif switch (compressionFunction) { case DEFLATE_STORED: if (strstart > blockStart) { huffman.FlushStoredBlock(window, blockStart, strstart - blockStart, false); blockStart = strstart; } UpdateHash(); break; case DEFLATE_FAST: if (strstart > blockStart) { huffman.FlushBlock(window, blockStart, strstart - blockStart, false); blockStart = strstart; } break; case DEFLATE_SLOW: if (prevAvailable) { huffman.TallyLit(window[strstart-1] & 0xff); } if (strstart > blockStart) { huffman.FlushBlock(window, blockStart, strstart - blockStart, false); blockStart = strstart; } prevAvailable = false; matchLen = MIN_MATCH - 1; break; } compressionFunction = COMPR_FUNC[level]; } } /// <summary> /// Fill the window /// </summary> public void FillWindow() { /* If the window is almost full and there is insufficient lookahead, * move the upper half to the lower one to make room in the upper half. */ if (strstart >= WSIZE + MAX_DIST) { SlideWindow(); } /* If there is not enough lookahead, but still some input left, * read in the input */ while (lookahead < DeflaterConstants.MIN_LOOKAHEAD && inputOff < inputEnd) { int more = 2 * WSIZE - lookahead - strstart; if (more > inputEnd - inputOff) { more = inputEnd - inputOff; } System.Array.Copy(inputBuf, inputOff, window, strstart + lookahead, more); adler.Update(inputBuf, inputOff, more); inputOff += more; totalIn += more; lookahead += more; } if (lookahead >= MIN_MATCH) { UpdateHash(); } } void UpdateHash() { /* if (DEBUGGING) { Console.WriteLine("updateHash: "+strstart); } */ ins_h = (window[strstart] << HASH_SHIFT) ^ window[strstart + 1]; } /// <summary> /// Inserts the current string in the head hash and returns the previous /// value for this hash. /// </summary> /// <returns>The previous hash value</returns> int InsertString() { short match; int hash = ((ins_h << HASH_SHIFT) ^ window[strstart + (MIN_MATCH -1)]) & HASH_MASK; #if DebugDeflation if (DeflaterConstants.DEBUGGING) { if (hash != (((window[strstart] << (2*HASH_SHIFT)) ^ (window[strstart + 1] << HASH_SHIFT) ^ (window[strstart + 2])) & HASH_MASK)) { throw new SharpZipBaseException("hash inconsistent: " + hash + "/" +window[strstart] + "," +window[strstart + 1] + "," +window[strstart + 2] + "," + HASH_SHIFT); } } #endif prev[strstart & WMASK] = match = head[hash]; head[hash] = unchecked((short)strstart); ins_h = hash; return match & 0xffff; } void SlideWindow() { Array.Copy(window, WSIZE, window, 0, WSIZE); matchStart -= WSIZE; strstart -= WSIZE; blockStart -= WSIZE; // Slide the hash table (could be avoided with 32 bit values // at the expense of memory usage). for (int i = 0; i < HASH_SIZE; ++i) { int m = head[i] & 0xffff; head[i] = (short)(m >= WSIZE ? (m - WSIZE) : 0); } // Slide the prev table. for (int i = 0; i < WSIZE; i++) { int m = prev[i] & 0xffff; prev[i] = (short)(m >= WSIZE ? (m - WSIZE) : 0); } } /// <summary> /// Find the best (longest) string in the window matching the /// string starting at strstart. /// /// Preconditions: /// <code> /// strstart + MAX_MATCH &lt;= window.length.</code> /// </summary> /// <param name="curMatch"></param> /// <returns>True if a match greater than the minimum length is found</returns> bool FindLongestMatch(int curMatch) { int chainLength = this.max_chain; int niceLength = this.niceLength; short[] prev = this.prev; int scan = this.strstart; int match; int best_end = this.strstart + matchLen; int best_len = Math.Max(matchLen, MIN_MATCH - 1); int limit = Math.Max(strstart - MAX_DIST, 0); int strend = strstart + MAX_MATCH - 1; byte scan_end1 = window[best_end - 1]; byte scan_end = window[best_end]; // Do not waste too much time if we already have a good match: if (best_len >= this.goodLength) { chainLength >>= 2; } /* Do not look for matches beyond the end of the input. This is necessary * to make deflate deterministic. */ if (niceLength > lookahead) { niceLength = lookahead; } #if DebugDeflation if (DeflaterConstants.DEBUGGING && (strstart > 2 * WSIZE - MIN_LOOKAHEAD)) { throw new InvalidOperationException("need lookahead"); } #endif do { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (curMatch >= strstart) ) { throw new InvalidOperationException("no future"); } #endif if (window[curMatch + best_len] != scan_end || window[curMatch + best_len - 1] != scan_end1 || window[curMatch] != window[scan] || window[curMatch + 1] != window[scan + 1]) { continue; } match = curMatch + 2; scan += 2; /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart + 258. */ while ( window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && (scan < strend)) { // Do nothing } if (scan > best_end) { #if DebugDeflation if (DeflaterConstants.DEBUGGING && (ins_h == 0) ) Console.Error.WriteLine("Found match: " + curMatch + "-" + (scan - strstart)); #endif matchStart = curMatch; best_end = scan; best_len = scan - strstart; if (best_len >= niceLength) { break; } scan_end1 = window[best_end - 1]; scan_end = window[best_end]; } scan = strstart; } while ((curMatch = (prev[curMatch & WMASK] & 0xffff)) > limit && --chainLength != 0); matchLen = Math.Min(best_len, lookahead); return matchLen >= MIN_MATCH; } bool DeflateStored(bool flush, bool finish) { if (!flush && (lookahead == 0)) { return false; } strstart += lookahead; lookahead = 0; int storedLength = strstart - blockStart; if ((storedLength >= DeflaterConstants.MAX_BLOCK_SIZE) || // Block is full (blockStart < WSIZE && storedLength >= MAX_DIST) || // Block may move out of window flush) { bool lastBlock = finish; if (storedLength > DeflaterConstants.MAX_BLOCK_SIZE) { storedLength = DeflaterConstants.MAX_BLOCK_SIZE; lastBlock = false; } #if DebugDeflation if (DeflaterConstants.DEBUGGING) { Console.WriteLine("storedBlock[" + storedLength + "," + lastBlock + "]"); } #endif huffman.FlushStoredBlock(window, blockStart, storedLength, lastBlock); blockStart += storedLength; return !lastBlock; } return true; } bool DeflateFast(bool flush, bool finish) { if (lookahead < MIN_LOOKAHEAD && !flush) { return false; } while (lookahead >= MIN_LOOKAHEAD || flush) { if (lookahead == 0) { // We are flushing everything huffman.FlushBlock(window, blockStart, strstart - blockStart, finish); blockStart = strstart; return false; } if (strstart > 2 * WSIZE - MIN_LOOKAHEAD) { /* slide window, as FindLongestMatch needs this. * This should only happen when flushing and the window * is almost full. */ SlideWindow(); } int hashHead; if (lookahead >= MIN_MATCH && (hashHead = InsertString()) != 0 && strategy != DeflateStrategy.HuffmanOnly && strstart - hashHead <= MAX_DIST && FindLongestMatch(hashHead)) { // longestMatch sets matchStart and matchLen #if DebugDeflation if (DeflaterConstants.DEBUGGING) { for (int i = 0 ; i < matchLen; i++) { if (window[strstart + i] != window[matchStart + i]) { throw new SharpZipBaseException("Match failure"); } } } #endif bool full = huffman.TallyDist(strstart - matchStart, matchLen); lookahead -= matchLen; if (matchLen <= max_lazy && lookahead >= MIN_MATCH) { while (--matchLen > 0) { ++strstart; InsertString(); } ++strstart; } else { strstart += matchLen; if (lookahead >= MIN_MATCH - 1) { UpdateHash(); } } matchLen = MIN_MATCH - 1; if (!full) { continue; } } else { // No match found huffman.TallyLit(window[strstart] & 0xff); ++strstart; --lookahead; } if (huffman.IsFull()) { bool lastBlock = finish && (lookahead == 0); huffman.FlushBlock(window, blockStart, strstart - blockStart, lastBlock); blockStart = strstart; return !lastBlock; } } return true; } bool DeflateSlow(bool flush, bool finish) { if (lookahead < MIN_LOOKAHEAD && !flush) { return false; } while (lookahead >= MIN_LOOKAHEAD || flush) { if (lookahead == 0) { if (prevAvailable) { huffman.TallyLit(window[strstart-1] & 0xff); } prevAvailable = false; // We are flushing everything #if DebugDeflation if (DeflaterConstants.DEBUGGING && !flush) { throw new SharpZipBaseException("Not flushing, but no lookahead"); } #endif huffman.FlushBlock(window, blockStart, strstart - blockStart, finish); blockStart = strstart; return false; } if (strstart >= 2 * WSIZE - MIN_LOOKAHEAD) { /* slide window, as FindLongestMatch needs this. * This should only happen when flushing and the window * is almost full. */ SlideWindow(); } int prevMatch = matchStart; int prevLen = matchLen; if (lookahead >= MIN_MATCH) { int hashHead = InsertString(); if (strategy != DeflateStrategy.HuffmanOnly && hashHead != 0 && strstart - hashHead <= MAX_DIST && FindLongestMatch(hashHead)) { // longestMatch sets matchStart and matchLen // Discard match if too small and too far away if (matchLen <= 5 && (strategy == DeflateStrategy.Filtered || (matchLen == MIN_MATCH && strstart - matchStart > TooFar))) { matchLen = MIN_MATCH - 1; } } } // previous match was better if ((prevLen >= MIN_MATCH) && (matchLen <= prevLen) ) { #if DebugDeflation if (DeflaterConstants.DEBUGGING) { for (int i = 0 ; i < matchLen; i++) { if (window[strstart-1+i] != window[prevMatch + i]) throw new SharpZipBaseException(); } } #endif huffman.TallyDist(strstart - 1 - prevMatch, prevLen); prevLen -= 2; do { strstart++; lookahead--; if (lookahead >= MIN_MATCH) { InsertString(); } } while (--prevLen > 0); strstart ++; lookahead--; prevAvailable = false; matchLen = MIN_MATCH - 1; } else { if (prevAvailable) { huffman.TallyLit(window[strstart-1] & 0xff); } prevAvailable = true; strstart++; lookahead--; } if (huffman.IsFull()) { int len = strstart - blockStart; if (prevAvailable) { len--; } bool lastBlock = (finish && (lookahead == 0) && !prevAvailable); huffman.FlushBlock(window, blockStart, len, lastBlock); blockStart += len; return !lastBlock; } } return true; } #region Instance Fields // Hash index of string to be inserted int ins_h; /// <summary> /// Hashtable, hashing three characters to an index for window, so /// that window[index]..window[index+2] have this hash code. /// Note that the array should really be unsigned short, so you need /// to and the values with 0xffff. /// </summary> short[] head; /// <summary> /// <code>prev[index &amp; WMASK]</code> points to the previous index that has the /// same hash code as the string starting at index. This way /// entries with the same hash code are in a linked list. /// Note that the array should really be unsigned short, so you need /// to and the values with 0xffff. /// </summary> short[] prev; int matchStart; // Length of best match int matchLen; // Set if previous match exists bool prevAvailable; int blockStart; /// <summary> /// Points to the current character in the window. /// </summary> int strstart; /// <summary> /// lookahead is the number of characters starting at strstart in /// window that are valid. /// So window[strstart] until window[strstart+lookahead-1] are valid /// characters. /// </summary> int lookahead; /// <summary> /// This array contains the part of the uncompressed stream that /// is of relevance. The current character is indexed by strstart. /// </summary> byte[] window; DeflateStrategy strategy; int max_chain, max_lazy, niceLength, goodLength; /// <summary> /// The current compression function. /// </summary> int compressionFunction; /// <summary> /// The input data for compression. /// </summary> byte[] inputBuf; /// <summary> /// The total bytes of input read. /// </summary> long totalIn; /// <summary> /// The offset into inputBuf, where input data starts. /// </summary> int inputOff; /// <summary> /// The end offset of the input data. /// </summary> int inputEnd; DeflaterPending pending; DeflaterHuffman huffman; /// <summary> /// The adler checksum /// </summary> Adler32 adler; #endregion } }
// 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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.38.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * Knowledge Graph Search API Version v1 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://developers.google.com/knowledge-graph/'>Knowledge Graph Search API</a> * <tr><th>API Version<td>v1 * <tr><th>API Rev<td>20190106 (1466) * <tr><th>API Docs * <td><a href='https://developers.google.com/knowledge-graph/'> * https://developers.google.com/knowledge-graph/</a> * <tr><th>Discovery Name<td>kgsearch * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using Knowledge Graph Search API can be found at * <a href='https://developers.google.com/knowledge-graph/'>https://developers.google.com/knowledge-graph/</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.Kgsearch.v1 { /// <summary>The Kgsearch Service.</summary> public class KgsearchService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public KgsearchService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public KgsearchService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { entities = new EntitiesResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "kgsearch"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://kgsearch.googleapis.com/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return ""; } } #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri { get { return "https://kgsearch.googleapis.com/batch"; } } /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath { get { return "batch"; } } #endif private readonly EntitiesResource entities; /// <summary>Gets the Entities resource.</summary> public virtual EntitiesResource Entities { get { return entities; } } } ///<summary>A base abstract class for Kgsearch requests.</summary> public abstract class KgsearchBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new KgsearchBaseServiceRequest instance.</summary> protected KgsearchBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string /// assigned to a user, but should not exceed 40 characters.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes Kgsearch parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "entities" collection of methods.</summary> public class EntitiesResource { private const string Resource = "entities"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public EntitiesResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Searches Knowledge Graph for entities that match the constraints. A list of matched entities will /// be returned in response, which will be in JSON-LD format and compatible with http://schema.org</summary> public virtual SearchRequest Search() { return new SearchRequest(service); } /// <summary>Searches Knowledge Graph for entities that match the constraints. A list of matched entities will /// be returned in response, which will be in JSON-LD format and compatible with http://schema.org</summary> public class SearchRequest : KgsearchBaseServiceRequest<Google.Apis.Kgsearch.v1.Data.SearchResponse> { /// <summary>Constructs a new Search request.</summary> public SearchRequest(Google.Apis.Services.IClientService service) : base(service) { InitParameters(); } /// <summary>Restricts returned entities with these types, e.g. Person (as defined in /// http://schema.org/Person). If multiple types are specified, returned entities will contain one or more /// of these types.</summary> [Google.Apis.Util.RequestParameterAttribute("types", Google.Apis.Util.RequestParameterType.Query)] public virtual Google.Apis.Util.Repeatable<string> Types { get; set; } /// <summary>Enables indenting of json results.</summary> [Google.Apis.Util.RequestParameterAttribute("indent", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> Indent { get; set; } /// <summary>The list of language codes (defined in ISO 693) to run the query with, e.g. 'en'.</summary> [Google.Apis.Util.RequestParameterAttribute("languages", Google.Apis.Util.RequestParameterType.Query)] public virtual Google.Apis.Util.Repeatable<string> Languages { get; set; } /// <summary>The list of entity id to be used for search instead of query string. To specify multiple ids in /// the HTTP request, repeat the parameter in the URL as in ...?ids=A=B</summary> [Google.Apis.Util.RequestParameterAttribute("ids", Google.Apis.Util.RequestParameterType.Query)] public virtual Google.Apis.Util.Repeatable<string> Ids { get; set; } /// <summary>Limits the number of entities to be returned.</summary> [Google.Apis.Util.RequestParameterAttribute("limit", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> Limit { get; set; } /// <summary>Enables prefix match against names and aliases of entities</summary> [Google.Apis.Util.RequestParameterAttribute("prefix", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> Prefix { get; set; } /// <summary>The literal query string for search.</summary> [Google.Apis.Util.RequestParameterAttribute("query", Google.Apis.Util.RequestParameterType.Query)] public virtual string Query { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "search"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/entities:search"; } } /// <summary>Initializes Search parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "types", new Google.Apis.Discovery.Parameter { Name = "types", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "indent", new Google.Apis.Discovery.Parameter { Name = "indent", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "languages", new Google.Apis.Discovery.Parameter { Name = "languages", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "ids", new Google.Apis.Discovery.Parameter { Name = "ids", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "limit", new Google.Apis.Discovery.Parameter { Name = "limit", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "prefix", new Google.Apis.Discovery.Parameter { Name = "prefix", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "query", new Google.Apis.Discovery.Parameter { Name = "query", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.Kgsearch.v1.Data { /// <summary>Response message includes the context and a list of matching results which contain the detail of /// associated entities.</summary> public class SearchResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The local context applicable for the response. See more details at http://www.w3.org/TR/json-ld /// /#context-definitions.</summary> [Newtonsoft.Json.JsonPropertyAttribute("@context")] public virtual object Context { get; set; } /// <summary>The schema type of top-level JSON-LD object, e.g. ItemList.</summary> [Newtonsoft.Json.JsonPropertyAttribute("@type")] public virtual object Type { get; set; } /// <summary>The item list of search results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("itemListElement")] public virtual System.Collections.Generic.IList<object> ItemListElement { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
// 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.ComponentModel; using System.Numerics.Hashing; namespace System.Drawing { /// <summary> /// Represents an ordered pair of x and y coordinates that /// define a point in a two-dimensional plane. /// </summary> [Serializable] public struct Point : IEquatable<Point> { /// <summary> /// Creates a new instance of the <see cref='System.Drawing.Point'/> class /// with member data left uninitialized. /// </summary> public static readonly Point Empty = new Point(); private int _x; private int _y; /// <summary> /// Initializes a new instance of the <see cref='System.Drawing.Point'/> class /// with the specified coordinates. /// </summary> public Point(int x, int y) { _x = x; _y = y; } /// <summary> /// <para> /// Initializes a new instance of the <see cref='System.Drawing.Point'/> class /// from a <see cref='System.Drawing.Size'/> . /// </para> /// </summary> public Point(Size sz) { _x = sz.Width; _y = sz.Height; } /// <summary> /// Initializes a new instance of the Point class using /// coordinates specified by an integer value. /// </summary> public Point(int dw) { _x = LowInt16(dw); _y = HighInt16(dw); } /// <summary> /// <para> /// Gets a value indicating whether this <see cref='System.Drawing.Point'/> is empty. /// </para> /// </summary> [Browsable(false)] public bool IsEmpty => _x == 0 && _y == 0; /// <summary> /// Gets the x-coordinate of this <see cref='System.Drawing.Point'/>. /// </summary> public int X { get { return _x; } set { _x = value; } } /// <summary> /// <para> /// Gets the y-coordinate of this <see cref='System.Drawing.Point'/>. /// </para> /// </summary> public int Y { get { return _y; } set { _y = value; } } /// <summary> /// <para> /// Creates a <see cref='System.Drawing.PointF'/> with the coordinates of the specified /// <see cref='System.Drawing.Point'/> /// </para> /// </summary> public static implicit operator PointF(Point p) => new PointF(p.X, p.Y); /// <summary> /// <para> /// Creates a <see cref='System.Drawing.Size'/> with the coordinates of the specified <see cref='System.Drawing.Point'/> . /// </para> /// </summary> public static explicit operator Size(Point p) => new Size(p.X, p.Y); /// <summary> /// <para> /// Translates a <see cref='System.Drawing.Point'/> by a given <see cref='System.Drawing.Size'/> . /// </para> /// </summary> public static Point operator +(Point pt, Size sz) => Add(pt, sz); /// <summary> /// <para> /// Translates a <see cref='System.Drawing.Point'/> by the negative of a given <see cref='System.Drawing.Size'/> . /// </para> /// </summary> public static Point operator -(Point pt, Size sz) => Subtract(pt, sz); /// <summary> /// <para> /// Compares two <see cref='System.Drawing.Point'/> objects. The result specifies /// whether the values of the <see cref='System.Drawing.Point.X'/> and <see cref='System.Drawing.Point.Y'/> properties of the two <see cref='System.Drawing.Point'/> /// objects are equal. /// </para> /// </summary> public static bool operator ==(Point left, Point right) => left.X == right.X && left.Y == right.Y; /// <summary> /// <para> /// Compares two <see cref='System.Drawing.Point'/> objects. The result specifies whether the values /// of the <see cref='System.Drawing.Point.X'/> or <see cref='System.Drawing.Point.Y'/> properties of the two /// <see cref='System.Drawing.Point'/> /// objects are unequal. /// </para> /// </summary> public static bool operator !=(Point left, Point right) => !(left == right); /// <summary> /// <para> /// Translates a <see cref='System.Drawing.Point'/> by a given <see cref='System.Drawing.Size'/> . /// </para> /// </summary> public static Point Add(Point pt, Size sz) => new Point(unchecked(pt.X + sz.Width), unchecked(pt.Y + sz.Height)); /// <summary> /// <para> /// Translates a <see cref='System.Drawing.Point'/> by the negative of a given <see cref='System.Drawing.Size'/> . /// </para> /// </summary> public static Point Subtract(Point pt, Size sz) => new Point(unchecked(pt.X - sz.Width), unchecked(pt.Y - sz.Height)); /// <summary> /// Converts a PointF to a Point by performing a ceiling operation on /// all the coordinates. /// </summary> public static Point Ceiling(PointF value) => new Point(unchecked((int)Math.Ceiling(value.X)), unchecked((int)Math.Ceiling(value.Y))); /// <summary> /// Converts a PointF to a Point by performing a truncate operation on /// all the coordinates. /// </summary> public static Point Truncate(PointF value) => new Point(unchecked((int)value.X), unchecked((int)value.Y)); /// <summary> /// Converts a PointF to a Point by performing a round operation on /// all the coordinates. /// </summary> public static Point Round(PointF value) => new Point(unchecked((int)Math.Round(value.X)), unchecked((int)Math.Round(value.Y))); /// <summary> /// <para> /// Specifies whether this <see cref='System.Drawing.Point'/> contains /// the same coordinates as the specified <see cref='System.Object'/>. /// </para> /// </summary> public override bool Equals(object obj) => obj is Point && Equals((Point)obj); public bool Equals(Point other) => this == other; /// <summary> /// <para> /// Returns a hash code. /// </para> /// </summary> public override int GetHashCode() => HashHelpers.Combine(X, Y); /// <summary> /// Translates this <see cref='System.Drawing.Point'/> by the specified amount. /// </summary> public void Offset(int dx, int dy) { unchecked { X += dx; Y += dy; } } /// <summary> /// Translates this <see cref='System.Drawing.Point'/> by the specified amount. /// </summary> public void Offset(Point p) => Offset(p.X, p.Y); /// <summary> /// <para> /// Converts this <see cref='System.Drawing.Point'/> /// to a human readable /// string. /// </para> /// </summary> public override string ToString() => "{X=" + X.ToString() + ",Y=" + Y.ToString() + "}"; private static short HighInt16(int n) => unchecked((short)((n >> 16) & 0xffff)); private static short LowInt16(int n) => unchecked((short)(n & 0xffff)); } }
using System; using System.Threading.Tasks; using Cirrious.FluentLayouts.Touch; using Foundation; using Google.SignIn; using MonoTouch.TTTAttributedLabel; using Toggl.Phoebe.Analytics; using Toggl.Phoebe.Logging; using Toggl.Phoebe.Net; using Toggl.Ross.Theme; using Toggl.Ross.Views; using UIKit; using XPlatUtils; namespace Toggl.Ross.ViewControllers { public class SignupViewController : UIViewController, ISignInDelegate, ISignInUIDelegate { private const string Tag = "SignupViewController"; private UIView inputsContainer; private UIView topBorder; private UIView middleBorder; private UIView bottomBorder; private UITextField emailTextField; private UITextField passwordTextField; private UIButton passwordActionButton; private UIButton googleActionButton; private TTTAttributedLabel legalLabel; public SignupViewController () { Title = "SignupTitle".Tr (); } public override void LoadView () { View = new UIView () .Apply (Style.Screen); View.Add (inputsContainer = new UIView ().Apply (Style.Signup.InputsContainer)); inputsContainer.Add (topBorder = new UIView ().Apply (Style.Signup.InputsBorder)); inputsContainer.Add (emailTextField = new UITextField () { Placeholder = "SignupEmailHint".Tr (), AutocapitalizationType = UITextAutocapitalizationType.None, KeyboardType = UIKeyboardType.EmailAddress, ReturnKeyType = UIReturnKeyType.Next, ClearButtonMode = UITextFieldViewMode.Always, ShouldReturn = HandleShouldReturn, } .Apply (Style.Signup.EmailField)); emailTextField.EditingChanged += OnTextFieldEditingChanged; inputsContainer.Add (middleBorder = new UIView ().Apply (Style.Signup.InputsBorder)); inputsContainer.Add (passwordTextField = new PasswordTextField () { Placeholder = "SignupPasswordHint".Tr (), AutocapitalizationType = UITextAutocapitalizationType.None, AutocorrectionType = UITextAutocorrectionType.No, SecureTextEntry = true, ReturnKeyType = UIReturnKeyType.Go, ShouldReturn = HandleShouldReturn, } .Apply (Style.Signup.PasswordField)); passwordTextField.EditingChanged += OnTextFieldEditingChanged; inputsContainer.Add (bottomBorder = new UIView ().Apply (Style.Signup.InputsBorder)); View.Add (passwordActionButton = new UIButton () .Apply (Style.Signup.SignupButton)); passwordActionButton.SetTitle ("SignupSignupButtonText".Tr (), UIControlState.Normal); passwordActionButton.TouchUpInside += OnPasswordActionButtonTouchUpInside; View.Add (googleActionButton = new UIButton () .Apply (Style.Signup.GoogleButton)); googleActionButton.SetTitle ("SignupGoogleButtonText".Tr (), UIControlState.Normal); googleActionButton.TouchUpInside += OnGoogleActionButtonTouchUpInside; View.Add (legalLabel = new TTTAttributedLabel () { Delegate = new LegalLabelDelegate (), } .Apply (Style.Signup.LegalLabel)); SetLegalText (legalLabel); inputsContainer.AddConstraints ( topBorder.AtTopOf (inputsContainer), topBorder.AtLeftOf (inputsContainer), topBorder.AtRightOf (inputsContainer), topBorder.Height ().EqualTo (1f), emailTextField.Below (topBorder), emailTextField.AtLeftOf (inputsContainer, 20f), emailTextField.AtRightOf (inputsContainer, 10f), emailTextField.Height ().EqualTo (42f), middleBorder.Below (emailTextField), middleBorder.AtLeftOf (inputsContainer, 20f), middleBorder.AtRightOf (inputsContainer), middleBorder.Height ().EqualTo (1f), passwordTextField.Below (middleBorder), passwordTextField.AtLeftOf (inputsContainer, 20f), passwordTextField.AtRightOf (inputsContainer), passwordTextField.Height ().EqualTo (42f), bottomBorder.Below (passwordTextField), bottomBorder.AtLeftOf (inputsContainer), bottomBorder.AtRightOf (inputsContainer), bottomBorder.AtBottomOf (inputsContainer), bottomBorder.Height ().EqualTo (1f) ); inputsContainer.SubviewsDoNotTranslateAutoresizingMaskIntoConstraints (); View.AddConstraints ( inputsContainer.AtTopOf (View, 80f), inputsContainer.AtLeftOf (View), inputsContainer.AtRightOf (View), passwordActionButton.Below (inputsContainer, 20f), passwordActionButton.AtLeftOf (View), passwordActionButton.AtRightOf (View), passwordActionButton.Height ().EqualTo (60f), googleActionButton.Below (passwordActionButton, 5f), googleActionButton.AtLeftOf (View), googleActionButton.AtRightOf (View), googleActionButton.Height ().EqualTo (60f), legalLabel.AtBottomOf (View, 30f), legalLabel.AtLeftOf (View, 40f), legalLabel.AtRightOf (View, 40f) ); View.SubviewsDoNotTranslateAutoresizingMaskIntoConstraints (); ResetSignupButtonState (); } public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); SignIn.SharedInstance.Delegate = this; SignIn.SharedInstance.UIDelegate = this; } public override void ViewDidAppear (bool animated) { base.ViewDidAppear (animated); ServiceContainer.Resolve<ITracker> ().CurrentScreen = "Signup"; } private void OnTextFieldEditingChanged (object sender, EventArgs e) { ResetSignupButtonState (); } private void ResetSignupButtonState () { var enabled = !IsAuthenticating && !String.IsNullOrWhiteSpace (emailTextField.Text) && emailTextField.Text.Contains ("@") && !String.IsNullOrWhiteSpace (passwordTextField.Text) && passwordTextField.Text.Length >= 6; passwordActionButton.Enabled = enabled; } private static void SetLegalText (TTTAttributedLabel label) { var template = "SignupLegal".Tr (); var arg0 = "SignupToS".Tr (); var arg1 = "SignupPrivacy".Tr (); var arg0idx = String.Format (template, "{0}", arg1).IndexOf ("{0}", StringComparison.Ordinal); var arg1idx = String.Format (template, arg0, "{1}").IndexOf ("{1}", StringComparison.Ordinal); label.Text = (NSString)String.Format (template, arg0, arg1); label.AddLinkToURL ( new NSUrl (Phoebe.Build.TermsOfServiceUrl.ToString ()), new NSRange (arg0idx, arg0.Length)); label.AddLinkToURL ( new NSUrl (Phoebe.Build.PrivacyPolicyUrl.ToString ()), new NSRange (arg1idx, arg1.Length)); } private bool HandleShouldReturn (UITextField textField) { if (textField == emailTextField) { passwordTextField.BecomeFirstResponder (); } else if (textField == passwordTextField) { textField.ResignFirstResponder (); TryPasswordSignup (); } else { return false; } return true; } private void OnPasswordActionButtonTouchUpInside (object sender, EventArgs e) { TryPasswordSignup (); } private void OnGoogleActionButtonTouchUpInside (object sender, EventArgs e) { // Automatically sign in the user. SignIn.SharedInstance.SignInUser (); } public void DidSignIn (SignIn signIn, GoogleUser user, NSError error) { InvokeOnMainThread (async delegate { await AuthWithGoogleTokenAsync (signIn, user, error); }); } private async void TryPasswordSignup () { if (IsAuthenticating) { return; } IsAuthenticating = true; try { var authManager = ServiceContainer.Resolve<AuthManager> (); var authRes = await authManager.SignupAsync (emailTextField.Text, passwordTextField.Text); if (authRes != AuthResult.Success) { AuthErrorAlert.Show (this, emailTextField.Text, authRes, AuthErrorAlert.Mode.Signup); } } finally { IsAuthenticating = false; } } public async Task AuthWithGoogleTokenAsync (SignIn signIn, GoogleUser user, Foundation.NSError error) { try { if (error == null) { IsAuthenticating = true; var token = user.Authentication.AccessToken; var authManager = ServiceContainer.Resolve<AuthManager> (); var authRes = await authManager.SignupWithGoogleAsync (token); // No need to keep the users Google account access around anymore signIn.DisconnectUser (); if (authRes != AuthResult.Success) { var email = user.Profile.Email; AuthErrorAlert.Show (this, email, authRes, AuthErrorAlert.Mode.Signup, googleAuth: true); } } else if (error.Code != -5) { // Cancel error code. new UIAlertView ( "WelcomeGoogleErrorTitle".Tr (), "WelcomeGoogleErrorMessage".Tr (), null, "WelcomeGoogleErrorOk".Tr (), null).Show (); } } catch (InvalidOperationException ex) { var log = ServiceContainer.Resolve<ILogger> (); log.Info (Tag, ex, "Failed to authenticate (G+) the user."); } finally { IsAuthenticating = false; } } private bool isAuthenticating; private bool IsAuthenticating { get { return isAuthenticating; } set { isAuthenticating = value; emailTextField.Enabled = !isAuthenticating; passwordTextField.Enabled = !isAuthenticating; passwordActionButton.Enabled = !isAuthenticating; googleActionButton.Enabled = !isAuthenticating; passwordActionButton.SetTitle ("SignupSignupProgressText".Tr (), UIControlState.Disabled); } } private class LegalLabelDelegate : TTTAttributedLabelDelegate { public override void DidSelectLinkWithURL (TTTAttributedLabel label, NSUrl url) { var stringUrl = url.AbsoluteString; var tosUrl = Phoebe.Build.TermsOfServiceUrl.ToString (); var privacyUrl = Phoebe.Build.PrivacyPolicyUrl.ToString (); if (stringUrl.Equals (tosUrl) || stringUrl.Equals (privacyUrl)) { url = new NSUrl (String.Format ("{0}?simple=true", stringUrl)); } WebViewController controller = new WebViewController (url); label.Window.RootViewController.PresentViewController (controller, true, null); } } } }
using DotNetProjects.IndexedLinq; using GeoCoordinatePortable; using KellermanSoftware.CompareNetObjects; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using OCM.API.Client; using OCM.API.Common; using OCM.API.Common.Model; using OCM.Import.Misc; using OCM.Import.Providers; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; namespace OCM.Import { /*Import Reporting: * before performing import, prepare report of items to be added/updated, ignored or delisted. * for each item, detail the reason for the categorisation and related items from the import * */ public enum ImportItemStatus { Added, Updated, Ignored, Delisted, IsDuplicate, LowQuality, MergeSource } public class ImportItem { public ImportItemStatus Status { get; set; } public string Comment { get; set; } /// <summary> /// If true, item is from the data source, otherwise item is target in OCM to be added/updated. /// </summary> public bool IsSourceItem { get; set; } public ChargePoint POI { get; set; } public List<ImportItem> RelatedItems { get; set; } public ImportItem() { RelatedItems = new List<ImportItem>(); } } public class ImportReport { public BaseImportProvider ProviderDetails { get; set; } public List<ImportItem> ImportItems { get; set; } public List<ChargePoint> Added { get; set; } public List<ChargePoint> Updated { get; set; } public List<ChargePoint> Unchanged { get; set; } public List<ChargePoint> LowDataQuality { get; set; } public List<ChargePoint> Delisted { get; set; } public List<ChargePoint> Duplicates { get; set; } public string Log { get; set; } public bool IsSuccess { get; set; } = false; public ImportReport() { ImportItems = new List<ImportItem>(); Added = new List<ChargePoint>(); Updated = new List<ChargePoint>(); Unchanged = new List<ChargePoint>(); LowDataQuality = new List<ChargePoint>(); Delisted = new List<ChargePoint>(); Duplicates = new List<ChargePoint>(); } } public class ImportProcessSettings { public ExportType ExportType { get; set; } public string DefaultDataPath { get; set; } public string ApiIdentifier { get; set; } public string ApiSessionToken { get; set; } public bool FetchLiveData { get; set; } = true; public bool CacheInputData { get; set; } = true; public bool FetchExistingFromAPI { get; set; } = false; public bool PerformDeduplication { get; set; } = true; public string ProviderName { get; set; } } public class ImportManager { public const int DUPLICATE_DISTANCE_METERS = 200; public bool ImportUpdatesOnly { get; set; } public bool IsSandboxedAPIMode { get; set; } public string GeonamesAPIUserName { get; set; } public string TempFolder { get; set; } private GeolocationCacheManager geolocationCacheManager = null; private AddressLookupCacheManager addressLookupCacheManager = null; public string ImportLog { get; set; } public bool UseDataModelComparison { get; set; } = false; private OCMClient _client = null; private ImportSettings _settings; private Microsoft.Extensions.Logging.ILogger _log; public ImportManager(ImportSettings settings, Microsoft.Extensions.Logging.ILogger log = null) { _settings = settings; _log = log; GeonamesAPIUserName = "openchargemap"; TempFolder = _settings.TempFolderPath; _client = new OCMClient(_settings.MasterAPIBaseUrl, _settings.ImportUserAPIKey, null, settings.ImportUserAgent); geolocationCacheManager = new GeolocationCacheManager(TempFolder); geolocationCacheManager.GeonamesAPIUserName = GeonamesAPIUserName; geolocationCacheManager.LoadCache(); addressLookupCacheManager = new AddressLookupCacheManager(TempFolder, _client); } public OCMClient OCMClient => _client; /** * Generic Import Process Provider Properties Import Method Import URL/Path Import Frequency IsMaster Fetch Latest Data For each item Check If Exists or Strong Duplicate, Get ID If New, Add if Exists Then Prepare update, if provider supports live status, set that What if item updated manually on OCM? Send Update End Loop Log Exceptions Log Count of Items Added or Modified Way to remove item (or log items) which no longer exist in data source? * */ public List<IImportProvider> GetImportProviders(List<OCM.API.Common.Model.DataProvider> AllDataProviders) { List<IImportProvider> providers = new List<IImportProvider>(); providers.Add(new ImportProvider_UKChargePointRegistry()); //providers.Add(new ImportProvider_CarStations()); providers.Add(new ImportProvider_Mobie()); if (_settings.ApiKeys.TryGetValue("afdc_energy_gov", out var afdcKey)) { providers.Add(new ImportProvider_AFDC(afdcKey)); } providers.Add(new ImportProvider_ESB_eCars()); if (_settings.ApiKeys.TryGetValue("addenergie_le", out var ae_le)) { providers.Add(new ImportProvider_AddEnergie(ImportProvider_AddEnergie.NetworkType.LeCircuitElectrique, ae_le)); } if (_settings.ApiKeys.TryGetValue("addenergie_re", out var ae_re)) { providers.Add(new ImportProvider_AddEnergie(ImportProvider_AddEnergie.NetworkType.ReseauVER, ae_re)); } if (_settings.ApiKeys.TryGetValue("nobil_no", out var nobil)) { providers.Add(new ImportProvider_NobilDotNo(nobil)); } //providers.Add(new ImportProvider_OplaadpalenNL()); providers.Add(new ImportProvider_ICAEN()); providers.Add(new ImportProvider_DataGouvFr()); providers.Add(new ImportProvider_GenericExcel()); providers.Add(new ImportProvider_Bundesnetzagentur()); //populate full data provider details for each import provider foreach (var provider in providers) { var providerDetails = (BaseImportProvider)provider; var dataProviderDetails = AllDataProviders.FirstOrDefault(p => p.ID == providerDetails.DataProviderID); if (dataProviderDetails != null) { providerDetails.DefaultDataProvider = dataProviderDetails; } } return providers; } public async Task<bool> PerformImportProcessing(ImportProcessSettings settings) { var credentials = GetAPISessionCredentials(settings.ApiIdentifier, settings.ApiSessionToken); var coreRefData = await _client.GetCoreReferenceDataAsync(); var providers = GetImportProviders(coreRefData.DataProviders); foreach (var provider in providers) { if (settings.ProviderName == null || settings.ProviderName.ToLower() == provider.GetProviderName().ToLower()) { var result = await PerformImport(settings, credentials, coreRefData, provider); Log(result.Log); return result.IsSuccess; } } return false; ; } public async Task<List<ChargePoint>> DeDuplicateList(List<ChargePoint> cpList, bool updateDuplicate, CoreReferenceData coreRefData, ImportReport report, bool allowDupeWithDifferentOperator = false, bool fetchExistingFromAPI = false, int dupeDistance = DUPLICATE_DISTANCE_METERS) { var stopWatch = new Stopwatch(); stopWatch.Start(); var poiManager = new POIManager(); //get list of all current POIs (in relevant countries) including most delisted ones int[] countryIds = (from poi in cpList where poi.AddressInfo.CountryID != null select (int)poi.AddressInfo.CountryID).Distinct().ToArray(); APIRequestParams filters = new APIRequestParams { CountryIDs = countryIds, MaxResults = 1000000, EnableCaching = true, SubmissionStatusTypeID = 0 }; IEnumerable<ChargePoint> masterList = new List<ChargePoint>(); if (fetchExistingFromAPI) { // fetch from API masterList = await _client.GetPOIListAsync(new SearchFilters { CountryIDs = countryIds, MaxResults = 1000000, EnableCaching = true, SubmissionStatusTypeIDs = new int[0] }); } else { // use local database masterList = await poiManager.GetPOIListAsync(filters); } /* var spec = new IndexSpecification<ChargePoint>() .Add(i => i.DataProviderID) .Add(i => i.DataProvidersReference) ; var masterList = new IndexSet<ChargePoint>(masterListCollection, spec); */ List<ChargePoint> masterListCopy = new List<ChargePoint>(); foreach (var tmp in masterList) { //fully copy of master list item so we have before/after masterListCopy.Add(JsonConvert.DeserializeObject<ChargePoint>(JsonConvert.SerializeObject(tmp))); } //if we failed to get a master list, quit with no result if (masterList.Count() == 0) return new List<ChargePoint>(); List<ChargePoint> duplicateList = new List<ChargePoint>(); List<ChargePoint> updateList = new List<ChargePoint>(); ChargePoint previousCP = null; //for each item to be imported, deduplicate by adding to updateList only the items which we don't already haves var cpListSortedByPos = cpList.OrderBy(c => c.AddressInfo.Latitude).ThenBy(c => c.AddressInfo.Longitude); int poiProcessed = 0; int totalPOI = cpListSortedByPos.Count(); Stopwatch dupeIdentWatch = new Stopwatch(); dupeIdentWatch.Start(); foreach (var item in cpListSortedByPos) { var itemGeoPos = new GeoCoordinate(item.AddressInfo.Latitude, item.AddressInfo.Longitude); //item is duplicate if we already seem to have it based on Data Providers reference or approx position match var dupeList = masterList.Where(c => ( // c.DataProvider != null && c.DataProviderID == item.DataProviderID && c.DataProvidersReference == item.DataProvidersReference) || (c.AddressInfo.Title == item.AddressInfo.Title && c.AddressInfo.AddressLine1 == item.AddressInfo.AddressLine1 && c.AddressInfo.Postcode == item.AddressInfo.Postcode) || (GeoManager.IsClose(c.AddressInfo.Latitude, c.AddressInfo.Longitude, item.AddressInfo.Latitude, item.AddressInfo.Longitude, 2) && new GeoCoordinate(c.AddressInfo.Latitude, c.AddressInfo.Longitude).GetDistanceTo(itemGeoPos) < DUPLICATE_DISTANCE_METERS) //meters distance apart ); if (dupeList.Any()) { if (updateDuplicate) { //if updating duplicates, get exact matching duplicate based on provider reference and update/merge with this item to update status/merge properties var updatedItem = dupeList.FirstOrDefault(d => d.DataProviderID == (item.DataProvider != null ? item.DataProvider.ID : item.DataProviderID) && d.DataProvidersReference == item.DataProvidersReference); if (updatedItem != null) { //only merge/update from live published items if (updatedItem.SubmissionStatus.IsLive == (bool?)true || updatedItem.SubmissionStatus.ID == (int)StandardSubmissionStatusTypes.Delisted_RemovedByDataProvider || updatedItem.SubmissionStatus.ID == (int)StandardSubmissionStatusTypes.Delisted_NotPublicInformation) { //item is an exact match from same data provider //overwrite existing with imported data (use import as master) //updatedItem = poiManager.PreviewPopulatedPOIFromModel(updatedItem); MergeItemChanges(item, updatedItem, false); updateList.Add(updatedItem); } } if (updatedItem == null) { //duplicates are not exact match //TODO: resolve whether imported data should change duplicate //merge new properties from imported item //if (item.StatusType != null) updatedItem.StatusType = item.StatusType; //updateList.Add(updatedItem); } } //item has one or more likely duplicates, add it to list of items to remove duplicateList.Add(item); } //mark item as duplicate if location/title exactly matches previous entry or lat/long is within DuplicateDistance meters if (previousCP != null) { //this branch is the most expensive part of dedupe: if (IsDuplicateLocation(item, previousCP, true)) { if (!duplicateList.Contains(item)) { if (allowDupeWithDifferentOperator && item.OperatorID != previousCP.OperatorID) { Log("Duplicated allowed due to different operator:" + item.AddressInfo.Title); } else { Log("Duplicated item removed:" + item.AddressInfo.Title); duplicateList.Add(item); } } } } previousCP = item; poiProcessed++; if (poiProcessed % 300 == 0) { System.Diagnostics.Debug.WriteLine("Deduplication: " + poiProcessed + " processed of " + totalPOI); } } dupeIdentWatch.Stop(); Log("De-dupe pass took " + dupeIdentWatch.Elapsed.TotalSeconds + " seconds. " + (dupeIdentWatch.Elapsed.TotalMilliseconds / cpList.Count) + "ms per item."); //remove duplicates from list to apply foreach (var dupe in duplicateList) { cpList.Remove(dupe); } Log("Duplicates removed from import:" + duplicateList.Count); //add updated items (replace duplicates with property changes) foreach (var updatedItem in updateList) { if (!cpList.Contains(updatedItem)) { cpList.Add(updatedItem); } } Log("Updated items to import:" + updateList.Count); //populate missing location info from geolocation cache if possible Stopwatch geoWatch = new Stopwatch(); geoWatch.Start(); PopulateLocationFromGeolocationCache(cpList, coreRefData); geoWatch.Stop(); Log("Populate Country from Lat/Long took " + geoWatch.Elapsed.TotalSeconds + " seconds. " + (geoWatch.Elapsed.TotalMilliseconds / cpList.Count) + "ms per item."); //final pass to catch duplicates present in data source, mark additional items as Delisted Duplicate so we have a record for them var submissionStatusDelistedDupe = coreRefData.SubmissionStatusTypes.First(s => s.ID == 1001); //delisted duplicate previousCP = null; //sort current cp list by position again cpListSortedByPos = cpList.OrderBy(c => c.AddressInfo.Latitude).ThenBy(c => c.AddressInfo.Longitude); //mark any duplicates in final list as delisted duplicates (submitted to api) foreach (var cp in cpListSortedByPos) { bool isDuplicate = false; if (previousCP != null) { isDuplicate = IsDuplicateLocation(cp, previousCP, false); if (isDuplicate) { cp.SubmissionStatus = submissionStatusDelistedDupe; cp.SubmissionStatusTypeID = submissionStatusDelistedDupe.ID; if (previousCP.ID > 0) { if (cp.GeneralComments == null) cp.GeneralComments = ""; cp.GeneralComments += " [Duplicate of OCM-" + previousCP.ID + "]"; cp.ParentChargePointID = previousCP.ID; } } } if (!isDuplicate) { previousCP = cp; } } report.Added = cpListSortedByPos.Where(cp => cp.ID == 0).ToList(); report.Updated = cpListSortedByPos.Where(cp => cp.ID > 0).ToList(); report.Duplicates = duplicateList; //TODO: add additional pass of duplicates from above //determine which POIs in our master list are no longer referenced in the import report.Delisted = masterList.Where(cp => cp.DataProviderID == report.ProviderDetails.DataProviderID && cp.SubmissionStatus != null && (cp.SubmissionStatus.IsLive == true || cp.SubmissionStatusTypeID == (int)StandardSubmissionStatusTypes.Imported_UnderReview) && !cpListSortedByPos.Any(master => master.ID == cp.ID) && !report.Duplicates.Any(master => master.ID == cp.ID) && cp.UserComments == null && cp.MediaItems == null).ToList(); //safety check to ensure we're not delisting items just because we have incomplete import data: if (cpList.Count < 50)// || (report.Delisted.Count > cpList.Count)) { report.Delisted = new List<ChargePoint>(); } //determine list of low quality POIs (incomplete address info etc) report.LowDataQuality = new List<ChargePoint>(); report.LowDataQuality.AddRange(GetLowDataQualityPOIs(report.Added)); report.LowDataQuality.AddRange(GetLowDataQualityPOIs(report.Updated)); Log("Removing " + report.LowDataQuality.Count + " low quality POIs from added/updated"); //remove references in added/updated to any low quality POIs foreach (var p in report.LowDataQuality) { report.Added.Remove(p); } foreach (var p in report.LowDataQuality) { report.Updated.Remove(p); } //remove updates which only change datelaststatusupdate var updatesToIgnore = new List<ChargePoint>(); foreach (var poi in report.Updated) { var origPOI = masterListCopy.FirstOrDefault(p => p.ID == poi.ID); // hydrate POI with all of its associated extended properties var hydratedPoi = UseDataModelComparison ? poiManager.PreviewPopulatedPOIFromModel(poi, coreRefData) : DehydratePOI(poi, coreRefData); var differences = poiManager.CheckDifferences(origPOI, hydratedPoi); differences.RemoveAll(d => d.Context == ".MetadataValues"); differences.RemoveAll(d => d.Context == ".DateLastStatusUpdate"); differences.RemoveAll(d => d.Context == ".DateLastConfirmed"); differences.RemoveAll(d => d.Context == ".DateLastVerified"); differences.RemoveAll(d => d.Context == ".UUID"); differences.RemoveAll(d => d.Context == ".LevelOfDetail"); differences.RemoveAll(d => d.Context == "DataProvider.DateLastImported"); differences.RemoveAll(d => d.Context == ".IsRecentlyVerified"); differences.RemoveAll(d => d.Context == ".DateLastVerified"); differences.RemoveAll(d => d.Context == ".UserComments"); differences.RemoveAll(d => d.Context == ".MediaItems"); if (!differences.Any()) { updatesToIgnore.Add(poi); } else { //differences exist CompareLogic compareLogic = new CompareLogic(); compareLogic.Config.MaxDifferences = 100; compareLogic.Config.IgnoreObjectTypes = false; compareLogic.Config.IgnoreUnknownObjectTypes = true; compareLogic.Config.CompareChildren = true; ComparisonResult result = compareLogic.Compare(origPOI, hydratedPoi); var diffReport = new KellermanSoftware.CompareNetObjects.Reports.UserFriendlyReport(); result.Differences.RemoveAll(d => d.PropertyName == ".MetadataValues"); result.Differences.RemoveAll(d => d.PropertyName == ".DateLastStatusUpdate"); result.Differences.RemoveAll(d => d.PropertyName == ".UUID"); result.Differences.RemoveAll(d => d.PropertyName == "DataProvider.DateLastImported"); result.Differences.RemoveAll(d => d.PropertyName == ".IsRecentlyVerified"); result.Differences.RemoveAll(d => d.PropertyName == ".DateLastVerified"); result.Differences.RemoveAll(d => d.PropertyName == ".UserComments"); result.Differences.RemoveAll(d => d.PropertyName == ".MediaItems"); System.Diagnostics.Debug.WriteLine("Difference:" + diffReport.OutputString(result.Differences)); if (!result.Differences.Any()) { updatesToIgnore.Add(poi); } } } foreach (var p in updatesToIgnore) { if (report.Unchanged == null) report.Unchanged = new List<ChargePoint>(); report.Unchanged.Add(p); report.Updated.Remove(p); } //TODO: if POi is a duplicate ensure imported data provider reference/URL is included as reference metadata in OCM's version of the POI stopWatch.Stop(); Log("Deduplicate List took " + stopWatch.Elapsed.TotalSeconds + " seconds"); //return final processed list ready for applying as insert/updates return cpListSortedByPos.ToList(); } /// <summary> /// For the given POI, populate extended navigation properties (DataProvider etc) based on current IDs /// </summary> /// <param name="poi"></param> /// <param name="refData"></param> /// <returns></returns> public ChargePoint DehydratePOI(ChargePoint poi, CoreReferenceData refData) { poi.DataProvider = refData.DataProviders.FirstOrDefault(i => i.ID == poi.DataProviderID); poi.OperatorInfo = refData.Operators.FirstOrDefault(i => i.ID == poi.OperatorID); poi.UsageType = refData.UsageTypes.FirstOrDefault(i => i.ID == poi.UsageTypeID); foreach (var c in poi.Connections) { c.ConnectionType = refData.ConnectionTypes.FirstOrDefault(i => i.ID == c.ConnectionTypeID); c.CurrentType = refData.CurrentTypes.FirstOrDefault(i => i.ID == c.CurrentTypeID); c.Level = refData.ChargerTypes.FirstOrDefault(i => i.ID == c.LevelID); c.StatusType = refData.StatusTypes.FirstOrDefault(i => i.ID == c.StatusTypeID); } return poi; } public List<ChargePoint> MergeDuplicatePOIEquipment(List<ChargePoint> importedPOIList) { var stopWatch = new Stopwatch(); stopWatch.Start(); List<ChargePoint> mergedPOIList = new List<ChargePoint>(); List<ChargePoint> tmpMergedPOIs = new List<ChargePoint>(); foreach (var poi in importedPOIList) { if (!tmpMergedPOIs.Contains(poi)) { int matchCount = 0; foreach (var otherPoi in importedPOIList.Where(p => p != poi)) { bool addressIsSame = (poi.AddressInfo.AddressLine1 == otherPoi.AddressInfo.AddressLine1 && poi.AddressInfo.AddressLine2 == otherPoi.AddressInfo.AddressLine2 && poi.AddressInfo.StateOrProvince == otherPoi.AddressInfo.StateOrProvince ); //if address matches or lat/long matches then merge the poi if (addressIsSame || poi.AddressInfo.Latitude == otherPoi.AddressInfo.Latitude && poi.AddressInfo.Longitude == otherPoi.AddressInfo.Longitude) { if (poi.OperatorID != otherPoi.OperatorID) { Log("Merged POI has different Operator: " + poi.AddressInfo.ToString()); } else { matchCount++; tmpMergedPOIs.Add(otherPoi); //track which POIs will now be discarded //add equipment info from merged poi to our main poi if (otherPoi.Connections != null) { if (poi.Connections == null) poi.Connections = new List<ConnectionInfo>(); poi.Connections.AddRange(otherPoi.Connections); } } } } if (matchCount > 0) { Log("POI equipment merged from " + matchCount + " other POIs. " + poi.AddressInfo.ToString()); } } mergedPOIList.Add(poi); } stopWatch.Stop(); Log("MergeDuplicatePOIEquipmentList took " + stopWatch.Elapsed.TotalSeconds + " seconds"); return mergedPOIList; } private void Log(string message) { if (_log != null) { _log.LogInformation(message); } else { this.ImportLog += message + "\r\n"; System.Diagnostics.Debug.WriteLine(message); } } /// <summary> /// Given a list of POIs, returns list of those which are low data quality based on their /// content (address etc) /// </summary> /// <param name="allPOIs"> </param> /// <returns> </returns> public List<ChargePoint> GetLowDataQualityPOIs(List<ChargePoint> allPOIs) { return allPOIs.Where(p => p.AddressInfo == null || p.AddressInfo != null && (String.IsNullOrEmpty(p.AddressInfo.Title) || String.IsNullOrEmpty(p.AddressInfo.AddressLine1) && String.IsNullOrEmpty(p.AddressInfo.Postcode) || (p.AddressInfo.CountryID == null && p.AddressInfo.Country == null)) ).ToList(); } /// <summary> /// Determine if 2 CPs have the same location details or very close lat/lng /// </summary> /// <param name="current"> </param> /// <param name="previous"> </param> /// <returns> </returns> public bool IsDuplicateLocation(ChargePoint current, ChargePoint previous, bool compareTitle) { //is duplicate item if latlon is exact match for previous item or latlon is within few meters of previous item if ( (GeoManager.IsClose(current.AddressInfo.Latitude, current.AddressInfo.Longitude, previous.AddressInfo.Latitude, previous.AddressInfo.Longitude) && new GeoCoordinate(current.AddressInfo.Latitude, current.AddressInfo.Longitude).GetDistanceTo(new GeoCoordinate(previous.AddressInfo.Latitude, previous.AddressInfo.Longitude)) < DUPLICATE_DISTANCE_METERS) //meters distance apart || (compareTitle && (previous.AddressInfo.Title == current.AddressInfo.Title)) //&& previous.AddressInfo.AddressLine1 == current.AddressInfo.AddressLine1 || (previous.AddressInfo.Latitude == current.AddressInfo.Latitude && previous.AddressInfo.Longitude == current.AddressInfo.Longitude) || (current.DataProvidersReference != null && current.DataProvidersReference.Length > 0 && previous.DataProvidersReference == current.DataProvidersReference) || (previous.AddressInfo.ToString() == current.AddressInfo.ToString()) ) { int dataProviderId = (previous.DataProvider != null ? previous.DataProvider.ID : (int)previous.DataProviderID); if (previous.AddressInfo.Latitude == current.AddressInfo.Latitude && previous.AddressInfo.Longitude == current.AddressInfo.Longitude) { Log(current.AddressInfo.ToString() + " is Duplicate due to exact equal latlon to [Data Provider " + dataProviderId + "]" + previous.AddressInfo.ToString()); } else if (new GeoCoordinate(current.AddressInfo.Latitude, current.AddressInfo.Longitude).GetDistanceTo(new GeoCoordinate(previous.AddressInfo.Latitude, previous.AddressInfo.Longitude)) < DUPLICATE_DISTANCE_METERS) { Log(current.AddressInfo.ToString() + " is Duplicate due to close proximity to [Data Provider " + dataProviderId + "]" + previous.AddressInfo.ToString()); } else if (previous.AddressInfo.Title == current.AddressInfo.Title && previous.AddressInfo.AddressLine1 == current.AddressInfo.AddressLine1 && previous.AddressInfo.Postcode == current.AddressInfo.Postcode) { Log(current.AddressInfo.ToString() + " is Duplicate due to same Title and matching AddressLine1 and Postcode [Data Provider " + dataProviderId + "]" + previous.AddressInfo.ToString()); } return true; } else { return false; } } public bool MergeItemChanges(ChargePoint sourceItem, ChargePoint destItem, bool statusOnly) { //TODO: move to POIManager or a common base? bool hasDifferences = true; //var diffs = GetDifferingProperties(sourceItem, destItem); //merge changes in sourceItem into destItem, preserving destItem ID's if (!statusOnly) { //update addressinfo destItem.AddressInfo.Title = sourceItem.AddressInfo.Title; destItem.AddressInfo.AddressLine1 = sourceItem.AddressInfo.AddressLine1; destItem.AddressInfo.AddressLine2 = sourceItem.AddressInfo.AddressLine2; destItem.AddressInfo.Town = sourceItem.AddressInfo.Town; destItem.AddressInfo.StateOrProvince = sourceItem.AddressInfo.StateOrProvince; destItem.AddressInfo.Postcode = sourceItem.AddressInfo.Postcode; destItem.AddressInfo.RelatedURL = sourceItem.AddressInfo.RelatedURL; if (sourceItem.AddressInfo.Country != null) destItem.AddressInfo.Country = sourceItem.AddressInfo.Country; destItem.AddressInfo.CountryID = sourceItem.AddressInfo.CountryID; destItem.AddressInfo.AccessComments = sourceItem.AddressInfo.AccessComments; destItem.AddressInfo.ContactEmail = sourceItem.AddressInfo.ContactEmail; destItem.AddressInfo.ContactTelephone1 = sourceItem.AddressInfo.ContactTelephone1; destItem.AddressInfo.ContactTelephone2 = sourceItem.AddressInfo.ContactTelephone2; #pragma warning disable 0612 destItem.AddressInfo.GeneralComments = sourceItem.AddressInfo.GeneralComments; #pragma warning restore 0612 destItem.AddressInfo.Latitude = sourceItem.AddressInfo.Latitude; destItem.AddressInfo.Longitude = sourceItem.AddressInfo.Longitude; //update general destItem.DataProvider = sourceItem.DataProvider; destItem.DataProviderID = sourceItem.DataProviderID; destItem.DataProvidersReference = sourceItem.DataProvidersReference; destItem.OperatorID = sourceItem.OperatorID; destItem.OperatorInfo = sourceItem.OperatorInfo; destItem.OperatorsReference = sourceItem.OperatorsReference; destItem.UsageType = sourceItem.UsageType; destItem.UsageTypeID = sourceItem.UsageTypeID; destItem.UsageCost = sourceItem.UsageCost; destItem.NumberOfPoints = sourceItem.NumberOfPoints; destItem.GeneralComments = sourceItem.GeneralComments; destItem.DateLastConfirmed = sourceItem.DateLastConfirmed; //destItem.DateLastStatusUpdate = sourceItem.DateLastStatusUpdate; destItem.DatePlanned = sourceItem.DatePlanned; //update connections //TODO:: update connections var connDeleteList = new List<ConnectionInfo>(); if (sourceItem.Connections != null) { if (destItem.Connections == null) { destItem.Connections = sourceItem.Connections; } else { var equipmentIndex = 0; foreach (var conn in sourceItem.Connections) { //imported equipment info is replaced in order they appear in the import //TODO: if the connection type/power rating has changed we need to create new equipment // rather than update existing as this is probably a physically different equipment installation ConnectionInfo existingConnection = null; existingConnection = destItem.Connections.FirstOrDefault(d => d.Reference == conn.Reference && !String.IsNullOrEmpty(conn.Reference)); if (existingConnection == null) { if (destItem.Connections != null && destItem.Connections.Count >= (equipmentIndex + 1)) { existingConnection = destItem.Connections[equipmentIndex]; } equipmentIndex++; } if (existingConnection != null) { //update existing- updates can be either object base reference data or use ID values existingConnection.ConnectionType = conn.ConnectionType; existingConnection.ConnectionTypeID = conn.ConnectionTypeID; existingConnection.Quantity = conn.Quantity; existingConnection.LevelID = conn.LevelID; existingConnection.Level = conn.Level; existingConnection.Reference = conn.Reference; existingConnection.StatusTypeID = conn.StatusTypeID; existingConnection.StatusType = conn.StatusType; existingConnection.Voltage = conn.Voltage; existingConnection.Amps = conn.Amps; existingConnection.PowerKW = conn.PowerKW; existingConnection.Comments = conn.Comments; existingConnection.CurrentType = conn.CurrentType; existingConnection.CurrentTypeID = conn.CurrentTypeID; } else { //add new destItem.Connections.Add(conn); } } } } } if (sourceItem.StatusType != null) destItem.StatusType = sourceItem.StatusType; return hasDifferences; } public async Task<ImportReport> PerformImport(ImportProcessSettings settings, APICredentials credentials, CoreReferenceData coreRefData, IImportProvider provider) { var p = ((BaseImportProvider)provider); p.ExportType = settings.ExportType; var outputPath = settings.DefaultDataPath; ImportReport resultReport = new ImportReport(); resultReport.ProviderDetails = p; try { bool loadOK = false; if (p.ImportInitialisationRequired && p is IImportProviderWithInit) { ((IImportProviderWithInit)provider).InitImportProvider(); } if (string.IsNullOrEmpty(p.InputPath)) { p.InputPath = Path.Combine(settings.DefaultDataPath, "cache_" + p.ProviderName + ".dat"); } if (settings.FetchLiveData && p.IsAutoRefreshed && !String.IsNullOrEmpty(p.AutoRefreshURL)) { Log("Loading input data from URL.."); loadOK = p.LoadInputFromURL(p.AutoRefreshURL); } else { if (p.IsStringData && !p.UseCustomReader) { Log("Loading input data from file.."); loadOK = p.LoadInputFromFile(p.InputPath); } else { //binary streams pass as OK by default loadOK = true; } } if (!loadOK) { //failed to load Log("Failed to load input data."); throw new Exception("Failed to fetch input data"); } else { if (settings.FetchLiveData && settings.CacheInputData) { //save input data p.SaveInputFile(p.InputPath); } } List<ChargePoint> duplicatesList = new List<ChargePoint>(); Log("Processing input.."); var list = provider.Process(coreRefData); int numAdded = 0; int numUpdated = 0; if (list.Count > 0) { if (list.Any(f => f.AddressCleaningRequired == true)) { await addressLookupCacheManager.LoadCache(); // need to perform address lookups foreach (var i in list) { if (i.AddressCleaningRequired == true) { await CleanPOIAddressInfo(i); } } await addressLookupCacheManager.SaveCache(); } if (p.MergeDuplicatePOIEquipment) { Log("Merging Equipment from Duplicate POIs"); list = MergeDuplicatePOIEquipment(list); } if (!p.IncludeInvalidPOIs) { Log("Cleaning invalid POIs"); var invalidPOIs = new List<ChargePoint>(); foreach (var poi in list) { if (!BaseImportProvider.IsPOIValidForImport(poi)) { invalidPOIs.Add(poi); } } foreach (var poi in invalidPOIs) { list.Remove(poi); } } GC.Collect(); List<ChargePoint> finalList = new List<ChargePoint>(); if (settings.PerformDeduplication) { Log("De-Deuplicating list (" + p.ProviderName + ":: " + list.Count + " Items).."); //de-duplicate and clean list based on existing data finalList = await DeDuplicateList(list, true, coreRefData, resultReport, p.AllowDuplicatePOIWithDifferentOperator, settings.FetchExistingFromAPI, DUPLICATE_DISTANCE_METERS); } else { //skip deduplication finalList = list.ToList(); } // remove items with no changes if (resultReport.Unchanged.Any()) { foreach (var r in resultReport.Unchanged) { finalList.Remove(r); } } if (ImportUpdatesOnly) { finalList = finalList.Where(l => l.ID > 0).ToList(); } GC.Collect(); //export/apply updates if (p.ExportType == ExportType.XML) { Log("Exporting XML.."); //output xml p.ExportXMLFile(finalList, outputPath + p.OutputNamePrefix + ".xml"); } if (p.ExportType == ExportType.CSV) { Log("Exporting CSV.."); //output csv p.ExportCSVFile(finalList, outputPath + p.OutputNamePrefix + ".csv"); } if (p.ExportType == ExportType.JSON) { Log("Exporting JSON.."); //output json p.ExportJSONFile(finalList, outputPath + "processed_" + p.OutputNamePrefix + ".json"); } if (p.ExportType == ExportType.JSONAPI) { Log("Exporting JSON.."); //output json var fileName = outputPath + "processed_" + p.OutputNamePrefix + ".json"; p.ExportJSONFile(finalList, fileName); Log("Uploading JSON to API.."); if (System.IO.File.Exists(fileName)) { var json = System.IO.File.ReadAllText(fileName); await UploadPOIList(json); } } if (p.ExportType == ExportType.API && p.IsProductionReady) { //publish list of locations to OCM via API Log("Publishing via API.."); foreach (ChargePoint cp in finalList.Where(l => l.AddressInfo.CountryID != null)) { _client.UpdatePOI(cp, credentials); if (cp.ID == 0) { numAdded++; } else { numUpdated++; } } } else { numAdded = finalList.Count(p => p.ID == 0); numUpdated = finalList.Count(p => p.ID > 0); } if (p.ExportType == ExportType.POIModelList) { //result report contains POI lists } } Log("Import Processed:" + provider.GetProviderName() + " Added:" + numAdded + " Updated:" + numUpdated); } catch (Exception exp) { Log("Import Failed:" + provider.GetProviderName() + " ::" + exp.ToString()); } resultReport.Log = ""; resultReport.Log += p.ProcessingLog; resultReport.Log += ImportLog; return resultReport; } private async Task<ChargePoint> CleanPOIAddressInfo(ChargePoint p) { var result = await addressLookupCacheManager.PerformLocationLookup(p.AddressInfo.Latitude, p.AddressInfo.Longitude); if (result != null && !string.IsNullOrEmpty(result.AddressResult.AddressLine1)) { p.AddressInfo.Title = result.AddressResult.Title; p.AddressInfo.AddressLine1 = result.AddressResult.AddressLine1; p.SubmissionStatusTypeID = (int)StandardSubmissionStatusTypes.Imported_Published; return p; } else { // address cannot be improved and is low quality if (!string.IsNullOrEmpty(p.AddressInfo.Postcode)) { p.AddressInfo.Title = p.AddressInfo.Postcode; p.AddressInfo.AddressLine1 = p.AddressInfo.Town; } return p; } } public async Task<string> UploadPOIList(string json, string apiIdentifier = null, string apiToken = null, string apiBaseUrl = null) { var credentials = GetAPISessionCredentials(apiIdentifier, apiToken); var poiList = JsonConvert.DeserializeObject<List<ChargePoint>>(json); Log("Publishing via API.."); var itemCount = poiList.Count(); var itemsProcessed = 0; var pageSize = 500; var pageIndex = 0; Log($"Publishing a total of {itemCount} items .."); while (itemsProcessed < itemCount) { IEnumerable<ChargePoint> subList = new List<ChargePoint>(); var currentIndex = pageIndex * pageSize; var itemsRemaining = itemCount - currentIndex; if (itemsRemaining > pageSize) { subList = poiList.Skip(currentIndex).Take(pageSize); itemsProcessed += pageSize; Log($"Publishing items { currentIndex } to {currentIndex + pageSize - 1}.."); } else { subList = poiList.Skip(currentIndex).Take(itemsRemaining); itemsProcessed += itemsRemaining; Log($"Publishing items { currentIndex } to {currentIndex + itemsRemaining}.."); } _client.UpdateItems(subList.ToList(), credentials); await Task.Delay(2500); pageIndex++; } return $"Added: {poiList.Count(i => i.ID == 0)} Updated: {poiList.Count(i => i.ID > 0)}"; } /// <summary> /// Tell API we have completed our import for this provider /// </summary> /// <param name="providerId"></param> /// <returns></returns> public async Task UpdateLastImportDate(int providerId) { await _client.Get("/system/importcompleted/" + providerId); } /// <summary> /// For a list of ChargePoint objects, attempt to populate the AddressInfo (at least country) /// based on lat/lon if not already populated /// </summary> /// <param name="itemList"> </param> /// <param name="coreRefData"> </param> public void UpdateImportedPOIList(ImportReport poiResults, User user) { var submissionManager = new SubmissionManager(); int itemCount = 1; foreach (var newPOI in poiResults.Added) { Log("Importing New POI " + itemCount + ": " + newPOI.AddressInfo.ToString()); submissionManager.PerformPOISubmission(newPOI, user, false); } foreach (var updatedPOI in poiResults.Updated) { Log("Importing Updated POI " + itemCount + ": " + updatedPOI.AddressInfo.ToString()); submissionManager.PerformPOISubmission(updatedPOI, user, performCacheRefresh: false, disablePOISuperseding: true); } foreach (var delisted in poiResults.Delisted) { Log("Delisting Removed POI " + itemCount + ": " + delisted.AddressInfo.ToString()); delisted.SubmissionStatus = null; delisted.SubmissionStatusTypeID = (int)StandardSubmissionStatusTypes.Delisted_RemovedByDataProvider; submissionManager.PerformPOISubmission(delisted, user, false); } //refresh POI cache var cacheTask = Task.Run(async () => { return await OCM.Core.Data.CacheManager.RefreshCachedData(); }); cacheTask.Wait(); //temp get all providers references for recognised duplicates /*var dupeRefs = from dupes in poiResults.Duplicates where !String.IsNullOrEmpty(dupes.DataProvidersReference) select dupes.DataProvidersReference; string dupeOutput = ""; foreach(var d in dupeRefs) { dupeOutput += ",'"+d+"'"; } System.Diagnostics.Debug.WriteLine(dupeOutput);*/ if (poiResults.ProviderDetails.DefaultDataProvider != null) { //update date last updated for this provider new DataProviderManager().UpdateDateLastImport(poiResults.ProviderDetails.DefaultDataProvider.ID); } } #region helper methods public List<ChargePoint> PopulateLocationFromGeolocationCache(IEnumerable<ChargePoint> itemList, CoreReferenceData coreRefData) { //OCM.Import.Analysis.SpatialAnalysis spatialAnalysis = new Analysis.SpatialAnalysis(_settings.GeolocationShapefilePath + "/ne_10m_admin_0_map_units.shp"); var spatialAnalysis = new Analysis.SpatialAnalysis(_settings.GeolocationShapefilePath + "\\ne_10m_admin_0_countries.shp"); List<ChargePoint> failedLookups = new List<ChargePoint>(); //process list of locations, populating country refreshing cache where required foreach (var item in itemList) { if (item.AddressInfo.Country == null && item.AddressInfo.CountryID == null) { Country country = null; var test = spatialAnalysis.ClassifyPoint((double)item.AddressInfo.Latitude, (double)item.AddressInfo.Longitude); if (test != null) { country = coreRefData.Countries.FirstOrDefault(c => c.ISOCode == test.CountryCode || c.Title == test.CountryName); } if (country == null) { var geoLookup = geolocationCacheManager.PerformLocationLookup((double)item.AddressInfo.Latitude, (double)item.AddressInfo.Longitude, coreRefData.Countries); if (geoLookup != null) { country = coreRefData.Countries.FirstOrDefault(c => c.ID == geoLookup.CountryID || c.ISOCode == geoLookup.CountryCode || c.Title == geoLookup.CountryName); } } if (country != null) { item.AddressInfo.Country = country; //remove country name from address line 1 if present if (item.AddressInfo.AddressLine1 != null) { if (item.AddressInfo.AddressLine1.ToLower().Contains(country.Title.ToLower())) { item.AddressInfo.AddressLine1 = item.AddressInfo.AddressLine1.Replace(country.Title, "").Trim(); } } } if (item.AddressInfo.Country == null) { LogHelper.Log("Failed to resolve country for item:" + item.AddressInfo.Title + " OCM-" + item.ID); failedLookups.Add(item); } else { item.AddressInfo.CountryID = item.AddressInfo.Country.ID; } } } //cache may have updates, save for next time geolocationCacheManager.SaveCache(); return failedLookups; } public APICredentials GetAPISessionCredentials(string identifier, string sessionToken) { return new APICredentials { Identifier = identifier, SessionToken = sessionToken }; } public async Task GeocodingTestCountries() { //get a few OCM listings and check that their country appears to be correct // curl "https://api.openchargemap.io/v3/poi?key=test&maxresults=20000000" --output C:\Temp\ocm\data\import\poi.json var cachePath = @"C:\temp\ocm\data\import\poi.json"; List<ChargePoint> poiList; var coreRefData = await _client.GetCoreReferenceDataAsync(); if (!File.Exists(cachePath)) { var filters = new SearchFilters { SubmissionStatusTypeIDs = new int[] { (int)StandardSubmissionStatusTypes.Imported_Published, (int)StandardSubmissionStatusTypes.Submitted_Published }, MaxResults = 200000, EnableCaching = true }; poiList = (await _client.GetPOIListAsync(filters)).ToList(); await System.IO.File.WriteAllTextAsync(cachePath, JsonConvert.SerializeObject(poiList)); } else { var list = new List<ChargePoint>(); JsonSerializer serializer = new JsonSerializer(); using (FileStream st = File.Open(cachePath, FileMode.Open)) using (StreamReader sr = new StreamReader(st)) using (JsonReader reader = new JsonTextReader(sr)) { while (reader.Read()) { // deserialize only when there's "{" character in the stream if (reader.TokenType == JsonToken.StartObject) { var o = serializer.Deserialize<ChargePoint>(reader); list.Add(o); } } } poiList = list.Where(p => p.AddressInfo.CountryID != 159 && p.AddressInfo.CountryID != 1).ToList(); } // if some locations are known to fail lookup, don't attempt them var knownFailsFile = @"C:\temp\ocm\data\import\failed-country-lookups.json"; List<ChargePoint> knownFails = new List<ChargePoint>(); if (File.Exists(knownFailsFile)) { knownFails = JsonConvert.DeserializeObject<List<ChargePoint>>(await File.ReadAllTextAsync(knownFailsFile)); var list = (List<ChargePoint>)poiList; foreach (var p in knownFails) { list.Remove(list.FirstOrDefault(l => l.ID == p.ID)); } } var poiListCopy = JsonConvert.DeserializeObject<List<ChargePoint>>(JsonConvert.SerializeObject(poiList)); // clear existing country info foreach (var p in poiList) { p.AddressInfo.Country = null; p.AddressInfo.CountryID = null; } // determine country var s = Stopwatch.StartNew(); var failedLookups = PopulateLocationFromGeolocationCache(poiList, coreRefData); s.Stop(); System.Diagnostics.Debug.WriteLine("Lookup took " + s.Elapsed.TotalSeconds + "s"); // log failed lookups foreach (var p in failedLookups) { if (!knownFails.Any(k => k.ID == p.ID)) { knownFails.Add(p); } } await System.IO.File.WriteAllTextAsync(knownFailsFile, JsonConvert.SerializeObject(knownFails, Formatting.Indented)); var file = @"C:\temp\ocm\data\import\country-fixes.csv"; using (var stream = File.CreateText(file)) { stream.WriteLine($"Id,AddressInfoId,OriginalCountryId,NewCountryId"); foreach (var p in poiList) { var orig = poiListCopy.Find(f => f.ID == p.ID); if (p.AddressInfo.CountryID == null) { // could not check, use original p.AddressInfo.Country = orig.AddressInfo.Country; p.AddressInfo.CountryID = orig.AddressInfo.CountryID; } if (orig.AddressInfo.CountryID != p.AddressInfo.CountryID) { stream.WriteLine($"{p.ID},{p.AddressInfo.ID},{orig.AddressInfo.CountryID}, {p.AddressInfo.CountryID}"); } } stream.Flush(); stream.Close(); } var changedCountries = 0; foreach (var p in poiList) { var orig = poiListCopy.Find(f => f.ID == p.ID); if (orig.AddressInfo.CountryID != p.AddressInfo.CountryID) { changedCountries++; System.Diagnostics.Debug.WriteLine("OCM-" + p.ID + " country changed to " + p.AddressInfo.CountryID + " from " + orig.AddressInfo.CountryID); } } System.Diagnostics.Debug.WriteLine("Total: " + changedCountries + " changed of " + poiList.Count()); } #endregion helper methods } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NuGet.Frameworks; using NuGet.Versioning; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using PropertyNames = NuGet.Client.ManagedCodeConventions.PropertyNames; namespace Microsoft.DotNet.Build.Tasks.Packaging { public class ValidatePackage : PackagingTask { [Required] public string ContractName { get; set; } [Required] public string PackageId { get; set; } [Required] public string PackageVersion { get; set; } /// <summary> /// Frameworks supported by this package /// Identity: name of framework, can suffx '+' to indicate all later frameworks under validation. /// RuntimeIDs: Semi-colon seperated list of runtime IDs. If specified overrides the value specified in Frameworks. /// Version: version of API supported /// </summary> [Required] public ITaskItem[] SupportedFrameworks { get; set; } /// <summary> /// Frameworks to evaluate. /// Identity: Framework /// RuntimeIDs: Semi-colon seperated list of runtime IDs /// </summary> [Required] public ITaskItem[] Frameworks { get; set; } /// <summary> /// Path to runtime.json that contains the runtime graph. /// </summary> [Required] public string RuntimeFile { get; set; } /// <summary> /// Suppressions /// Identity: suppression name /// Value: optional semicolon-delimited list of values for the suppression /// </summary> public ITaskItem[] Suppressions { get;set; } /// <summary> /// A file containing names of suppressions with optional semi-colon values specified as follows /// suppression1 /// suppression2=foo /// suppression3=foo;bar /// </summary> public string SuppressionFile { get; set; } public bool SkipGenerationCheck { get; set; } public bool SkipIndexCheck { get; set; } public bool SkipSupportCheck { get; set; } public bool UseNetPlatform { get { return _generationIdentifier == FrameworkConstants.FrameworkIdentifiers.NetPlatform; } set { _generationIdentifier = value ? FrameworkConstants.FrameworkIdentifiers.NetPlatform : FrameworkConstants.FrameworkIdentifiers.NetStandard; } } /// <summary> /// List of frameworks which were validated and determined to be supported /// Identity: framework short name /// Framework: framework full name /// Version: assembly version of API that is supported /// Inbox: true if assembly is expected to come from targeting pack /// ValidatedRIDs: all RIDs that were scanned /// </summary> [Output] public ITaskItem[] AllSupportedFrameworks { get; set; } /// <summary> /// JSON file describing results of validation /// </summary> public string ReportFile { get; set; } /// <summary> /// Package index files used to define package version mapping. /// </summary> [Required] public ITaskItem[] PackageIndexes { get; set; } /// <summary> /// property bag of error suppressions /// </summary> private Dictionary<Suppression, HashSet<string>> _suppressions; private Dictionary<NuGetFramework, ValidationFramework> _frameworks; private PackageIndex _index; private PackageReport _report; private string _generationIdentifier = FrameworkConstants.FrameworkIdentifiers.NetStandard; public override bool Execute() { LoadSuppressions(); LoadReport(); if (!SkipSupportCheck) { LoadSupport(); if (!SkipGenerationCheck) { ValidateGenerations(); } // TODO: need to validate dependencies. ValidateSupport(); } ValidateIndex(); return !Log.HasLoggedErrors; } private void ValidateGenerations() { // get the generation of all portable implementation dlls. var allRuntimeGenerations = _report.Targets.Values.SelectMany(t => t.RuntimeAssets.NullAsEmpty()) .Select(r => r.TargetFramework) .Where(fx => fx != null && fx.Framework == _generationIdentifier && fx.Version != null) .Select(fx => fx.Version); // get the generation of all supported frameworks (some may have framework specific implementations // or placeholders). var allSupportedGenerations = _frameworks.Values.Where(vf => vf.SupportedVersion != null && FrameworkUtilities.IsGenerationMoniker(vf.Framework) && vf.Framework.Version != null) .Select(vf => vf.Framework.Version); // find the minimum supported version as the minimum of any generation explicitly implemented // with a portable implementation, or the generation of a framework with a platform specific // implementation. Version minSupportedGeneration = allRuntimeGenerations.Concat(allSupportedGenerations).Min(); // validate API version against generation for all files foreach (var compileAsset in _report.Targets.Values.SelectMany(t => t.CompileAssets) .Where(f => IsDll(f.LocalPath) && FrameworkUtilities.IsGenerationMoniker(f.TargetFramework))) { if (compileAsset.TargetFramework.Version < minSupportedGeneration) { Log.LogError($"Invalid generation {compileAsset.TargetFramework.Version} for {compileAsset.LocalPath}, must be at least {minSupportedGeneration} based on the implementations in the package. If you meant to target the lower generation you may be missing an implementation for a framework on that lower generation. If not you should raise the generation of the reference assembly to match that of the lowest supported generation of all implementations/placeholders."); } } } private void ValidateSupport() { var runtimeFxSuppression = GetSuppressionValues(Suppression.PermitRuntimeTargetMonikerMismatch) ?? new HashSet<string>(); // validate support for each TxM:RID foreach (var validateFramework in _frameworks.Values) { NuGetFramework fx = validateFramework.Framework; Version supportedVersion = validateFramework.SupportedVersion; Target compileTarget; if (!_report.Targets.TryGetValue(fx.ToString(), out compileTarget)) { Log.LogError($"Missing target {fx.ToString()} from validation report {ReportFile}"); continue; } var compileAssetPaths = compileTarget.CompileAssets.Select(ca => ca.PackagePath); bool hasCompileAsset, hasCompilePlaceHolder; NuGetAssetResolver.ExamineAssets(Log, "Compile", ContractName, fx.ToString(), compileAssetPaths, out hasCompileAsset, out hasCompilePlaceHolder); // resolve/test for each RID associated with this framework. foreach (string runtimeId in validateFramework.RuntimeIds) { string target = String.IsNullOrEmpty(runtimeId) ? fx.ToString() : $"{fx}/{runtimeId}"; Target runtimeTarget; if (!_report.Targets.TryGetValue(target, out runtimeTarget)) { Log.LogError($"Missing target {target} from validation report {ReportFile}"); continue; } var runtimeAssetPaths = runtimeTarget.RuntimeAssets.Select(ra => ra.PackagePath); bool hasRuntimeAsset, hasRuntimePlaceHolder; NuGetAssetResolver.ExamineAssets(Log, "Runtime", ContractName, target, runtimeAssetPaths, out hasRuntimeAsset, out hasRuntimePlaceHolder); if (null == supportedVersion) { // Contract should not be supported on this platform. bool permitImplementation = HasSuppression(Suppression.PermitImplementation, target); if (hasCompileAsset && (hasRuntimeAsset & !permitImplementation)) { Log.LogError($"{ContractName} should not be supported on {target} but has both compile and runtime assets."); } else if (hasRuntimeAsset & !permitImplementation) { Log.LogError($"{ContractName} should not be supported on {target} but has runtime assets."); } if (hasRuntimePlaceHolder && hasCompilePlaceHolder) { Log.LogError($"{ContractName} should not be supported on {target} but has placeholders for both compile and runtime which will permit the package to install."); } } else { if (validateFramework.IsInbox) { if (!hasCompileAsset && !hasCompilePlaceHolder) { Log.LogError($"Framework {fx} should support {ContractName} inbox but was missing a placeholder for compile-time. You may need to add <InboxOnTargetFramework Include=\"{fx.GetShortFolderName()}\" /> to your project."); } else if (hasCompileAsset) { Log.LogError($"Framework {fx} should support {ContractName} inbox but contained a reference assemblies: {String.Join(", ", compileAssetPaths)}. You may need to add <InboxOnTargetFramework Include=\"{fx.GetShortFolderName()}\" /> to your project."); } if (!hasRuntimeAsset && !hasRuntimePlaceHolder) { Log.LogError($"Framework {fx} should support {ContractName} inbox but was missing a placeholder for run-time. You may need to add <InboxOnTargetFramework Include=\"{fx.GetShortFolderName()}\" /> to your project."); } else if (hasRuntimeAsset) { Log.LogError($"Framework {fx} should support {ContractName} inbox but contained a implementation assemblies: {String.Join(", ", runtimeAssetPaths)}. You may need to add <InboxOnTargetFramework Include=\"{fx.GetShortFolderName()}\" /> to your project."); } } else { Version referenceAssemblyVersion = null; if (!hasCompileAsset) { Log.LogError($"{ContractName} should be supported on {target} but has no compile assets."); } else { var referenceAssemblies = compileTarget.CompileAssets.Where(ca => IsDll(ca.PackagePath)); if (referenceAssemblies.Count() > 1) { Log.LogError($"{ContractName} should only contain a single compile asset for {target}."); } foreach (var referenceAssembly in referenceAssemblies) { referenceAssemblyVersion = referenceAssembly.Version; if (!VersionUtility.IsCompatibleApiVersion(supportedVersion, referenceAssemblyVersion)) { Log.LogError($"{ContractName} should support API version {supportedVersion} on {target} but {referenceAssembly.LocalPath} was found to support {referenceAssemblyVersion?.ToString() ?? "<unknown version>"}."); } } } if (!hasRuntimeAsset && !FrameworkUtilities.IsGenerationMoniker(validateFramework.Framework)) { Log.LogError($"{ContractName} should be supported on {target} but has no runtime assets."); } else { var implementationAssemblies = runtimeTarget.RuntimeAssets.Where(ra => IsDll(ra.PackagePath)); Dictionary<string, PackageAsset> implementationFiles = new Dictionary<string, PackageAsset>(); foreach (var implementationAssembly in implementationAssemblies) { Version implementationVersion = implementationAssembly.Version; if (!VersionUtility.IsCompatibleApiVersion(supportedVersion, implementationVersion)) { Log.LogError($"{ContractName} should support API version {supportedVersion} on {target} but {implementationAssembly.LocalPath} was found to support {implementationVersion?.ToString() ?? "<unknown version>"}."); } // Previously we only permitted compatible mismatch if Suppression.PermitHigherCompatibleImplementationVersion was specified // this is a permitted thing on every framework but desktop (which requires exact match to ensure bindingRedirects exist) // Now make this the default, we'll check desktop, where it matters, more strictly if (referenceAssemblyVersion != null && !VersionUtility.IsCompatibleApiVersion(referenceAssemblyVersion, implementationVersion)) { Log.LogError($"{ContractName} has mismatched compile ({referenceAssemblyVersion}) and runtime ({implementationVersion}) versions on {target}."); } if (fx.Framework == FrameworkConstants.FrameworkIdentifiers.Net && referenceAssemblyVersion != null && !referenceAssemblyVersion.Equals(implementationVersion)) { Log.LogError($"{ContractName} has a higher runtime version ({implementationVersion}) than compile version ({referenceAssemblyVersion}) on .NET Desktop framework {target}. This will break bindingRedirects. If the live reference was replaced with a harvested reference you may need to set <Preserve>true</Preserve> on your reference assembly ProjectReference."); } string fileName = Path.GetFileName(implementationAssembly.PackagePath); if (implementationFiles.ContainsKey(fileName)) { Log.LogError($"{ContractName} includes both {implementationAssembly.LocalPath} and {implementationFiles[fileName].LocalPath} an on {target} which have the same name and will clash when both packages are used."); } else { implementationFiles[fileName] = implementationAssembly; } if (!implementationAssembly.TargetFramework.Equals(fx) && !runtimeFxSuppression.Contains(fx.ToString())) { // the selected asset wasn't an exact framework match, let's see if we have an exact match in any other runtime asset. var matchingFxAssets = _report.UnusedAssets.Where(i => i.TargetFramework != null && i.TargetFramework.Equals(fx) && // exact framework // Same file Path.GetFileName(i.PackagePath).Equals(fileName, StringComparison.OrdinalIgnoreCase) && // Is implementation (i.PackagePath.StartsWith("lib") || i.PackagePath.StartsWith("runtimes")) && // is not the same source file as was already selected i.LocalPath != implementationAssembly.LocalPath); if (matchingFxAssets.Any()) { Log.LogError($"When targeting {target} {ContractName} will use {implementationAssembly.LocalPath} which targets {implementationAssembly.TargetFramework.GetShortFolderName()} but {String.Join(";", matchingFxAssets.Select(i => i.PackagePath))} targets {fx.GetShortFolderName()} specifically."); } } } } } } } } // Set output items AllSupportedFrameworks = _frameworks.Values.Where(fx => fx.SupportedVersion != null).Select(fx => fx.ToItem()).OrderBy(i => i.ItemSpec).ToArray(); } private void ValidateIndex() { if (SkipIndexCheck) { return; } if (PackageIndexes == null || PackageIndexes.Length == 0) { return; } var index = PackageIndex.Load(PackageIndexes.Select(pi => pi.GetMetadata("FullPath"))); PackageInfo info; if (!index.Packages.TryGetValue(PackageId, out info)) { Log.LogError($"PackageIndex from {String.Join(", ", PackageIndexes.Select(i => i.ItemSpec))} is missing an entry for package {PackageId}. Please run /t:UpdatePackageIndex on this project to commit an update."); return; } var allDlls = _report.Targets.Values.SelectMany(t => t.CompileAssets.NullAsEmpty().Concat(t.RuntimeAssets.NullAsEmpty())); var allAssemblies = allDlls.Where(f => f.Version != null); var assemblyVersions = new HashSet<Version>(allAssemblies.Select(f => VersionUtility.As4PartVersion(f.Version))); var thisPackageVersion = VersionUtility.As3PartVersion(NuGetVersion.Parse(PackageVersion).Version); foreach (var fileVersion in assemblyVersions) { Version packageVersion; // determine if we're missing a mapping for this package if (!info.AssemblyVersionInPackageVersion.TryGetValue(fileVersion, out packageVersion)) { Log.LogError($"PackageIndex from {String.Join(", ", PackageIndexes.Select(i => i.ItemSpec))} is missing an assembly version entry for {fileVersion} for package {PackageId}. Please run /t:UpdatePackageIndex on this project to commit an update."); } else { // determine if we have a mapping for an unstable package and that unstable package is not this one if (!info.StableVersions.Contains(packageVersion) && packageVersion != thisPackageVersion) { Log.LogError($"PackageIndex from {String.Join(", ", PackageIndexes.Select(i => i.ItemSpec))} indicates that assembly version {fileVersion} is contained in non-stable package version {packageVersion} which differs from this package version {thisPackageVersion}."); } } } var orphanedAssemblyVersions = info.AssemblyVersionInPackageVersion .Where(pair => pair.Value == thisPackageVersion && !assemblyVersions.Contains(pair.Key)) .Select(pair => pair.Key); if (orphanedAssemblyVersions.Any()) { Log.LogError($"PackageIndex from {String.Join(", ", PackageIndexes.Select(i => i.ItemSpec))} is has an assembly version entry(s) for {String.Join(", ", orphanedAssemblyVersions)} which are no longer in package {PackageId}. Please run /t:UpdatePackageIndex on this project to commit an update."); } // if no assemblies are present in this package nor were ever present if (assemblyVersions.Count == 0 && info.AssemblyVersionInPackageVersion.Count == 0) { // if in the native module map if (index.ModulesToPackages.Values.Any(p => p.Equals(PackageId))) { // ensure the baseline is set if (info.BaselineVersion != thisPackageVersion) { Log.LogError($"PackageIndex from {String.Join(", ", PackageIndexes.Select(i => i.ItemSpec))} is missing an baseline entry(s) for native module {PackageId}. Please run /t:UpdatePackageIndex on this project to commit an update."); } } else { // not in the native module map, see if any of the modules in this package are present // (with a different package, as would be the case for runtime-specific packages) var moduleNames = allDlls.Select(d => Path.GetFileNameWithoutExtension(d.LocalPath)); var missingModuleNames = moduleNames.Where(m => !index.ModulesToPackages.ContainsKey(m)); if (missingModuleNames.Any()) { Log.LogError($"PackageIndex from {String.Join(", ", PackageIndexes.Select(i => i.ItemSpec))} is missing ModulesToPackages entry(s) for {String.Join(", ", missingModuleNames)} to package {PackageId}. Please add a an entry for the appropriate package."); } } } } private static bool IsDll(string path) { return !String.IsNullOrWhiteSpace(path) && Path.GetExtension(path).Equals(".dll", StringComparison.OrdinalIgnoreCase); } private HashSet<string> GetSuppressionValues(Suppression key) { HashSet<string> values; _suppressions.TryGetValue(key, out values); return values; } private string GetSingleSuppressionValue(Suppression key) { var values = GetSuppressionValues(key); return (values != null && values.Count == 1) ? values.Single() : null; } private bool HasSuppression(Suppression key) { return _suppressions.ContainsKey(key); } private bool HasSuppression(Suppression key, string value) { HashSet<string> values; if (_suppressions.TryGetValue(key, out values) && values != null) { return values.Contains(value); } return false; } private void LoadSuppressions() { _suppressions = new Dictionary<Suppression, HashSet<string>>(); if (Suppressions != null) { foreach(var suppression in Suppressions) { AddSuppression(suppression.ItemSpec, suppression.GetMetadata("Value")); } } if (File.Exists(SuppressionFile)) { foreach (string suppression in File.ReadAllLines(SuppressionFile)) { if (suppression.TrimStart().StartsWith(@"//", StringComparison.OrdinalIgnoreCase) || String.IsNullOrWhiteSpace(suppression)) { continue; } var parts = suppression.Split(new[] { '=' }, 2); AddSuppression(parts[0], parts.Length > 1 ? parts[1] : null); } } } private void AddSuppression(string keyString, string valueString) { Suppression key; HashSet<string> values = null; if (!Enum.TryParse<Suppression>(keyString, out key)) { Log.LogError($"{SuppressionFile} contained unknown suppression {keyString}"); return; } _suppressions.TryGetValue(key, out values); if (valueString != null) { var valuesToAdd = valueString.Split(';'); if (values == null) { values = new HashSet<string>(valuesToAdd); } else { foreach(var valueToAdd in valuesToAdd) { values.Add(valueToAdd); } } } _suppressions[key] = values; } private void LoadReport() { _report = PackageReport.Load(ReportFile); } private void LoadSupport() { _frameworks = new Dictionary<NuGetFramework, ValidationFramework>(); // determine which TxM:RIDs should be considered for support based on Frameworks item foreach (var framework in Frameworks) { NuGetFramework fx; try { fx = FrameworkUtilities.ParseNormalized(framework.ItemSpec); } catch (Exception ex) { Log.LogError($"Could not parse Framework {framework.ItemSpec}. {ex}"); continue; } if (fx.Equals(NuGetFramework.UnsupportedFramework)) { Log.LogError($"Did not recognize {framework.ItemSpec} as valid Framework."); continue; } string runtimeIdList = framework.GetMetadata("RuntimeIDs"); if (_frameworks.ContainsKey(fx)) { Log.LogError($"Framework {fx} has been listed in Frameworks more than once."); continue; } _frameworks[fx] = new ValidationFramework(fx); if (!String.IsNullOrWhiteSpace(runtimeIdList)) { _frameworks[fx].RuntimeIds = runtimeIdList.Split(';'); } } // keep a list of explicitly listed supported frameworks so that we can check for conflicts. HashSet<NuGetFramework> explicitlySupportedFrameworks = new HashSet<NuGetFramework>(NuGetFramework.Comparer); // determine what version should be supported based on SupportedFramework items foreach (var supportedFramework in SupportedFrameworks) { NuGetFramework fx; string fxString = supportedFramework.ItemSpec; bool isExclusiveVersion = fxString.Length > 1 && fxString[0] == '[' && fxString[fxString.Length - 1] == ']'; if (isExclusiveVersion) { fxString = fxString.Substring(1, fxString.Length - 2); } try { fx = FrameworkUtilities.ParseNormalized(fxString); } catch (Exception ex) { Log.LogError($"Could not parse TargetFramework {fxString} as a SupportedFramework. {ex}"); continue; } if (fx.Equals(NuGetFramework.UnsupportedFramework)) { Log.LogError($"Did not recognize TargetFramework {fxString} as a SupportedFramework."); continue; } Version supportedVersion; string version = supportedFramework.GetMetadata("Version"); try { supportedVersion = Version.Parse(version); } catch (Exception ex) { Log.LogError($"Could not parse Version {version} on SupportedFramework item {supportedFramework.ItemSpec}. {ex}"); continue; } ValidationFramework validationFramework = null; if (!_frameworks.TryGetValue(fx, out validationFramework)) { Log.LogError($"SupportedFramework {fx} was specified but is not part of the Framework list to use for validation."); continue; } if (explicitlySupportedFrameworks.Contains(fx)) { if (supportedVersion <= validationFramework.SupportedVersion) { // if we've already picked up a higher/equal version, prefer it continue; } } else { explicitlySupportedFrameworks.Add(fx); } validationFramework.SupportedVersion = supportedVersion; if (!isExclusiveVersion) { // find all frameworks of higher version, sorted by version ascending IEnumerable<ValidationFramework> higherFrameworks = _frameworks.Values.Where(vf => vf.Framework.Framework == fx.Framework && vf.Framework.Version > fx.Version).OrderBy(vf => vf.Framework.Version); // netcore50 is the last `netcore` framework, after that we use `uap` if (fx.Framework == FrameworkConstants.FrameworkIdentifiers.NetCore) { var uapFrameworks = _frameworks.Values.Where(vf => vf.Framework.Framework == FrameworkConstants.FrameworkIdentifiers.UAP).OrderBy(vf => vf.Framework.Version); higherFrameworks = higherFrameworks.Concat(uapFrameworks); } foreach (var higherFramework in higherFrameworks) { if (higherFramework.SupportedVersion != null && higherFramework.SupportedVersion > supportedVersion) { // found an higher framework version a higher API version, stop applying this supported version break; } higherFramework.SupportedVersion = supportedVersion; } } } // determine which Frameworks should support inbox _index = PackageIndex.Load(PackageIndexes.Select(pi => pi.GetMetadata("FullPath"))); PackageInfo packageInfo; if (_index.Packages.TryGetValue(ContractName, out packageInfo)) { foreach (var inboxPair in packageInfo.InboxOn.GetInboxVersions()) { if (!_frameworks.ContainsKey(inboxPair.Key)) { _frameworks[inboxPair.Key] = new ValidationFramework(inboxPair.Key) { SupportedVersion = inboxPair.Value, IsInbox = true }; } } foreach (var validationFramework in _frameworks.Values) { if (packageInfo.InboxOn.IsInbox(validationFramework.Framework, validationFramework.SupportedVersion, permitRevisions: HasSuppression(Suppression.PermitInboxRevsion))) { validationFramework.IsInbox = true; } } } // for every framework we know about, also infer it's netstandard version to ensure it can // be targeted by PCL. Even if a package only supports a single framework we still // want to include a portable reference assembly. This allows 3rd parties to add // their own implementation via a lineup/runtime.json. // only consider frameworks that support the contract at a specific version var inferFrameworks = _frameworks.Values.Where(fx => fx.SupportedVersion != null && fx.SupportedVersion != VersionUtility.MaxVersion).ToArray(); var genVersionSuppression = GetSuppressionValues(Suppression.PermitPortableVersionMismatch) ?? new HashSet<string>(); var inferNETStandardSuppression = GetSuppressionValues(Suppression.SuppressNETStandardInference) ?? new HashSet<string>(); Dictionary<NuGetFramework, ValidationFramework> generationsToValidate = new Dictionary<NuGetFramework, ValidationFramework>(); foreach (var inferFramework in inferFrameworks) { var inferFrameworkMoniker = inferFramework.Framework.ToString(); if (inferNETStandardSuppression.Contains(inferFrameworkMoniker)) { continue; } NuGetFramework generation = new NuGetFramework(_generationIdentifier, Generations.DetermineGenerationForFramework(inferFramework.Framework, UseNetPlatform)); Log.LogMessage(LogImportance.Low, $"Validating {generation} for {ContractName}, {inferFramework.SupportedVersion} since it is supported by {inferFrameworkMoniker}"); ValidationFramework existingGeneration = null; if (generationsToValidate.TryGetValue(generation, out existingGeneration)) { // the netstandard version should be the minimum version supported by all platforms that support that netstandard version. if (inferFramework.SupportedVersion < existingGeneration.SupportedVersion) { Log.LogMessage($"Framework {inferFramework.Framework} supports {ContractName} at {inferFramework.SupportedVersion} which is lower than {existingGeneration.SupportedVersion} supported by generation {generation.GetShortFolderName()}. Lowering the version supported by {generation.GetShortFolderName()}."); existingGeneration.SupportedVersion = inferFramework.SupportedVersion; } } else { generationsToValidate.Add(generation, new ValidationFramework(generation) { SupportedVersion = inferFramework.SupportedVersion }); } } foreach (var generation in generationsToValidate) { _frameworks.Add(generation.Key, generation.Value); } } private class ValidationFramework { private static readonly string[] s_nullRidList = new string[] { null }; public ValidationFramework(NuGetFramework framework) { Framework = framework; RuntimeIds = s_nullRidList; } public NuGetFramework Framework { get; } public string[] RuntimeIds { get; set; } // if null indicates the contract should not be supported. public Version SupportedVersion { get; set; } public bool IsInbox { get; set; } public string ShortName { get { return Framework.GetShortFolderName(); } } public ITaskItem ToItem() { ITaskItem item = new TaskItem(Framework.ToString()); item.SetMetadata("ShortName", ShortName); item.SetMetadata("Version", SupportedVersion.ToString()); item.SetMetadata("Inbox", IsInbox.ToString()); item.SetMetadata("ValidatedRIDs", String.Join(";", RuntimeIds)); return item; } } } public enum Suppression { /// <summary> /// Permits a runtime asset of the targets specified, semicolon delimited /// </summary> PermitImplementation, /// <summary> /// Permits a higher revision/build to still be considered as a match for an inbox assembly /// </summary> PermitInboxRevsion, /// <summary> /// Permits a lower version on specified frameworks, semicolon delimitied, than the generation supported by that framework /// </summary> PermitPortableVersionMismatch, /// <summary> /// Permits a compatible API version match between ref and impl, rather than exact match /// </summary> PermitHigherCompatibleImplementationVersion, /// <summary> /// Permits a non-matching targetFramework asset to be used even when a matching one exists. /// </summary> PermitRuntimeTargetMonikerMismatch, /// <summary> /// Suppresses a particular set of SupportedFrameworks from inferring NETStandard support. /// EG: package supports netcore45, wp8, net451, wpa81. /// package cannot support net45, and thus doesn't wish to expose netstandard1.0 or netstandard1.1 /// reference assemblies. /// It can use SuppressNETStandardInference=WindowsPhone,Version=v8.0;.NETCore,Version=v4.5 to still /// validate support for wp8 and netcore45 without forcing it to support netstandard1.0 and 1.1. /// </summary> SuppressNETStandardInference } }
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Text; namespace Lucene.Net.Support { /// <summary> /// A C# emulation of the <a href="http://download.oracle.com/javase/1,5.0/docs/api/java/util/HashMap.html">Java Hashmap</a> /// <para> /// A <see cref="Dictionary{TKey, TValue}" /> is a close equivalent to the Java /// Hashmap. One difference java implementation of the class is that /// the Hashmap supports both null keys and values, where the C# Dictionary /// only supports null values not keys. Also, <c>V Get(TKey)</c> /// method in Java returns null if the key doesn't exist, instead of throwing /// an exception. This implementation doesn't throw an exception when a key /// doesn't exist, it will return null. This class is slower than using a /// <see cref="Dictionary{TKey, TValue}"/>, because of extra checks that have to be /// done on each access, to check for null. /// </para> /// <para> /// <b>NOTE:</b> This class works best with nullable types. default(T) is returned /// when a key doesn't exist in the collection (this being similar to how Java returns /// null). Therefore, if the expected behavior of the java code is to execute code /// based on if the key exists, when the key is an integer type, it will return 0 instead of null. /// </para> /// <remaks> /// Consider also implementing IDictionary, IEnumerable, and ICollection /// like <see cref="Dictionary{TKey, TValue}" /> does, so HashMap can be /// used in substituted in place for the same interfaces it implements. /// </remaks> /// </summary> /// <typeparam name="TKey">The type of keys in the dictionary</typeparam> /// <typeparam name="TValue">The type of values in the dictionary</typeparam> /// <remarks> /// <h2>Unordered Dictionaries</h2> /// <list type="bullet"> /// <item><description><see cref="Dictionary{TKey, TValue}"/> - use when order is not important and all keys are non-null.</description></item> /// <item><description><see cref="HashMap{TKey, TValue}"/> - use when order is not important and support for a null key is required.</description></item> /// </list> /// <h2>Ordered Dictionaries</h2> /// <list type="bullet"> /// <item><description><see cref="LinkedHashMap{TKey, TValue}"/> - use when you need to preserve entry insertion order. Keys are nullable.</description></item> /// <item><description><see cref="SortedDictionary{TKey, TValue}"/> - use when you need natural sort order. Keys must be unique.</description></item> /// <item><description><see cref="TreeDictionary{K, V}"/> - use when you need natural sort order. Keys may contain duplicates.</description></item> /// <item><description><see cref="LurchTable{TKey, TValue}"/> - use when you need to sort by most recent access or most recent update. Works well for LRU caching.</description></item> /// </list> /// </remarks> #if FEATURE_SERIALIZABLE [Serializable] #endif public class HashMap<TKey, TValue> : IDictionary<TKey, TValue> { internal IEqualityComparer<TKey> _comparer; internal IDictionary<TKey, TValue> _dict; // Indicates if a null key has been assigned, used for iteration private bool _hasNullValue; // stores the value for the null key private TValue _nullValue; // Indicates the type of key is a non-nullable valuetype private readonly bool _isValueType; public HashMap() : this(0) { } public HashMap(IEqualityComparer<TKey> comparer) : this(0, comparer) { } public HashMap(int initialCapacity) : this(initialCapacity, Support.EqualityComparer<TKey>.Default) { } public HashMap(int initialCapacity, IEqualityComparer<TKey> comparer) : this(new Dictionary<TKey, TValue>(initialCapacity, comparer), comparer) { } public HashMap(IEnumerable<KeyValuePair<TKey, TValue>> other) : this(0) { foreach (var kvp in other) { Add(kvp.Key, kvp.Value); } } internal HashMap(IDictionary<TKey, TValue> wrappedDict, IEqualityComparer<TKey> comparer) { // LUCENENET TODO: Is this a bug? Shouldn't we be using the passed in comparer if non-null? _comparer = /* comparer ?? */ Support.EqualityComparer<TKey>.Default; _dict = wrappedDict; _hasNullValue = false; if (typeof(TKey).GetTypeInfo().IsValueType) { _isValueType = Nullable.GetUnderlyingType(typeof(TKey)) == null; } } public bool ContainsValue(TValue value) { if (!_isValueType && _hasNullValue && _nullValue.Equals(value)) return true; return _dict.Values.Contains(value); } public TValue AddIfAbsent(TKey key, TValue value) { if (!ContainsKey(key)) { Add(key, value); return default(TValue); } return this[key]; } #region Object overrides public override bool Equals(object obj) { if (obj == this) return true; if (!(obj is IDictionary<TKey, TValue>)) return false; IDictionary<TKey, TValue> m = (IDictionary<TKey, TValue>)obj; if (m.Count != Count) return false; try { var i = GetEnumerator(); while (i.MoveNext()) { KeyValuePair<TKey, TValue> e = i.Current; TKey key = e.Key; TValue value = e.Value; if (value == null) { if (!(m[key] == null && m.ContainsKey(key))) return false; } else { if (!value.Equals(m[key])) return false; } } } catch (InvalidCastException) { return false; } catch (NullReferenceException) { return false; } return true; } public override int GetHashCode() { int h = 0; var i = GetEnumerator(); while (i.MoveNext()) h += i.Current.GetHashCode(); return h; } public override string ToString() { var i = GetEnumerator(); if (!i.MoveNext()) return "{}"; StringBuilder sb = new StringBuilder(); sb.Append('{'); for (;;) { var e = i.Current; TKey key = e.Key; TValue value = e.Value; sb.Append(key); sb.Append('='); sb.Append(value); if (!i.MoveNext()) return sb.Append('}').ToString(); sb.Append(',').Append(' '); } } #endregion #region Implementation of IEnumerable public virtual IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator() { if (!_isValueType && _hasNullValue) { yield return new KeyValuePair<TKey, TValue>(default(TKey), _nullValue); } foreach (var kvp in _dict) { yield return kvp; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion Implementation of IEnumerable #region Implementation of ICollection<KeyValuePair<TKey,TValue>> public virtual void Add(KeyValuePair<TKey, TValue> item) { Add(item.Key, item.Value); } public virtual void Clear() { _hasNullValue = false; _nullValue = default(TValue); _dict.Clear(); } public virtual bool Contains(KeyValuePair<TKey, TValue> item) { if (!_isValueType && _comparer.Equals(item.Key, default(TKey))) { return _hasNullValue && Support.EqualityComparer<TValue>.Default.Equals(item.Value, _nullValue); } return _dict.Contains(item); } public virtual void CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { _dict.CopyTo(array, arrayIndex); if (!_isValueType && _hasNullValue) { array[array.Length - 1] = new KeyValuePair<TKey, TValue>(default(TKey), _nullValue); } } public virtual bool Remove(KeyValuePair<TKey, TValue> item) { if (!_isValueType && _comparer.Equals(item.Key, default(TKey))) { if (!_hasNullValue) return false; _hasNullValue = false; _nullValue = default(TValue); return true; } return _dict.Remove(item); } public virtual int Count { get { return _dict.Count + (_hasNullValue ? 1 : 0); } } public virtual bool IsReadOnly { get { return false; } } #endregion Implementation of ICollection<KeyValuePair<TKey,TValue>> #region Implementation of IDictionary<TKey,TValue> public virtual bool ContainsKey(TKey key) { if (!_isValueType && _comparer.Equals(key, default(TKey))) { if (_hasNullValue) { return true; } return false; } return _dict.ContainsKey(key); } public virtual void Add(TKey key, TValue value) { if (!_isValueType && _comparer.Equals(key, default(TKey))) { _hasNullValue = true; _nullValue = value; } else { _dict[key] = value; } } public virtual bool Remove(TKey key) { if (!_isValueType && _comparer.Equals(key, default(TKey))) { _hasNullValue = false; _nullValue = default(TValue); return true; } else { return _dict.Remove(key); } } public virtual bool TryGetValue(TKey key, out TValue value) { if (!_isValueType && _comparer.Equals(key, default(TKey))) { if (_hasNullValue) { value = _nullValue; return true; } value = default(TValue); return false; } else { return _dict.TryGetValue(key, out value); } } public virtual TValue this[TKey key] { get { if (!_isValueType && _comparer.Equals(key, default(TKey))) { if (!_hasNullValue) { return default(TValue); } return _nullValue; } return _dict.ContainsKey(key) ? _dict[key] : default(TValue); } set { Add(key, value); } } public virtual ICollection<TKey> Keys { get { if (!_hasNullValue) return _dict.Keys; // Using a List<T> to generate an ICollection<TKey> // would incur a costly copy of the dict's KeyCollection // use out own wrapper instead return new NullKeyCollection(_dict); } } public virtual ICollection<TValue> Values { get { if (!_hasNullValue) return _dict.Values; // Using a List<T> to generate an ICollection<TValue> // would incur a costly copy of the dict's ValueCollection // use out own wrapper instead return new NullValueCollection(_dict, _nullValue); } } #endregion Implementation of IDictionary<TKey,TValue> #region NullValueCollection /// <summary> /// Wraps a dictionary and adds the value /// represented by the null key /// </summary> private class NullValueCollection : ICollection<TValue> { private readonly TValue _nullValue; private readonly IDictionary<TKey, TValue> _internalDict; public NullValueCollection(IDictionary<TKey, TValue> dict, TValue nullValue) { _internalDict = dict; _nullValue = nullValue; } #region Implementation of IEnumerable public IEnumerator<TValue> GetEnumerator() { yield return _nullValue; foreach (var val in _internalDict.Values) { yield return val; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion Implementation of IEnumerable #region Implementation of ICollection<TValue> public void CopyTo(TValue[] array, int arrayIndex) { throw new NotImplementedException("Implement as needed"); } public int Count { get { return _internalDict.Count + 1; } } public bool IsReadOnly { get { return true; } } #region Explicit Interface Methods void ICollection<TValue>.Add(TValue item) { throw new NotSupportedException(); } void ICollection<TValue>.Clear() { throw new NotSupportedException(); } bool ICollection<TValue>.Contains(TValue item) { throw new NotSupportedException(); } bool ICollection<TValue>.Remove(TValue item) { throw new NotSupportedException("Collection is read only!"); } #endregion Explicit Interface Methods #endregion Implementation of ICollection<TValue> } #endregion NullValueCollection #region NullKeyCollection /// <summary> /// Wraps a dictionary's collection, adding in a /// null key. /// </summary> private class NullKeyCollection : ICollection<TKey> { private readonly IDictionary<TKey, TValue> _internalDict; public NullKeyCollection(IDictionary<TKey, TValue> dict) { _internalDict = dict; } public IEnumerator<TKey> GetEnumerator() { yield return default(TKey); foreach (var key in _internalDict.Keys) { yield return key; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public void CopyTo(TKey[] array, int arrayIndex) { throw new NotImplementedException("Implement this as needed"); } public int Count { get { return _internalDict.Count + 1; } } public bool IsReadOnly { get { return true; } } #region Explicit Interface Definitions bool ICollection<TKey>.Contains(TKey item) { throw new NotSupportedException(); } void ICollection<TKey>.Add(TKey item) { throw new NotSupportedException(); } void ICollection<TKey>.Clear() { throw new NotSupportedException(); } bool ICollection<TKey>.Remove(TKey item) { throw new NotSupportedException(); } #endregion Explicit Interface Definitions } #endregion NullKeyCollection } }
//---------------------------------------------------------------------------- // Anti-Grain Geometry - Version 2.4 // Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com) // // C# port by: Lars Brubaker // larsbrubaker@gmail.com // Copyright (C) 2007 // // Permission to copy, use, modify, sell and distribute this software // is granted provided this copyright notice appears in all copies. // This software is provided "as is" without express or implied // warranty, and with no claim as to its suitability for any purpose. // //---------------------------------------------------------------------------- // Contact: mcseem@antigrain.com // mcseemagg@yahoo.com // http://www.antigrain.com //---------------------------------------------------------------------------- using System; using System.Drawing; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Timers; using System.Windows.Forms; using MatterHackers.VectorMath; namespace MatterHackers.Agg.UI { public abstract class WinformsSystemWindow : Form, IPlatformWindow { public static bool SingleWindowMode { get; set; } = false; public static bool EnableInputHook { get; set; } = true; public static bool ShowingSystemDialog { get; set; } = false; public static WinformsSystemWindow MainWindowsFormsWindow { get; private set; } public static Func<SystemWindow, FormInspector> InspectorCreator { get; set; } private static System.Timers.Timer idleCallBackTimer = null; private static bool processingOnIdle = false; private static readonly object SingleInvokeLock = new object(); protected WinformsEventSink EventSink; private SystemWindow systemWindow; private int drawCount = 0; private int onPaintCount; public SystemWindow AggSystemWindow { get => systemWindow; set { systemWindow = value; if (systemWindow != null) { this.Caption = systemWindow.Title; if (SingleWindowMode) { if (firstWindow) { this.MinimumSize = systemWindow.MinimumSize; } // Set this system window as the event target this.EventSink?.SetActiveSystemWindow(systemWindow); } else { this.MinimumSize = systemWindow.MinimumSize; } } } } public bool IsMainWindow { get; } = false; public bool IsInitialized { get; set; } = false; public WinformsSystemWindow() { if (idleCallBackTimer == null) { idleCallBackTimer = new System.Timers.Timer(); // call up to 100 times a second idleCallBackTimer.Interval = 10; idleCallBackTimer.Elapsed += InvokePendingOnIdleActions; idleCallBackTimer.Start(); } // Track first window if (MainWindowsFormsWindow == null) { MainWindowsFormsWindow = this; IsMainWindow = true; } this.TitleBarHeight = RectangleToScreen(ClientRectangle).Top - this.Top; this.AllowDrop = true; string iconPath = File.Exists("application.ico") ? "application.ico" : "../MonoBundle/StaticData/application.ico"; try { if (File.Exists(iconPath)) { this.Icon = new Icon(iconPath); } } catch { } } protected override void OnClosed(EventArgs e) { if (IsMainWindow) { // Ensure that when the MainWindow is closed, we null the field so we can recreate the MainWindow MainWindowsFormsWindow = null; } AggSystemWindow = null; base.OnClosed(e); } public void ReleaseOnIdleGuard() { lock (SingleInvokeLock) { processingOnIdle = false; } } private void InvokePendingOnIdleActions(object sender, ElapsedEventArgs e) { if (!this.IsDisposed) { lock (SingleInvokeLock) { if (processingOnIdle) { // If the pending invoke has not completed, skip the timer event return; } processingOnIdle = true; } try { if (InvokeRequired) { Invoke(new Action(UiThread.InvokePendingActions)); } else { UiThread.InvokePendingActions(); } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { lock (SingleInvokeLock) { processingOnIdle = false; } } } } public abstract Graphics2D NewGraphics2D(); protected override void OnPaint(PaintEventArgs paintEventArgs) { if (AggSystemWindow == null || AggSystemWindow.HasBeenClosed) { return; } base.OnPaint(paintEventArgs); if (ShowingSystemDialog) { // We do this because calling Invalidate within an OnPaint message will cause our // SaveDialog to not show its 'overwrite' dialog if needed. // We use the Invalidate to cause a continuous pump of the OnPaint message to call our OnIdle. // We could figure another solution but it must be very careful to ensure we don't break SaveDialog return; } Rectangle rect = paintEventArgs.ClipRectangle; if (ClientSize.Width > 0 && ClientSize.Height > 0) { drawCount++; var graphics2D = this.NewGraphics2D(); if (!SingleWindowMode) { // We must call on draw background as this is effectively our child and that is the way it is done in GuiWidget. // Parents call child OnDrawBackground before they call OnDraw AggSystemWindow.OnDrawBackground(graphics2D); AggSystemWindow.OnDraw(graphics2D); } else { for (var i = 0; i < this.WindowProvider.OpenWindows.Count; i++) { graphics2D.FillRectangle(this.WindowProvider.OpenWindows[0].LocalBounds, new Color(Color.Black, 160)); this.WindowProvider.OpenWindows[i].OnDraw(graphics2D); } } /* var bitmap = new Bitmap((int)SystemWindow.Width, (int)SystemWindow.Height); paintEventArgs.Graphics.DrawImage(bitmap, 0, 0); bitmap.Save($"c:\\temp\\gah-{DateTime.Now.Ticks}.png"); */ CopyBackBufferToScreen(paintEventArgs.Graphics); } // use this to debug that windows are drawing and updating. // onPaintCount++; // Text = string.Format("Draw {0}, OnPaint {1}", drawCount, onPaintCount); } public abstract void CopyBackBufferToScreen(Graphics displayGraphics); protected override void OnPaintBackground(PaintEventArgs e) { // don't call this so that windows will not erase the background. //base.OnPaintBackground(e); } protected override void OnActivated(EventArgs e) { // focus the first child of the forms window (should be the system window) if (AggSystemWindow != null && AggSystemWindow.Children.Count > 0 && AggSystemWindow.Children.FirstOrDefault() != null) { AggSystemWindow.Children.FirstOrDefault().Focus(); } base.OnActivated(e); } protected override void OnResize(EventArgs e) { var systemWindow = AggSystemWindow; if (systemWindow != null) { systemWindow.LocalBounds = new RectangleDouble(0, 0, ClientSize.Width, ClientSize.Height); // Wait until the control is initialized (and thus WindowState has been set) to ensure we don't wipe out // the persisted data before its loaded if (this.IsInitialized) { // Push the current maximized state into the SystemWindow where it can be used or persisted by Agg applications systemWindow.Maximized = this.WindowState == FormWindowState.Maximized; } systemWindow.Invalidate(); } base.OnResize(e); } protected override void SetVisibleCore(bool value) { // Force Activation/BringToFront behavior when Visibility enabled. This ensures Agg forms // always come to front after ShowSystemWindow() if (value) { this.Activate(); } base.SetVisibleCore(value); } private bool winformAlreadyClosing = false; protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { if (AggSystemWindow != null && !AggSystemWindow.HasBeenClosed) { // Call on closing and check if we can close (a "do you want to save" might cancel the close. :). var eventArgs = new ClosingEventArgs(); AggSystemWindow.OnClosing(eventArgs); if (eventArgs.Cancel) { e.Cancel = true; } else { // Stop the RunOnIdle timer/pump if (this.IsMainWindow) { idleCallBackTimer.Elapsed -= InvokePendingOnIdleActions; idleCallBackTimer.Stop(); // Workaround for "Cannot access disposed object." exception // https://stackoverflow.com/a/9669702/84369 - ".Stop() without .DoEvents() is not enough, as it'll dispose objects without waiting for your thread to finish its work" Application.DoEvents(); } // Close the SystemWindow if (AggSystemWindow != null && !AggSystemWindow.HasBeenClosed) { // Store that the Close operation started here winformAlreadyClosing = true; AggSystemWindow.Close(); } } } base.OnClosing(e); } public ISystemWindowProvider WindowProvider { get; set; } #region WidgetForWindowsFormsAbstract/WinformsWindowWidget #endregion #region IPlatformWindow public new Keys ModifierKeys => (Keys)Control.ModifierKeys; /* // Can't simply override BringToFront. Change Interface method name/signature if required. Leaving as is * // to call base/this.BringToFront via Interface call public override void BringToFront() { // Numerous articles on the web claim that Activate does not always bring to front (something MatterControl // suffers when running automation tests). If we were to continue to use Activate, we might consider calling // BringToFront after this.Activate(); this.BringToFront(); }*/ // TODO: Why is this member named Caption instead of Title? public string Caption { get => this.Text; set => this.Text = value; } public Point2D DesktopPosition { get => new Point2D(this.DesktopLocation.X, this.DesktopLocation.Y); set { if (!this.Visible) { this.StartPosition = FormStartPosition.Manual; } this.DesktopLocation = new Point(value.x, value.y); } } public new void Show() { this.ClientSize = new Size((int)systemWindow.Width, (int)systemWindow.Height); // Center the window if specified on the SystemWindow if (MainWindowsFormsWindow != this && systemWindow.CenterInParent) { Rectangle desktopBounds = MainWindowsFormsWindow.DesktopBounds; RectangleDouble newItemBounds = systemWindow.LocalBounds; this.Left = desktopBounds.X + desktopBounds.Width / 2 - (int)newItemBounds.Width / 2; this.Top = desktopBounds.Y + desktopBounds.Height / 2 - (int)newItemBounds.Height / 2 - TitleBarHeight / 2; } else if (systemWindow.InitialDesktopPosition == new Point2D(-1, -1)) { this.CenterToScreen(); } else { this.StartPosition = FormStartPosition.Manual; this.DesktopPosition = systemWindow.InitialDesktopPosition; } if (MainWindowsFormsWindow != this && systemWindow.AlwaysOnTopOfMain) { base.Show(MainWindowsFormsWindow); } else { base.Show(); } } public void ShowModal() { // Release the onidle guard so that the onidle pump continues processing while we block at ShowDialog below Task.Run(() => this.ReleaseOnIdleGuard()); if (MainWindowsFormsWindow != this && systemWindow.CenterInParent) { Rectangle mainBounds = MainWindowsFormsWindow.DesktopBounds; RectangleDouble newItemBounds = systemWindow.LocalBounds; this.Left = mainBounds.X + mainBounds.Width / 2 - (int)newItemBounds.Width / 2; this.Top = mainBounds.Y + mainBounds.Height / 2 - (int)newItemBounds.Height / 2; } this.ShowDialog(); } public void Invalidate(RectangleDouble rectToInvalidate) { // Ignore problems with buggy WinForms on Linux try { this.Invalidate(); } catch (Exception e) { Console.WriteLine("WinForms Exception: " + e.Message); } } public void SetCursor(Cursors cursorToSet) { switch (cursorToSet) { case Cursors.Arrow: this.Cursor = System.Windows.Forms.Cursors.Arrow; break; case Cursors.Hand: this.Cursor = System.Windows.Forms.Cursors.Hand; break; case Cursors.IBeam: this.Cursor = System.Windows.Forms.Cursors.IBeam; break; case Cursors.Cross: this.Cursor = System.Windows.Forms.Cursors.Cross; break; case Cursors.Default: this.Cursor = System.Windows.Forms.Cursors.Default; break; case Cursors.Help: this.Cursor = System.Windows.Forms.Cursors.Help; break; case Cursors.HSplit: this.Cursor = System.Windows.Forms.Cursors.HSplit; break; case Cursors.No: this.Cursor = System.Windows.Forms.Cursors.No; break; case Cursors.NoMove2D: this.Cursor = System.Windows.Forms.Cursors.NoMove2D; break; case Cursors.NoMoveHoriz: this.Cursor = System.Windows.Forms.Cursors.NoMoveHoriz; break; case Cursors.NoMoveVert: this.Cursor = System.Windows.Forms.Cursors.NoMoveVert; break; case Cursors.PanEast: this.Cursor = System.Windows.Forms.Cursors.PanEast; break; case Cursors.PanNE: this.Cursor = System.Windows.Forms.Cursors.PanNE; break; case Cursors.PanNorth: this.Cursor = System.Windows.Forms.Cursors.PanNorth; break; case Cursors.PanNW: this.Cursor = System.Windows.Forms.Cursors.PanNW; break; case Cursors.PanSE: this.Cursor = System.Windows.Forms.Cursors.PanSE; break; case Cursors.PanSouth: this.Cursor = System.Windows.Forms.Cursors.PanSouth; break; case Cursors.PanSW: this.Cursor = System.Windows.Forms.Cursors.PanSW; break; case Cursors.PanWest: this.Cursor = System.Windows.Forms.Cursors.PanWest; break; case Cursors.SizeAll: this.Cursor = System.Windows.Forms.Cursors.SizeAll; break; case Cursors.SizeNESW: this.Cursor = System.Windows.Forms.Cursors.SizeNESW; break; case Cursors.SizeNS: this.Cursor = System.Windows.Forms.Cursors.SizeNS; break; case Cursors.SizeNWSE: this.Cursor = System.Windows.Forms.Cursors.SizeNWSE; break; case Cursors.SizeWE: this.Cursor = System.Windows.Forms.Cursors.SizeWE; break; case Cursors.UpArrow: this.Cursor = System.Windows.Forms.Cursors.UpArrow; break; case Cursors.VSplit: this.Cursor = System.Windows.Forms.Cursors.VSplit; break; case Cursors.WaitCursor: this.Cursor = System.Windows.Forms.Cursors.WaitCursor; break; } } public int TitleBarHeight { get; private set; } = 0; #endregion #region Agg Event Proxies /* protected override void OnMouseLeave(EventArgs e) { SystemWindow.OnMouseMove(new MatterHackers.Agg.UI.MouseEventArgs(MatterHackers.Agg.UI.MouseButtons.None, 0, -10, -10, 0)); base.OnMouseLeave(e); } protected override void OnGotFocus(EventArgs e) { SystemWindow.OnFocusChanged(e); base.OnGotFocus(e); } protected override void OnLostFocus(EventArgs e) { SystemWindow.Unfocus(); SystemWindow.OnFocusChanged(e); base.OnLostFocus(e); } protected override void OnKeyDown(System.Windows.Forms.KeyEventArgs e) { MatterHackers.Agg.UI.KeyEventArgs aggKeyEvent; if (OsInformation.OperatingSystem == OSType.Mac && (e.KeyData & System.Windows.Forms.Keys.Alt) == System.Windows.Forms.Keys.Alt) { aggKeyEvent = new MatterHackers.Agg.UI.KeyEventArgs((MatterHackers.Agg.UI.Keys)(System.Windows.Forms.Keys.Control | (e.KeyData & ~System.Windows.Forms.Keys.Alt))); } else { aggKeyEvent = new MatterHackers.Agg.UI.KeyEventArgs((MatterHackers.Agg.UI.Keys)e.KeyData); } SystemWindow.OnKeyDown(aggKeyEvent); Keyboard.SetKeyDownState(aggKeyEvent.KeyCode, true); e.Handled = aggKeyEvent.Handled; e.SuppressKeyPress = aggKeyEvent.SuppressKeyPress; base.OnKeyDown(e); } protected override void OnKeyUp(System.Windows.Forms.KeyEventArgs e) { MatterHackers.Agg.UI.KeyEventArgs aggKeyEvent = new MatterHackers.Agg.UI.KeyEventArgs((MatterHackers.Agg.UI.Keys)e.KeyData); SystemWindow.OnKeyUp(aggKeyEvent); Keyboard.SetKeyDownState(aggKeyEvent.KeyCode, false); e.Handled = aggKeyEvent.Handled; e.SuppressKeyPress = aggKeyEvent.SuppressKeyPress; base.OnKeyUp(e); } protected override void OnKeyPress(System.Windows.Forms.KeyPressEventArgs e) { MatterHackers.Agg.UI.KeyPressEventArgs aggKeyPressEvent = new MatterHackers.Agg.UI.KeyPressEventArgs(e.KeyChar); SystemWindow.OnKeyPress(aggKeyPressEvent); e.Handled = aggKeyPressEvent.Handled; base.OnKeyPress(e); } private MatterHackers.Agg.UI.MouseEventArgs ConvertWindowsMouseEventToAggMouseEvent(System.Windows.Forms.MouseEventArgs windowsMouseEvent) { // we invert the y as we are bottom left coordinate system and windows is top left. int Y = windowsMouseEvent.Y; Y = (int)SystemWindow.BoundsRelativeToParent.Height - Y; return new MatterHackers.Agg.UI.MouseEventArgs((MatterHackers.Agg.UI.MouseButtons)windowsMouseEvent.Button, windowsMouseEvent.Clicks, windowsMouseEvent.X, Y, windowsMouseEvent.Delta); } protected override void OnMouseDown(System.Windows.Forms.MouseEventArgs e) { SystemWindow.OnMouseDown(ConvertWindowsMouseEventToAggMouseEvent(e)); base.OnMouseDown(e); } protected override void OnMouseMove(System.Windows.Forms.MouseEventArgs e) { // TODO: Remove short term workaround for automation issues where mouse events fire differently if mouse is within window region if (!EnableInputHook) { return; } SystemWindow.OnMouseMove(ConvertWindowsMouseEventToAggMouseEvent(e)); base.OnMouseMove(e); } protected override void OnMouseUp(System.Windows.Forms.MouseEventArgs e) { SystemWindow.OnMouseUp(ConvertWindowsMouseEventToAggMouseEvent(e)); base.OnMouseUp(e); } protected override void OnMouseCaptureChanged(EventArgs e) { if (SystemWindow.ChildHasMouseCaptured || SystemWindow.MouseCaptured) { SystemWindow.OnMouseUp(new MatterHackers.Agg.UI.MouseEventArgs(Agg.UI.MouseButtons.Left, 0, -10, -10, 0)); } base.OnMouseCaptureChanged(e); } protected override void OnMouseWheel(System.Windows.Forms.MouseEventArgs e) { SystemWindow.OnMouseWheel(ConvertWindowsMouseEventToAggMouseEvent(e)); base.OnMouseWheel(e); } */ #endregion public new Vector2 MinimumSize { get => new Vector2(base.MinimumSize.Width, base.MinimumSize.Height); set { var clientSize = new Size((int)Math.Ceiling(value.X), (int)Math.Ceiling(value.Y)); var windowSize = new Size( clientSize.Width + this.Width - this.ClientSize.Width, clientSize.Height + this.Height - this.ClientSize.Height); base.MinimumSize = windowSize; } } private static bool firstWindow = true; public void ShowSystemWindow(SystemWindow systemWindow) { // If ShowSystemWindow is called on loaded/visible SystemWindow, call BringToFront and exit if (systemWindow.PlatformWindow == this && !SingleWindowMode) { this.BringToFront(); return; } // Set the active SystemWindow & PlatformWindow references this.AggSystemWindow = systemWindow; systemWindow.PlatformWindow = this; systemWindow.AnchorAll(); if (firstWindow) { firstWindow = false; this.Show(); Application.Run(this); } else if (!SingleWindowMode) { UiThread.RunOnIdle(() => { if (systemWindow.IsModal) { this.ShowModal(); } else { this.Show(); this.BringToFront(); } }); } else if (SingleWindowMode) { // Notify the embedded window of its new single windows parent size // If client code has called ShowSystemWindow and we're minimized, we must restore in order // to establish correct window bounds from ClientSize below. Otherwise we're zeroed out and // will create invalid surfaces of (0,0) if (this.WindowState == FormWindowState.Minimized) { this.WindowState = FormWindowState.Normal; } systemWindow.Size = new Vector2( this.ClientSize.Width, this.ClientSize.Height); } } public void CloseSystemWindow(SystemWindow systemWindow) { // Prevent our call to SystemWindow.Close from recursing if (winformAlreadyClosing) { return; } // Check for RootSystemWindow, close if found string windowTypeName = systemWindow.GetType().Name; if ((SingleWindowMode && windowTypeName == "RootSystemWindow") || (MainWindowsFormsWindow != null && systemWindow == MainWindowsFormsWindow.systemWindow && !SingleWindowMode)) { // Close the main (first) PlatformWindow if it's being requested and not this instance if (MainWindowsFormsWindow.InvokeRequired) { MainWindowsFormsWindow.Invoke((Action)MainWindowsFormsWindow.Close); } else { MainWindowsFormsWindow.Close(); } return; } if (SingleWindowMode) { AggSystemWindow = this.WindowProvider.TopWindow; AggSystemWindow?.Invalidate(); } else { if (!this.IsDisposed && !this.Disposing) { if (this.InvokeRequired) { this.Invoke((Action)this.Close); } else { this.Close(); } } } } public class FormInspector : Form { public virtual bool Inspecting { get; set; } = true; } } }
using NetApp.Tests.Helpers; using Microsoft.Azure.Management.NetApp.Models; using Microsoft.Azure.Management.NetApp; using Microsoft.Azure.Management.Resources; using Microsoft.Azure.Test.HttpRecorder; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using System.IO; using System.Linq; using System.Net; using System.Reflection; using Xunit; using System; using System.Collections.Generic; using System.Threading; using System.ComponentModel; using Microsoft.Rest.Azure; namespace NetApp.Tests.ResourceTests { public class VolumeTests : TestBase { private const int delay = 10000; public static ExportPolicyRule exportPolicyRule = new ExportPolicyRule() { RuleIndex = 1, UnixReadOnly = false, UnixReadWrite = true, Cifs = false, Nfsv3 = true, Nfsv41 = false, AllowedClients = "1.2.3.0/24" }; public static IList<ExportPolicyRule> exportPolicyRuleList = new List<ExportPolicyRule>() { exportPolicyRule }; public static VolumePropertiesExportPolicy exportPolicy = new VolumePropertiesExportPolicy() { Rules = exportPolicyRuleList }; public static VolumePatchPropertiesExportPolicy exportPatchPolicy = new VolumePatchPropertiesExportPolicy() { Rules = exportPolicyRuleList }; [Fact] public void CreateDeleteVolume() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // create a volume, get all and check var resource = ResourceUtils.CreateVolume(netAppMgmtClient); Assert.Equal(ResourceUtils.defaultExportPolicy.ToString(), resource.ExportPolicy.ToString()); Assert.Null(resource.Tags); // check DP properties exist but unassigned because // dataprotection volume was not created Assert.Null(resource.VolumeType); Assert.Null(resource.DataProtection); var volumesBefore = netAppMgmtClient.Volumes.List(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1); Assert.Single(volumesBefore); // delete the volume and check again netAppMgmtClient.Volumes.Delete(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1); var volumesAfter = netAppMgmtClient.Volumes.List(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1); Assert.Empty(volumesAfter); // cleanup ResourceUtils.DeletePool(netAppMgmtClient); ResourceUtils.DeleteAccount(netAppMgmtClient); } } [Fact] public void CreateVolumeWithProperties() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // create a volume with tags and export policy var dict = new Dictionary<string, string>(); dict.Add("Tag2", "Value2"); var protocolTypes = new List<string>() { "NFSv3" }; var resource = ResourceUtils.CreateVolume(netAppMgmtClient, protocolTypes: protocolTypes, tags: dict, exportPolicy: exportPolicy); Assert.Equal(exportPolicy.ToString(), resource.ExportPolicy.ToString()); Assert.Equal(protocolTypes, resource.ProtocolTypes); Assert.True(resource.Tags.ContainsKey("Tag2")); Assert.Equal("Value2", resource.Tags["Tag2"]); var volumesBefore = netAppMgmtClient.Volumes.List(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1); Assert.Single(volumesBefore); // delete the volume and check again netAppMgmtClient.Volumes.Delete(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1); var volumesAfter = netAppMgmtClient.Volumes.List(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1); Assert.Empty(volumesAfter); // cleanup ResourceUtils.DeletePool(netAppMgmtClient); ResourceUtils.DeleteAccount(netAppMgmtClient); } } [Fact] public void ListVolumes() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // create two volumes under same pool ResourceUtils.CreateVolume(netAppMgmtClient); ResourceUtils.CreateVolume(netAppMgmtClient, ResourceUtils.volumeName2, volumeOnly: true); // get the account list and check var volumes = netAppMgmtClient.Volumes.List(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1); //Assert.Equal(volumes.ElementAt(1).Name, ResourceUtils.accountName1 + '/' + ResourceUtils.poolName1 + '/' + ResourceUtils.volumeName1); //Assert.Equal(volumes.ElementAt(0).Name, ResourceUtils.accountName1 + '/' + ResourceUtils.poolName1 + '/' + ResourceUtils.volumeName2); Assert.Contains(volumes, item => item.Name == $"{ResourceUtils.accountName1}/{ResourceUtils.poolName1}/{ResourceUtils.volumeName1}"); Assert.Contains(volumes, item => item.Name == $"{ResourceUtils.accountName1}/{ResourceUtils.poolName1}/{ResourceUtils.volumeName2}"); Assert.Equal(2, volumes.Count()); // clean up - delete the two volumes, the pool and the account ResourceUtils.DeleteVolume(netAppMgmtClient); ResourceUtils.DeleteVolume(netAppMgmtClient, ResourceUtils.volumeName2); ResourceUtils.DeletePool(netAppMgmtClient); ResourceUtils.DeleteAccount(netAppMgmtClient); } } [Fact] public void GetVolumeByName() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // create the volume ResourceUtils.CreateVolume(netAppMgmtClient); // retrieve it var volume = netAppMgmtClient.Volumes.Get(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1); Assert.Equal(volume.Name, ResourceUtils.accountName1 + '/' + ResourceUtils.poolName1 + '/' + ResourceUtils.volumeName1); // clean up - delete the volume, pool and account ResourceUtils.DeleteVolume(netAppMgmtClient); ResourceUtils.DeletePool(netAppMgmtClient); ResourceUtils.DeleteAccount(netAppMgmtClient); } } [Fact] public void GetVolumeByNameNotFound() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // create volume ResourceUtils.CreatePool(netAppMgmtClient); // try and get a volume in the pool - none have been created yet try { var volume = netAppMgmtClient.Volumes.Get(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1); Assert.True(false); // expecting exception } catch (Exception ex) { Assert.Contains("was not found", ex.Message); } // cleanup ResourceUtils.DeletePool(netAppMgmtClient); ResourceUtils.DeleteAccount(netAppMgmtClient); } } [Fact] public void GetVolumeByNamePoolNotFound() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); ResourceUtils.CreateAccount(netAppMgmtClient); // try and create a volume before the pool exist try { var volume = netAppMgmtClient.Volumes.Get(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1); Assert.True(false); // expecting exception } catch (Exception ex) { Assert.Contains("not found", ex.Message); } // cleanup - remove the account ResourceUtils.DeleteAccount(netAppMgmtClient); } } [Fact] public void CreateVolumePoolNotFound() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); ResourceUtils.CreateAccount(netAppMgmtClient); // try and create a volume before the pool exist try { ResourceUtils.CreateVolume(netAppMgmtClient, volumeOnly: true); Assert.True(false); // expecting exception } catch (Exception ex) { Assert.Contains("not found", ex.Message); } // cleanup - remove the account ResourceUtils.DeleteAccount(netAppMgmtClient); } } [Fact] public void DeletePoolWithVolumePresent() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // create the account and pool ResourceUtils.CreateVolume(netAppMgmtClient); var poolsBefore = netAppMgmtClient.Pools.List(ResourceUtils.resourceGroup, ResourceUtils.accountName1); Assert.Single(poolsBefore); // try and delete the pool try { netAppMgmtClient.Pools.Delete(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1); Assert.True(false); // expecting exception } catch (Exception ex) { Assert.Contains("Can not delete resource before nested resources are deleted", ex.Message); } // clean up ResourceUtils.DeleteVolume(netAppMgmtClient); ResourceUtils.DeletePool(netAppMgmtClient); ResourceUtils.DeleteAccount(netAppMgmtClient); } } [Fact] public void CheckAvailability() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // check account resource name - should be available var response = netAppMgmtClient.NetAppResource.CheckNameAvailability(ResourceUtils.location, ResourceUtils.accountName1, CheckNameResourceTypes.MicrosoftNetAppNetAppAccounts, ResourceUtils.resourceGroup); Assert.True(response.IsAvailable); // now check file path availability response = netAppMgmtClient.NetAppResource.CheckFilePathAvailability(ResourceUtils.location, ResourceUtils.volumeName1, CheckNameResourceTypes.MicrosoftNetAppNetAppAccountsCapacityPoolsVolumes, ResourceUtils.resourceGroup); Assert.True(response.IsAvailable); // create the volume var volume = ResourceUtils.CreateVolume(netAppMgmtClient); // check volume resource name - should be unavailable after its creation var resourceName = ResourceUtils.accountName1 + '/' + ResourceUtils.poolName1 + '/' + ResourceUtils.volumeName1; response = netAppMgmtClient.NetAppResource.CheckNameAvailability(ResourceUtils.location, resourceName, CheckNameResourceTypes.MicrosoftNetAppNetAppAccountsCapacityPoolsVolumes, ResourceUtils.resourceGroup); Assert.False(response.IsAvailable); // now check file path availability again response = netAppMgmtClient.NetAppResource.CheckFilePathAvailability(ResourceUtils.location, ResourceUtils.volumeName1, CheckNameResourceTypes.MicrosoftNetAppNetAppAccountsCapacityPoolsVolumes, ResourceUtils.resourceGroup); Assert.False(response.IsAvailable); // clean up ResourceUtils.DeleteVolume(netAppMgmtClient); ResourceUtils.DeletePool(netAppMgmtClient); ResourceUtils.DeleteAccount(netAppMgmtClient); } } [Fact] public void UpdateVolume() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // create the volume var oldVolume = ResourceUtils.CreateVolume(netAppMgmtClient); Assert.Equal("Premium", oldVolume.ServiceLevel); Assert.Equal(100 * ResourceUtils.gibibyte, oldVolume.UsageThreshold); // The returned volume contains some items which cnanot be part of the payload, such as baremetaltenant, therefore create a new object selectively from the old one var volume = new Volume { Location = oldVolume.Location, ServiceLevel = oldVolume.ServiceLevel, CreationToken = oldVolume.CreationToken, SubnetId = oldVolume.SubnetId, }; // update volume.UsageThreshold = 2 * oldVolume.UsageThreshold; var updatedVolume = netAppMgmtClient.Volumes.CreateOrUpdate(volume, ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1); Assert.Equal("Premium", updatedVolume.ServiceLevel); // didn't attempt to change - it would be rejected Assert.Equal(100 * ResourceUtils.gibibyte * 2, updatedVolume.UsageThreshold); // cleanup ResourceUtils.DeleteVolume(netAppMgmtClient); ResourceUtils.DeletePool(netAppMgmtClient); ResourceUtils.DeleteAccount(netAppMgmtClient); } } [Fact] public void PatchVolume() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // create the volume var volume = ResourceUtils.CreateVolume(netAppMgmtClient); Assert.Equal("Premium", volume.ServiceLevel); Assert.Equal(100 * ResourceUtils.gibibyte, volume.UsageThreshold); Assert.Equal(ResourceUtils.defaultExportPolicy.ToString(), volume.ExportPolicy.ToString()); Assert.Null(volume.Tags); // create a volume with tags and export policy var dict = new Dictionary<string, string>(); dict.Add("Tag2", "Value2"); // Now try and modify it var volumePatch = new VolumePatch() { UsageThreshold = 2 * volume.UsageThreshold, Tags = dict, ExportPolicy = exportPatchPolicy }; // patch var updatedVolume = netAppMgmtClient.Volumes.Update(volumePatch, ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1); Assert.Equal("Premium", updatedVolume.ServiceLevel); // didn't attempt to change - it would be rejected Assert.Equal(200 * ResourceUtils.gibibyte, updatedVolume.UsageThreshold); Assert.Equal(exportPolicy.ToString(), updatedVolume.ExportPolicy.ToString()); Assert.True(updatedVolume.Tags.ContainsKey("Tag2")); Assert.Equal("Value2", updatedVolume.Tags["Tag2"]); // cleanup ResourceUtils.DeleteVolume(netAppMgmtClient); ResourceUtils.DeletePool(netAppMgmtClient); ResourceUtils.DeleteAccount(netAppMgmtClient); } } private void WaitForReplicationStatus(AzureNetAppFilesManagementClient netAppMgmtClient, string targetState) { ReplicationStatus replicationStatus = new ReplicationStatus {Healthy=false, MirrorState = "Uninitialized" }; int attempts = 0; do { try { replicationStatus = netAppMgmtClient.Volumes.ReplicationStatusMethod(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.volumeName1ReplDest); } catch(CloudException ex) { if (!ex.Message.Contains("the volume replication is: 'Creating'")) { throw; } } Thread.Sleep(1); } while (replicationStatus.MirrorState != targetState); //sometimes they dont sync up right away if (!replicationStatus.Healthy.Value) { do { replicationStatus = netAppMgmtClient.Volumes.ReplicationStatusMethod(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.volumeName1ReplDest); attempts++; if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record") { Thread.Sleep(1000); } } while (replicationStatus.Healthy.Value || attempts == 10); } Assert.True(replicationStatus.Healthy); } private void WaitForSucceeded(AzureNetAppFilesManagementClient netAppMgmtClient, string accountName = ResourceUtils.accountName1, string poolName = ResourceUtils.poolName1, string volumeName = ResourceUtils.volumeName1) { Volume sourceVolume; Volume dpVolume; do { sourceVolume = netAppMgmtClient.Volumes.Get(ResourceUtils.repResourceGroup, accountName, poolName, volumeName); dpVolume = netAppMgmtClient.Volumes.Get(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.volumeName1ReplDest); Thread.Sleep(1); } while ((sourceVolume.ProvisioningState != "Succeeded") || (dpVolume.ProvisioningState != "Succeeded")); } [Fact] public void CreateDpVolume() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // create the source volume var sourceVolume = ResourceUtils.CreateVolume(netAppMgmtClient, resourceGroup: ResourceUtils.repResourceGroup, vnet: ResourceUtils.repVnet, volumeName: ResourceUtils.volumeName1ReplSource, accountName: ResourceUtils.accountName1Repl, poolName: ResourceUtils.poolName1Repl); sourceVolume = netAppMgmtClient.Volumes.Get(ResourceUtils.repResourceGroup, ResourceUtils.accountName1Repl, ResourceUtils.poolName1Repl, ResourceUtils.volumeName1ReplSource); if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record") { Thread.Sleep(delay); // some robustness against ARM caching } // create the data protection volume from the source var dpVolume = ResourceUtils.CreateDpVolume(netAppMgmtClient, sourceVolume); Assert.Equal(ResourceUtils.volumeName1ReplDest, dpVolume.Name.Substring(dpVolume.Name.LastIndexOf('/') + 1)); Assert.NotNull(dpVolume.DataProtection); if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record") { Thread.Sleep(30000); } var getDPVolume = netAppMgmtClient.Volumes.Get(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.volumeName1ReplDest); var authorizeRequest = new AuthorizeRequest { RemoteVolumeResourceId = dpVolume.Id }; netAppMgmtClient.Volumes.AuthorizeReplication(ResourceUtils.repResourceGroup, ResourceUtils.accountName1Repl, ResourceUtils.poolName1Repl, ResourceUtils.volumeName1ReplSource, authorizeRequest); if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record") { Thread.Sleep(30000); } WaitForSucceeded(netAppMgmtClient, accountName: ResourceUtils.accountName1Repl, poolName: ResourceUtils.poolName1Repl, volumeName: ResourceUtils.volumeName1ReplSource); WaitForReplicationStatus(netAppMgmtClient, "Mirrored"); netAppMgmtClient.Volumes.BreakReplication(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.volumeName1ReplDest); WaitForReplicationStatus(netAppMgmtClient, "Broken"); if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record") { Thread.Sleep(30000); } // sync to the test WaitForSucceeded(netAppMgmtClient, accountName: ResourceUtils.accountName1Repl, poolName: ResourceUtils.poolName1Repl, volumeName: ResourceUtils.volumeName1ReplSource); // resync netAppMgmtClient.Volumes.ResyncReplication(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.volumeName1ReplDest); WaitForReplicationStatus(netAppMgmtClient, "Mirrored"); if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record") { Thread.Sleep(30000); } // break again netAppMgmtClient.Volumes.BreakReplication(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.volumeName1ReplDest); WaitForReplicationStatus(netAppMgmtClient, "Broken"); if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record") { Thread.Sleep(30000); } // delete the data protection object // - initiate delete replication on destination, this then releases on source, both resulting in object deletion netAppMgmtClient.Volumes.DeleteReplication(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.volumeName1ReplDest); var replicationFound = true; // because it was previously present while (replicationFound) { try { var replicationStatus = netAppMgmtClient.Volumes.ReplicationStatusMethod(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.volumeName1ReplDest); } catch { // an exception means the replication was not found // i.e. it has been deleted // ok without checking it could have been for another reason // but then the delete below will fail replicationFound = false; } Thread.Sleep(1); } // seems the volumes are not always in a terminal state here so check again // and ensure the replication objects are removed do { sourceVolume = netAppMgmtClient.Volumes.Get(ResourceUtils.repResourceGroup, ResourceUtils.accountName1Repl, ResourceUtils.poolName1Repl, ResourceUtils.volumeName1ReplSource); dpVolume = netAppMgmtClient.Volumes.Get(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.volumeName1ReplDest); Thread.Sleep(1); } while ((sourceVolume.ProvisioningState != "Succeeded") || (dpVolume.ProvisioningState != "Succeeded") || (sourceVolume.DataProtection.Replication != null) || (dpVolume.DataProtection.Replication != null)); // now proceed with the delete of the volumes netAppMgmtClient.Volumes.Delete(ResourceUtils.remoteResourceGroup, ResourceUtils.remoteAccountName1, ResourceUtils.remotePoolName1, ResourceUtils.volumeName1ReplDest); netAppMgmtClient.Volumes.Delete(ResourceUtils.repResourceGroup, ResourceUtils.accountName1Repl, ResourceUtils.poolName1Repl, ResourceUtils.volumeName1ReplSource); // cleanup pool and account ResourceUtils.DeletePool(netAppMgmtClient, resourceGroup: ResourceUtils.repResourceGroup, accountName: ResourceUtils.accountName1Repl, poolName: ResourceUtils.poolName1Repl); ResourceUtils.DeletePool(netAppMgmtClient, ResourceUtils.remotePoolName1, ResourceUtils.remoteAccountName1, ResourceUtils.remoteResourceGroup); if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record") { Thread.Sleep(30000); } ResourceUtils.DeleteAccount(netAppMgmtClient, accountName: ResourceUtils.accountName1Repl, resourceGroup: ResourceUtils.repResourceGroup); ResourceUtils.DeleteAccount(netAppMgmtClient, ResourceUtils.remoteAccountName1, ResourceUtils.remoteResourceGroup); } } [Fact] public void ChangePoolForVolume() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // create the volume var volume = ResourceUtils.CreateVolume(netAppMgmtClient); // create the other pool var secondPool = ResourceUtils.CreatePool(netAppMgmtClient, ResourceUtils.poolName2, accountName: ResourceUtils.accountName1, resourceGroup: ResourceUtils.resourceGroup, location: ResourceUtils.location, poolOnly: true, serviceLevel: ServiceLevel.Standard); Assert.Equal("Premium", volume.ServiceLevel); Assert.Equal(100 * ResourceUtils.gibibyte, volume.UsageThreshold); if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record") { Thread.Sleep(30000); } var poolChangeRequest = new PoolChangeRequest() { NewPoolResourceId = secondPool.Id }; //Change pools netAppMgmtClient.Volumes.PoolChange(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName1, ResourceUtils.volumeName1, poolChangeRequest); if (Environment.GetEnvironmentVariable("AZURE_TEST_MODE") == "Record") { Thread.Sleep(30000); } // retrieve the volume and check var volume2 = netAppMgmtClient.Volumes.Get(ResourceUtils.resourceGroup, ResourceUtils.accountName1, ResourceUtils.poolName2, ResourceUtils.volumeName1); Assert.Equal(volume2.Name, ResourceUtils.accountName1 + '/' + ResourceUtils.poolName2 + '/' + ResourceUtils.volumeName1); // cleanup ResourceUtils.DeleteVolume(netAppMgmtClient, volumeName: ResourceUtils.volumeName1, accountName: ResourceUtils.accountName1, poolName: ResourceUtils.poolName2); ResourceUtils.DeletePool(netAppMgmtClient); ResourceUtils.DeletePool(netAppMgmtClient, poolName: ResourceUtils.poolName2); ResourceUtils.DeleteAccount(netAppMgmtClient); } } [Fact] public void LongListVolumes() { HttpMockServer.RecordsDirectory = GetSessionsDirectoryPath(); using (MockContext context = MockContext.Start(this.GetType())) { var netAppMgmtClient = NetAppTestUtilities.GetNetAppManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); //get list of volumnes var volumesPage = netAppMgmtClient.Volumes.List("sara-systemic", "Sara-Systemic-NA", "Sara-Systemic-CP"); // Get all resources by polling on next page link var volumeResponseList = ListNextLink<Volume>.GetAllResourcesByPollingNextLink(volumesPage, netAppMgmtClient.Volumes.ListNext); var volumesList = new List<Volume>(); foreach (var volume in volumeResponseList) { volumesList.Add(volume); } Assert.Equal(166, volumesList.Count()); } } private static string GetSessionsDirectoryPath() { string executingAssemblyPath = typeof(NetApp.Tests.ResourceTests.VolumeTests).GetTypeInfo().Assembly.Location; return Path.Combine(Path.GetDirectoryName(executingAssemblyPath), "SessionRecords"); } } }
/* * Project: WhaTBI? (What's The Big Idea?) * Filename: Database.cs * Description: Database-based datasources */ using System; using System.Collections; using System.Data; using System.Data.SqlClient; using System.IO; using Finisar.SQLite; namespace Pdbartlett.Whatbi { public enum DatabaseType { MsSqlServer, SQLite } public interface IDbObjectFactory { IDbConnection GetConnection(); IDbCommand GetCommand(); IDataParameter GetParameter(string name, DbType type, int length, object oValue); } public abstract class DatabaseDataSourceHelper : DataSourceHelper, IUpdatableDataSource { private IDbObjectFactory m_factory; private IORMapping m_mapper; protected IDbObjectFactory Factory { get { if (m_factory == null) throw new BaseException("Factory not set"); return m_factory; } set { if (value == null) throw new ArgumentNullException(); m_factory = value; } } protected IORMapping Mapper { get { if (m_mapper == null) throw new BaseException("Mapper not set"); return m_mapper; } set { if (value == null) throw new ArgumentNullException(); m_mapper = value; } } protected DatabaseDataSourceHelper() { } protected DatabaseDataSourceHelper(IDbObjectFactory factory, IORMapping mapper) { Factory = factory; Mapper = mapper; } public override int Count { get { return (int)ExecuteSqlScalar(Mapper.GetCountCmd()); } } protected override ICollection InternalGetAll(out bool IsCopy) { IsCopy = true; return ExecuteSqlQuery(Mapper.GetAllCmd()); } public void Insert(object obj) { ExecuteSqlCmd(Mapper.GetInsertCmd(obj)); } public void Update(object obj) { ExecuteSqlCmd(Mapper.GetUpdateCmd(obj)); } public void Delete(object key) { ExecuteSqlCmd(Mapper.GetDeleteCmd(key)); } public override ICollection Query(IPredicate pred) { ICollection results = QueryAsSql(pred); return results == null ? base.Query(pred) : results; } private ICollection QueryAsSql(object query) { ISqlConvertible sqlQuery = query as ISqlConvertible; if (sqlQuery != null) { try { IDbCommand cmd = Mapper.GetQueryCmd(sqlQuery.ConvertToSql(Mapper)); return ExecuteSqlQuery(cmd); } catch (Exception) {} } return null; } private ICollection ExecuteSqlQuery(IDbCommand cmd) { using (cmd) { ArrayList data = new ArrayList(); using (IDbConnection conn = Factory.GetConnection()) { conn.Open(); cmd.Connection = conn; using (IDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) data.Add(Mapper.ExtractObjectFromDataReader(reader)); } } return data; } } private void ExecuteSqlCmd(IDbCommand cmd) { using (cmd) { using (IDbConnection conn = Factory.GetConnection()) { conn.Open(); cmd.Connection = conn; int cRows = cmd.ExecuteNonQuery(); switch (cRows) { case 0: throw new BaseException("SQL command failed: " + cmd.CommandText); case 1: return; default: throw new BaseException("Unexpected results from SQL command '" + cmd.CommandText + "': " + cRows.ToString() + " rows affected."); } } } } private object ExecuteSqlScalar(IDbCommand cmd) { using (cmd) { using (IDbConnection conn = Factory.GetConnection()) { conn.Open(); cmd.Connection = conn; return cmd.ExecuteScalar(); } } } public static IDbObjectFactory GetFactory(DatabaseType type, string server, string database) { if (!Enum.IsDefined(typeof(DatabaseType), type)) throw new ArgumentException("type"); switch(type) { case DatabaseType.MsSqlServer: return new SqlServerFactory(server, database); case DatabaseType.SQLite: return new SQLiteFactory(server, database); default: throw new BaseException("Unsupported database type: " + type); } } } public class SqlServerFactory : IDbObjectFactory { private string m_connectionString; public SqlServerFactory(string server, string database) { m_connectionString = String.Format("Server={0};Database={1};Integrated Security=SSPI", server, database); } public IDbConnection GetConnection() { return new SqlConnection(m_connectionString); } public IDbCommand GetCommand() { return new SqlCommand(); } public IDataParameter GetParameter(string name, DbType type, int len, object oValue) { SqlParameter param = new SqlParameter(name, ConvertType(type), len); param.Value = oValue; return param; } private static SqlDbType ConvertType(DbType type) { switch(type) { case DbType.String: return SqlDbType.NVarChar; case DbType.AnsiString: return SqlDbType.VarChar; default: throw new ArgumentException("Unsupport database type"); } } } public class SQLiteFactory : IDbObjectFactory { private string m_connectionString; public SQLiteFactory(string server, string database) { if (server != null && server.Length > 0) throw new ArgumentException("Sqlite only supports local connections - server should not be specified"); bool create = !File.Exists(database); m_connectionString = String.Format("Data Source={0};New={1};Compress=True", database, create); } public IDbConnection GetConnection() { return new SQLiteConnection(m_connectionString); } public IDbCommand GetCommand() { return new SQLiteCommand(); } public IDataParameter GetParameter(string name, DbType type, int len, object oValue) { return new SQLiteParameter(name, type); } } }
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* using SDKTemplate; using System; using System.Collections.Generic; using System.Threading.Tasks; using Windows.Devices.Enumeration; using Windows.Media.Audio; using Windows.Media.Capture; using Windows.Media.Devices; using Windows.Media.MediaProperties; using Windows.Media.Render; using Windows.Media.Transcoding; using Windows.Storage; using Windows.Storage.Pickers; using Windows.UI; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace AudioCreation { /// <summary> /// This scenario shows using AudioGraph for audio capture from a microphone with low latency. /// </summary> public sealed partial class Scenario2_DeviceCapture : Page { private MainPage rootPage; private AudioGraph graph; private AudioFileOutputNode fileOutputNode; private AudioDeviceOutputNode deviceOutputNode; private AudioDeviceInputNode deviceInputNode; private DeviceInformationCollection outputDevices; public Scenario2_DeviceCapture() { this.InitializeComponent(); } protected override async void OnNavigatedTo(NavigationEventArgs e) { rootPage = MainPage.Current; await PopulateDeviceList(); } protected override void OnNavigatedFrom(NavigationEventArgs e) { if (graph != null) { graph.Dispose(); } } private async void FileButton_Click(object sender, RoutedEventArgs e) { await SelectOutputFile(); } private async void RecordStopButton_Click(object sender, RoutedEventArgs e) { await ToggleRecordStop(); } private async void CreateGraphButton_Click(object sender, RoutedEventArgs e) { await CreateAudioGraph(); } private async Task SelectOutputFile() { FileSavePicker saveFilePicker = new FileSavePicker(); saveFilePicker.FileTypeChoices.Add("Pulse Code Modulation", new List<string>() { ".wav" }); saveFilePicker.FileTypeChoices.Add("Windows Media Audio", new List<string>() { ".wma" }); saveFilePicker.FileTypeChoices.Add("MPEG Audio Layer-3", new List<string>() { ".mp3" }); saveFilePicker.SuggestedFileName = "New Audio Track"; StorageFile file = await saveFilePicker.PickSaveFileAsync(); // File can be null if cancel is hit in the file picker if (file == null) { return; } rootPage.NotifyUser(String.Format("Recording to {0}", file.Name.ToString()), NotifyType.StatusMessage); MediaEncodingProfile fileProfile = CreateMediaEncodingProfile(file); // Operate node at the graph format, but save file at the specified format CreateAudioFileOutputNodeResult fileOutputNodeResult = await graph.CreateFileOutputNodeAsync(file, fileProfile); if (fileOutputNodeResult.Status != AudioFileNodeCreationStatus.Success) { // FileOutputNode creation failed rootPage.NotifyUser(String.Format("Cannot create output file because {0}", fileOutputNodeResult.Status.ToString()), NotifyType.ErrorMessage); fileButton.Background = new SolidColorBrush(Colors.Red); return; } fileOutputNode = fileOutputNodeResult.FileOutputNode; fileButton.Background = new SolidColorBrush(Colors.YellowGreen); // Connect the input node to both output nodes deviceInputNode.AddOutgoingConnection(fileOutputNode); deviceInputNode.AddOutgoingConnection(deviceOutputNode); recordStopButton.IsEnabled = true; } private MediaEncodingProfile CreateMediaEncodingProfile(StorageFile file) { switch(file.FileType.ToString().ToLowerInvariant()) { case ".wma": return MediaEncodingProfile.CreateWma(AudioEncodingQuality.High); case ".mp3": return MediaEncodingProfile.CreateMp3(AudioEncodingQuality.High); case ".wav": return MediaEncodingProfile.CreateWav(AudioEncodingQuality.High); default: throw new ArgumentException(); } } private async Task ToggleRecordStop() { if (recordStopButton.Content.Equals("Record")) { graph.Start(); recordStopButton.Content = "Stop"; audioPipe1.Fill = new SolidColorBrush(Colors.Blue); audioPipe2.Fill = new SolidColorBrush(Colors.Blue); } else if (recordStopButton.Content.Equals("Stop")) { // Good idea to stop the graph to avoid data loss graph.Stop(); audioPipe1.Fill = new SolidColorBrush(Color.FromArgb(255, 49, 49, 49)); audioPipe2.Fill = new SolidColorBrush(Color.FromArgb(255, 49, 49, 49)); TranscodeFailureReason finalizeResult = await fileOutputNode.FinalizeAsync(); if (finalizeResult != TranscodeFailureReason.None) { // Finalization of file failed. Check result code to see why rootPage.NotifyUser(String.Format("Finalization of file failed because {0}", finalizeResult.ToString()), NotifyType.ErrorMessage); fileButton.Background = new SolidColorBrush(Colors.Red); return; } recordStopButton.Content = "Record"; rootPage.NotifyUser("Recording to file completed successfully!", NotifyType.StatusMessage); fileButton.Background = new SolidColorBrush(Colors.Green); recordStopButton.IsEnabled = false; createGraphButton.IsEnabled = false; } } private async Task PopulateDeviceList() { outputDevicesListBox.Items.Clear(); outputDevices = await DeviceInformation.FindAllAsync(MediaDevice.GetAudioRenderSelector()); outputDevicesListBox.Items.Add("-- Pick output device --"); foreach (var device in outputDevices) { outputDevicesListBox.Items.Add(device.Name); } } private async Task CreateAudioGraph() { AudioGraphSettings settings = new AudioGraphSettings(AudioRenderCategory.Media); settings.QuantumSizeSelectionMode = QuantumSizeSelectionMode.LowestLatency; settings.PrimaryRenderDevice = outputDevices[outputDevicesListBox.SelectedIndex - 1]; CreateAudioGraphResult result = await AudioGraph.CreateAsync(settings); if (result.Status != AudioGraphCreationStatus.Success) { // Cannot create graph rootPage.NotifyUser(String.Format("AudioGraph Creation Error because {0}", result.Status.ToString()), NotifyType.ErrorMessage); return; } graph = result.Graph; rootPage.NotifyUser("Graph successfully created!", NotifyType.StatusMessage); // Create a device output node CreateAudioDeviceOutputNodeResult deviceOutputNodeResult = await graph.CreateDeviceOutputNodeAsync(); if (deviceOutputNodeResult.Status != AudioDeviceNodeCreationStatus.Success) { // Cannot create device output node rootPage.NotifyUser(String.Format("Audio Device Output unavailable because {0}", deviceOutputNodeResult.Status.ToString()), NotifyType.ErrorMessage); outputDeviceContainer.Background = new SolidColorBrush(Colors.Red); return; } deviceOutputNode = deviceOutputNodeResult.DeviceOutputNode; rootPage.NotifyUser("Device Output connection successfully created", NotifyType.StatusMessage); outputDeviceContainer.Background = new SolidColorBrush(Colors.Green); // Create a device input node using the default audio input device CreateAudioDeviceInputNodeResult deviceInputNodeResult = await graph.CreateDeviceInputNodeAsync(MediaCategory.Other); if (deviceInputNodeResult.Status != AudioDeviceNodeCreationStatus.Success) { // Cannot create device input node rootPage.NotifyUser(String.Format("Audio Device Input unavailable because {0}", deviceInputNodeResult.Status.ToString()), NotifyType.ErrorMessage); inputDeviceContainer.Background = new SolidColorBrush(Colors.Red); return; } deviceInputNode = deviceInputNodeResult.DeviceInputNode; rootPage.NotifyUser("Device Input connection successfully created", NotifyType.StatusMessage); inputDeviceContainer.Background = new SolidColorBrush(Colors.Green); // Since graph is successfully created, enable the button to select a file output fileButton.IsEnabled = true; // Disable the graph button to prevent accidental click createGraphButton.IsEnabled = false; // Because we are using lowest latency setting, we need to handle device disconnection errors graph.UnrecoverableErrorOccurred += Graph_UnrecoverableErrorOccurred; } private async void Graph_UnrecoverableErrorOccurred(AudioGraph sender, AudioGraphUnrecoverableErrorOccurredEventArgs args) { // Recreate the graph and all nodes when this happens await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () => { sender.Dispose(); // Re-query for devices await PopulateDeviceList(); // Reset UI fileButton.IsEnabled = false; recordStopButton.IsEnabled = false; recordStopButton.Content = "Record"; outputDeviceContainer.Background = new SolidColorBrush(Color.FromArgb(255, 74, 74, 74)); audioPipe1.Fill = new SolidColorBrush(Color.FromArgb(255, 49, 49, 49)); audioPipe2.Fill = new SolidColorBrush(Color.FromArgb(255, 49, 49, 49)); }); } private void outputDevicesListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { if (outputDevicesListBox.SelectedIndex == 0) { createGraphButton.IsEnabled = false; outputDevice.Foreground = new SolidColorBrush(Color.FromArgb(255, 110, 110, 110)); outputDeviceContainer.Background = new SolidColorBrush(Color.FromArgb(255, 74, 74, 74)); fileButton.IsEnabled = false; fileButton.Background = new SolidColorBrush(Color.FromArgb(255, 74, 74, 74)); inputDeviceContainer.Background = new SolidColorBrush(Color.FromArgb(255, 74, 74, 74)); // Destroy graph if (graph != null) { graph.Dispose(); graph = null; } } else { createGraphButton.IsEnabled = true; outputDevice.Foreground = new SolidColorBrush(Colors.White); } } } }
using System; using System.Collections.Generic; using System.Web.Mvc; using MvcContrib.UnitTests.FluentHtml.Fakes; using MvcContrib.UnitTests.FluentHtml.Helpers; using NUnit.Framework; using MvcContrib.FluentHtml.Elements; using MvcContrib.FluentHtml.Html; using HtmlAttribute = MvcContrib.FluentHtml.Html.HtmlAttribute; namespace MvcContrib.UnitTests.FluentHtml { [TestFixture] public class SelectTests { [Test] public void basic_select_renders_with_no_options() { var element = new Select("foo.Bar").ToString() .ShouldHaveHtmlNode("foo_Bar") .ShouldHaveAttributesCount(2) .ShouldBeNamed(HtmlTag.Select); element.ShouldHaveAttribute(HtmlAttribute.Name).WithValue("foo.Bar"); element.ShouldHaveNoChildNodes(); } [Test] public void basic_select_renders_with_options_from_dictionary() { var options = new Dictionary<int, string> {{1, "One"}, {2, "Two"}}; var html = new Select("foo.Bar").Selected(1).Options(options).ToString(); var element = html.ShouldHaveHtmlNode("foo_Bar"); var optionNodes = element.ShouldHaveChildNodesCount(2); optionNodes[0].ShouldBeSelectedOption(1, "One"); optionNodes[1].ShouldBeUnSelectedOption(2, "Two"); } [Test] public void can_render_options_from_enumerable_of_simple_objects() { var optionNodes = new Select("foo.Bar").Options(new[] {1, 2}).ToString() .ShouldHaveHtmlNode("foo_Bar") .ShouldHaveChildNodesCount(2); optionNodes[0].ShouldBeUnSelectedOption("1", "1"); optionNodes[1].ShouldBeUnSelectedOption("2", "2"); } [Test] public void basic_select_renders_select_with_options_from_select_list() { var items = new List<FakeModel> { new FakeModel {Id = 1, Title = "One"}, new FakeModel {Id = 2, Title = "Two"} }; var selectList = new SelectList(items, "Id", "Title", items[0].Id); var html = new Select("foo.Bar").Options(selectList).ToString(); var element = html.ShouldHaveHtmlNode("foo_Bar"); var optionNodes = element.ShouldHaveChildNodesCount(2); optionNodes[0].ShouldBeSelectedOption(items[0].Id, items[0].Title); optionNodes[1].ShouldBeUnSelectedOption(items[1].Id, items[1].Title); } [Test] public void basic_select_renders_select_size() { new Select("foo.Bar").Size(22).ToString() .ShouldHaveHtmlNode("foo_Bar") .ShouldHaveAttribute(HtmlAttribute.Size).WithValue("22"); } [Test] public void select_with_options_for_enum_renders_enum_values_as_options() { var html = new Select("foo.Bar").Options<FakeEnum>().Selected(FakeEnum.Two).ToString(); var element = html.ShouldHaveHtmlNode("foo_Bar"); var optionNodes = element.ShouldHaveChildNodesCount(4); optionNodes[0].ShouldBeUnSelectedOption((int)FakeEnum.Zero, FakeEnum.Zero); optionNodes[1].ShouldBeUnSelectedOption((int)FakeEnum.One, FakeEnum.One); optionNodes[2].ShouldBeSelectedOption((int)FakeEnum.Two, FakeEnum.Two); optionNodes[3].ShouldBeUnSelectedOption((int)FakeEnum.Three, FakeEnum.Three); } [Test] public void select_with_options_for_subset_enum_renders_enum_values_as_options() { var html = new Select("foo.Bar").Options(new[] {FakeEnum.One, FakeEnum.Two, FakeEnum.Three}) .Selected(FakeEnum.Two).ToString(); var element = html.ShouldHaveHtmlNode("foo_Bar"); var optionNodes = element.ShouldHaveChildNodesCount(3); optionNodes[0].ShouldBeUnSelectedOption((int)FakeEnum.One, FakeEnum.One); optionNodes[1].ShouldBeSelectedOption((int)FakeEnum.Two, FakeEnum.Two); optionNodes[2].ShouldBeUnSelectedOption((int)FakeEnum.Three, FakeEnum.Three); } [Test] public void select_with_options_for_enum_renders_null_first_option() { var html = new Select("foo.Bar").Options<FakeEnum>().FirstOption("-Choose-").ToString(); var element = html.ShouldHaveHtmlNode("foo_Bar"); var optionNodes = element.ShouldHaveChildNodesCount(5); optionNodes[0].ShouldBeUnSelectedOption(string.Empty, "-Choose-"); } [Test] public void basic_select_can_select_null_valued_options() { var items = new List<FakeModel> { new FakeModel {Price = null, Title = "One"}, new FakeModel {Price = 2, Title = "Two"} }; var optionNodes = new Select("foo.Bar").Options(items, "Price", "Title").Selected(items[0].Price).ToString() .ShouldHaveHtmlNode("foo_Bar") .ShouldHaveChildNodesCount(2); optionNodes[0].ShouldBeSelectedOption(items[0].Price, items[0].Title); optionNodes[1].ShouldBeUnSelectedOption(items[1].Price, items[1].Title); } [Test] public void basic_select_can_group_by() { var items = new List<FakeModel> { new FakeModel {Id = 1, Title = "One", Selection = FakeEnum.One}, new FakeModel {Id = 2, Title = "Two", Selection = FakeEnum.Zero} }; var select = new Select("foo").Options(items, "Id", "Title", x => x.Selection).ToString(); var optgroups = select.ShouldHaveHtmlNode("foo") .ShouldHaveChildNodesCount(2); optgroups[0].ShouldHaveAttribute("label").WithValue("One"); optgroups[1].ShouldHaveAttribute("label").WithValue("Zero"); optgroups[0].ShouldHaveChildNodesCount(1)[0] .ShouldHaveAttribute("value").WithValue("1"); optgroups[1].ShouldHaveChildNodesCount(1)[0] .ShouldHaveAttribute("value").WithValue("2"); } [Test] public void basic_select_can_group_by_overload() { var items = new List<FakeModel> { new FakeModel {Id = 1, Title = "One", Selection = FakeEnum.One}, new FakeModel {Id = 2, Title = "Two", Selection = FakeEnum.Zero} }; var select = new Select("foo").Options(items, x => x.Id, x => x.Title, x => x.Selection).ToString(); var optgroups = select.ShouldHaveHtmlNode("foo") .ShouldHaveChildNodesCount(2); optgroups[0].ShouldHaveAttribute("label").WithValue("One"); optgroups[1].ShouldHaveAttribute("label").WithValue("Zero"); optgroups[0].ShouldHaveChildNodesCount(1)[0] .ShouldHaveAttribute("value").WithValue("1"); optgroups[1].ShouldHaveChildNodesCount(1)[0] .ShouldHaveAttribute("value").WithValue("2"); } [Test] public void basic_select_can_set_selected_value_before_options() { var items = new List<FakeModel> { new FakeModel {Price = 1, Title = "One"}, new FakeModel {Price = 2, Title = "Two"} }; var optionNodes = new Select("foo.Bar").Options(items, "Price", "Title").Selected(items[1].Price).ToString() .ShouldHaveHtmlNode("foo_Bar") .ShouldHaveChildNodesCount(2); optionNodes[0].ShouldBeUnSelectedOption(items[0].Price, items[0].Title); optionNodes[1].ShouldBeSelectedOption(items[1].Price, items[1].Title); } [Test] public void select_option_null_renders_with_no_options() { new Select("foo.Bar").Options(null).ToString() .ShouldHaveHtmlNode("foo_Bar").ShouldHaveChildNodesCount(0); } [Test] public void select_option_with_no_items_renders_with_no_options() { new Select("foo.Bar").Options(new Dictionary<int, string>()).ToString() .ShouldHaveHtmlNode("foo_Bar").ShouldHaveChildNodesCount(0); } [Test, ExpectedException(typeof(ArgumentException))] public void select_options_with_wrong_data_value_field_throws_on_tostring() { var items = new List<FakeModel> {new FakeModel {Price = null, Title = "One"}}; new Select("x").Options(items, "Wrong", "Title").ToString(); } [Test, ExpectedException(typeof(ArgumentException))] public void select_options_with_wrong_data_text_field_throws_on_tostring() { var items = new List<FakeModel> {new FakeModel {Price = null, Title = "One"}}; new Select("x").Options(items, "Price", "Wrong").ToString(); } [Test, ExpectedException(typeof(ArgumentException))] public void select_options_with_generic_param_not_enum_throws() { new Select("x").Options<int>().ToString(); } [Test] public void select_option_of_enumerable_select_list_item_renders_options() { var items = new List<SelectListItem> { new SelectListItem {Value = "1", Text = "One", Selected = false}, new SelectListItem {Value = "2", Text = "Two", Selected = true}, new SelectListItem {Value = "3", Text = "Three", Selected = true} }; var html = new Select("foo.Bar").Options(items).ToString(); var element = html.ShouldHaveHtmlNode("foo_Bar"); var optionNodes = element.ShouldHaveChildNodesCount(3); optionNodes[0].ShouldBeUnSelectedOption(items[0].Value, items[0].Text); optionNodes[1].ShouldBeSelectedOption(items[1].Value, items[1].Text); optionNodes[2].ShouldBeSelectedOption(items[2].Value, items[2].Text); } [Test] public void select_with_lambda_selector_for_options_should_render() { var items = new List<FakeModel> {new FakeModel {Price = 1, Title = "One"}}; var options = new Select("x").Options(items, x => x.Price, x => x.Title).ToString() .ShouldHaveHtmlNode("x") .ShouldHaveChildNodesCount(1); options[0].ShouldBeUnSelectedOption("1", "One"); } [Test] public void select_with_lambda_selector_can_called_selected_before_options() { var items = new List<FakeModel> { new FakeModel {Price = 1, Title = "One"}, new FakeModel {Price = 2, Title = "Two"} }; var options = new Select("x").Selected(2).Options(items, x => x.Price, x => x.Title).ToString() .ShouldHaveHtmlNode("x") .ShouldHaveChildNodesCount(2); options[0].ShouldBeUnSelectedOption("1", "One"); options[1].ShouldBeSelectedOption("2", "Two"); } [Test, ExpectedException(typeof(ArgumentNullException))] public void select_options_with_null_text_field_selector_should_throw() { new Select("x").Options(new List<FakeModel>(), null, x => x.Title); } [Test, ExpectedException(typeof(ArgumentNullException))] public void select_options_with_null_value_field_selector_should_throw() { new Select("x").Options(new List<FakeModel>(), x => x.Price, null); } [Test] public void select_options_with_simple_enumeration_of_objects_can_have_selected_called_first() { var optionNodes = new Select("foo").Selected(2).Options(new[] {1, 2}).ToString() .ShouldHaveHtmlNode("foo") .ShouldHaveChildNodesCount(2); optionNodes[0].ShouldBeUnSelectedOption("1", "1"); optionNodes[1].ShouldBeSelectedOption("2", "2"); } [Test] public void select_options_with_simple_enumeration_of_objects_can_have_a_first_option_text_specified() { var optionNodes = new Select("foo").Options(new[] {1, 2}).FirstOption("-Choose-").ToString() .ShouldHaveHtmlNode("foo") .ShouldHaveChildNodesCount(3); optionNodes[0].ShouldBeUnSelectedOption("", "-Choose-"); optionNodes[1].ShouldBeUnSelectedOption("1", "1"); optionNodes[2].ShouldBeUnSelectedOption("2", "2"); } [Test] public void select_options_with_simple_enumeration_of_objects_can_have_a_first_option_specified() { var optionNodes = new Select("foo").Options(new[] {1, 2}).FirstOption(new Option().Text("No Relation").Value("-1")).ToString() .ShouldHaveHtmlNode("foo") .ShouldHaveChildNodesCount(3); optionNodes[0].ShouldBeUnSelectedOption("-1", "No Relation"); optionNodes[1].ShouldBeUnSelectedOption("1", "1"); optionNodes[2].ShouldBeUnSelectedOption("2", "2"); } [Test] public void select_options_not_told_to_hide_the_first_option_should_emit_the_first_option_text() { var optionNodes = new Select("foo").Options(new[] {1, 2}).FirstOption("-Choose-").HideFirstOptionWhen(false).ToString() .ShouldHaveHtmlNode("foo") .ShouldHaveChildNodesCount(3); optionNodes[0].ShouldBeUnSelectedOption("", "-Choose-"); optionNodes[1].ShouldBeUnSelectedOption("1", "1"); optionNodes[2].ShouldBeUnSelectedOption("2", "2"); } [Test] public void select_options_told_to_hide_the_first_option_should_not_emit_the_first_option_text() { var optionNodes = new Select("foo").Options(new[] {1, 2}).FirstOption("-Choose-").HideFirstOptionWhen(true).ToString() .ShouldHaveHtmlNode("foo") .ShouldHaveChildNodesCount(2); optionNodes[0].ShouldBeUnSelectedOption("1", "1"); optionNodes[1].ShouldBeUnSelectedOption("2", "2"); } [Test] public void can_modify_each_option_element_using_the_option_data_item() { var items = new List<FakeModel> { new FakeModel {Price = 1, Title = "One"}, new FakeModel {Price = 2, Title = "Two", Done = true}, }; const string name = "foo"; var optionNodes = new Select(name).Options(items, x => x.Price, x => x.Title) .EachOption((cb, opt, i) => cb.Disabled(((FakeModel)opt).Done)).ToString() .ShouldHaveHtmlNode(name) .ShouldHaveChildNodesCount(2); optionNodes[0].ShouldNotHaveAttribute("disabled"); optionNodes[1].ShouldHaveAttribute("disabled"); } } }
// 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; using System.Collections.Generic; using Xunit; namespace System.Linq.Expressions.Tests { public class NoParameterBlockTests : SharedBlockTests { [Theory] [PerCompilationType(nameof(ConstantValueData))] public void SingleElementBlock(object value, bool useInterpreter) { Type type = value.GetType(); ConstantExpression constant = Expression.Constant(value, type); BlockExpression block = Expression.Block( constant ); Assert.Equal(type, block.Type); Expression equal = Expression.Equal(constant, block); Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)()); } [Theory] [PerCompilationType(nameof(ConstantValueData))] public void DoubleElementBlock(object value, bool useInterpreter) { Type type = value.GetType(); ConstantExpression constant = Expression.Constant(value, type); BlockExpression block = Expression.Block( Expression.Empty(), constant ); Assert.Equal(type, block.Type); Expression equal = Expression.Equal(constant, block); Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)()); } [Fact] public void DoubleElementBlockNullArgument() { Assert.Throws<ArgumentNullException>("arg0", () => Expression.Block(default(Expression), Expression.Constant(1))); Assert.Throws<ArgumentNullException>("arg1", () => Expression.Block(Expression.Constant(1), default(Expression))); } [Fact] public void DoubleElementBlockUnreadable() { Assert.Throws<ArgumentException>("arg0", () => Expression.Block(UnreadableExpression, Expression.Constant(1))); Assert.Throws<ArgumentException>("arg1", () => Expression.Block(Expression.Constant(1), UnreadableExpression)); } [Theory] [PerCompilationType(nameof(ConstantValueData))] public void TripleElementBlock(object value, bool useInterpreter) { Type type = value.GetType(); ConstantExpression constant = Expression.Constant(value, type); BlockExpression block = Expression.Block( Expression.Empty(), Expression.Empty(), constant ); Assert.Equal(type, block.Type); Expression equal = Expression.Equal(constant, block); Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)()); } [Fact] public void TripleElementBlockNullArgument() { Assert.Throws<ArgumentNullException>("arg0", () => Expression.Block(default(Expression), Expression.Constant(1), Expression.Constant(1))); Assert.Throws<ArgumentNullException>("arg1", () => Expression.Block(Expression.Constant(1), default(Expression), Expression.Constant(1))); Assert.Throws<ArgumentNullException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), default(Expression))); } [Fact] public void TripleElementBlockUnreadable() { Assert.Throws<ArgumentException>("arg0", () => Expression.Block(UnreadableExpression, Expression.Constant(1), Expression.Constant(1))); Assert.Throws<ArgumentException>("arg1", () => Expression.Block(Expression.Constant(1), UnreadableExpression, Expression.Constant(1))); Assert.Throws<ArgumentException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), UnreadableExpression)); } [Theory] [PerCompilationType(nameof(ConstantValueData))] public void QuadrupleElementBlock(object value, bool useInterpreter) { Type type = value.GetType(); ConstantExpression constant = Expression.Constant(value, type); BlockExpression block = Expression.Block( Expression.Empty(), Expression.Empty(), Expression.Empty(), constant ); Assert.Equal(type, block.Type); Expression equal = Expression.Equal(constant, block); Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)()); } [Fact] public void QuadrupleElementBlockNullArgument() { Assert.Throws<ArgumentNullException>("arg0", () => Expression.Block(default(Expression), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1))); Assert.Throws<ArgumentNullException>("arg1", () => Expression.Block(Expression.Constant(1), default(Expression), Expression.Constant(1), Expression.Constant(1))); Assert.Throws<ArgumentNullException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), default(Expression), Expression.Constant(1))); Assert.Throws<ArgumentNullException>("arg3", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), default(Expression))); } [Fact] public void QuadrupleElementBlockUnreadable() { Assert.Throws<ArgumentException>("arg0", () => Expression.Block(UnreadableExpression, Expression.Constant(1), Expression.Constant(1), Expression.Constant(1))); Assert.Throws<ArgumentException>("arg1", () => Expression.Block(Expression.Constant(1), UnreadableExpression, Expression.Constant(1), Expression.Constant(1))); Assert.Throws<ArgumentException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), UnreadableExpression, Expression.Constant(1))); Assert.Throws<ArgumentException>("arg3", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), UnreadableExpression)); } [Theory] [PerCompilationType(nameof(ConstantValueData))] public void QuintupleElementBlock(object value, bool useInterpreter) { Type type = value.GetType(); ConstantExpression constant = Expression.Constant(value, type); BlockExpression block = Expression.Block( Expression.Empty(), Expression.Empty(), Expression.Empty(), Expression.Empty(), constant ); Assert.Equal(type, block.Type); Expression equal = Expression.Equal(constant, block); Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)()); } [Fact] public void QuintupleElementBlockNullArgument() { Assert.Throws<ArgumentNullException>("arg0", () => Expression.Block(default(Expression), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1))); Assert.Throws<ArgumentNullException>("arg1", () => Expression.Block(Expression.Constant(1), default(Expression), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1))); Assert.Throws<ArgumentNullException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), default(Expression), Expression.Constant(1), Expression.Constant(1))); Assert.Throws<ArgumentNullException>("arg3", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), default(Expression), Expression.Constant(1))); Assert.Throws<ArgumentNullException>("arg4", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), default(Expression))); } [Fact] public void QuintupleElementBlockUnreadable() { Assert.Throws<ArgumentException>("arg0", () => Expression.Block(UnreadableExpression, Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1))); Assert.Throws<ArgumentException>("arg1", () => Expression.Block(Expression.Constant(1), UnreadableExpression, Expression.Constant(1), Expression.Constant(1), Expression.Constant(1))); Assert.Throws<ArgumentException>("arg2", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), UnreadableExpression, Expression.Constant(1), Expression.Constant(1))); Assert.Throws<ArgumentException>("arg3", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), UnreadableExpression, Expression.Constant(1))); Assert.Throws<ArgumentException>("arg4", () => Expression.Block(Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), Expression.Constant(1), UnreadableExpression)); } [Theory] [PerCompilationType(nameof(ConstantValueData))] public void SextupleElementBlock(object value, bool useInterpreter) { Type type = value.GetType(); ConstantExpression constant = Expression.Constant(value, type); BlockExpression block = Expression.Block( Expression.Empty(), Expression.Empty(), Expression.Empty(), Expression.Empty(), Expression.Empty(), constant ); Assert.Equal(type, block.Type); Expression equal = Expression.Equal(constant, block); Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)()); } [Fact] public void NullExpicitType() { Assert.Throws<ArgumentNullException>("type", () => Expression.Block(default(Type), default(IEnumerable<ParameterExpression>), Expression.Constant(0))); Assert.Throws<ArgumentNullException>("type", () => Expression.Block(default(Type), null, Enumerable.Repeat(Expression.Constant(0), 1))); } [Fact] public void NullExpressionList() { Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(default(Expression[]))); Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(default(IEnumerable<Expression>))); } [Theory] [MemberData(nameof(BlockSizes))] public void NullExpressionInExpressionList(int size) { List<Expression> expressionList = Enumerable.Range(0, size).Select(i => (Expression)Expression.Constant(1)).ToList(); for (int i = 0; i != expressionList.Count; ++i) { Expression[] expressions = expressionList.ToArray(); expressions[i] = null; Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(expressions)); Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(expressions.Skip(0))); Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(typeof(int), expressions)); Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(typeof(int), expressions.Skip(0))); Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(typeof(int), null, expressions)); Assert.Throws<ArgumentNullException>("expressions", () => Expression.Block(typeof(int), null, expressions.Skip(0))); } } [Theory] [MemberData(nameof(BlockSizes))] public void UnreadableExpressionInExpressionList(int size) { List<Expression> expressionList = Enumerable.Range(0, size).Select(i => (Expression)Expression.Constant(1)).ToList(); for (int i = 0; i != expressionList.Count; ++i) { Expression[] expressions = expressionList.ToArray(); expressions[i] = UnreadableExpression; Assert.Throws<ArgumentException>("expressions", () => Expression.Block(expressions)); Assert.Throws<ArgumentException>("expressions", () => Expression.Block(expressions.Skip(0))); Assert.Throws<ArgumentException>("expressions", () => Expression.Block(typeof(int), expressions)); Assert.Throws<ArgumentException>("expressions", () => Expression.Block(typeof(int), expressions.Skip(0))); Assert.Throws<ArgumentException>("expressions", () => Expression.Block(typeof(int), null, expressions)); Assert.Throws<ArgumentException>("expressions", () => Expression.Block(typeof(int), null, expressions.Skip(0))); } } [Theory] [PerCompilationType(nameof(ObjectAssignableConstantValuesAndSizes))] public void BlockExplicitType(object value, int blockSize, bool useInterpreter) { ConstantExpression constant = Expression.Constant(value, value.GetType()); BlockExpression block = Expression.Block(typeof(object), PadBlock(blockSize - 1, constant)); Assert.Equal(typeof(object), block.Type); Expression equal = Expression.Equal(constant, block); Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)()); } [Theory] [MemberData(nameof(BlockSizes))] public void BlockInvalidExplicitType(int blockSize) { ConstantExpression constant = Expression.Constant(0); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0)); Assert.Throws<ArgumentException>(() => Expression.Block(typeof(string), expressions)); Assert.Throws<ArgumentException>(() => Expression.Block(typeof(string), expressions.ToArray())); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] public void InvalidExpressionIndex(object value, int blockSize) { BlockExpression block = Expression.Block(PadBlock(blockSize - 1, Expression.Constant(value, value.GetType()))); Assert.Throws<ArgumentOutOfRangeException>("index", () => block.Expressions[-1]); Assert.Throws<ArgumentOutOfRangeException>("index", () => block.Expressions[blockSize]); } [Fact] public void EmptyBlockWithNonVoidTypeNotAllowed() { Assert.Throws<ArgumentException>(() => Expression.Block(typeof(int))); Assert.Throws<ArgumentException>(() => Expression.Block(typeof(int), Enumerable.Empty<Expression>())); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] public void ResultPropertyFromParams(object value, int blockSize) { ConstantExpression constant = Expression.Constant(value, value.GetType()); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant); BlockExpression block = Expression.Block(expressions.ToArray()); Assert.Same(constant, block.Result); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] public void ResultPropertyFromEnumerable(object value, int blockSize) { ConstantExpression constant = Expression.Constant(value, value.GetType()); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant); BlockExpression block = Expression.Block(expressions); Assert.Same(constant, block.Result); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] public void VariableCountZeroOnNonVariableAcceptingForms(object value, int blockSize) { ConstantExpression constant = Expression.Constant(value, value.GetType()); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant); BlockExpression block = Expression.Block(expressions); Assert.Empty(block.Variables); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] [ActiveIssue(3958)] public void RewriteToSameWithSameValues(object value, int blockSize) { ConstantExpression constant = Expression.Constant(value, value.GetType()); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant).ToArray(); BlockExpression block = Expression.Block(expressions); Assert.Same(block, block.Update(null, expressions)); Assert.Same(block, block.Update(Enumerable.Empty<ParameterExpression>(), expressions)); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] public void CanFindItems(object value, int blockSize) { ConstantExpression[] values = new ConstantExpression[blockSize]; for (int i = 0; i != values.Length; ++i) values[i] = Expression.Constant(value); BlockExpression block = Expression.Block(values); IList<Expression> expressions = block.Expressions; for (int i = 0; i != values.Length; ++i) Assert.Equal(i, expressions.IndexOf(values[i])); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] public void IdentifyNonAbsentItemAsAbsent(object value, int blockSize) { ConstantExpression constant = Expression.Constant(value, value.GetType()); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant); BlockExpression block = Expression.Block(expressions); Assert.Equal(-1, block.Expressions.IndexOf(Expression.Default(typeof(long)))); Assert.False(block.Expressions.Contains(null)); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] public void ExpressionsEnumerable(object value, int blockSize) { ConstantExpression[] values = new ConstantExpression[blockSize]; for (int i = 0; i != values.Length; ++i) values[i] = Expression.Constant(value); BlockExpression block = Expression.Block(values); Assert.True(values.SequenceEqual(block.Expressions)); int index = 0; foreach (Expression exp in ((IEnumerable)block.Expressions)) Assert.Same(exp, values[index++]); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] public void UpdateWithExpressionsReturnsSame(object value, int blockSize) { ConstantExpression constant = Expression.Constant(value, value.GetType()); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant); BlockExpression block = Expression.Block(expressions); Assert.Same(block, block.Update(block.Variables, block.Expressions)); } [Theory] [MemberData(nameof(ConstantValuesAndSizes))] public void Visit(object value, int blockSize) { ConstantExpression constant = Expression.Constant(value, value.GetType()); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant); BlockExpression block = Expression.Block(expressions); Assert.NotSame(block, new TestVistor().Visit(block)); } [Theory] [MemberData(nameof(ObjectAssignableConstantValuesAndSizes))] public void VisitTyped(object value, int blockSize) { ConstantExpression constant = Expression.Constant(value, value.GetType()); IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant); BlockExpression block = Expression.Block(typeof(object), expressions); Assert.NotSame(block, new TestVistor().Visit(block)); } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Net; using AutoMapper; using Microsoft.WindowsAzure.Commands.ServiceManagement.Extensions; using Microsoft.WindowsAzure.Commands.ServiceManagement.Helpers; using Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS.Extensions; using Microsoft.WindowsAzure.Commands.Utilities.Common; using Microsoft.WindowsAzure.Management.Models; using Microsoft.WindowsAzure.Management.Storage.Models; namespace Microsoft.WindowsAzure.Commands.ServiceManagement { using NSM = Management.Compute.Models; using NVM = Management.Network.Models; using PVM = Model; using Microsoft.Azure; public class ServiceManagementProfile : Profile { private static IMapper _mapper = null; private static readonly object _lock = new object(); public static IMapper Mapper { get { lock(_lock) { if (_mapper == null) { Initialize(); } return _mapper; } } } public override string ProfileName { get { return "ServiceManagementProfile"; } } public static void Initialize() { var config = new MapperConfiguration(cfg => { cfg.AddProfile<ServiceManagementProfile>(); // Service Extension Image cfg.CreateMap<OperationStatusResponse, ExtensionImageContext>() .ForMember(c => c.OperationId, o => o.MapFrom(r => r.Id)) .ForMember(c => c.OperationStatus, o => o.MapFrom(r => r.Status.ToString())); cfg.CreateMap<NSM.ExtensionImage, ExtensionImageContext>() .ForMember(c => c.ThumbprintAlgorithm, o => o.MapFrom(r => r.Certificate.ThumbprintAlgorithm)) .ForMember(c => c.ExtensionName, o => o.MapFrom(r => r.Type)); // VM Extension Image cfg.CreateMap<OperationStatusResponse, VirtualMachineExtensionImageContext>() .ForMember(c => c.OperationId, o => o.MapFrom(r => r.Id)) .ForMember(c => c.OperationStatus, o => o.MapFrom(r => r.Status.ToString())); cfg.CreateMap<NSM.VirtualMachineExtensionListResponse.ResourceExtension, VirtualMachineExtensionImageContext>() .ForMember(c => c.ExtensionName, o => o.MapFrom(r => r.Name)); //Image mapping cfg.CreateMap<NSM.VirtualMachineOSImageListResponse.VirtualMachineOSImage, PVM.OSImageContext>() .ForMember(c => c.MediaLink, o => o.MapFrom(r => r.MediaLinkUri)) .ForMember(c => c.ImageName, o => o.MapFrom(r => r.Name)) .ForMember(c => c.OS, o => o.MapFrom(r => r.OperatingSystemType)) .ForMember(c => c.PublishedDate, o => o.MapFrom(r => new DateTime?(r.PublishedDate))) .ForMember(c => c.IconUri, o => o.MapFrom(r => r.SmallIconUri)) .ForMember(c => c.LogicalSizeInGB, o => o.MapFrom(r => (int)r.LogicalSizeInGB)); cfg.CreateMap<NSM.VirtualMachineOSImageGetResponse, PVM.OSImageContext>() .ForMember(c => c.ImageName, o => o.MapFrom(r => r.Name)) .ForMember(c => c.MediaLink, o => o.MapFrom(r => r.MediaLinkUri)) .ForMember(c => c.OS, o => o.MapFrom(r => r.OperatingSystemType)) .ForMember(c => c.PublishedDate, o => o.MapFrom(r => new DateTime?(r.PublishedDate))) .ForMember(c => c.LogicalSizeInGB, o => o.MapFrom(r => (int)r.LogicalSizeInGB)); cfg.CreateMap<NSM.VirtualMachineOSImageCreateResponse, PVM.OSImageContext>() .ForMember(c => c.ImageName, o => o.MapFrom(r => r.Name)) .ForMember(c => c.MediaLink, o => o.MapFrom(r => r.MediaLinkUri)) .ForMember(c => c.IconUri, o => o.MapFrom(r => r.SmallIconUri)) .ForMember(c => c.OS, o => o.MapFrom(r => r.OperatingSystemType)) .ForMember(c => c.PublishedDate, o => o.MapFrom(r => r.PublishedDate)) .ForMember(c => c.LogicalSizeInGB, o => o.MapFrom(r => (int)r.LogicalSizeInGB)); cfg.CreateMap<NSM.VirtualMachineOSImageUpdateResponse, PVM.OSImageContext>() .ForMember(c => c.ImageName, o => o.MapFrom(r => r.Name)) .ForMember(c => c.MediaLink, o => o.MapFrom(r => r.MediaLinkUri)) .ForMember(c => c.IconUri, o => o.MapFrom(r => r.SmallIconUri)) .ForMember(c => c.OS, o => o.MapFrom(r => r.OperatingSystemType)) .ForMember(c => c.PublishedDate, o => o.MapFrom(r => r.PublishedDate)) .ForMember(c => c.LogicalSizeInGB, o => o.MapFrom(r => (int)r.LogicalSizeInGB)); cfg.CreateMap<OperationStatusResponse, PVM.OSImageContext>() .ForMember(c => c.OperationId, o => o.MapFrom(r => r.Id)) .ForMember(c => c.OperationStatus, o => o.MapFrom(r => r.Status.ToString())); cfg.CreateMap<NSM.VirtualMachineDiskCreateResponse, PVM.OSImageContext>() .ForMember(c => c.MediaLink, o => o.MapFrom(r => r.MediaLinkUri)) .ForMember(c => c.ImageName, o => o.MapFrom(r => r.Name)) .ForMember(c => c.OS, o => o.MapFrom(r => r.OperatingSystem)); // VM Image mapping cfg.CreateMap<NSM.VirtualMachineOSImageListResponse.VirtualMachineOSImage, PVM.VMImageContext>() .ForMember(c => c.MediaLink, o => o.MapFrom(r => r.MediaLinkUri)) .ForMember(c => c.ImageName, o => o.MapFrom(r => r.Name)) .ForMember(c => c.OS, o => o.MapFrom(r => r.OperatingSystemType)) .ForMember(c => c.PublishedDate, o => o.MapFrom(r => new DateTime?(r.PublishedDate))) .ForMember(c => c.IconUri, o => o.MapFrom(r => r.SmallIconUri)) .ForMember(c => c.LogicalSizeInGB, o => o.MapFrom(r => (int)r.LogicalSizeInGB)); cfg.CreateMap<NSM.VirtualMachineOSImageGetResponse, PVM.VMImageContext>() .ForMember(c => c.ImageName, o => o.MapFrom(r => r.Name)) .ForMember(c => c.MediaLink, o => o.MapFrom(r => r.MediaLinkUri)) .ForMember(c => c.OS, o => o.MapFrom(r => r.OperatingSystemType)) .ForMember(c => c.PublishedDate, o => o.MapFrom(r => new DateTime?(r.PublishedDate))) .ForMember(c => c.LogicalSizeInGB, o => o.MapFrom(r => (int)r.LogicalSizeInGB)); cfg.CreateMap<NSM.VirtualMachineOSImageCreateResponse, PVM.VMImageContext>() .ForMember(c => c.ImageName, o => o.MapFrom(r => r.Name)) .ForMember(c => c.MediaLink, o => o.MapFrom(r => r.MediaLinkUri)) .ForMember(c => c.IconUri, o => o.MapFrom(r => r.SmallIconUri)) .ForMember(c => c.OS, o => o.MapFrom(r => r.OperatingSystemType)) .ForMember(c => c.PublishedDate, o => o.MapFrom(r => r.PublishedDate)) .ForMember(c => c.LogicalSizeInGB, o => o.MapFrom(r => (int)r.LogicalSizeInGB)); cfg.CreateMap<NSM.VirtualMachineOSImageUpdateResponse, PVM.VMImageContext>() .ForMember(c => c.ImageName, o => o.MapFrom(r => r.Name)) .ForMember(c => c.MediaLink, o => o.MapFrom(r => r.MediaLinkUri)) .ForMember(c => c.IconUri, o => o.MapFrom(r => r.SmallIconUri)) .ForMember(c => c.OS, o => o.MapFrom(r => r.OperatingSystemType)) .ForMember(c => c.PublishedDate, o => o.MapFrom(r => r.PublishedDate)) .ForMember(c => c.LogicalSizeInGB, o => o.MapFrom(r => (int)r.LogicalSizeInGB)); cfg.CreateMap<OperationStatusResponse, PVM.VMImageContext>() .ForMember(c => c.OperationId, o => o.MapFrom(r => r.Id)) .ForMember(c => c.OperationStatus, o => o.MapFrom(r => r.Status.ToString())); cfg.CreateMap<NSM.VirtualMachineDiskCreateResponse, PVM.VMImageContext>() .ForMember(c => c.MediaLink, o => o.MapFrom(r => r.MediaLinkUri)) .ForMember(c => c.ImageName, o => o.MapFrom(r => r.Name)) .ForMember(c => c.OS, o => o.MapFrom(r => r.OperatingSystem)); // VM Image Disk Mapping cfg.CreateMap<NSM.VirtualMachineVMImageListResponse.OSDiskConfiguration, PVM.OSDiskConfiguration>() .ForMember(c => c.OS, o => o.MapFrom(r => r.OperatingSystem)); cfg.CreateMap<NSM.VirtualMachineVMImageListResponse.DataDiskConfiguration, PVM.DataDiskConfiguration>() .ForMember(c => c.Lun, o => o.MapFrom(r => r.LogicalUnitNumber)); cfg.CreateMap<IList<NSM.DataDiskConfigurationCreateParameters>, List<PVM.DataDiskConfiguration>>(); cfg.CreateMap<List<NSM.DataDiskConfigurationCreateParameters>, List<PVM.DataDiskConfiguration>>(); cfg.CreateMap<IList<NSM.DataDiskConfigurationCreateParameters>, PVM.DataDiskConfigurationList>(); cfg.CreateMap<IList<NSM.DataDiskConfigurationUpdateParameters>, List<PVM.DataDiskConfiguration>>(); cfg.CreateMap<List<NSM.DataDiskConfigurationUpdateParameters>, List<PVM.DataDiskConfiguration>>(); cfg.CreateMap<IList<NSM.DataDiskConfigurationUpdateParameters>, PVM.DataDiskConfigurationList>(); cfg.CreateMap<PVM.OSDiskConfiguration, NSM.OSDiskConfigurationCreateParameters>() .ForMember(c => c.HostCaching, o => o.MapFrom(r => r.HostCaching)) .ForMember(c => c.MediaLink, o => o.MapFrom(r => r.MediaLink)) .ForMember(c => c.OS, o => o.MapFrom(r => r.OS)) .ForMember(c => c.OSState, o => o.MapFrom(r => r.OSState)); cfg.CreateMap<PVM.DataDiskConfiguration, NSM.DataDiskConfigurationCreateParameters>() .ForMember(c => c.LogicalUnitNumber, o => o.MapFrom(r => r.Lun)); cfg.CreateMap<PVM.OSDiskConfiguration, NSM.OSDiskConfigurationUpdateParameters>(); cfg.CreateMap<PVM.DataDiskConfiguration, NSM.DataDiskConfigurationUpdateParameters>() .ForMember(c => c.LogicalUnitNumber, o => o.MapFrom(r => r.Lun)); cfg.CreateMap<IList<PVM.DataDiskConfiguration>, IList<NSM.DataDiskConfigurationCreateParameters>>(); cfg.CreateMap<List<PVM.DataDiskConfiguration>, List<NSM.DataDiskConfigurationCreateParameters>>(); cfg.CreateMap<PVM.DataDiskConfigurationList, Collection<PVM.DataDiskConfiguration>>(); cfg.CreateMap<Collection<PVM.DataDiskConfiguration>, IList<NSM.DataDiskConfigurationCreateParameters>>(); cfg.CreateMap<Collection<PVM.DataDiskConfiguration>, List<NSM.DataDiskConfigurationCreateParameters>>(); cfg.CreateMap<PVM.DataDiskConfigurationList, IList<NSM.DataDiskConfigurationCreateParameters>>(); cfg.CreateMap<PVM.DataDiskConfigurationList, List<NSM.DataDiskConfigurationCreateParameters>>(); cfg.CreateMap<IList<PVM.DataDiskConfiguration>, IList<NSM.DataDiskConfigurationUpdateParameters>>(); cfg.CreateMap<List<PVM.DataDiskConfiguration>, List<NSM.DataDiskConfigurationUpdateParameters>>(); cfg.CreateMap<PVM.DataDiskConfigurationList, Collection<PVM.DataDiskConfiguration>>(); cfg.CreateMap<Collection<PVM.DataDiskConfiguration>, IList<NSM.DataDiskConfigurationUpdateParameters>>(); cfg.CreateMap<Collection<PVM.DataDiskConfiguration>, List<NSM.DataDiskConfigurationUpdateParameters>>(); cfg.CreateMap<PVM.DataDiskConfigurationList, IList<NSM.DataDiskConfigurationUpdateParameters>>(); cfg.CreateMap<PVM.DataDiskConfigurationList, List<NSM.DataDiskConfigurationUpdateParameters>>(); cfg.CreateMap<NSM.VirtualMachineVMImageListResponse.VirtualMachineVMImage, PVM.VMImageContext>() .ForMember(c => c.ImageName, o => o.MapFrom(r => r.Name)); cfg.CreateMap<OperationStatusResponse, PVM.VMImageContext>() .ForMember(c => c.OS, o => o.Ignore()) .ForMember(c => c.LogicalSizeInGB, o => o.Ignore()) .ForMember(c => c.OperationId, o => o.MapFrom(r => r.Id)) .ForMember(c => c.OperationStatus, o => o.MapFrom(r => r.Status.ToString())); // VM Resource Extensions cfg.CreateMap<NSM.GuestAgentMessage, PVM.GuestAgentMessage>(); cfg.CreateMap<NSM.GuestAgentFormattedMessage, PVM.GuestAgentFormattedMessage>(); cfg.CreateMap<NSM.GuestAgentStatus, PVM.GuestAgentStatus>() .ForMember(c => c.TimestampUtc, o => o.MapFrom(r => r.Timestamp)); cfg.CreateMap<NSM.MaintenanceStatus, PVM.MaintenanceStatus>(); cfg.CreateMap<NSM.ResourceExtensionConfigurationStatus, PVM.ResourceExtensionConfigurationStatus>() .ForMember(c => c.TimestampUtc, o => o.MapFrom(r => r.Timestamp)) .ForMember(c => c.ConfigurationAppliedTimeUtc, o => o.MapFrom(r => r.ConfigurationAppliedTime)); cfg.CreateMap<NSM.ResourceExtensionSubStatus, PVM.ResourceExtensionSubStatus>(); cfg.CreateMap<IList<NSM.ResourceExtensionSubStatus>, PVM.ResourceExtensionStatusList>(); cfg.CreateMap<IEnumerable<NSM.ResourceExtensionSubStatus>, PVM.ResourceExtensionStatusList>(); cfg.CreateMap<List<NSM.ResourceExtensionSubStatus>, PVM.ResourceExtensionStatusList>(); cfg.CreateMap<NSM.ResourceExtensionStatus, PVM.ResourceExtensionStatus>(); cfg.CreateMap<IList<NSM.ResourceExtensionStatus>, PVM.ResourceExtensionStatusList>(); cfg.CreateMap<IEnumerable<NSM.ResourceExtensionStatus>, PVM.ResourceExtensionStatusList>(); cfg.CreateMap<List<NSM.ResourceExtensionStatus>, PVM.ResourceExtensionStatusList>(); //SM to NewSM mapping cfg.CreateMap<PVM.LoadBalancerProbe, NSM.LoadBalancerProbe>() .ForMember(c => c.Protocol, o => o.MapFrom(r => r.Protocol)); cfg.CreateMap<PVM.AccessControlListRule, NSM.AccessControlListRule>(); cfg.CreateMap<PVM.EndpointAccessControlList, NSM.EndpointAcl>() .ForMember(c => c.Rules, o => o.MapFrom(r => r.Rules.ToList())); cfg.CreateMap<PVM.InputEndpoint, NSM.InputEndpoint>() .ForMember(c => c.VirtualIPAddress, o => o.MapFrom(r => r.Vip != null ? IPAddress.Parse(r.Vip) : null)) .ForMember(c => c.EndpointAcl, o => o.MapFrom(r => r.EndpointAccessControlList)) .ForMember(c => c.LoadBalancerName, o => o.MapFrom(r => r.LoadBalancerName)); cfg.CreateMap<PVM.DataVirtualHardDisk, NSM.DataVirtualHardDisk>() .ForMember(c => c.Name, o => o.MapFrom(r => r.DiskName)) .ForMember(c => c.Label, o => o.MapFrom(r => r.DiskLabel)) .ForMember(c => c.LogicalUnitNumber, o => o.MapFrom(r => r.Lun)); cfg.CreateMap<PVM.OSVirtualHardDisk, NSM.OSVirtualHardDisk>() .ForMember(c => c.Name, o => o.MapFrom(r => r.DiskName)) .ForMember(c => c.Label, o => o.MapFrom(r => r.DiskLabel)) .ForMember(c => c.OperatingSystem, o => o.MapFrom(r => r.OS)); cfg.CreateMap<PVM.NetworkConfigurationSet, NSM.ConfigurationSet>() .ForMember(c => c.InputEndpoints, o => o.MapFrom(r => r.InputEndpoints != null ? r.InputEndpoints.ToList() : null)) .ForMember(c => c.SubnetNames, o => o.MapFrom(r => r.SubnetNames != null ? r.SubnetNames.ToList() : null)) .ForMember(c => c.PublicIPs, o => o.MapFrom(r => r.PublicIPs != null ? r.PublicIPs.ToList() : null)); cfg.CreateMap<PVM.DebugSettings, NSM.DebugSettings>(); cfg.CreateMap<PVM.LinuxProvisioningConfigurationSet.SSHKeyPair, NSM.SshSettingKeyPair>(); cfg.CreateMap<PVM.LinuxProvisioningConfigurationSet.SSHPublicKey, NSM.SshSettingPublicKey>(); cfg.CreateMap<PVM.LinuxProvisioningConfigurationSet.SSHSettings, NSM.SshSettings>(); cfg.CreateMap<PVM.LinuxProvisioningConfigurationSet, NSM.ConfigurationSet>() .ForMember(c => c.PublicIPs, o => o.Ignore()) .ForMember(c => c.UserPassword, o => o.MapFrom(r => r.UserPassword == null ? null : r.UserPassword.ConvertToUnsecureString())) .ForMember(c => c.SshSettings, o => o.MapFrom(r => r.SSH)); cfg.CreateMap<PVM.WindowsProvisioningConfigurationSet, NSM.ConfigurationSet>() .ForMember(c => c.PublicIPs, o => o.Ignore()) .ForMember(c => c.AdminPassword, o => o.MapFrom(r => r.AdminPassword == null ? null : r.AdminPassword.ConvertToUnsecureString())); cfg.CreateMap<PVM.ProvisioningConfigurationSet, NSM.ConfigurationSet>() .ForMember(c => c.PublicIPs, o => o.Ignore()); cfg.CreateMap<PVM.ConfigurationSet, NSM.ConfigurationSet>() .ForMember(c => c.PublicIPs, o => o.Ignore()); cfg.CreateMap<PVM.InstanceEndpoint, NSM.InstanceEndpoint>() .ForMember(c => c.VirtualIPAddress, o => o.MapFrom(r => r.Vip != null ? IPAddress.Parse(r.Vip) : null)) .ForMember(c => c.Port, o => o.MapFrom(r => r.PublicPort)); cfg.CreateMap<PVM.WindowsProvisioningConfigurationSet.WinRmConfiguration, NSM.WindowsRemoteManagementSettings>(); cfg.CreateMap<PVM.WindowsProvisioningConfigurationSet.WinRmListenerProperties, NSM.WindowsRemoteManagementListener>() .ForMember(c => c.ListenerType, o => o.MapFrom(r => r.Protocol)); cfg.CreateMap<PVM.WindowsProvisioningConfigurationSet.WinRmListenerCollection, IList<NSM.WindowsRemoteManagementListener>>(); //NewSM to SM mapping cfg.CreateMap<NSM.LoadBalancerProbe, PVM.LoadBalancerProbe>() .ForMember(c => c.Protocol, o => o.MapFrom(r => r.Protocol.ToString().ToLower())); cfg.CreateMap<NSM.AccessControlListRule, PVM.AccessControlListRule>(); cfg.CreateMap<NSM.EndpointAcl, PVM.EndpointAccessControlList>() .ForMember(c => c.Rules, o => o.MapFrom(r => r.Rules)); cfg.CreateMap<NSM.InputEndpoint, PVM.InputEndpoint>() .ForMember(c => c.LoadBalancerName, o => o.MapFrom(r => r.LoadBalancerName)) .ForMember(c => c.Vip, o => o.MapFrom(r => r.VirtualIPAddress != null ? r.VirtualIPAddress.ToString() : null)) .ForMember(c => c.EndpointAccessControlList, o => o.MapFrom(r => r.EndpointAcl)); cfg.CreateMap<NSM.DataVirtualHardDisk, PVM.DataVirtualHardDisk>() .ForMember(c => c.DiskName, o => o.MapFrom(r => r.Name)) .ForMember(c => c.DiskLabel, o => o.MapFrom(r => r.Label)) .ForMember(c => c.Lun, o => o.MapFrom(r => r.LogicalUnitNumber)); cfg.CreateMap<NSM.OSVirtualHardDisk, PVM.OSVirtualHardDisk>() .ForMember(c => c.DiskName, o => o.MapFrom(r => r.Name)) .ForMember(c => c.DiskLabel, o => o.MapFrom(r => r.Label)) .ForMember(c => c.OS, o => o.MapFrom(r => r.OperatingSystem)); cfg.CreateMap<NSM.ConfigurationSet, PVM.ConfigurationSet>(); cfg.CreateMap<NSM.ConfigurationSet, PVM.NetworkConfigurationSet>(); cfg.CreateMap<NSM.DebugSettings, PVM.DebugSettings>(); cfg.CreateMap<NSM.SshSettingKeyPair, PVM.LinuxProvisioningConfigurationSet.SSHKeyPair>(); cfg.CreateMap<NSM.SshSettingPublicKey, PVM.LinuxProvisioningConfigurationSet.SSHPublicKey>(); cfg.CreateMap<NSM.SshSettings, PVM.LinuxProvisioningConfigurationSet.SSHSettings>(); cfg.CreateMap<NSM.ConfigurationSet, PVM.LinuxProvisioningConfigurationSet>() .ForMember(c => c.UserPassword, o => o.MapFrom(r => SecureStringHelper.GetSecureString(r.UserPassword))) .ForMember(c => c.SSH, o => o.MapFrom(r => r.SshSettings)); cfg.CreateMap<NSM.ConfigurationSet, PVM.WindowsProvisioningConfigurationSet>() .ForMember(c => c.AdminPassword, o => o.MapFrom(r => SecureStringHelper.GetSecureString(r.AdminPassword))); cfg.CreateMap<NSM.InstanceEndpoint, PVM.InstanceEndpoint>() .ForMember(c => c.Vip, o => o.MapFrom(r => r.VirtualIPAddress != null ? r.VirtualIPAddress.ToString() : null)) .ForMember(c => c.PublicPort, o => o.MapFrom(r => r.Port)); cfg.CreateMap<NSM.WindowsRemoteManagementSettings, PVM.WindowsProvisioningConfigurationSet.WinRmConfiguration>(); cfg.CreateMap<NSM.WindowsRemoteManagementListener, PVM.WindowsProvisioningConfigurationSet.WinRmListenerProperties>() .ForMember(c => c.Protocol, o => o.MapFrom(r => r.ListenerType.ToString())); cfg.CreateMap<IList<NSM.WindowsRemoteManagementListener>, PVM.WindowsProvisioningConfigurationSet.WinRmListenerCollection>(); // LoadBalancedEndpointList mapping cfg.CreateMap<PVM.AccessControlListRule, NSM.AccessControlListRule>(); cfg.CreateMap<PVM.EndpointAccessControlList, NSM.EndpointAcl>(); cfg.CreateMap<PVM.InputEndpoint, NSM.VirtualMachineUpdateLoadBalancedSetParameters.InputEndpoint>() .ForMember(c => c.Rules, o => o.MapFrom(r => r.EndpointAccessControlList == null ? null : r.EndpointAccessControlList.Rules)) .ForMember(c => c.VirtualIPAddress, o => o.MapFrom(r => r.Vip)); cfg.CreateMap<NSM.AccessControlListRule, PVM.AccessControlListRule>(); cfg.CreateMap<NSM.EndpointAcl, PVM.EndpointAccessControlList>(); cfg.CreateMap<NSM.VirtualMachineUpdateLoadBalancedSetParameters.InputEndpoint, PVM.InputEndpoint>() .ForMember(c => c.EndpointAccessControlList, o => o.MapFrom(r => r.Rules == null ? null : r.Rules)) .ForMember(c => c.Vip, o => o.MapFrom(r => r.VirtualIPAddress)); //Common mapping cfg.CreateMap<AzureOperationResponse, ManagementOperationContext>() .ForMember(c => c.OperationId, o => o.MapFrom(r => r.RequestId)) .ForMember(c => c.OperationStatus, o => o.MapFrom(r => r.StatusCode.ToString())); cfg.CreateMap<OperationStatusResponse, ManagementOperationContext>() .ForMember(c => c.OperationId, o => o.MapFrom(r => r.Id)) .ForMember(c => c.OperationStatus, o => o.MapFrom(r => r.Status.ToString())); //AffinityGroup mapping cfg.CreateMap<AffinityGroupGetResponse, PVM.AffinityGroupContext>() .ForMember(c => c.VirtualMachineRoleSizes, o => o.MapFrom(r => r.ComputeCapabilities == null ? null : r.ComputeCapabilities.VirtualMachinesRoleSizes)) .ForMember(c => c.WebWorkerRoleSizes, o => o.MapFrom(r => r.ComputeCapabilities == null ? null : r.ComputeCapabilities.WebWorkerRoleSizes)); cfg.CreateMap<AffinityGroupListResponse.AffinityGroup, PVM.AffinityGroupContext>() .ForMember(c => c.VirtualMachineRoleSizes, o => o.MapFrom(r => r.ComputeCapabilities == null ? null : r.ComputeCapabilities.VirtualMachinesRoleSizes)) .ForMember(c => c.WebWorkerRoleSizes, o => o.MapFrom(r => r.ComputeCapabilities == null ? null : r.ComputeCapabilities.WebWorkerRoleSizes)); cfg.CreateMap<AffinityGroupGetResponse.HostedServiceReference, PVM.AffinityGroupContext.Service>() .ForMember(c => c.Url, o => o.MapFrom(r => r.Uri)); cfg.CreateMap<AffinityGroupGetResponse.StorageServiceReference, PVM.AffinityGroupContext.Service>() .ForMember(c => c.Url, o => o.MapFrom(r => r.Uri)); cfg.CreateMap<OperationStatusResponse, PVM.AffinityGroupContext>() .ForMember(c => c.OperationId, o => o.MapFrom(r => r.Id)) .ForMember(c => c.OperationStatus, o => o.MapFrom(r => r.Status.ToString())); //Location mapping cfg.CreateMap<LocationsListResponse.Location, PVM.LocationsContext>() .ForMember(c => c.VirtualMachineRoleSizes, o => o.MapFrom(r => r.ComputeCapabilities == null ? null : r.ComputeCapabilities.VirtualMachinesRoleSizes)) .ForMember(c => c.WebWorkerRoleSizes, o => o.MapFrom(r => r.ComputeCapabilities == null ? null : r.ComputeCapabilities.WebWorkerRoleSizes)) .ForMember(c => c.StorageAccountTypes, o => o.MapFrom(r => r.StorageCapabilities == null ? null : r.StorageCapabilities.StorageAccountTypes)); cfg.CreateMap<OperationStatusResponse, PVM.LocationsContext>() .ForMember(c => c.OperationId, o => o.MapFrom(r => r.Id)) .ForMember(c => c.OperationStatus, o => o.MapFrom(r => r.Status.ToString())); //Role sizes mapping cfg.CreateMap<RoleSizeListResponse.RoleSize, PVM.RoleSizeContext>() .ForMember(c => c.InstanceSize, o => o.MapFrom(r => r.Name)) .ForMember(c => c.RoleSizeLabel, o => o.MapFrom(r => r.Label)); cfg.CreateMap<OperationStatusResponse, PVM.RoleSizeContext>() .ForMember(c => c.OperationId, o => o.MapFrom(r => r.Id)) .ForMember(c => c.OperationStatus, o => o.MapFrom(r => r.Status.ToString())); //ServiceCertificate mapping cfg.CreateMap<NSM.ServiceCertificateGetResponse, PVM.CertificateContext>() .ForMember(c => c.Data, o => o.MapFrom(r => r.Data != null ? Convert.ToBase64String(r.Data) : null)); cfg.CreateMap<NSM.ServiceCertificateListResponse.Certificate, PVM.CertificateContext>() .ForMember(c => c.Url, o => o.MapFrom(r => r.CertificateUri)) .ForMember(c => c.Data, o => o.MapFrom(r => r.Data != null ? Convert.ToBase64String(r.Data) : null)); cfg.CreateMap<OperationStatusResponse, PVM.CertificateContext>() .ForMember(c => c.OperationId, o => o.MapFrom(r => r.Id)) .ForMember(c => c.OperationStatus, o => o.MapFrom(r => r.Status.ToString())); cfg.CreateMap<OperationStatusResponse, ManagementOperationContext>() .ForMember(c => c.OperationId, o => o.MapFrom(r => r.Id)) .ForMember(c => c.OperationStatus, o => o.MapFrom(r => r.Status.ToString())); //OperatingSystems mapping cfg.CreateMap<NSM.OperatingSystemListResponse.OperatingSystem, PVM.OSVersionsContext>(); cfg.CreateMap<OperationStatusResponse, PVM.OSVersionsContext>() .ForMember(c => c.OperationId, o => o.MapFrom(r => r.Id)) .ForMember(c => c.OperationStatus, o => o.MapFrom(r => r.Status.ToString())); //Service mapping cfg.CreateMap<NSM.HostedServiceProperties, PVM.HostedServiceDetailedContext>() .ForMember(c => c.Description, o => o.MapFrom(r => string.IsNullOrEmpty(r.Description) ? null : r.Description)) .ForMember(c => c.DateModified, o => o.MapFrom(r => r.DateLastModified)); cfg.CreateMap<NSM.HostedServiceGetResponse, PVM.HostedServiceDetailedContext>() .ForMember(c => c.ExtendedProperties, o => o.MapFrom(r => r.Properties == null ? null : r.Properties.ExtendedProperties)) .ForMember(c => c.VirtualMachineRoleSizes, o => o.MapFrom(r => r.ComputeCapabilities == null ? null : r.ComputeCapabilities.VirtualMachinesRoleSizes)) .ForMember(c => c.WebWorkerRoleSizes, o => o.MapFrom(r => r.ComputeCapabilities == null ? null : r.ComputeCapabilities.WebWorkerRoleSizes)) .ForMember(c => c.Url, o => o.MapFrom(r => r.Uri)); cfg.CreateMap<NSM.HostedServiceListResponse.HostedService, PVM.HostedServiceDetailedContext>() .ForMember(c => c.ExtendedProperties, o => o.MapFrom(r => r.Properties == null ? null : r.Properties.ExtendedProperties)) .ForMember(c => c.VirtualMachineRoleSizes, o => o.MapFrom(r => r.ComputeCapabilities == null ? null : r.ComputeCapabilities.VirtualMachinesRoleSizes)) .ForMember(c => c.WebWorkerRoleSizes, o => o.MapFrom(r => r.ComputeCapabilities == null ? null : r.ComputeCapabilities.WebWorkerRoleSizes)) .ForMember(c => c.Url, o => o.MapFrom(r => r.Uri)); cfg.CreateMap<OperationStatusResponse, PVM.HostedServiceDetailedContext>() .ForMember(c => c.OperationId, o => o.MapFrom(r => r.Id)) .ForMember(c => c.OperationStatus, o => o.MapFrom(r => r.Status.ToString())); //Disk mapping cfg.CreateMap<NSM.VirtualMachineDiskListResponse.VirtualMachineDisk, PVM.DiskContext>() .ForMember(c => c.MediaLink, o => o.MapFrom(r => r.MediaLinkUri)) .ForMember(c => c.DiskSizeInGB, o => o.MapFrom(r => r.LogicalSizeInGB)) .ForMember(c => c.OS, o => o.MapFrom(r => r.OperatingSystemType)) .ForMember(c => c.DiskName, o => o.MapFrom(r => r.Name)) .ForMember(c => c.AttachedTo, o => o.MapFrom(r => r.UsageDetails)); cfg.CreateMap<NSM.VirtualMachineDiskListResponse.VirtualMachineDiskUsageDetails, PVM.DiskContext.RoleReference>(); cfg.CreateMap<NSM.VirtualMachineDiskGetResponse, PVM.DiskContext>() .ForMember(c => c.AttachedTo, o => o.MapFrom(r => r.UsageDetails)) .ForMember(c => c.DiskName, o => o.MapFrom(r => r.Name)) .ForMember(c => c.DiskSizeInGB, o => o.MapFrom(r => r.LogicalSizeInGB)) .ForMember(c => c.IsCorrupted, o => o.MapFrom(r => r.IsCorrupted)) .ForMember(c => c.MediaLink, o => o.MapFrom(r => r.MediaLinkUri)) .ForMember(c => c.OS, o => o.MapFrom(r => r.OperatingSystemType)); cfg.CreateMap<NSM.VirtualMachineDiskGetResponse.VirtualMachineDiskUsageDetails, PVM.DiskContext.RoleReference>(); cfg.CreateMap<NSM.VirtualMachineDiskCreateResponse, PVM.DiskContext>() .ForMember(c => c.DiskName, o => o.MapFrom(r => r.Name)) .ForMember(c => c.OS, o => o.MapFrom(r => r.OperatingSystem)) .ForMember(c => c.MediaLink, o => o.MapFrom(r => r.MediaLinkUri)) .ForMember(c => c.DiskSizeInGB, o => o.MapFrom(r => r.LogicalSizeInGB)) .ForMember(c => c.AttachedTo, o => o.MapFrom(r => r.UsageDetails)); cfg.CreateMap<NSM.VirtualMachineDiskCreateResponse.VirtualMachineDiskUsageDetails, PVM.DiskContext.RoleReference>(); cfg.CreateMap<NSM.VirtualMachineDiskUpdateResponse, PVM.DiskContext>() .ForMember(c => c.DiskName, o => o.MapFrom(r => r.Name)) .ForMember(c => c.MediaLink, o => o.MapFrom(r => r.MediaLinkUri)) .ForMember(c => c.DiskSizeInGB, o => o.MapFrom(r => r.LogicalSizeInGB)); cfg.CreateMap<OperationStatusResponse, PVM.DiskContext>() .ForMember(c => c.OperationId, o => o.MapFrom(r => r.Id)) .ForMember(c => c.OperationStatus, o => o.MapFrom(r => r.Status.ToString())); //Storage mapping cfg.CreateMap<StorageAccountGetResponse, PVM.StorageServicePropertiesOperationContext>() .ForMember(c => c.StorageAccountDescription, o => o.MapFrom(r => r.StorageAccount.Properties == null ? null : r.StorageAccount.Properties.Description)) .ForMember(c => c.StorageAccountName, o => o.MapFrom(r => r.StorageAccount.Name)) .ForMember(c => c.MigrationState, o => o.MapFrom(r => r.StorageAccount.MigrationState)); cfg.CreateMap<StorageAccountProperties, PVM.StorageServicePropertiesOperationContext>() .ForMember(c => c.StorageAccountDescription, o => o.MapFrom(r => r.Description)) .ForMember(c => c.GeoPrimaryLocation, o => o.MapFrom(r => r.GeoPrimaryRegion)) .ForMember(c => c.GeoSecondaryLocation, o => o.MapFrom(r => r.GeoSecondaryRegion)) .ForMember(c => c.StorageAccountStatus, o => o.MapFrom(r => r.Status)) .ForMember(c => c.StatusOfPrimary, o => o.MapFrom(r => r.StatusOfGeoPrimaryRegion)) .ForMember(c => c.StatusOfSecondary, o => o.MapFrom(r => r.StatusOfGeoSecondaryRegion)); cfg.CreateMap<StorageAccount, PVM.StorageServicePropertiesOperationContext>() .ForMember(c => c.StorageAccountDescription, o => o.MapFrom(r => r.Properties == null ? null : r.Properties.Description)) .ForMember(c => c.StorageAccountName, o => o.MapFrom(r => r.Name)); cfg.CreateMap<OperationStatusResponse, PVM.StorageServicePropertiesOperationContext>() .ForMember(c => c.OperationId, o => o.MapFrom(r => r.Id)) .ForMember(c => c.OperationStatus, o => o.MapFrom(r => r.Status.ToString())); cfg.CreateMap<StorageAccountGetKeysResponse, PVM.StorageServiceKeyOperationContext>() .ForMember(c => c.Primary, o => o.MapFrom(r => r.PrimaryKey)) .ForMember(c => c.Secondary, o => o.MapFrom(r => r.SecondaryKey)); cfg.CreateMap<OperationStatusResponse, PVM.StorageServiceKeyOperationContext>() .ForMember(c => c.OperationId, o => o.MapFrom(r => r.Id)) .ForMember(c => c.OperationStatus, o => o.MapFrom(r => r.Status.ToString())); cfg.CreateMap<OperationStatusResponse, ManagementOperationContext>() .ForMember(c => c.OperationId, o => o.MapFrom(r => r.Id)) .ForMember(c => c.OperationStatus, o => o.MapFrom(r => r.Status.ToString())); // DomainJoinSettings mapping for IaaS cfg.CreateMap<NSM.DomainJoinCredentials, PVM.WindowsProvisioningConfigurationSet.DomainJoinCredentials>() .ForMember(c => c.Domain, o => o.MapFrom(r => r.Domain)) .ForMember(c => c.Username, o => o.MapFrom(r => r.UserName)) .ForMember(c => c.Password, o => o.MapFrom(r => SecureStringHelper.GetSecureString(r.Password))); cfg.CreateMap<NSM.DomainJoinProvisioning, PVM.WindowsProvisioningConfigurationSet.DomainJoinProvisioning>() .ForMember(c => c.AccountData, o => o.MapFrom(r => r.AccountData)); cfg.CreateMap<NSM.DomainJoinSettings, PVM.WindowsProvisioningConfigurationSet.DomainJoinSettings>() .ForMember(c => c.Credentials, o => o.MapFrom(r => r.Credentials)) .ForMember(c => c.JoinDomain, o => o.MapFrom(r => r.DomainToJoin)) .ForMember(c => c.MachineObjectOU, o => o.MapFrom(r => r.LdapMachineObjectOU)) .ForMember(c => c.Provisioning, o => o.MapFrom(r => r.Provisioning)); cfg.CreateMap<PVM.WindowsProvisioningConfigurationSet.DomainJoinCredentials, NSM.DomainJoinCredentials>() .ForMember(c => c.Domain, o => o.MapFrom(r => r.Domain)) .ForMember(c => c.UserName, o => o.MapFrom(r => r.Username)) .ForMember(c => c.Password, o => o.MapFrom(r => r.Password.ConvertToUnsecureString())); cfg.CreateMap<PVM.WindowsProvisioningConfigurationSet.DomainJoinProvisioning, NSM.DomainJoinProvisioning>() .ForMember(c => c.AccountData, o => o.MapFrom(r => r.AccountData)); cfg.CreateMap<PVM.WindowsProvisioningConfigurationSet.DomainJoinSettings, NSM.DomainJoinSettings>() .ForMember(c => c.Credentials, o => o.MapFrom(r => r.Credentials)) .ForMember(c => c.DomainToJoin, o => o.MapFrom(r => r.JoinDomain)) .ForMember(c => c.LdapMachineObjectOU, o => o.MapFrom(r => r.MachineObjectOU)) .ForMember(c => c.Provisioning, o => o.MapFrom(r => r.Provisioning)); // Networks mapping cfg.CreateMap<NVM.NetworkListResponse.AddressSpace, PVM.AddressSpace>(); cfg.CreateMap<NVM.NetworkListResponse.Connection, PVM.Connection>(); cfg.CreateMap<NVM.NetworkListResponse.LocalNetworkSite, PVM.LocalNetworkSite>(); cfg.CreateMap<NVM.NetworkListResponse.DnsServer, PVM.DnsServer>(); cfg.CreateMap<NVM.NetworkListResponse.Subnet, PVM.Subnet>(); cfg.CreateMap<IList<NVM.NetworkListResponse.DnsServer>, PVM.DnsSettings>() .ForMember(c => c.DnsServers, o => o.MapFrom(r => r)); cfg.CreateMap<IList<NVM.NetworkListResponse.Gateway>, PVM.Gateway>(); cfg.CreateMap<NVM.NetworkListResponse.VirtualNetworkSite, PVM.VirtualNetworkSite>(); cfg.CreateMap<NVM.NetworkListResponse.VirtualNetworkSite, PVM.VirtualNetworkSiteContext>() .ForMember(c => c.AddressSpacePrefixes, o => o.MapFrom(r => r.AddressSpace == null ? null : r.AddressSpace.AddressPrefixes == null ? null : r.AddressSpace.AddressPrefixes.Select(p => p))) .ForMember(c => c.DnsServers, o => o.MapFrom(r => r.DnsServers.AsEnumerable())) .ForMember(c => c.GatewayProfile, o => o.MapFrom(r => r.Gateway.Profile)) .ForMember(c => c.GatewaySites, o => o.MapFrom(r => r.Gateway.Sites)); cfg.CreateMap<OperationStatusResponse, PVM.VirtualNetworkSiteContext>() .ForMember(c => c.OperationId, o => o.MapFrom(r => r.Id)) .ForMember(c => c.OperationStatus, o => o.MapFrom(r => r.Status.ToString())) .ForMember(c => c.Id, o => o.Ignore()); // Check Static IP Availability Response Mapping cfg.CreateMap<NVM.NetworkStaticIPAvailabilityResponse, PVM.VirtualNetworkStaticIPAvailabilityContext>(); cfg.CreateMap<OperationStatusResponse, PVM.VirtualNetworkStaticIPAvailabilityContext>() .ForMember(c => c.OperationId, o => o.MapFrom(r => r.Id)) .ForMember(c => c.OperationStatus, o => o.MapFrom(r => r.Status.ToString())); // New SM to Model cfg.CreateMap<NSM.StoredCertificateSettings, PVM.CertificateSetting>(); // Model to New SM cfg.CreateMap<PVM.CertificateSetting, NSM.StoredCertificateSettings>(); // Resource Extensions cfg.CreateMap<NSM.ResourceExtensionParameterValue, PVM.ResourceExtensionParameterValue>() .ForMember(c => c.SecureValue, o => o.MapFrom(r => SecureStringHelper.GetSecureString(r))) .ForMember(c => c.Value, o => o.MapFrom(r => SecureStringHelper.GetPlainString(r))); cfg.CreateMap<NSM.ResourceExtensionReference, PVM.ResourceExtensionReference>(); cfg.CreateMap<PVM.ResourceExtensionParameterValue, NSM.ResourceExtensionParameterValue>() .ForMember(c => c.Value, o => o.MapFrom(r => SecureStringHelper.GetPlainString(r))); cfg.CreateMap<PVM.ResourceExtensionReference, NSM.ResourceExtensionReference>(); // Reserved IP cfg.CreateMap<OperationStatusResponse, PVM.ReservedIPContext>() .ForMember(c => c.OperationId, o => o.MapFrom(r => r.Id)) .ForMember(c => c.OperationStatus, o => o.MapFrom(r => r.Status.ToString())) .ForMember(c => c.Id, o => o.Ignore()); cfg.CreateMap<NVM.NetworkReservedIPGetResponse, PVM.ReservedIPContext>() .ForMember(c => c.ReservedIPName, o => o.MapFrom(r => r.Name)); cfg.CreateMap<NVM.NetworkReservedIPListResponse.ReservedIP, PVM.ReservedIPContext>() .ForMember(c => c.ReservedIPName, o => o.MapFrom(r => r.Name)); // Public IP cfg.CreateMap<PVM.PublicIP, NSM.RoleInstance.PublicIP>(); cfg.CreateMap<PVM.AssignPublicIP, NSM.ConfigurationSet.PublicIP>(); cfg.CreateMap<NSM.RoleInstance.PublicIP, PVM.PublicIP>(); cfg.CreateMap<NSM.ConfigurationSet.PublicIP, PVM.AssignPublicIP>(); // NetworkInterface cfg.CreateMap<PVM.AssignNetworkInterface, NSM.NetworkInterface>(); cfg.CreateMap<PVM.AssignIPConfiguration, NSM.IPConfiguration>(); cfg.CreateMap<PVM.NetworkInterface, NSM.NetworkInterfaceInstance>(); cfg.CreateMap<PVM.IPConfiguration, NSM.IPConfigurationInstance>(); cfg.CreateMap<NSM.NetworkInterface, PVM.AssignNetworkInterface>(); cfg.CreateMap<NSM.IPConfiguration, PVM.AssignIPConfiguration>(); cfg.CreateMap<NSM.NetworkInterfaceInstance, PVM.NetworkInterface>(); cfg.CreateMap<NSM.IPConfigurationInstance, PVM.IPConfiguration>(); }); _mapper = config.CreateMapper(); } } }
//------------------------------------------------------------------------------ // <copyright file="asttree.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ namespace System.Xml.Schema { using System.Xml.XPath; using System.Diagnostics; using System.Globalization; using System.IO; using System.Collections; using System.Xml.Schema; using MS.Internal.Xml.XPath; /*--------------------------------------------------------------------------------------------- * * Dynamic Part Below... * * -------------------------------------------------------------------------------------------- */ // stack element class // this one needn't change, even the parameter in methods internal class AxisElement { internal DoubleLinkAxis curNode; // current under-checking node during navigating internal int rootDepth; // root depth -- contextDepth + 1 if ! isDss; context + {1...} if isDss internal int curDepth; // current depth internal bool isMatch; // current is already matching or waiting for matching internal DoubleLinkAxis CurNode { get { return this.curNode; } } // constructor internal AxisElement (DoubleLinkAxis node, int depth) { this.curNode = node; this.rootDepth = this.curDepth = depth; this.isMatch = false; } internal void SetDepth (int depth) { this.rootDepth = this.curDepth = depth; return; } // "a/b/c" pointer from b move to a // needn't change even tree structure changes internal void MoveToParent(int depth, ForwardAxis parent) { // "a/b/c", trying to match b (current node), but meet the end of a, so move pointer to a if ( depth == this.curDepth - 1 ) { // really need to move the current node pointer to parent // what i did here is for seperating the case of IsDss or only IsChild // bcoz in the first case i need to expect "a" from random depth // -1 means it doesn't expect some specific depth (referecing the dealing to -1 in movetochild method // while in the second case i can't change the root depth which is 1. if ((this.curNode.Input == parent.RootNode ) && (parent.IsDss)) { this.curNode = parent.RootNode; this.rootDepth = this.curDepth = -1; return; } else if (this.curNode.Input != null) { // else cur-depth --, cur-node change this.curNode = (DoubleLinkAxis) (this.curNode.Input); this.curDepth --; return; } else return; } // "a/b/c", trying to match b (current node), but meet the end of x (another child of a) // or maybe i matched, now move out the current node // or move out after failing to match attribute // the node i m next expecting is still the current node else if (depth == this.curDepth) { // after matched or [2] failed in matching attribute if (this.isMatch) { this.isMatch = false; } } return; // this node is still what i am expecting // ignore } // equal & ! attribute then move // "a/b/c" pointer from a move to b // return true if reach c and c is an element and c is the axis internal bool MoveToChild(string name, string URN, int depth, ForwardAxis parent) { // an attribute can never be the same as an element if (Asttree.IsAttribute(this.curNode)) { return false; } // either moveToParent or moveToChild status will have to be changed into unmatch... if (this.isMatch) { this.isMatch = false; } if (! AxisStack.Equal (this.curNode.Name, this.curNode.Urn, name, URN)) { return false; } if (this.curDepth == -1) { SetDepth (depth); } else if (depth > this.curDepth) { return false; } // matched ... if (this.curNode == parent.TopNode) { this.isMatch = true; return true; } // move down this.curNode DoubleLinkAxis nowNode = (DoubleLinkAxis) (this.curNode.Next); if (Asttree.IsAttribute (nowNode)) { this.isMatch = true; // for attribute return false; } this.curNode = nowNode; this.curDepth ++; return false; } } internal class AxisStack { // property private ArrayList stack; // of AxisElement private ForwardAxis subtree; // reference to the corresponding subtree private ActiveAxis parent; internal ForwardAxis Subtree { get { return this.subtree; } } internal int Length { // stack length get {return this.stack.Count; } } // instructor public AxisStack (ForwardAxis faxis, ActiveAxis parent) { this.subtree = faxis; this.stack = new ArrayList(); this.parent = parent; // need to use its contextdepth each time.... // improvement: // if ! isDss, there has nothing to do with Push/Pop, only one copy each time will be kept // if isDss, push and pop each time.... if (! faxis.IsDss) { // keep an instance this.Push (1); // context depth + 1 } // else just keep stack empty } // method internal void Push (int depth) { AxisElement eaxis = new AxisElement (this.subtree.RootNode, depth); this.stack.Add (eaxis); } internal void Pop () { this.stack.RemoveAt (Length - 1); } // used in the beginning of .// and MoveToChild // didn't consider Self, only consider name internal static bool Equal (string thisname, string thisURN, string name, string URN) { // which means "b" in xpath, no namespace should be specified if (thisURN == null) { if ( !((URN == null) || (URN.Length == 0))) { return false; } } // != "*" else if ((thisURN.Length != 0) && (thisURN != URN)) { return false; } // != "a:*" || "*" if ((thisname.Length != 0) && (thisname != name)) { return false; } return true; } // "a/b/c" pointer from b move to a // needn't change even tree structure changes internal void MoveToParent(string name, string URN, int depth) { if (this.subtree.IsSelfAxis) { return; } for (int i = 0; i < this.stack.Count; ++i) { ((AxisElement)stack[i]).MoveToParent (depth, this.subtree); } // in ".//"'s case, since each time you push one new element while match, why not pop one too while match? if ( this.subtree.IsDss && Equal (this.subtree.RootNode.Name, this.subtree.RootNode.Urn, name, URN)) { Pop(); } // only the last one } // "a/b/c" pointer from a move to b // return true if reach c internal bool MoveToChild(string name, string URN, int depth) { bool result = false; // push first if ( this.subtree.IsDss && Equal (this.subtree.RootNode.Name, this.subtree.RootNode.Urn, name, URN)) { Push(-1); } for (int i = 0; i < this.stack.Count; ++i) { if (((AxisElement)stack[i]).MoveToChild(name, URN, depth, this.subtree)) { result = true; } } return result; } // attribute can only at the topaxis part // dealing with attribute only here, didn't go into stack element at all // stack element only deal with moving the pointer around elements internal bool MoveToAttribute(string name, string URN, int depth) { if (! this.subtree.IsAttribute) { return false; } if (! Equal (this.subtree.TopNode.Name, this.subtree.TopNode.Urn, name, URN) ) { return false; } bool result = false; // no stack element for single attribute, so dealing with it seperately if (this.subtree.TopNode.Input == null) { return (this.subtree.IsDss || (depth == 1)); } for (int i = 0; i < this.stack.Count; ++i) { AxisElement eaxis = (AxisElement)this.stack[i]; if ((eaxis.isMatch) && (eaxis.CurNode == this.subtree.TopNode.Input)) { result = true; } } return result; } } // whenever an element is under identity-constraint, an instance of this class will be called // only care about property at this time internal class ActiveAxis { // consider about reactivating.... the stack should be clear right?? // just reset contextDepth & isActive.... private int currentDepth; // current depth, trace the depth by myself... movetochild, movetoparent, movetoattribute private bool isActive; // not active any more after moving out context node private Asttree axisTree; // reference to the whole tree // for each subtree i need to keep a stack... private ArrayList axisStack; // of AxisStack public int CurrentDepth { get { return this.currentDepth; } } // if an instance is !IsActive, then it can be reactive and reuse // still need thinking..... internal void Reactivate () { this.isActive = true; this.currentDepth = -1; } internal ActiveAxis (Asttree axisTree) { this.axisTree = axisTree; // only a pointer. do i need it? this.currentDepth = -1; // context depth is 0 -- enforce moveToChild for the context node // otherwise can't deal with "." node this.axisStack = new ArrayList(axisTree.SubtreeArray.Count); // defined length // new one stack element for each one for (int i = 0; i < axisTree.SubtreeArray.Count; ++i) { AxisStack stack = new AxisStack ((ForwardAxis)axisTree.SubtreeArray[i], this); axisStack.Add (stack); } this.isActive = true; } public bool MoveToStartElement (string localname, string URN) { if (!isActive) { return false; } // for each: this.currentDepth ++; bool result = false; for (int i = 0; i < this.axisStack.Count; ++i) { AxisStack stack = (AxisStack)this.axisStack[i]; // special case for self tree "." | ".//." if (stack.Subtree.IsSelfAxis) { if ( stack.Subtree.IsDss || (this.CurrentDepth == 0)) result = true; continue; } // otherwise if it's context node then return false if (this.CurrentDepth == 0) continue; if (stack.MoveToChild (localname, URN, this.currentDepth)) { result = true; // even already know the last result is true, still need to continue... // run everyone once } } return result; } // return result doesn't have any meaning until in SelectorActiveAxis public virtual bool EndElement (string localname, string URN) { // need to think if the early quitting will affect reactivating.... if (this.currentDepth == 0) { // leave context node this.isActive = false; this.currentDepth --; } if (! this.isActive) { return false; } for (int i = 0; i < this.axisStack.Count; ++i) { ((AxisStack)axisStack[i]).MoveToParent (localname, URN, this.currentDepth); } this.currentDepth -- ; return false; } // Secondly field interface public bool MoveToAttribute (string localname, string URN) { if (! this.isActive) { return false; } bool result = false; for (int i = 0; i < this.axisStack.Count; ++i) { if (((AxisStack)axisStack[i]).MoveToAttribute(localname, URN, this.currentDepth + 1)) { // don't change depth for attribute, but depth is add 1 result = true; } } return result; } } /* ---------------------------------------------------------------------------------------------- * * Static Part Below... * * ---------------------------------------------------------------------------------------------- */ // each node in the xpath tree internal class DoubleLinkAxis : Axis { internal Axis next; internal Axis Next { get { return this.next; } set { this.next = value; } } //constructor internal DoubleLinkAxis(Axis axis, DoubleLinkAxis inputaxis) : base(axis.TypeOfAxis, inputaxis, axis.Prefix, axis.Name, axis.NodeType) { this.next = null; this.Urn = axis.Urn; this.abbrAxis = axis.AbbrAxis; if (inputaxis != null) { inputaxis.Next = this; } } // recursive here internal static DoubleLinkAxis ConvertTree (Axis axis) { if (axis == null) { return null; } return ( new DoubleLinkAxis (axis, ConvertTree ((Axis) (axis.Input)))); } } // only keep axis, rootNode, isAttribute, isDss inside // act as an element tree for the Asttree internal class ForwardAxis { // Axis tree private DoubleLinkAxis topNode; private DoubleLinkAxis rootNode; // the root for reverse Axis // Axis tree property private bool isAttribute; // element or attribute? "@"? private bool isDss; // has ".//" in front of it? private bool isSelfAxis; // only one node in the tree, and it's "." (self) node internal DoubleLinkAxis RootNode { get { return this.rootNode; } } internal DoubleLinkAxis TopNode { get { return this.topNode; } } internal bool IsAttribute { get { return this.isAttribute; } } // has ".//" in front of it? internal bool IsDss { get { return this.isDss; } } internal bool IsSelfAxis { get { return this.isSelfAxis; } } public ForwardAxis (DoubleLinkAxis axis, bool isdesorself) { this.isDss = isdesorself; this.isAttribute = Asttree.IsAttribute (axis); this.topNode = axis; this.rootNode = axis; while ( this.rootNode.Input != null ) { this.rootNode = (DoubleLinkAxis)(this.rootNode.Input); } // better to calculate it out, since it's used so often, and if the top is self then the whole tree is self this.isSelfAxis = Asttree.IsSelf (this.topNode); } } // static, including an array of ForwardAxis (this is the whole picture) internal class Asttree { // set private then give out only get access, to keep it intact all along private ArrayList fAxisArray; private string xpathexpr; private bool isField; // field or selector private XmlNamespaceManager nsmgr; internal ArrayList SubtreeArray { get { return fAxisArray; } } // when making a new instance for Asttree, we do the compiling, and create the static tree instance public Asttree (string xPath, bool isField, XmlNamespaceManager nsmgr) { this.xpathexpr = xPath; this.isField = isField; this.nsmgr = nsmgr; // checking grammar... and build fAxisArray this.CompileXPath (xPath, isField, nsmgr); // might throw exception in the middle } // only for debug #if DEBUG public void PrintTree (StreamWriter msw) { for (int i = 0; i < fAxisArray.Count; ++i) { ForwardAxis axis = (ForwardAxis)fAxisArray[i]; msw.WriteLine("<Tree IsDss=\"{0}\" IsAttribute=\"{1}\">", axis.IsDss, axis.IsAttribute); DoubleLinkAxis printaxis = axis.TopNode; while ( printaxis != null ) { msw.WriteLine (" <node>"); msw.WriteLine (" <URN> {0} </URN>", printaxis.Urn); msw.WriteLine (" <Prefix> {0} </Prefix>", printaxis.Prefix); msw.WriteLine (" <Name> {0} </Name>", printaxis.Name); msw.WriteLine (" <NodeType> {0} </NodeType>", printaxis.NodeType); msw.WriteLine (" <AxisType> {0} </AxisType>", printaxis.TypeOfAxis); msw.WriteLine (" </node>"); printaxis = (DoubleLinkAxis) (printaxis.Input); } msw.WriteLine ("</Tree>"); } } #endif // this part is for parsing restricted xpath from grammar private static bool IsNameTest(Axis ast) { // Type = Element, abbrAxis = false // all are the same, has child:: or not return ((ast.TypeOfAxis == Axis.AxisType.Child) && (ast.NodeType == XPathNodeType.Element)); } internal static bool IsAttribute(Axis ast) { return ((ast.TypeOfAxis == Axis.AxisType.Attribute) && (ast.NodeType == XPathNodeType.Attribute)); } private static bool IsDescendantOrSelf(Axis ast) { return ((ast.TypeOfAxis == Axis.AxisType.DescendantOrSelf) && (ast.NodeType == XPathNodeType.All) && (ast.AbbrAxis)); } internal static bool IsSelf(Axis ast) { return ((ast.TypeOfAxis == Axis.AxisType.Self) && (ast.NodeType == XPathNodeType.All) && (ast.AbbrAxis)); } // don't return true or false, if it's invalid path, just throw exception during the process // for whitespace thing, i will directly trim the tree built here... public void CompileXPath (string xPath, bool isField, XmlNamespaceManager nsmgr) { if ((xPath == null) || (xPath.Length == 0)) { throw new XmlSchemaException(Res.Sch_EmptyXPath, string.Empty); } // firstly i still need to have an ArrayList to store tree only... // can't new ForwardAxis right away string[] xpath = xPath.Split('|'); ArrayList AstArray = new ArrayList(xpath.Length); this.fAxisArray = new ArrayList(xpath.Length); // throw compile exceptions // can i only new one builder here then run compile several times?? try { for (int i = 0; i < xpath.Length; ++i) { // default ! isdesorself (no .//) Axis ast = (Axis) (XPathParser.ParseXPathExpresion(xpath[i])); AstArray.Add (ast); } } catch { throw new XmlSchemaException(Res.Sch_ICXpathError, xPath); } Axis stepAst; for (int i = 0; i < AstArray.Count; ++i) { Axis ast = (Axis) AstArray[i]; // Restricted form // field can have an attribute: // throw exceptions during casting if ((stepAst = ast) == null) { throw new XmlSchemaException(Res.Sch_ICXpathError, xPath); } Axis top = stepAst; // attribute will have namespace too // field can have top attribute if (IsAttribute (stepAst)) { if (! isField) { throw new XmlSchemaException(Res.Sch_SelectorAttr, xPath); } else { SetURN (stepAst, nsmgr); try { stepAst = (Axis) (stepAst.Input); } catch { throw new XmlSchemaException(Res.Sch_ICXpathError, xPath); } } } // field or selector while ((stepAst != null) && (IsNameTest (stepAst) || IsSelf (stepAst))) { // trim tree "." node, if it's not the top one if (IsSelf (stepAst) && (ast != stepAst)) { top.Input = stepAst.Input; } else { top = stepAst; // set the URN if (IsNameTest(stepAst)) { SetURN (stepAst, nsmgr); } } try { stepAst = (Axis) (stepAst.Input); } catch { throw new XmlSchemaException(Res.Sch_ICXpathError, xPath); } } // the rest part can only be .// or null // trim the rest part, but need compile the rest part first top.Input = null; if (stepAst == null) { // top "." and has other element beneath, trim this "." node too if (IsSelf(ast) && (ast.Input != null)) { this.fAxisArray.Add ( new ForwardAxis ( DoubleLinkAxis.ConvertTree ((Axis) (ast.Input)), false)); } else { this.fAxisArray.Add ( new ForwardAxis ( DoubleLinkAxis.ConvertTree (ast), false)); } continue; } if (! IsDescendantOrSelf (stepAst)) { throw new XmlSchemaException(Res.Sch_ICXpathError, xPath); } try { stepAst = (Axis) (stepAst.Input); } catch { throw new XmlSchemaException(Res.Sch_ICXpathError, xPath); } if ((stepAst == null) || (! IsSelf (stepAst)) || (stepAst.Input != null)) { throw new XmlSchemaException(Res.Sch_ICXpathError, xPath); } // trim top "." if it's not the only node if (IsSelf(ast) && (ast.Input != null)) { this.fAxisArray.Add ( new ForwardAxis ( DoubleLinkAxis.ConvertTree ((Axis) (ast.Input)), true)); } else { this.fAxisArray.Add ( new ForwardAxis ( DoubleLinkAxis.ConvertTree (ast), true)); } } } // depending on axis.Name & axis.Prefix, i will set the axis.URN; // also, record urn from prefix during this // 4 different types of element or attribute (with @ before it) combinations: // (1) a:b (2) b (3) * (4) a:* // i will check xpath to be strictly conformed from these forms // for (1) & (4) i will have URN set properly // for (2) the URN is null // for (3) the URN is empty private void SetURN (Axis axis, XmlNamespaceManager nsmgr) { if (axis.Prefix.Length != 0) { // (1) (4) axis.Urn = nsmgr.LookupNamespace(axis.Prefix); if (axis.Urn == null) { throw new XmlSchemaException(Res.Sch_UnresolvedPrefix, axis.Prefix); } } else if (axis.Name.Length != 0) { // (2) axis.Urn = null; } else { // (3) axis.Urn = ""; } } }// Asttree }
using DotVVM.Framework.Controls; using System; using System.Collections; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using DotVVM.Framework.Compilation.ControlTree; using DotVVM.Framework.Compilation.ControlTree.Resolved; using System.Security.Cryptography; using System.Text; using System.Globalization; using System.Collections.Concurrent; using DotVVM.Framework.Compilation.Binding; using System.Diagnostics.CodeAnalysis; using System.Runtime.Serialization; using System.Threading.Tasks; using DotVVM.Framework.Binding; using FastExpressionCompiler; using RecordExceptions; namespace DotVVM.Framework.Utils { public static class ReflectionUtils { /// <summary> /// Gets the property name from lambda expression, e.g. 'a => a.FirstName' /// </summary> public static MemberInfo GetMemberFromExpression(Expression expression) { var originalExpression = expression; if (expression.NodeType == ExpressionType.Lambda) expression = ((LambdaExpression)expression).Body; while (expression is UnaryExpression unary) expression = unary.Operand; var body = expression as MemberExpression; if (body == null) throw new NotSupportedException($"Cannot get member from {originalExpression}"); return body.Member; } // http://haacked.com/archive/2012/07/23/get-all-types-in-an-assembly.aspx/ public static IEnumerable<Type> GetLoadableTypes(this Assembly assembly) { if (assembly == null) throw new ArgumentNullException("assembly"); try { return assembly.GetTypes(); } catch (ReflectionTypeLoadException e) { return e.Types.Where(t => t != null)!; } } ///<summary> Gets all members from the type, including inherited classes, implemented interfaces and interfaces inherited by the interface </summary> public static IEnumerable<MemberInfo> GetAllMembers(this Type type, BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static) { if (type.IsInterface) return type.GetMembers(flags).Concat(type.GetInterfaces().SelectMany(t => t.GetMembers(flags))); else return type.GetMembers(flags); } ///<summary> Gets all methods from the type, including inherited classes, implemented interfaces and interfaces inherited by the interface </summary> public static IEnumerable<MethodInfo> GetAllMethods(this Type type, BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static) { if (type.IsInterface) return type.GetMethods(flags).Concat(type.GetInterfaces().SelectMany(t => t.GetMethods(flags))); else return type.GetMethods(flags); } /// <summary> /// Gets filesystem path of assembly CodeBase /// http://stackoverflow.com/questions/52797/how-do-i-get-the-path-of-the-assembly-the-code-is-in /// </summary> public static string? GetCodeBasePath(this Assembly assembly) { return assembly.Location; } /// <summary> /// Checks whether given instantiated type is compatible with the open generic type /// </summary> public static bool IsAssignableToGenericType(this Type givenType, Type genericType, [NotNullWhen(returnValue: true)] out Type? commonType) { var interfaceTypes = givenType.GetInterfaces(); foreach (var it in interfaceTypes) { if (it.IsGenericType && it.GetGenericTypeDefinition() == genericType) { commonType = it; return true; } } if (givenType.IsGenericType && givenType.GetGenericTypeDefinition() == genericType) { commonType = givenType; return true; } var baseType = givenType.BaseType; if (baseType == null) { commonType = null; return false; } return IsAssignableToGenericType(baseType, genericType, out commonType); } /// <summary> /// Converts a value to a specified type /// </summary> /// <exception cref="TypeConvertException" /> public static object? ConvertValue(object? value, Type type) { // handle null values if (value == null) { if (type == typeof(bool)) return BoxingUtils.False; else if (type == typeof(int)) return BoxingUtils.Zero; else if (type.IsValueType) return Activator.CreateInstance(type); else return null; } if (type.IsInstanceOfType(value)) return value; // handle nullable types if (type.IsGenericType && Nullable.GetUnderlyingType(type) is Type nullableElementType) { if (value is string && (string)value == string.Empty) { // value is an empty string, return null return null; } // value is not null type = nullableElementType; } // handle exceptions if (value is string && type == typeof(Guid)) { return new Guid((string)value); } if (type == typeof(object)) { return value; } // handle enums if (type.IsEnum && value is string) { var split = ((string)value).Split(',', '|'); var isFlags = type.IsDefined(typeof(FlagsAttribute)); if (!isFlags && split.Length > 1) throw new Exception($"Enum {type} does allow multiple values. Use [FlagsAttribute] to allow it."); dynamic? result = null; foreach (var val in split) { try { if (result == null) result = Enum.Parse(type, val.Trim(), ignoreCase: true); // Enum.TryParse requires type parameter else { result |= (dynamic)Enum.Parse(type, val.Trim(), ignoreCase: true); } } catch (Exception ex) { throw new Exception($"The enum {type} does not allow a value '{val}'!", ex); } } return result; } // generic to string if (type == typeof(string)) { return value.ToString(); } // comma-separated array values if (value is string str && type.IsArray) { var objectArray = str.Split(',') .Select(s => ConvertValue(s.Trim(), type.GetElementType()!)) .ToArray(); var array = Array.CreateInstance(type.GetElementType()!, objectArray.Length); objectArray.CopyTo(array, 0); return array; } // numbers const NumberStyles numberStyle = NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent | NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite; if (value is string str2) { if (type == typeof(bool)) return BoxingUtils.Box(bool.Parse(str2)); else if (type == typeof(int)) return BoxingUtils.Box(int.Parse(str2, numberStyle & NumberStyles.Integer, CultureInfo.InvariantCulture)); else if (type == typeof(double)) return double.Parse(str2, numberStyle & NumberStyles.Float, CultureInfo.InvariantCulture); else if (type == typeof(float)) return float.Parse(str2, numberStyle & NumberStyles.Float, CultureInfo.InvariantCulture); else if (type == typeof(decimal)) return decimal.Parse(str2, numberStyle & NumberStyles.Float, CultureInfo.InvariantCulture); else if (type == typeof(ulong)) return ulong.Parse(str2, numberStyle & NumberStyles.Integer, CultureInfo.InvariantCulture); else if (type.IsNumericType()) return Convert.ChangeType(long.Parse(str2, numberStyle & NumberStyles.Integer, CultureInfo.InvariantCulture), type, CultureInfo.InvariantCulture); } // convert try { return Convert.ChangeType(value, type, CultureInfo.InvariantCulture); } catch (Exception e) { throw new TypeConvertException(value, type, e); } } public record TypeConvertException(object Value, Type Type, Exception InnerException): RecordException(InnerException) { public override string Message => $"Can not convert value '{Value}' to {Type}: {InnerException!.Message}"; } public static Type? GetEnumerableType(this Type collectionType) { var result = TypeDescriptorUtils.GetCollectionItemType(new ResolvedTypeDescriptor(collectionType)); if (result == null) return null; return ResolvedTypeDescriptor.ToSystemType(result); } public static readonly HashSet<Type> DateTimeTypes = new HashSet<Type>() { typeof(DateTime), typeof(DateTimeOffset), typeof(TimeSpan) }; public static readonly HashSet<Type> NumericTypes = new HashSet<Type>() { typeof (sbyte), typeof (byte), typeof (short), typeof (ushort), typeof (int), typeof (uint), typeof (long), typeof (ulong), typeof (char), typeof (float), typeof (double), typeof (decimal) }; public static readonly HashSet<Type> PrimitiveTypes = new HashSet<Type>() { typeof(string), typeof(char), typeof(bool), typeof(DateTime), typeof(DateTimeOffset), typeof(TimeSpan), typeof(Guid), typeof(byte), typeof(sbyte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(float), typeof(double), typeof(decimal) }; public static bool IsNumericType(this Type type) { return NumericTypes.Contains(type); } public static bool IsDateOrTimeType(this Type type) { return DateTimeTypes.Contains(type); } /// <summary> Return true for Tuple, ValueTuple, KeyValuePair </summary> public static bool IsTupleLike(Type type) => type.IsGenericType && ( type.FullName!.StartsWith(typeof(Tuple).FullName + "`") || type.FullName!.StartsWith(typeof(ValueTuple).FullName + "`") || type.GetGenericTypeDefinition() == typeof(KeyValuePair<,>) ); public static bool IsEnumerable(Type type) { return typeof(IEnumerable).IsAssignableFrom(type); } public static bool IsDictionary(Type type) { return type.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IDictionary<,>)); } public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition) { if (!genericInterfaceDefinition.IsInterface || !genericInterfaceDefinition.IsGenericTypeDefinition) { throw new ArgumentNullException($"'{genericInterfaceDefinition.FullName}' is not a generic interface definition."); } return type.GetInterfaces() .Concat(new[] { type }) .Where(i => i.IsGenericType) .Any(i => i.GetGenericTypeDefinition() == genericInterfaceDefinition); } public static bool IsCollection(Type type) { return type != typeof(string) && IsEnumerable(type) && !IsDictionary(type); } public static bool IsPrimitiveType(Type type) { return PrimitiveTypes.Contains(type) || (IsNullableType(type) && IsPrimitiveType(type.UnwrapNullableType())) || type.IsEnum; } public static bool IsNullableType(Type type) { return type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>); } public static bool IsComplexType(Type type) { return !IsPrimitiveType(type); } public static bool IsDelegate(this Type type) => typeof(Delegate).IsAssignableFrom(type); public static bool IsDelegate(this Type type, [NotNullWhen(true)] out MethodInfo? invokeMethod) { if (type.IsDelegate()) { invokeMethod = type.GetMethod("Invoke", BindingFlags.Public | BindingFlags.Instance).NotNull("Could not find delegate Invoke method"); return true; } else { invokeMethod = null; return false; } } public static ParameterInfo[]? GetDelegateArguments(this Type type) => type.IsDelegate(out var m) ? m.GetParameters() : null; public static bool Implements(this Type type, Type ifc) => Implements(type, ifc, out var _); public static bool Implements(this Type type, Type ifc, [NotNullWhen(true)] out Type? concreteInterface) { bool isInterface(Type a, Type b) => a == b || a.IsGenericType && a.GetGenericTypeDefinition() == b; if (isInterface(type, ifc)) { concreteInterface = type; return true; } return (concreteInterface = type.GetInterfaces().FirstOrDefault(i => isInterface(i, ifc))) != null; } public static bool IsNullable(this Type type) { return Nullable.GetUnderlyingType(type) != null; } public static Type UnwrapNullableType(this Type type) { return Nullable.GetUnderlyingType(type) ?? type; } public static Type MakeNullableType(this Type type) { return type.IsValueType && Nullable.GetUnderlyingType(type) == null && type != typeof(void) ? typeof(Nullable<>).MakeGenericType(type) : type; } public static Type UnwrapTaskType(this Type type) { if (type.IsGenericType && typeof(Task<>).IsAssignableFrom(type.GetGenericTypeDefinition())) return type.GetGenericArguments()[0]; else if (typeof(Task).IsAssignableFrom(type)) return typeof(void); #if DotNetCore else if (type.IsGenericType && typeof(ValueTask<>).IsAssignableFrom(type.GetGenericTypeDefinition())) return type.GetGenericArguments()[0]; #endif else return type; } public static bool IsValueOrBinding(this Type type, [NotNullWhen(true)] out Type? elementType) { type = type.UnwrapNullableType(); if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(ValueOrBinding<>)) { elementType = type.GenericTypeArguments.Single(); return true; } else if (typeof(ValueOrBinding).IsAssignableFrom(type)) { elementType = typeof(object); return true; } else { elementType = null; return false; } } public static Type UnwrapValueOrBinding(this Type type) => type.IsValueOrBinding(out var x) ? x : type; public static T? GetCustomAttribute<T>(this ICustomAttributeProvider attributeProvider, bool inherit = true) => (T?)attributeProvider.GetCustomAttributes(typeof(T), inherit).FirstOrDefault(); public static T[] GetCustomAttributes<T>(this ICustomAttributeProvider attributeProvider, bool inherit = true) { var resultObj = attributeProvider.GetCustomAttributes(typeof(T), inherit); var resultT = new T[resultObj.Length]; for (int i = 0; i < resultObj.Length; i++) { resultT[i] = (T)resultObj[i]; } return resultT; } private static ConcurrentDictionary<Type, string> cache_GetTypeHash = new ConcurrentDictionary<Type, string>(); public static string GetTypeHash(this Type type) { return cache_GetTypeHash.GetOrAdd(type, t => { using (var sha1 = SHA1.Create()) { var typeName = t.FullName + ", " + t.Assembly.GetName().Name; var hashBytes = sha1.ComputeHash(Encoding.UTF8.GetBytes(typeName)); return Convert.ToBase64String(hashBytes, 0, 12); } }); } private static ConcurrentDictionary<Type, Func<Delegate, object?[], object?>> delegateInvokeCache = new ConcurrentDictionary<Type, Func<Delegate, object?[], object?>>(); private static ParameterExpression delegateParameter = Expression.Parameter(typeof(Delegate), "delegate"); private static ParameterExpression argsParameter = Expression.Parameter(typeof(object[]), "args"); public static object? ExceptionSafeDynamicInvoke(this Delegate d, object?[] args) => delegateInvokeCache.GetOrAdd(d.GetType(), type => Expression.Lambda<Func<Delegate, object?[], object?>>( Expression.Invoke(Expression.Convert(delegateParameter, type), d.Method.GetParameters().Select((p, i) => Expression.Convert(Expression.ArrayIndex(argsParameter, Expression.Constant(i)), p.ParameterType))).ConvertToObject(), delegateParameter, argsParameter) .CompileFast(flags: CompilerFlags.ThrowOnNotSupportedExpression)) .Invoke(d, args); public static Type GetResultType(this MemberInfo member) => member is PropertyInfo property ? property.PropertyType : member is FieldInfo field ? field.FieldType : member is MethodInfo method ? method.ReturnType : member is TypeInfo type ? type.AsType() : throw new NotImplementedException($"Could not get return type of member {member.GetType().FullName}"); public static string ToEnumString<T>(this T instance) where T : Enum { return ToEnumString(instance.GetType(), instance.ToString()); } public static string ToEnumString(Type enumType, string name) { var field = enumType.GetField(name); if (field != null) { var attr = (EnumMemberAttribute?)field.GetCustomAttributes(typeof(EnumMemberAttribute), false).SingleOrDefault(); if (attr is { Value: {} }) { return attr.Value; } } return name; } public static Type GetDelegateType(MethodInfo methodInfo) { return Expression.GetDelegateType(methodInfo.GetParameters().Select(a => a.ParameterType).Append(methodInfo.ReturnType).ToArray()); } /// <summary> Clear cache when hot reload happens </summary> internal static void ClearCaches(Type[] types) { foreach (var t in types) { delegateInvokeCache.TryRemove(t, out _); cache_GetTypeHash.TryRemove(t, out _); } } } }
using UnityEngine; using UnityEditor; using System.Collections.Generic; using System.IO; namespace tk2dEditor.SpriteCollectionBuilder { public static class PlatformBuilder { public static void InitializeSpriteCollectionPlatforms(tk2dSpriteCollection gen, string root) { // Create all missing platform directories and sprite collection objects for (int i = 0; i < gen.platforms.Count; ++i) { tk2dSpriteCollectionPlatform plat = gen.platforms[i]; if (plat.name.Length > 0 && !plat.spriteCollection) { plat.spriteCollection = tk2dSpriteCollectionEditor.CreateSpriteCollection(root, gen.name + "@" + plat.name); plat.spriteCollection.managedSpriteCollection = true; EditorUtility.SetDirty(gen.spriteCollection); } } } static string FindFileInPath(string directory, string filename, string preferredExt, string[] otherExts) { string target = directory + "/" + filename + preferredExt; if (System.IO.File.Exists(target)) return target; foreach (string ext in otherExts) { if (ext == preferredExt) continue; target = directory + "/" + filename + ext; if (System.IO.File.Exists(target)) return target; } return ""; // not found } static readonly string[] textureExtensions = { ".psd", ".tiff", ".jpg", ".jpeg", ".tga", ".png", ".gif", ".bmp", ".iff", ".pict" }; static readonly string[] fontExtensions = { ".fnt", ".xml", ".txt" }; // Given a path to a texture, finds a platform specific version of it. Returns "" if not found in search paths static string FindAssetForPlatform(string platformName, string path, string[] extensions) { string directory = System.IO.Path.GetDirectoryName(path); string ext = System.IO.Path.GetExtension(path); string filename = System.IO.Path.GetFileNameWithoutExtension(path); int lastIndexOf = filename.LastIndexOf('@'); if (lastIndexOf != -1) filename = filename.Substring(0, lastIndexOf); // Find texture with same filename @platform // The first preferred path is with the filename@platform.ext string platformTexture = FindFileInPath(directory, filename + "@" + platformName, ext, extensions); // Second path to look for is platform/filename.ext if (platformTexture.Length == 0) { string altDirectory = directory + "/" + platformName; if (System.IO.Directory.Exists(altDirectory)) platformTexture = FindFileInPath(altDirectory, filename, ext, extensions); } // Third path to look for is platform/filename@platform.ext if (platformTexture.Length == 0) { string altDirectory = directory + "/" + platformName; if (System.IO.Directory.Exists(altDirectory)) platformTexture = FindFileInPath(altDirectory, filename + "@" + platformName, ext, extensions); } // Fourth path to look for is ../platform/filename.ext - so you can have all textures in platform folders // Based on a contribution by Marcus Svensson if (platformTexture.Length == 0) { int lastIndex = directory.LastIndexOf("/"); if (lastIndex >= 0) { string parentDirectory = directory.Remove(lastIndex, directory.Length - lastIndex); string altDirectory = parentDirectory + "/" + platformName; if (System.IO.Directory.Exists(altDirectory)) platformTexture = FindFileInPath(altDirectory, filename, ext, extensions); } } return platformTexture; } // Update target platforms public static void UpdatePlatformSpriteCollection(tk2dSpriteCollection source, tk2dSpriteCollection target, string dataPath, bool root, float scale, string platformName) { tk2dEditor.SpriteCollectionEditor.SpriteCollectionProxy proxy = new tk2dEditor.SpriteCollectionEditor.SpriteCollectionProxy(source); // Restore old sprite collection proxy.spriteCollection = target.spriteCollection; proxy.atlasTextures = target.atlasTextures; proxy.atlasMaterials = target.atlasMaterials; proxy.altMaterials = target.altMaterials; // This must always be zero, as children cannot have nested platforms. // That would open the door to a lot of unnecessary insanity proxy.platforms = new List<tk2dSpriteCollectionPlatform>(); // Update atlas sizes proxy.atlasWidth = (int)(proxy.atlasWidth * scale); proxy.atlasHeight = (int)(proxy.atlasHeight * scale); proxy.maxTextureSize = (int)(proxy.maxTextureSize * scale); proxy.forcedTextureWidth = (int)(proxy.forcedTextureWidth * scale); proxy.forcedTextureHeight = (int)(proxy.forcedTextureHeight * scale); proxy.globalScale = 1.0f / scale; // Don't bother changing stuff on the root object // The root object is the one that the sprite collection is defined on initially if (!root) { // Update textures foreach (tk2dSpriteCollectionDefinition param in proxy.textureParams) { if (param.texture == null) continue; string path = AssetDatabase.GetAssetPath(param.texture); string platformTexture = FindAssetForPlatform(platformName, path, textureExtensions); if (platformTexture.Length == 0) { LogNotFoundError(platformName, param.texture.name, "texture"); } else { Texture2D tex = AssetDatabase.LoadAssetAtPath(platformTexture, typeof(Texture2D)) as Texture2D; if (tex == null) { Debug.LogError("Unable to load platform specific texture '" + platformTexture + "'"); } else { param.texture = tex; } } // Handle spritesheets. Odd coordinates could cause issues if (param.extractRegion) { param.regionX = (int)(param.regionX * scale); param.regionY = (int)(param.regionY * scale); param.regionW = (int)(param.regionW * scale); param.regionH = (int)(param.regionH * scale); } if (param.anchor == tk2dSpriteCollectionDefinition.Anchor.Custom) { param.anchorX = (int)(param.anchorX * scale); param.anchorY = (int)(param.anchorY * scale); } if (param.customSpriteGeometry) { foreach (tk2dSpriteColliderIsland geom in param.geometryIslands) { for (int p = 0; p < geom.points.Length; ++p) geom.points[p] *= scale; } } else if (param.dice) { param.diceUnitX = (int)(param.diceUnitX * scale); param.diceUnitY = (int)(param.diceUnitY * scale); } if (param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.Polygon) { foreach (tk2dSpriteColliderIsland geom in param.polyColliderIslands) { for (int p = 0; p < geom.points.Length; ++p) geom.points[p] *= scale; } } else if (param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.BoxCustom) { param.boxColliderMax *= scale; param.boxColliderMin *= scale; } for (int i = 0; i < param.attachPoints.Count; ++i) { param.attachPoints[i].position = param.attachPoints[i].position * scale; } } } // We ALWAYS duplicate fonts if (target.fonts == null) target.fonts = new tk2dSpriteCollectionFont[0]; for (int i = 0; i < proxy.fonts.Count; ++i) { tk2dSpriteCollectionFont font = proxy.fonts[i]; if (!font.InUse || font.texture == null || font.data == null || font.editorData == null || font.bmFont == null) continue; // not valid for some reason or other bool needFontData = true; bool needFontEditorData = true; bool hasCorrespondingData = i < target.fonts.Length && target.fonts[i] != null; if (hasCorrespondingData) { tk2dSpriteCollectionFont targetFont = target.fonts[i]; if (targetFont.data != null) { font.data = targetFont.data; needFontData = false; } if (targetFont.editorData != null) { font.editorData = targetFont.editorData; needFontEditorData = false; } } string bmFontPath = AssetDatabase.GetAssetPath(font.bmFont); string texturePath = AssetDatabase.GetAssetPath(font.texture); if (!root) { // find platform specific versions bmFontPath = FindAssetForPlatform(platformName, bmFontPath, fontExtensions); texturePath = FindAssetForPlatform(platformName, texturePath, textureExtensions); if (bmFontPath.Length != 0 && texturePath.Length == 0) { // try to find a texture tk2dEditor.Font.Info fontInfo = tk2dEditor.Font.Builder.ParseBMFont(bmFontPath); if (fontInfo != null) texturePath = System.IO.Path.GetDirectoryName(bmFontPath).Replace('\\', '/') + "/" + System.IO.Path.GetFileName(fontInfo.texturePaths[0]); } if (bmFontPath.Length == 0) LogNotFoundError(platformName, font.bmFont.name, "font"); if (texturePath.Length == 0) LogNotFoundError(platformName, font.texture.name, "texture"); if (bmFontPath.Length == 0 || texturePath.Length == 0) continue; // not found // load the assets font.bmFont = AssetDatabase.LoadAssetAtPath(bmFontPath, typeof(UnityEngine.Object)); font.texture = AssetDatabase.LoadAssetAtPath(texturePath, typeof(Texture2D)) as Texture2D; } string targetDir = System.IO.Path.GetDirectoryName(AssetDatabase.GetAssetPath(target)); // create necessary assets if (needFontData) { string srcPath = AssetDatabase.GetAssetPath(font.data); string destPath = AssetDatabase.GenerateUniqueAssetPath(GetCopyAtTargetPath(platformName, targetDir, srcPath)); AssetDatabase.CopyAsset(srcPath, destPath); AssetDatabase.Refresh(); font.data = AssetDatabase.LoadAssetAtPath(destPath, typeof(tk2dFontData)) as tk2dFontData; } if (needFontEditorData) { string srcPath = AssetDatabase.GetAssetPath(font.editorData); string destPath = AssetDatabase.GenerateUniqueAssetPath(GetCopyAtTargetPath(platformName, targetDir, srcPath)); AssetDatabase.CopyAsset(srcPath, destPath); AssetDatabase.Refresh(); font.editorData = AssetDatabase.LoadAssetAtPath(destPath, typeof(tk2dFont)) as tk2dFont; } if (font.editorData.bmFont != font.bmFont || font.editorData.texture != font.texture || font.editorData.data != font.data) { font.editorData.bmFont = font.bmFont; font.editorData.texture = font.texture; font.editorData.data = font.data; EditorUtility.SetDirty(font.editorData); } } proxy.CopyToTarget(target); } static string GetCopyAtTargetPath(string platformName, string targetDir, string srcPath) { string filename = System.IO.Path.GetFileNameWithoutExtension(srcPath); string ext = System.IO.Path.GetExtension(srcPath); string targetPath = targetDir + "/" + filename + "@" + platformName + ext; string destPath = AssetDatabase.GenerateUniqueAssetPath(targetPath); return destPath; } static void LogNotFoundError(string platformName, string assetName, string assetType) { Debug.LogError(string.Format("Unable to find platform specific {0} '{1}' for platform '{2}'", assetType, assetName, platformName)); } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; using System.Threading; using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation.Remoting { /// <summary> /// This class implements a Finite State Machine (FSM) to control the remote connection on the client side. /// There is a similar but not identical FSM on the server side for this connection. /// /// The FSM's states and events are defined to be the same for both the client FSM and the server FSM. /// This design allows the client and server FSM's to /// be as similar as possible, so that the complexity of maintaining them is minimized. /// /// This FSM only controls the remote connection state. States related to runspace and pipeline are managed by runspace /// pipeline themselves. /// /// This FSM defines an event handling matrix, which is filled by the event handlers. /// The state transitions can only be performed by these event handlers, which are private /// to this class. The event handling is done by a single thread, which makes this /// implementation solid and thread safe. /// /// This implementation of the FSM does not allow the remote session to be reused for a connection /// after it is been closed. This design decision is made to simplify the implementation. /// However, the design can be easily modified to allow the reuse of the remote session /// to reconnect after the connection is closed. /// </summary> internal class ClientRemoteSessionDSHandlerStateMachine { [TraceSourceAttribute("CRSessionFSM", "CRSessionFSM")] private static readonly PSTraceSource s_trace = PSTraceSource.GetTracer("CRSessionFSM", "CRSessionFSM"); /// <summary> /// Event handling matrix. It defines what action to take when an event occur. /// [State,Event]=>Action. /// </summary> private readonly EventHandler<RemoteSessionStateMachineEventArgs>[,] _stateMachineHandle; private readonly Queue<RemoteSessionStateEventArgs> _clientRemoteSessionStateChangeQueue; /// <summary> /// Current state of session. /// </summary> private RemoteSessionState _state; private readonly Queue<RemoteSessionStateMachineEventArgs> _processPendingEventsQueue = new Queue<RemoteSessionStateMachineEventArgs>(); // all events raised through the state machine // will be queued in this private readonly object _syncObject = new object(); // object for synchronizing access to the above // queue private bool _eventsInProcess = false; // whether some thread is actively processing events // in a loop. If this is set then other threads // should simply add to the queue and not attempt // at processing the events in the queue. This will // guarantee that events will always be serialized // and processed /// <summary> /// Timer to be used for key exchange. /// </summary> private Timer _keyExchangeTimer; /// <summary> /// Indicates that the client has previously completed the session key exchange. /// </summary> private bool _keyExchanged = false; /// <summary> /// This is to queue up a disconnect request when a key exchange is in process /// the session will be disconnect once the exchange is complete /// intermediate disconnect requests are tracked by this flag. /// </summary> private bool _pendingDisconnect = false; /// <summary> /// Processes events in the queue. If there are no /// more events to process, then sets eventsInProcess /// variable to false. This will ensure that another /// thread which raises an event can then take control /// of processing the events. /// </summary> private void ProcessEvents() { RemoteSessionStateMachineEventArgs eventArgs = null; do { lock (_syncObject) { if (_processPendingEventsQueue.Count == 0) { _eventsInProcess = false; break; } eventArgs = _processPendingEventsQueue.Dequeue(); } try { RaiseEventPrivate(eventArgs); } catch (Exception ex) { HandleFatalError(ex); } try { RaiseStateMachineEvents(); } catch (Exception ex) { HandleFatalError(ex); } } while (_eventsInProcess); } private void HandleFatalError(Exception ex) { // Event handlers should not throw exceptions. But if they do we need to // handle them here to prevent the state machine from not responding when there are pending // events to process. // Enqueue a fatal error event if such an exception occurs; clear all existing events.. we are going to terminate the session PSRemotingDataStructureException fatalError = new PSRemotingDataStructureException(ex, RemotingErrorIdStrings.FatalErrorCausingClose); RemoteSessionStateMachineEventArgs closeEvent = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close, fatalError); RaiseEvent(closeEvent, true); } /// <summary> /// Raises the StateChanged events which are queued /// All StateChanged events will be raised once the /// processing of the State Machine events are /// complete. /// </summary> private void RaiseStateMachineEvents() { RemoteSessionStateEventArgs queuedEventArg = null; while (_clientRemoteSessionStateChangeQueue.Count > 0) { queuedEventArg = _clientRemoteSessionStateChangeQueue.Dequeue(); StateChanged.SafeInvoke(this, queuedEventArg); } } /// <summary> /// Unique identifier for this state machine. Used /// in tracing. /// </summary> private readonly Guid _id; /// <summary> /// Handler to be used in cases, where setting the state is the /// only task being performed. This method also asserts /// if the specified event is valid for the current state of /// the state machine. /// </summary> /// <param name="sender">Sender of this event.</param> /// <param name="eventArgs">Event args.</param> private void SetStateHandler(object sender, RemoteSessionStateMachineEventArgs eventArgs) { switch (eventArgs.StateEvent) { case RemoteSessionEvent.NegotiationCompleted: { Dbg.Assert(_state == RemoteSessionState.NegotiationReceived, "State can be set to Established only when current state is NegotiationReceived"); SetState(RemoteSessionState.Established, null); } break; case RemoteSessionEvent.NegotiationReceived: { Dbg.Assert(eventArgs.RemoteSessionCapability != null, "State can be set to NegotiationReceived only when RemoteSessionCapability is not null"); if (eventArgs.RemoteSessionCapability == null) { throw PSTraceSource.NewArgumentException(nameof(eventArgs)); } SetState(RemoteSessionState.NegotiationReceived, null); } break; case RemoteSessionEvent.NegotiationSendCompleted: { Dbg.Assert((_state == RemoteSessionState.NegotiationSending) || (_state == RemoteSessionState.NegotiationSendingOnConnect), "Negotiating send can be completed only when current state is NegotiationSending"); SetState(RemoteSessionState.NegotiationSent, null); } break; case RemoteSessionEvent.ConnectFailed: { Dbg.Assert(_state == RemoteSessionState.Connecting, "A ConnectFailed event can be raised only when the current state is Connecting"); SetState(RemoteSessionState.ClosingConnection, eventArgs.Reason); } break; case RemoteSessionEvent.CloseFailed: { SetState(RemoteSessionState.Closed, eventArgs.Reason); } break; case RemoteSessionEvent.CloseCompleted: { SetState(RemoteSessionState.Closed, eventArgs.Reason); } break; case RemoteSessionEvent.KeyRequested: { Dbg.Assert(_state == RemoteSessionState.Established, "Server can request a key only after the client reaches the Established state"); if (_state == RemoteSessionState.Established) { SetState(RemoteSessionState.EstablishedAndKeyRequested, eventArgs.Reason); } } break; case RemoteSessionEvent.KeyReceived: { Dbg.Assert(_state == RemoteSessionState.EstablishedAndKeySent, "Key Receiving can only be raised after reaching the Established state"); if (_state == RemoteSessionState.EstablishedAndKeySent) { Timer tmp = Interlocked.Exchange(ref _keyExchangeTimer, null); if (tmp != null) { tmp.Dispose(); } _keyExchanged = true; SetState(RemoteSessionState.Established, eventArgs.Reason); if (_pendingDisconnect) { // session key exchange is complete, if there is a disconnect pending, process it now _pendingDisconnect = false; DoDisconnect(sender, eventArgs); } } } break; case RemoteSessionEvent.KeySent: { Dbg.Assert(_state >= RemoteSessionState.Established, "Client can send a public key only after reaching the Established state"); Dbg.Assert(!_keyExchanged, "Client should do key exchange only once"); if (_state == RemoteSessionState.Established || _state == RemoteSessionState.EstablishedAndKeyRequested) { SetState(RemoteSessionState.EstablishedAndKeySent, eventArgs.Reason); // start the timer and wait _keyExchangeTimer = new Timer(HandleKeyExchangeTimeout, null, BaseTransportManager.ClientDefaultOperationTimeoutMs, Timeout.Infinite); } } break; case RemoteSessionEvent.DisconnectCompleted: { Dbg.Assert(_state == RemoteSessionState.Disconnecting || _state == RemoteSessionState.RCDisconnecting, "DisconnectCompleted event received while state machine is in wrong state"); if (_state == RemoteSessionState.Disconnecting || _state == RemoteSessionState.RCDisconnecting) { SetState(RemoteSessionState.Disconnected, eventArgs.Reason); } } break; case RemoteSessionEvent.DisconnectFailed: { Dbg.Assert(_state == RemoteSessionState.Disconnecting, "DisconnectCompleted event received while state machine is in wrong state"); if (_state == RemoteSessionState.Disconnecting) { SetState(RemoteSessionState.Disconnected, eventArgs.Reason); // set state to disconnected even TODO. Put some ETW event describing the disconnect process failure } } break; case RemoteSessionEvent.ReconnectCompleted: { Dbg.Assert(_state == RemoteSessionState.Reconnecting, "ReconnectCompleted event received while state machine is in wrong state"); if (_state == RemoteSessionState.Reconnecting) { SetState(RemoteSessionState.Established, eventArgs.Reason); } } break; } } /// <summary> /// Handles the timeout for key exchange. /// </summary> /// <param name="sender">Sender of this event.</param> private void HandleKeyExchangeTimeout(object sender) { Dbg.Assert(_state == RemoteSessionState.EstablishedAndKeySent, "timeout should only happen when waiting for a key"); Timer tmp = Interlocked.Exchange(ref _keyExchangeTimer, null); if (tmp != null) { tmp.Dispose(); } PSRemotingDataStructureException exception = new PSRemotingDataStructureException(RemotingErrorIdStrings.ClientKeyExchangeFailed); RaiseEvent(new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.KeyReceiveFailed, exception)); } /// <summary> /// Handler to be used in cases, where raising an event to /// the state needs to be performed. This method also /// asserts if the specified event is valid for /// the current state of the state machine. /// </summary> /// <param name="sender">Sender of this event.</param> /// <param name="eventArgs">Event args.</param> private void SetStateToClosedHandler(object sender, RemoteSessionStateMachineEventArgs eventArgs) { Dbg.Assert(_state == RemoteSessionState.NegotiationReceived && eventArgs.StateEvent == RemoteSessionEvent.NegotiationFailed || eventArgs.StateEvent == RemoteSessionEvent.SendFailed || eventArgs.StateEvent == RemoteSessionEvent.ReceiveFailed || eventArgs.StateEvent == RemoteSessionEvent.NegotiationTimeout || eventArgs.StateEvent == RemoteSessionEvent.KeySendFailed || eventArgs.StateEvent == RemoteSessionEvent.KeyReceiveFailed || eventArgs.StateEvent == RemoteSessionEvent.KeyRequestFailed || eventArgs.StateEvent == RemoteSessionEvent.ReconnectFailed, "An event to close the state machine can be raised only on the following conditions: " + "1. Negotiation failed 2. Send failed 3. Receive failed 4. Negotiation timedout 5. Key send failed 6. key receive failed 7. key exchange failed 8. Reconnection failed"); // if there is a NegotiationTimeout event raised, it // shouldn't matter if we are currently in the // Established state if (eventArgs.StateEvent == RemoteSessionEvent.NegotiationTimeout && State == RemoteSessionState.Established) { return; } // raise an event to close the state machine RaiseEvent(new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close, eventArgs.Reason)); } #region constructor /// <summary> /// Creates an instance of ClientRemoteSessionDSHandlerStateMachine. /// </summary> internal ClientRemoteSessionDSHandlerStateMachine() { _clientRemoteSessionStateChangeQueue = new Queue<RemoteSessionStateEventArgs>(); // Initialize the state machine event handling matrix _stateMachineHandle = new EventHandler<RemoteSessionStateMachineEventArgs>[(int)RemoteSessionState.MaxState, (int)RemoteSessionEvent.MaxEvent]; for (int i = 0; i < _stateMachineHandle.GetLength(0); i++) { _stateMachineHandle[i, (int)RemoteSessionEvent.FatalError] += DoFatal; _stateMachineHandle[i, (int)RemoteSessionEvent.Close] += DoClose; _stateMachineHandle[i, (int)RemoteSessionEvent.CloseFailed] += SetStateHandler; _stateMachineHandle[i, (int)RemoteSessionEvent.CloseCompleted] += SetStateHandler; _stateMachineHandle[i, (int)RemoteSessionEvent.NegotiationTimeout] += SetStateToClosedHandler; _stateMachineHandle[i, (int)RemoteSessionEvent.SendFailed] += SetStateToClosedHandler; _stateMachineHandle[i, (int)RemoteSessionEvent.ReceiveFailed] += SetStateToClosedHandler; _stateMachineHandle[i, (int)RemoteSessionEvent.CreateSession] += DoCreateSession; _stateMachineHandle[i, (int)RemoteSessionEvent.ConnectSession] += DoConnectSession; } _stateMachineHandle[(int)RemoteSessionState.Idle, (int)RemoteSessionEvent.NegotiationSending] += DoNegotiationSending; _stateMachineHandle[(int)RemoteSessionState.Idle, (int)RemoteSessionEvent.NegotiationSendingOnConnect] += DoNegotiationSending; _stateMachineHandle[(int)RemoteSessionState.NegotiationSending, (int)RemoteSessionEvent.NegotiationSendCompleted] += SetStateHandler; _stateMachineHandle[(int)RemoteSessionState.NegotiationSendingOnConnect, (int)RemoteSessionEvent.NegotiationSendCompleted] += SetStateHandler; _stateMachineHandle[(int)RemoteSessionState.NegotiationSent, (int)RemoteSessionEvent.NegotiationReceived] += SetStateHandler; _stateMachineHandle[(int)RemoteSessionState.NegotiationReceived, (int)RemoteSessionEvent.NegotiationCompleted] += SetStateHandler; _stateMachineHandle[(int)RemoteSessionState.NegotiationReceived, (int)RemoteSessionEvent.NegotiationFailed] += SetStateToClosedHandler; _stateMachineHandle[(int)RemoteSessionState.Connecting, (int)RemoteSessionEvent.ConnectFailed] += SetStateHandler; _stateMachineHandle[(int)RemoteSessionState.ClosingConnection, (int)RemoteSessionEvent.CloseCompleted] += SetStateHandler; _stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.DisconnectStart] += DoDisconnect; _stateMachineHandle[(int)RemoteSessionState.Disconnecting, (int)RemoteSessionEvent.DisconnectCompleted] += SetStateHandler; _stateMachineHandle[(int)RemoteSessionState.Disconnecting, (int)RemoteSessionEvent.DisconnectFailed] += SetStateHandler; // dont close _stateMachineHandle[(int)RemoteSessionState.Disconnected, (int)RemoteSessionEvent.ReconnectStart] += DoReconnect; _stateMachineHandle[(int)RemoteSessionState.Reconnecting, (int)RemoteSessionEvent.ReconnectCompleted] += SetStateHandler; _stateMachineHandle[(int)RemoteSessionState.Reconnecting, (int)RemoteSessionEvent.ReconnectFailed] += SetStateToClosedHandler; _stateMachineHandle[(int)RemoteSessionState.Disconnecting, (int)RemoteSessionEvent.RCDisconnectStarted] += DoRCDisconnectStarted; _stateMachineHandle[(int)RemoteSessionState.Disconnected, (int)RemoteSessionEvent.RCDisconnectStarted] += DoRCDisconnectStarted; _stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.RCDisconnectStarted] += DoRCDisconnectStarted; _stateMachineHandle[(int)RemoteSessionState.RCDisconnecting, (int)RemoteSessionEvent.DisconnectCompleted] += SetStateHandler; // Disconnect during key exchange process _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeySent, (int)RemoteSessionEvent.DisconnectStart] += DoDisconnectDuringKeyExchange; _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyRequested, (int)RemoteSessionEvent.DisconnectStart] += DoDisconnectDuringKeyExchange; _stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.KeyRequested] += SetStateHandler; // _stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.KeySent] += SetStateHandler; // _stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.KeySendFailed] += SetStateToClosedHandler; // _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeySent, (int)RemoteSessionEvent.KeyReceived] += SetStateHandler; // _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyRequested, (int)RemoteSessionEvent.KeySent] += SetStateHandler; // _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeySent, (int)RemoteSessionEvent.KeyReceiveFailed] += SetStateToClosedHandler; // _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyRequested, (int)RemoteSessionEvent.KeySendFailed] += SetStateToClosedHandler; // TODO: All these are potential unexpected state transitions.. should have a way to track these calls.. // should atleast put a dbg assert in this handler for (int i = 0; i < _stateMachineHandle.GetLength(0); i++) { for (int j = 0; j < _stateMachineHandle.GetLength(1); j++) { if (_stateMachineHandle[i, j] == null) { _stateMachineHandle[i, j] += DoClose; } } } _id = Guid.NewGuid(); // initialize the state to be Idle: this means it is ready to start connecting. SetState(RemoteSessionState.Idle, null); } #endregion constructor /// <summary> /// Helper method used by dependents to figure out if the RaiseEvent /// method can be short-circuited. This will be useful in cases where /// the dependent code wants to take action immediately instead of /// going through state machine. /// </summary> /// <param name="arg"></param> internal bool CanByPassRaiseEvent(RemoteSessionStateMachineEventArgs arg) { if (arg.StateEvent == RemoteSessionEvent.MessageReceived) { if (_state == RemoteSessionState.Established || _state == RemoteSessionState.EstablishedAndKeyReceived || // TODO - Client session would never get into this state... to be removed _state == RemoteSessionState.EstablishedAndKeySent || _state == RemoteSessionState.Disconnecting || // There can be input data until disconnect has been completed _state == RemoteSessionState.Disconnected) // Data can arrive while state machine is transitioning to disconnected { return true; } } return false; } /// <summary> /// This method is used by all classes to raise a FSM event. /// The method will queue the event. The event queue will be handled in /// a thread safe manner by a single dedicated thread. /// </summary> /// <param name="arg"> /// This parameter contains the event to be raised. /// </param> /// <param name="clearQueuedEvents"> /// optional bool indicating whether to clear currently queued events /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter is null. /// </exception> internal void RaiseEvent(RemoteSessionStateMachineEventArgs arg, bool clearQueuedEvents = false) { lock (_syncObject) { s_trace.WriteLine("Event received : {0} for {1}", arg.StateEvent, _id); if (clearQueuedEvents) { _processPendingEventsQueue.Clear(); } _processPendingEventsQueue.Enqueue(arg); if (!_eventsInProcess) { _eventsInProcess = true; } else { return; } } ProcessEvents(); } /// <summary> /// This is the private version of raising a FSM event. /// It can only be called by the dedicated thread that processes the event queue. /// It calls the event handler /// in the right position of the event handling matrix. /// </summary> /// <param name="arg"> /// The parameter contains the actual FSM event. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter is null. /// </exception> private void RaiseEventPrivate(RemoteSessionStateMachineEventArgs arg) { if (arg == null) { throw PSTraceSource.NewArgumentNullException(nameof(arg)); } EventHandler<RemoteSessionStateMachineEventArgs> handler = _stateMachineHandle[(int)State, (int)arg.StateEvent]; if (handler != null) { s_trace.WriteLine("Before calling state machine event handler: state = {0}, event = {1}, id = {2}", State, arg.StateEvent, _id); handler(this, arg); s_trace.WriteLine("After calling state machine event handler: state = {0}, event = {1}, id = {2}", State, arg.StateEvent, _id); } } /// <summary> /// This is a readonly property available to all other classes. It gives the FSM state. /// Other classes can query for this state. Only the FSM itself can change the state. /// </summary> internal RemoteSessionState State { get { return _state; } } /// <summary> /// This event indicates that the FSM state changed. /// </summary> internal event EventHandler<RemoteSessionStateEventArgs> StateChanged; #region Event Handlers /// <summary> /// This is the handler for CreateSession event of the FSM. This is the beginning of everything /// else. From this moment on, the FSM will proceeds step by step to eventually reach /// Established state or Closed state. /// </summary> /// <param name="sender"></param> /// <param name="arg"> /// This parameter contains the FSM event. /// </param> /// <exception cref="PSArgumentNullException"> /// If the parameter <paramref name="arg"/> is null. /// </exception> private void DoCreateSession(object sender, RemoteSessionStateMachineEventArgs arg) { using (s_trace.TraceEventHandlers()) { Dbg.Assert(_state == RemoteSessionState.Idle, "State needs to be idle to start connection"); Dbg.Assert(_state != RemoteSessionState.ClosingConnection || _state != RemoteSessionState.Closed, "Reconnect after connection is closing or closed is not allowed"); if (State == RemoteSessionState.Idle) { // we are short-circuiting the state by going directly to NegotiationSending.. // This will save 1 network trip just to establish a connection. // Raise the event for sending the negotiation RemoteSessionStateMachineEventArgs sendingArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.NegotiationSending); RaiseEvent(sendingArg); } } } /// <summary> /// This is the handler for ConnectSession event of the FSM. This is the beginning of everything /// else. From this moment on, the FSM will proceeds step by step to eventually reach /// Established state or Closed state. /// </summary> /// <param name="sender"></param> /// <param name="arg"> /// This parameter contains the FSM event. /// </param> /// <exception cref="PSArgumentNullException"> /// If the parameter <paramref name="arg"/> is null. /// </exception> private void DoConnectSession(object sender, RemoteSessionStateMachineEventArgs arg) { using (s_trace.TraceEventHandlers()) { Dbg.Assert(_state == RemoteSessionState.Idle, "State needs to be idle to start connection"); if (State == RemoteSessionState.Idle) { // We need to send negotiation and connect algorithm related info // Change state to let other DSHandlers add appropriate messages to be piggybacked on transport's Create payload RemoteSessionStateMachineEventArgs sendingArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.NegotiationSendingOnConnect); RaiseEvent(sendingArg); } } } /// <summary> /// This is the handler for NegotiationSending event. /// It sets the new state to be NegotiationSending and /// calls data structure handler to send the negotiation packet. /// </summary> /// <param name="sender"></param> /// <param name="arg"> /// This parameter contains the FSM event. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter <paramref name="arg"/> is null. /// </exception> private void DoNegotiationSending(object sender, RemoteSessionStateMachineEventArgs arg) { if (arg.StateEvent == RemoteSessionEvent.NegotiationSending) { SetState(RemoteSessionState.NegotiationSending, null); } else if (arg.StateEvent == RemoteSessionEvent.NegotiationSendingOnConnect) { SetState(RemoteSessionState.NegotiationSendingOnConnect, null); } else { Dbg.Assert(false, "NegotiationSending called on wrong event"); } } private void DoDisconnectDuringKeyExchange(object sender, RemoteSessionStateMachineEventArgs arg) { // set flag to indicate Disconnect request queue up _pendingDisconnect = true; } private void DoDisconnect(object sender, RemoteSessionStateMachineEventArgs arg) { SetState(RemoteSessionState.Disconnecting, null); } private void DoReconnect(object sender, RemoteSessionStateMachineEventArgs arg) { SetState(RemoteSessionState.Reconnecting, null); } private void DoRCDisconnectStarted(object sender, RemoteSessionStateMachineEventArgs arg) { if (State != RemoteSessionState.Disconnecting && State != RemoteSessionState.Disconnected) { SetState(RemoteSessionState.RCDisconnecting, null); } } /// <summary> /// This is the handler for Close event. /// </summary> /// <param name="sender"></param> /// <param name="arg"> /// This parameter contains the FSM event. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter <paramref name="arg"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// If the parameter <paramref name="arg"/> does not contain remote data. /// </exception> private void DoClose(object sender, RemoteSessionStateMachineEventArgs arg) { using (s_trace.TraceEventHandlers()) { RemoteSessionState oldState = _state; switch (oldState) { case RemoteSessionState.ClosingConnection: case RemoteSessionState.Closed: // do nothing break; case RemoteSessionState.Connecting: case RemoteSessionState.Connected: case RemoteSessionState.Established: case RemoteSessionState.EstablishedAndKeyReceived: // TODO - Client session would never get into this state... to be removed case RemoteSessionState.EstablishedAndKeySent: case RemoteSessionState.NegotiationReceived: case RemoteSessionState.NegotiationSent: case RemoteSessionState.NegotiationSending: case RemoteSessionState.Disconnected: case RemoteSessionState.Disconnecting: case RemoteSessionState.Reconnecting: case RemoteSessionState.RCDisconnecting: SetState(RemoteSessionState.ClosingConnection, arg.Reason); break; case RemoteSessionState.Idle: case RemoteSessionState.UndefinedState: default: PSRemotingTransportException forceClosedException = new PSRemotingTransportException(arg.Reason, RemotingErrorIdStrings.ForceClosed); SetState(RemoteSessionState.Closed, forceClosedException); break; } CleanAll(); } } /// <summary> /// Handles a fatal error message. Throws a well defined error message, /// which contains the reason for the fatal error as an inner exception. /// This way the internal details are not surfaced to the user. /// </summary> /// <param name="sender">Sender of this event, unused.</param> /// <param name="eventArgs">Arguments describing this event.</param> private void DoFatal(object sender, RemoteSessionStateMachineEventArgs eventArgs) { PSRemotingDataStructureException fatalError = new PSRemotingDataStructureException(eventArgs.Reason, RemotingErrorIdStrings.FatalErrorCausingClose); RemoteSessionStateMachineEventArgs closeEvent = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close, fatalError); RaiseEvent(closeEvent); } #endregion Event Handlers private static void CleanAll() { } /// <summary> /// Sets the state of the state machine. Since only /// one thread can be manipulating the state at a time /// the state is not synchronized. /// </summary> /// <param name="newState">New state of the state machine.</param> /// <param name="reason">reason why the state machine is set /// to the new state</param> private void SetState(RemoteSessionState newState, Exception reason) { RemoteSessionState oldState = _state; if (newState != oldState) { _state = newState; s_trace.WriteLine("state machine state transition: from state {0} to state {1}", oldState, _state); RemoteSessionStateInfo stateInfo = new RemoteSessionStateInfo(_state, reason); RemoteSessionStateEventArgs sessionStateEventArg = new RemoteSessionStateEventArgs(stateInfo); _clientRemoteSessionStateChangeQueue.Enqueue(sessionStateEventArg); } } } }
// *********************************************************************** // Copyright (c) 2010 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Xml; using NUnit.Framework.Api; namespace NUnit.Framework.Internal { /// <summary> /// The TestResult class represents the result of a test. /// </summary> public abstract class TestResult : ITestResult { #region Fields /// <summary> /// Indicates the result of the test /// </summary> // [CLSCompliant(false)] protected ResultState resultState; /// <summary> /// The elapsed time for executing this test /// </summary> private double time = 0.0; /// <summary> /// The test that this result pertains to /// </summary> // [CLSCompliant(false)] protected readonly ITest test; #if !NETCF_1_0 /// <summary> /// The stacktrace at the point of failure /// </summary> private string stackTrace; #endif /// <summary> /// Message giving the reason for failure, error or skipping the test /// </summary> // [CLSCompliant(false)] protected string message; /// <summary> /// Number of asserts executed by this test /// </summary> // [CLSCompliant(false)] protected int assertCount = 0; /// <summary> /// List of child results /// </summary> #if true private System.Collections.Generic.List<ITestResult> children; #else private ArrayList children; #endif #endregion #region Constructor /// <summary> /// Construct a test result given a Test /// </summary> /// <param name="test">The test to be used</param> public TestResult(ITest test) { this.test = test; this.resultState = ResultState.Inconclusive; } #endregion #region ITestResult Members public ITest Test { get { return test; } } /// <summary> /// Gets the ResultState of the test result, which /// indicates the success or failure of the test. /// </summary> public ResultState ResultState { get { return resultState; } } /// <summary> /// Gets the name of the test result /// </summary> public virtual string Name { get { return test.Name; } } /// <summary> /// Gets the full name of the test result /// </summary> public virtual string FullName { get { return test.FullName; } } /// <summary> /// Gets or sets the elapsed time for running the test /// </summary> public double Time { get { return time; } set { time = value; } } /// <summary> /// Gets the message associated with a test /// failure or with not running the test /// </summary> public string Message { get { return message; } } #if !NETCF_1_0 /// <summary> /// Gets any stacktrace associated with an /// error or failure. Not available in /// the Compact Framework 1.0. /// </summary> public virtual string StackTrace { get { return stackTrace; } } #endif /// <summary> /// Gets or sets the count of asserts executed /// when running the test. /// </summary> public int AssertCount { get { return assertCount; } set { assertCount = value; } } /// <summary> /// Gets the number of test cases that failed /// when running the test and all its children. /// </summary> public abstract int FailCount { get; } /// <summary> /// Gets the number of test cases that passed /// when running the test and all its children. /// </summary> public abstract int PassCount { get; } /// <summary> /// Gets the number of test cases that were skipped /// when running the test and all its children. /// </summary> public abstract int SkipCount { get; } /// <summary> /// Gets the number of test cases that were inconclusive /// when running the test and all its children. /// </summary> public abstract int InconclusiveCount { get; } /// <summary> /// Indicates whether this result has any child results. /// Test HasChildren before accessing Children to avoid /// the creation of an empty collection. /// </summary> public bool HasChildren { get { return children != null && children.Count > 0; } } /// <summary> /// Gets the collection of child results. /// </summary> #if true public System.Collections.Generic.IList<ITestResult> Children { get { if (children == null) children = new System.Collections.Generic.List<ITestResult>(); return children; } } #else public IList Children { get { if (children == null) children = new ArrayList(); return children; } } #endif #endregion #region IXmlNodeBuilder Members /// <summary> /// Returns the Xml representation of the result. /// </summary> /// <param name="recursive">If true, descendant results are included</param> /// <returns>An XmlNode representing the result</returns> public XmlNode ToXml(bool recursive) { XmlNode topNode = XmlHelper.CreateTopLevelElement("dummy"); AddToXml(topNode, recursive); return topNode.FirstChild; } /// <summary> /// Adds the XML representation of the result as a child of the /// supplied parent node.. /// </summary> /// <param name="parentNode">The parent node.</param> /// <param name="recursive">If true, descendant results are included</param> /// <returns></returns> public virtual XmlNode AddToXml(XmlNode parentNode, bool recursive) { // A result node looks like a test node with extra info added XmlNode thisNode = this.test.AddToXml(parentNode, false); XmlHelper.AddAttribute(thisNode, "result", ResultState.Status.ToString()); if (ResultState.Label != string.Empty) // && ResultState.Label != ResultState.Status.ToString()) XmlHelper.AddAttribute(thisNode, "label", ResultState.Label); XmlHelper.AddAttribute(thisNode, "time", this.Time.ToString("0.000", System.Globalization.CultureInfo.InvariantCulture)); if (this.test is TestSuite) { XmlHelper.AddAttribute(thisNode, "total", (PassCount + FailCount + SkipCount + InconclusiveCount).ToString()); XmlHelper.AddAttribute(thisNode, "passed", PassCount.ToString()); XmlHelper.AddAttribute(thisNode, "failed", FailCount.ToString()); XmlHelper.AddAttribute(thisNode, "inconclusive", InconclusiveCount.ToString()); XmlHelper.AddAttribute(thisNode, "skipped", SkipCount.ToString()); } XmlHelper.AddAttribute(thisNode, "asserts", this.AssertCount.ToString()); switch (ResultState.Status) { case TestStatus.Failed: AddFailureElement(thisNode); break; case TestStatus.Skipped: AddReasonElement(thisNode); break; case TestStatus.Passed: break; case TestStatus.Inconclusive: break; } if (recursive && HasChildren) foreach (TestResult child in Children) child.AddToXml(thisNode, recursive); return thisNode; } #endregion public void AddResult(ITestResult result) { if (children == null) #if true children = new System.Collections.Generic.List<ITestResult>(); #else children = new ArrayList(); #endif children.Add(result); switch (result.ResultState.Status) { case TestStatus.Failed: this.SetResult(ResultState.Failure, "Component test failure"); break; default: break; } } #region Other Public Methods /// <summary> /// Set the result of the test /// </summary> /// <param name="resultState">The ResultState to use in the result</param> public void SetResult(ResultState resultState) { SetResult(resultState, null, null); } /// <summary> /// Set the result of the test /// </summary> /// <param name="resultState">The ResultState to use in the result</param> /// <param name="message">A message associated with the result state</param> public void SetResult(ResultState resultState, string message) { SetResult(resultState, message, null); } /// <summary> /// Set the result of the test /// </summary> /// <param name="resultState">The ResultState to use in the result</param> /// <param name="message">A message associated with the result state</param> /// <param name="stackTrace">Stack trace giving the location of the command</param> public void SetResult(ResultState resultState, string message, string stackTrace) { this.resultState = resultState; this.message = message; this.stackTrace = stackTrace; } /// <summary> /// Set the test result based on the type of exception thrown /// </summary> /// <param name="ex">The exception that was thrown</param> public void RecordException(Exception ex) { if (ex is NUnitException) ex = ex.InnerException; #if !NETCF_1_0 if (ex is System.Threading.ThreadAbortException) SetResult(ResultState.Cancelled, "Test cancelled by user", ex.StackTrace); else if (ex is AssertionException) SetResult(ResultState.Failure, ex.Message, StackFilter.Filter(ex.StackTrace)); else if (ex is IgnoreException) SetResult(ResultState.Ignored, ex.Message, StackFilter.Filter(ex.StackTrace)); else if (ex is InconclusiveException) SetResult(ResultState.Inconclusive, ex.Message, StackFilter.Filter(ex.StackTrace)); else if (ex is SuccessException) SetResult(ResultState.Success, ex.Message, StackFilter.Filter(ex.StackTrace)); else SetResult(ResultState.Error, ExceptionHelper.BuildMessage(ex), ExceptionHelper.BuildStackTrace(ex)); #else if (ex is AssertionException) SetResult(ResultState.Failure, ex.Message); else if (ex is IgnoreException) SetResult(ResultState.Ignored, ex.Message); else if (ex is InconclusiveException) SetResult(ResultState.Inconclusive, ex.Message); else if (ex is SuccessException) SetResult(ResultState.Success, ex.Message); else SetResult(ResultState.Error, ExceptionHelper.BuildMessage(ex)); #endif } #endregion #region Helper Methods /// <summary> /// Adds a reason element to a node and returns it. /// </summary> /// <param name="targetNode">The target node.</param> /// <returns>The new reason element.</returns> private XmlNode AddReasonElement(XmlNode targetNode) { XmlNode reasonNode = XmlHelper.AddElement(targetNode, "reason"); XmlHelper.AddElementWithCDataSection(reasonNode, "message", this.Message); return reasonNode; } /// <summary> /// Adds a failure element to a node and returns it. /// </summary> /// <param name="targetNode">The target node.</param> /// <returns>The new failure element.</returns> private XmlNode AddFailureElement(XmlNode targetNode) { XmlNode failureNode = XmlHelper.AddElement(targetNode, "failure"); if (this.Message != null) { XmlHelper.AddElementWithCDataSection(failureNode, "message", this.Message); } #if !NETCF_1_0 if (this.StackTrace != null) { XmlHelper.AddElementWithCDataSection(failureNode, "stack-trace", this.StackTrace); } #endif return failureNode; } //private static bool IsTestCase(ITest test) //{ // return !(test is TestSuite); //} #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Net.Http.Headers { public class EntityTagHeaderValue : ICloneable { private static EntityTagHeaderValue s_any; private string _tag; private bool _isWeak; public string Tag { get { return _tag; } } public bool IsWeak { get { return _isWeak; } } public static EntityTagHeaderValue Any { get { if (s_any == null) { s_any = new EntityTagHeaderValue(); s_any._tag = "*"; s_any._isWeak = false; } return s_any; } } public EntityTagHeaderValue(string tag) : this(tag, false) { } public EntityTagHeaderValue(string tag, bool isWeak) { if (string.IsNullOrEmpty(tag)) { throw new ArgumentException(SR.net_http_argument_empty_string, "tag"); } int length = 0; if ((HttpRuleParser.GetQuotedStringLength(tag, 0, out length) != HttpParseResult.Parsed) || (length != tag.Length)) { // Note that we don't allow 'W/' prefixes for weak ETags in the 'tag' parameter. If the user wants to // add a weak ETag, he can set 'isWeak' to true. throw new FormatException(SR.net_http_headers_invalid_etag_name); } _tag = tag; _isWeak = isWeak; } private EntityTagHeaderValue(EntityTagHeaderValue source) { Contract.Requires(source != null); _tag = source._tag; _isWeak = source._isWeak; } private EntityTagHeaderValue() { } public override string ToString() { if (_isWeak) { return "W/" + _tag; } return _tag; } public override bool Equals(object obj) { EntityTagHeaderValue other = obj as EntityTagHeaderValue; if (other == null) { return false; } // Since the tag is a quoted-string we treat it case-sensitive. return ((_isWeak == other._isWeak) && (string.CompareOrdinal(_tag, other._tag) == 0)); } public override int GetHashCode() { // Since the tag is a quoted-string we treat it case-sensitive. return _tag.GetHashCode() ^ _isWeak.GetHashCode(); } public static EntityTagHeaderValue Parse(string input) { int index = 0; return (EntityTagHeaderValue)GenericHeaderParser.SingleValueEntityTagParser.ParseValue( input, null, ref index); } public static bool TryParse(string input, out EntityTagHeaderValue parsedValue) { int index = 0; object output; parsedValue = null; if (GenericHeaderParser.SingleValueEntityTagParser.TryParseValue(input, null, ref index, out output)) { parsedValue = (EntityTagHeaderValue)output; return true; } return false; } internal static int GetEntityTagLength(string input, int startIndex, out EntityTagHeaderValue parsedValue) { Contract.Requires(startIndex >= 0); parsedValue = null; if (string.IsNullOrEmpty(input) || (startIndex >= input.Length)) { return 0; } // Caller must remove leading whitespaces. If not, we'll return 0. bool isWeak = false; int current = startIndex; char firstChar = input[startIndex]; if (firstChar == '*') { // We have '*' value, indicating "any" ETag. parsedValue = Any; current++; } else { // The RFC defines 'W/' as prefix, but we'll be flexible and also accept lower-case 'w'. if ((firstChar == 'W') || (firstChar == 'w')) { current++; // We need at least 3 more chars: the '/' character followed by two quotes. if ((current + 2 >= input.Length) || (input[current] != '/')) { return 0; } isWeak = true; current++; // we have a weak-entity tag. current = current + HttpRuleParser.GetWhitespaceLength(input, current); } int tagStartIndex = current; int tagLength = 0; if (HttpRuleParser.GetQuotedStringLength(input, current, out tagLength) != HttpParseResult.Parsed) { return 0; } parsedValue = new EntityTagHeaderValue(); if (tagLength == input.Length) { // Most of the time we'll have strong ETags without leading/trailing whitespaces. Debug.Assert(startIndex == 0); Debug.Assert(!isWeak); parsedValue._tag = input; parsedValue._isWeak = false; } else { parsedValue._tag = input.Substring(tagStartIndex, tagLength); parsedValue._isWeak = isWeak; } current = current + tagLength; } current = current + HttpRuleParser.GetWhitespaceLength(input, current); return current - startIndex; } object ICloneable.Clone() { if (this == s_any) { return s_any; } else { return new EntityTagHeaderValue(this); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.CSharp.DocumentationComments; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.VisualBasic.DocumentationComments; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.MetadataAsSource { public class DocCommentFormatterTests { private CSharpDocumentationCommentFormattingService _csharpService = new CSharpDocumentationCommentFormattingService(); private VisualBasicDocumentationCommentFormattingService _vbService = new VisualBasicDocumentationCommentFormattingService(); private void TestFormat(string docCommentXmlFragment, string expected) { TestFormat(docCommentXmlFragment, expected, expected); } private void TestFormat(string docCommentXmlFragment, string expectedCSharp, string expectedVB) { var docComment = DocumentationComment.FromXmlFragment(docCommentXmlFragment); var csharpFormattedComment = string.Join("\r\n", AbstractMetadataAsSourceService.DocCommentFormatter.Format(_csharpService, docComment)); var vbFormattedComment = string.Join("\r\n", AbstractMetadataAsSourceService.DocCommentFormatter.Format(_vbService, docComment)); Assert.Equal(expectedCSharp, csharpFormattedComment); Assert.Equal(expectedVB, vbFormattedComment); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Summary() { var comment = "<summary>This is a summary.</summary>"; var expected = $@"{FeaturesResources.Summary} This is a summary."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Wrapping1() { var comment = "<summary>I am the very model of a modern major general. This is a very long comment. And getting longer by the minute.</summary>"; var expected = $@"{FeaturesResources.Summary} I am the very model of a modern major general. This is a very long comment. And getting longer by the minute."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Wrapping2() { var comment = "<summary>I amtheverymodelofamodernmajorgeneral.Thisisaverylongcomment.Andgettinglongerbythe minute.</summary>"; var expected = $@"{FeaturesResources.Summary} I amtheverymodelofamodernmajorgeneral.Thisisaverylongcomment.Andgettinglongerbythe minute."; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Exception() { var comment = @"<exception cref=""T:System.NotImplementedException"">throws NotImplementedException</exception>"; var expected = $@"{FeaturesResources.Exceptions} T:System.NotImplementedException: throws NotImplementedException"; TestFormat(comment, expected); } [Fact] [Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void MultipleExceptionTags() { var comment = @"<exception cref=""T:System.NotImplementedException"">throws NotImplementedException</exception> <exception cref=""T:System.InvalidOperationException"">throws InvalidOperationException</exception>"; var expected = $@"{FeaturesResources.Exceptions} T:System.NotImplementedException: throws NotImplementedException T:System.InvalidOperationException: throws InvalidOperationException"; TestFormat(comment, expected); } [Fact, WorkItem(530760, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530760")] [Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void MultipleExceptionTagsWithSameType() { var comment = @"<exception cref=""T:System.NotImplementedException"">throws NotImplementedException for reason X</exception> <exception cref=""T:System.InvalidOperationException"">throws InvalidOperationException</exception> <exception cref=""T:System.NotImplementedException"">also throws NotImplementedException for reason Y</exception>"; var expected = $@"{FeaturesResources.Exceptions} T:System.NotImplementedException: throws NotImplementedException for reason X T:System.NotImplementedException: also throws NotImplementedException for reason Y T:System.InvalidOperationException: throws InvalidOperationException"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void Returns() { var comment = @"<returns>A string is returned</returns>"; var expected = $@"{FeaturesResources.Returns} A string is returned"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void SummaryAndParams() { var comment = @"<summary>This is the summary.</summary> <param name=""a"">The param named 'a'</param> <param name=""b"">The param named 'b'</param>"; var expected = $@"{FeaturesResources.Summary} This is the summary. {FeaturesResources.Parameters} a: The param named 'a' b: The param named 'b'"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void TypeParameters() { var comment = @"<typeparam name=""T"">The type param named 'T'</typeparam> <typeparam name=""U"">The type param named 'U'</typeparam>"; var expected = $@"{FeaturesResources.TypeParameters} T: The type param named 'T' U: The type param named 'U'"; TestFormat(comment, expected); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public void FormatEverything() { var comment = @"<summary> This is a summary of something. </summary> <param name=""a"">The param named 'a'.</param> <param name=""b""></param> <param name=""c"">The param named 'c'.</param> <typeparam name=""T"">A type parameter.</typeparam> <typeparam name=""U""></typeparam> <typeparam name=""V"">Another type parameter.</typeparam> <returns>This returns nothing.</returns> <exception cref=""System.FooException"">Thrown for an unknown reason</exception> <exception cref=""System.BarException""></exception> <exception cref=""System.BlahException"">Thrown when blah blah blah</exception> <remarks>This doc comment is really not very remarkable.</remarks>"; var expected = $@"{FeaturesResources.Summary} This is a summary of something. {FeaturesResources.Parameters} a: The param named 'a'. b: c: The param named 'c'. {FeaturesResources.TypeParameters} T: A type parameter. U: V: Another type parameter. {FeaturesResources.Returns} This returns nothing. {FeaturesResources.Exceptions} System.FooException: Thrown for an unknown reason System.BarException: System.BlahException: Thrown when blah blah blah {FeaturesResources.Remarks} This doc comment is really not very remarkable."; TestFormat(comment, expected); } } }
/* * Translation into C# and Magnesium interface 2016 * Vulkan Example - Basic indexed triangle rendering by 2016 by Copyright (C) Sascha Willems - www.saschawillems.de * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ using Magnesium; using System.Collections.Generic; using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace TriangleDemo { public class VulkanExample : IDisposable { // Vertex buffer and attributes class VertexBufferInfo { public IMgDeviceMemory memory; // Handle to the device memory for this buffer public IMgBuffer buffer; // Handle to the Vulkan buffer object that the memory is bound to public MgPipelineVertexInputStateCreateInfo inputState; public MgVertexInputBindingDescription inputBinding; public MgVertexInputAttributeDescription[] inputAttributes; } VertexBufferInfo vertices = new VertexBufferInfo(); struct IndicesInfo { public IMgDeviceMemory memory; public IMgBuffer buffer; public UInt32 count; } IndicesInfo indices = new IndicesInfo(); private IMgGraphicsConfiguration mConfiguration; // Uniform block object struct UniformData { public IMgDeviceMemory memory; public IMgBuffer buffer; public MgDescriptorBufferInfo descriptor; } struct UniformBufferObject { public Matrix4 projectionMatrix; public Matrix4 modelMatrix; public Matrix4 viewMatrix; }; UniformBufferObject uboVS; UniformData uniformDataVS = new UniformData(); IMgPipelineLayout mPipelineLayout; IMgPipeline mPipeline; IMgDescriptorSetLayout mDescriptorSetLayout; IMgDescriptorSet mDescriptorSet; IMgSemaphore mPresentCompleteSemaphore; IMgSemaphore mRenderCompleteSemaphore; List<IMgFence> mWaitFences = new List<IMgFence>(); private uint mWidth; private uint mHeight; private IMgGraphicsDevice mGraphicsDevice; private IMgDescriptorPool mDescriptorPool; private IMgCommandBuffer mPrePresentCmdBuffer; private IMgCommandBuffer mPostPresentCmdBuffer; private IMgPresentationLayer mPresentationLayer; public VulkanExample ( IMgGraphicsConfiguration configuration, IMgSwapchainCollection swapchains, IMgGraphicsDevice graphicsDevice, IMgPresentationLayer presentationLayer, ITriangleDemoShaderPath shaderPath ) { mConfiguration = configuration; mSwapchains = swapchains; mGraphicsDevice = graphicsDevice; mPresentationLayer = presentationLayer; mTrianglePath = shaderPath; mWidth = 1280U; mHeight = 720U; try { mConfiguration.Initialize(mWidth, mHeight); InitSwapchain(mWidth, mHeight); Prepare(); } catch(Exception ex) { throw ex; } } private IMgSwapchainCollection mSwapchains; private void InitSwapchain(uint width, uint height) { Debug.Assert(mConfiguration.Partition != null); const int NO_OF_BUFFERS = 1; var buffers = new IMgCommandBuffer[NO_OF_BUFFERS]; var pAllocateInfo = new MgCommandBufferAllocateInfo { CommandBufferCount = NO_OF_BUFFERS, CommandPool = mConfiguration.Partition.CommandPool, Level = MgCommandBufferLevel.PRIMARY, }; mConfiguration.Device.AllocateCommandBuffers(pAllocateInfo, buffers); var createInfo = new MgGraphicsDeviceCreateInfo { Samples = MgSampleCountFlagBits.COUNT_1_BIT, Color = MgFormat.R8G8B8A8_UINT, DepthStencil = MgFormat.D24_UNORM_S8_UINT, Width = mWidth, Height = mHeight, }; var setupCmdBuffer = buffers[0]; var cmdBufInfo = new MgCommandBufferBeginInfo(); var err = setupCmdBuffer.BeginCommandBuffer(cmdBufInfo); Debug.Assert(err == Result.SUCCESS); mGraphicsDevice.Create(setupCmdBuffer, mSwapchains, createInfo); err = setupCmdBuffer.EndCommandBuffer(); Debug.Assert(err == Result.SUCCESS); var submission = new[] { new MgSubmitInfo { CommandBuffers = new IMgCommandBuffer[] { buffers[0], }, } }; err = mConfiguration.Queue.QueueSubmit(submission, null); Debug.Assert(err == Result.SUCCESS); mConfiguration.Queue.QueueWaitIdle(); mConfiguration.Device.FreeCommandBuffers(mConfiguration.Partition.CommandPool, buffers); } #region prepare private bool mPrepared = false; void Prepare() { BeforePrepare(); PrepareSynchronizationPrimitives(); PrepareVertices(); PrepareUniformBuffers(); SetupDescriptorSetLayout(); PreparePipelines(); SetupDescriptorPool(); SetupDescriptorSet(); BuildCommandBuffers(); mPrepared = true; } private void BeforePrepare() { CreateCommandBuffers(); } void PrepareSynchronizationPrimitives() { var semaphoreCreateInfo = new MgSemaphoreCreateInfo { }; Debug.Assert(mConfiguration.Device != null); var err = mConfiguration.Device.CreateSemaphore(semaphoreCreateInfo, null, out mPresentCompleteSemaphore); Debug.Assert(err == Result.SUCCESS); err = mConfiguration.Device.CreateSemaphore(semaphoreCreateInfo, null, out mRenderCompleteSemaphore); Debug.Assert(err == Result.SUCCESS); var fenceCreateInfo = new MgFenceCreateInfo { Flags = MgFenceCreateFlagBits.SIGNALED_BIT, }; var noOfCommandBuffers = drawCmdBuffers.Length; for (var i = 0; i < noOfCommandBuffers; ++i) { IMgFence fence; err = mConfiguration.Device.CreateFence(fenceCreateInfo, null, out fence); Debug.Assert(err == Result.SUCCESS); mWaitFences.Add(fence); } } struct TriangleVertex { public Vector3 position; public Vector3 color; }; class StagingBuffer { public IMgDeviceMemory memory; public IMgBuffer buffer; }; void PrepareVertices() { TriangleVertex[] vertexBuffer = { new TriangleVertex{ position =new Vector3(1.0f, 1.0f, 0.0f), color = new Vector3( 1.0f, 0.0f, 0.0f ) }, new TriangleVertex{ position =new Vector3(-1.0f, 1.0f, 0.0f ), color = new Vector3( 0.0f, 1.0f, 0.0f ) }, new TriangleVertex{ position =new Vector3( 0.0f, -1.0f, 0.0f ), color = new Vector3( 0.0f, 0.0f, 1.0f ) }, }; var structSize = Marshal.SizeOf(typeof(TriangleVertex)); var vertexBufferSize = (ulong)(vertexBuffer.Length * structSize); UInt32[] indexBuffer = { 0, 1, 2 }; indices.count = (uint)indexBuffer.Length; var indexBufferSize = indices.count * sizeof(UInt32); var stagingBuffers = new { vertices = new StagingBuffer(), indices = new StagingBuffer(), }; { var vertexBufferInfo = new MgBufferCreateInfo { Size = vertexBufferSize, Usage = MgBufferUsageFlagBits.TRANSFER_SRC_BIT, }; var err = mConfiguration.Device.CreateBuffer(vertexBufferInfo, null, out stagingBuffers.vertices.buffer); Debug.Assert(err == Result.SUCCESS); mConfiguration.Device.GetBufferMemoryRequirements(stagingBuffers.vertices.buffer, out MgMemoryRequirements memReqs); var isValid = mConfiguration.Partition.GetMemoryType(memReqs.MemoryTypeBits, MgMemoryPropertyFlagBits.HOST_VISIBLE_BIT | MgMemoryPropertyFlagBits.HOST_COHERENT_BIT, out uint typeIndex); Debug.Assert(isValid); MgMemoryAllocateInfo memAlloc = new MgMemoryAllocateInfo { AllocationSize = memReqs.Size, MemoryTypeIndex = typeIndex, }; err = mConfiguration.Device.AllocateMemory(memAlloc, null, out stagingBuffers.vertices.memory); Debug.Assert(err == Result.SUCCESS); // Map and copy err = stagingBuffers.vertices.memory.MapMemory(mConfiguration.Device, 0, memAlloc.AllocationSize, 0, out IntPtr data); Debug.Assert(err == Result.SUCCESS); var offset = 0; foreach (var vertex in vertexBuffer) { IntPtr dest = IntPtr.Add(data, offset); Marshal.StructureToPtr(vertex, dest, false); offset += structSize; } stagingBuffers.vertices.memory.UnmapMemory(mConfiguration.Device); stagingBuffers.vertices.buffer.BindBufferMemory(mConfiguration.Device, stagingBuffers.vertices.memory, 0); Debug.Assert(err == Result.SUCCESS); } { var vertexBufferInfo = new MgBufferCreateInfo { Size = vertexBufferSize, Usage = MgBufferUsageFlagBits.VERTEX_BUFFER_BIT | MgBufferUsageFlagBits.TRANSFER_DST_BIT, }; var err = mConfiguration.Device.CreateBuffer(vertexBufferInfo, null, out vertices.buffer); Debug.Assert(err == Result.SUCCESS); mConfiguration.Device.GetBufferMemoryRequirements(vertices.buffer, out MgMemoryRequirements memReqs); var isValid = mConfiguration.Partition.GetMemoryType(memReqs.MemoryTypeBits, MgMemoryPropertyFlagBits.DEVICE_LOCAL_BIT, out uint typeIndex); Debug.Assert(isValid); var memAlloc = new MgMemoryAllocateInfo { AllocationSize = memReqs.Size, MemoryTypeIndex = typeIndex, }; err = mConfiguration.Device.AllocateMemory(memAlloc, null, out vertices.memory); Debug.Assert(err == Result.SUCCESS); err = vertices.buffer.BindBufferMemory(mConfiguration.Device, vertices.memory, 0); Debug.Assert(err == Result.SUCCESS); } { var indexbufferInfo = new MgBufferCreateInfo { Size = indexBufferSize, Usage = MgBufferUsageFlagBits.TRANSFER_SRC_BIT, }; var err = mConfiguration.Device.CreateBuffer(indexbufferInfo, null, out stagingBuffers.indices.buffer); Debug.Assert(err == Result.SUCCESS); mConfiguration.Device.GetBufferMemoryRequirements(stagingBuffers.indices.buffer, out MgMemoryRequirements memReqs); var isValid = mConfiguration.Partition.GetMemoryType(memReqs.MemoryTypeBits, MgMemoryPropertyFlagBits.HOST_VISIBLE_BIT | MgMemoryPropertyFlagBits.HOST_COHERENT_BIT, out uint typeIndex); Debug.Assert(isValid); var memAlloc = new MgMemoryAllocateInfo { AllocationSize = memReqs.Size, MemoryTypeIndex = typeIndex, }; err = mConfiguration.Device.AllocateMemory(memAlloc, null, out stagingBuffers.indices.memory); Debug.Assert(err == Result.SUCCESS); err = stagingBuffers.indices.memory.MapMemory(mConfiguration.Device, 0, indexBufferSize, 0, out IntPtr data); Debug.Assert(err == Result.SUCCESS); var uintBuffer = new byte[indexBufferSize]; var bufferSize = (int)indexBufferSize; Buffer.BlockCopy(indexBuffer, 0, uintBuffer, 0, bufferSize); Marshal.Copy(uintBuffer, 0, data, bufferSize); stagingBuffers.indices.memory.UnmapMemory(mConfiguration.Device); err = stagingBuffers.indices.buffer.BindBufferMemory(mConfiguration.Device, stagingBuffers.indices.memory, 0); Debug.Assert(err == Result.SUCCESS); } { var indexbufferInfo = new MgBufferCreateInfo { Size = indexBufferSize, Usage = MgBufferUsageFlagBits.INDEX_BUFFER_BIT | MgBufferUsageFlagBits.TRANSFER_DST_BIT, }; var err = mConfiguration.Device.CreateBuffer(indexbufferInfo, null, out indices.buffer); Debug.Assert(err == Result.SUCCESS); mConfiguration.Device.GetBufferMemoryRequirements(indices.buffer, out MgMemoryRequirements memReqs); var isValid = mConfiguration.Partition.GetMemoryType(memReqs.MemoryTypeBits, MgMemoryPropertyFlagBits.DEVICE_LOCAL_BIT, out uint typeIndex); Debug.Assert(isValid); var memAlloc = new MgMemoryAllocateInfo { AllocationSize = memReqs.Size, MemoryTypeIndex = typeIndex, }; err = mConfiguration.Device.AllocateMemory(memAlloc, null, out indices.memory); Debug.Assert(err == Result.SUCCESS); err = indices.buffer.BindBufferMemory(mConfiguration.Device, indices.memory, 0); Debug.Assert(err == Result.SUCCESS); } { var cmdBufferBeginInfo = new MgCommandBufferBeginInfo { }; IMgCommandBuffer copyCmd = getCommandBuffer(true); copyCmd.CmdCopyBuffer( stagingBuffers.vertices.buffer, vertices.buffer, new[] { new MgBufferCopy { Size = vertexBufferSize, } } ); copyCmd.CmdCopyBuffer(stagingBuffers.indices.buffer, indices.buffer, new[] { new MgBufferCopy { Size = indexBufferSize, } }); flushCommandBuffer(copyCmd); stagingBuffers.vertices.buffer.DestroyBuffer(mConfiguration.Device, null); stagingBuffers.vertices.memory.FreeMemory(mConfiguration.Device, null); stagingBuffers.indices.buffer.DestroyBuffer(mConfiguration.Device, null); stagingBuffers.indices.memory.FreeMemory(mConfiguration.Device, null); } const uint VERTEX_BUFFER_BIND_ID = 0; vertices.inputBinding = new MgVertexInputBindingDescription { Binding = VERTEX_BUFFER_BIND_ID, Stride = (uint) structSize, InputRate = MgVertexInputRate.VERTEX, }; var vertexSize = (uint) Marshal.SizeOf(typeof(Vector3)); vertices.inputAttributes = new MgVertexInputAttributeDescription[] { new MgVertexInputAttributeDescription { Binding = VERTEX_BUFFER_BIND_ID, Location = 0, Format = MgFormat.R32G32B32_SFLOAT, Offset = 0, }, new MgVertexInputAttributeDescription { Binding = VERTEX_BUFFER_BIND_ID, Location = 1, Format = MgFormat.R32G32B32_SFLOAT, Offset = vertexSize, } }; vertices.inputState = new MgPipelineVertexInputStateCreateInfo { VertexBindingDescriptions = new MgVertexInputBindingDescription[] { vertices.inputBinding, }, VertexAttributeDescriptions = vertices.inputAttributes, }; } IMgCommandBuffer getCommandBuffer(bool begin) { var buffers = new IMgCommandBuffer[1]; var cmdBufAllocateInfo = new MgCommandBufferAllocateInfo { CommandPool = mConfiguration.Partition.CommandPool, Level = MgCommandBufferLevel.PRIMARY, CommandBufferCount = 1, }; var err = mConfiguration.Device.AllocateCommandBuffers(cmdBufAllocateInfo, buffers); Debug.Assert(err == Result.SUCCESS); var cmdBuf = buffers[0]; if (begin) { var cmdBufInfo = new MgCommandBufferBeginInfo(); err = cmdBuf.BeginCommandBuffer(cmdBufInfo); Debug.Assert(err == Result.SUCCESS); } return cmdBuf; } void flushCommandBuffer(IMgCommandBuffer commandBuffer) { Debug.Assert(commandBuffer != null); var err = commandBuffer.EndCommandBuffer(); Debug.Assert(err == Result.SUCCESS); var submitInfos = new [] { new MgSubmitInfo { CommandBuffers = new [] { commandBuffer } } }; var fenceCreateInfo = new MgFenceCreateInfo(); err = mConfiguration.Device.CreateFence(fenceCreateInfo, null, out IMgFence fence); Debug.Assert(err == Result.SUCCESS); err = mConfiguration.Queue.QueueSubmit(submitInfos, fence); Debug.Assert(err == Result.SUCCESS); err = mConfiguration.Queue.QueueWaitIdle(); Debug.Assert(err == Result.SUCCESS); err = mConfiguration.Device.WaitForFences(new[] { fence }, true, ulong.MaxValue); Debug.Assert(err == Result.SUCCESS); fence.DestroyFence(mConfiguration.Device, null); mConfiguration.Device.FreeCommandBuffers(mConfiguration.Partition.CommandPool, new[] { commandBuffer } ); } void PrepareUniformBuffers() { var structSize = (uint)Marshal.SizeOf(typeof(UniformBufferObject)); MgBufferCreateInfo bufferInfo = new MgBufferCreateInfo { Size = structSize, Usage = MgBufferUsageFlagBits.UNIFORM_BUFFER_BIT, }; var err = mConfiguration.Device.CreateBuffer(bufferInfo, null, out uniformDataVS.buffer); Debug.Assert(err == Result.SUCCESS); mConfiguration.Device.GetBufferMemoryRequirements(uniformDataVS.buffer, out MgMemoryRequirements memReqs); var isValid = mConfiguration.Partition.GetMemoryType(memReqs.MemoryTypeBits, MgMemoryPropertyFlagBits.HOST_VISIBLE_BIT | MgMemoryPropertyFlagBits.HOST_COHERENT_BIT, out uint typeIndex); Debug.Assert(isValid); MgMemoryAllocateInfo allocInfo = new MgMemoryAllocateInfo { AllocationSize = memReqs.Size, MemoryTypeIndex = typeIndex, }; err = mConfiguration.Device.AllocateMemory(allocInfo, null, out uniformDataVS.memory); Debug.Assert(err == Result.SUCCESS); err = uniformDataVS.buffer.BindBufferMemory(mConfiguration.Device, uniformDataVS.memory, 0); Debug.Assert(err == Result.SUCCESS); uniformDataVS.descriptor = new MgDescriptorBufferInfo { Buffer = uniformDataVS.buffer, Offset = 0, Range = structSize, }; UpdateUniformBuffers(); } void SetupDescriptorSetLayout() { var descriptorLayout = new MgDescriptorSetLayoutCreateInfo { Bindings = new[] { new MgDescriptorSetLayoutBinding { DescriptorCount = 1, StageFlags = MgShaderStageFlagBits.VERTEX_BIT, ImmutableSamplers = null, DescriptorType = MgDescriptorType.UNIFORM_BUFFER, Binding = 0, } }, }; var err = mConfiguration.Device.CreateDescriptorSetLayout(descriptorLayout, null, out mDescriptorSetLayout); Debug.Assert(err == Result.SUCCESS); var pPipelineLayoutCreateInfo = new MgPipelineLayoutCreateInfo { SetLayouts = new IMgDescriptorSetLayout[] { mDescriptorSetLayout, } }; err = mConfiguration.Device.CreatePipelineLayout(pPipelineLayoutCreateInfo, null, out mPipelineLayout); Debug.Assert(err == Result.SUCCESS); } void PreparePipelines() { using (var vertFs = mTrianglePath.OpenVertexShader()) using (var fragFs = mTrianglePath.OpenFragmentShader()) { IMgShaderModule vsModule; { var vsCreateInfo = new MgShaderModuleCreateInfo { Code = vertFs, CodeSize = new UIntPtr((ulong)vertFs.Length), }; mConfiguration.Device.CreateShaderModule(vsCreateInfo, null, out vsModule); } IMgShaderModule fsModule; { var fsCreateInfo = new MgShaderModuleCreateInfo { Code = fragFs, CodeSize = new UIntPtr((ulong)fragFs.Length), }; mConfiguration.Device.CreateShaderModule(fsCreateInfo, null, out fsModule); } var pipelineCreateInfo = new MgGraphicsPipelineCreateInfo { Stages = new [] { new MgPipelineShaderStageCreateInfo { Stage = MgShaderStageFlagBits.VERTEX_BIT, Module = vsModule, Name = "vertFunc", }, new MgPipelineShaderStageCreateInfo { Stage = MgShaderStageFlagBits.FRAGMENT_BIT, Module = fsModule, Name = "fragFunc", }, }, VertexInputState = vertices.inputState, InputAssemblyState = new MgPipelineInputAssemblyStateCreateInfo { // GL002 - TRIANGLE STRIP TEST Topology = MgPrimitiveTopology.TRIANGLE_STRIP, }, RasterizationState = new MgPipelineRasterizationStateCreateInfo { PolygonMode = MgPolygonMode.FILL, CullMode = MgCullModeFlagBits.NONE, FrontFace = MgFrontFace.COUNTER_CLOCKWISE, DepthClampEnable = false, RasterizerDiscardEnable = false, DepthBiasEnable = false, LineWidth = 1.0f, }, ColorBlendState = new MgPipelineColorBlendStateCreateInfo { Attachments = new [] { new MgPipelineColorBlendAttachmentState { ColorWriteMask = MgColorComponentFlagBits.R_BIT | MgColorComponentFlagBits.G_BIT | MgColorComponentFlagBits.B_BIT | MgColorComponentFlagBits.A_BIT, BlendEnable = false, } }, }, MultisampleState = new MgPipelineMultisampleStateCreateInfo { RasterizationSamples = MgSampleCountFlagBits.COUNT_1_BIT, SampleMask = null, }, Layout = mPipelineLayout, RenderPass = mGraphicsDevice.Renderpass, ViewportState = null, DepthStencilState = new MgPipelineDepthStencilStateCreateInfo { DepthTestEnable = true, DepthWriteEnable = true, DepthCompareOp = MgCompareOp.LESS_OR_EQUAL, DepthBoundsTestEnable = false, Back = new MgStencilOpState { FailOp = MgStencilOp.KEEP, PassOp = MgStencilOp.KEEP, CompareOp = MgCompareOp.ALWAYS, }, StencilTestEnable = false, Front = new MgStencilOpState { FailOp = MgStencilOp.KEEP, PassOp = MgStencilOp.KEEP, CompareOp = MgCompareOp.ALWAYS, }, }, DynamicState = new MgPipelineDynamicStateCreateInfo { DynamicStates = new[] { MgDynamicState.VIEWPORT, MgDynamicState.SCISSOR, } }, }; var err = mConfiguration.Device.CreateGraphicsPipelines(null, new[] { pipelineCreateInfo }, null, out IMgPipeline[] pipelines); Debug.Assert(err == Result.SUCCESS); vsModule.DestroyShaderModule(mConfiguration.Device, null); fsModule.DestroyShaderModule(mConfiguration.Device, null); mPipeline = pipelines[0]; } } void SetupDescriptorPool() { var descriptorPoolInfo = new MgDescriptorPoolCreateInfo { PoolSizes = new MgDescriptorPoolSize[] { new MgDescriptorPoolSize { Type = MgDescriptorType.UNIFORM_BUFFER, DescriptorCount = 1, }, }, MaxSets = 1, }; var err = mConfiguration.Device.CreateDescriptorPool(descriptorPoolInfo, null, out mDescriptorPool); Debug.Assert(err == Result.SUCCESS); } void SetupDescriptorSet() { var allocInfo = new MgDescriptorSetAllocateInfo { DescriptorPool = mDescriptorPool, DescriptorSetCount = 1, SetLayouts = new[] { mDescriptorSetLayout }, }; IMgDescriptorSet[] dSets; var err = mConfiguration.Device.AllocateDescriptorSets(allocInfo, out dSets); mDescriptorSet = dSets[0]; Debug.Assert(err == Result.SUCCESS); mConfiguration.Device.UpdateDescriptorSets( new [] { new MgWriteDescriptorSet { DstSet = mDescriptorSet, DescriptorCount = 1, DescriptorType = MgDescriptorType.UNIFORM_BUFFER, BufferInfo = new MgDescriptorBufferInfo[] { uniformDataVS.descriptor, }, DstBinding = 0, }, }, null); } IMgCommandBuffer[] drawCmdBuffers; void CreateCommandBuffers() { drawCmdBuffers = new IMgCommandBuffer[mGraphicsDevice.Framebuffers.Length]; { var cmdBufAllocateInfo = new MgCommandBufferAllocateInfo { CommandBufferCount = (uint)mGraphicsDevice.Framebuffers.Length, CommandPool = mConfiguration.Partition.CommandPool, Level = MgCommandBufferLevel.PRIMARY, }; var err = mConfiguration.Device.AllocateCommandBuffers(cmdBufAllocateInfo, drawCmdBuffers); Debug.Assert(err == Result.SUCCESS); } { var cmdBufAllocateInfo = new MgCommandBufferAllocateInfo { CommandBufferCount = 2, CommandPool = mConfiguration.Partition.CommandPool, Level = MgCommandBufferLevel.PRIMARY, }; var presentBuffers = new IMgCommandBuffer[2]; var err = mConfiguration.Device.AllocateCommandBuffers(cmdBufAllocateInfo, presentBuffers); Debug.Assert(err == Result.SUCCESS); mPrePresentCmdBuffer = presentBuffers[0]; mPostPresentCmdBuffer = presentBuffers[1]; } } void BuildCommandBuffers() { var renderPassBeginInfo = new MgRenderPassBeginInfo { RenderPass = mGraphicsDevice.Renderpass, RenderArea = new MgRect2D { Offset = new MgOffset2D { X = 0, Y = 0 }, Extent = new MgExtent2D { Width = mWidth, Height = mHeight }, }, ClearValues = new MgClearValue[] { MgClearValue.FromColorAndFormat(mSwapchains.Format, new MgColor4f(0f, 0f, 0f, 0f)), new MgClearValue { DepthStencil = new MgClearDepthStencilValue( 1.0f, 0) }, }, }; for (var i = 0; i < drawCmdBuffers.Length; ++i) { renderPassBeginInfo.Framebuffer = mGraphicsDevice.Framebuffers[i]; var cmdBuf = drawCmdBuffers[i]; var cmdBufInfo = new MgCommandBufferBeginInfo { }; var err = cmdBuf.BeginCommandBuffer(cmdBufInfo); Debug.Assert(err == Result.SUCCESS); cmdBuf.CmdBeginRenderPass(renderPassBeginInfo, MgSubpassContents.INLINE); cmdBuf.CmdSetViewport(0, new[] { new MgViewport { Height = (float) mHeight, Width = (float) mWidth, MinDepth = 0.0f, MaxDepth = 1.0f, } } ); cmdBuf.CmdSetScissor(0, new[] { new MgRect2D { Extent = new MgExtent2D { Width = mWidth, Height = mHeight }, Offset = new MgOffset2D { X = 0, Y = 0 }, } } ); cmdBuf.CmdBindDescriptorSets( MgPipelineBindPoint.GRAPHICS, mPipelineLayout, 0, 1, new[] { mDescriptorSet }, null); cmdBuf.CmdBindPipeline(MgPipelineBindPoint.GRAPHICS, mPipeline); cmdBuf.CmdBindVertexBuffers(0, new[] { vertices.buffer }, new [] { 0UL }); cmdBuf.CmdBindIndexBuffer(indices.buffer, 0, MgIndexType.UINT32); cmdBuf.CmdDrawIndexed(indices.count, 1, 0, 0, 1); cmdBuf.CmdEndRenderPass(); err = cmdBuf.EndCommandBuffer(); Debug.Assert(err == Result.SUCCESS); } } #endregion /// <summary> /// Convert degrees to radians /// </summary> /// <param name="degrees">An angle in degrees</param> /// <returns>The angle expressed in radians</returns> public static float DegreesToRadians(float degrees) { const double degToRad = System.Math.PI / 180.0; return (float) (degrees * degToRad); } void UpdateUniformBuffers() { // Update matrices uboVS.projectionMatrix = Matrix4.CreatePerspectiveFieldOfView( DegreesToRadians(60.0f), (mWidth / mHeight), 1.0f, 256.0f); const float ZOOM = -2.5f; uboVS.viewMatrix = Matrix4.CreateTranslation(0, 0, ZOOM); uboVS.modelMatrix = Matrix4.Identity; var structSize = (ulong) Marshal.SizeOf(typeof(UniformBufferObject)); var err = uniformDataVS.memory.MapMemory(mConfiguration.Device, 0, structSize, 0, out IntPtr pData); Marshal.StructureToPtr(uboVS, pData, false); uniformDataVS.memory.UnmapMemory(mConfiguration.Device); } public void RenderLoop() { render(); } void render() { if (!mPrepared) return; Draw(); } void Draw() { var currentBufferIndex = mPresentationLayer.BeginDraw(mPostPresentCmdBuffer, mPresentCompleteSemaphore); var fence = mWaitFences[(int) currentBufferIndex]; var err = mConfiguration.Device.WaitForFences(new[] { fence } , true, ulong.MaxValue); Debug.Assert(err == Result.SUCCESS); err = mConfiguration.Device.ResetFences(new[] { fence }); var submitInfos = new MgSubmitInfo[] { new MgSubmitInfo { WaitSemaphores = new [] { new MgSubmitInfoWaitSemaphoreInfo { WaitDstStageMask = MgPipelineStageFlagBits.COLOR_ATTACHMENT_OUTPUT_BIT, WaitSemaphore = mPresentCompleteSemaphore, } }, CommandBuffers = new [] { drawCmdBuffers[currentBufferIndex] }, SignalSemaphores = new [] { mRenderCompleteSemaphore }, } }; err = mConfiguration.Queue.QueueSubmit(submitInfos, fence); Debug.Assert(err == Result.SUCCESS); mPresentationLayer.EndDraw(new[] { currentBufferIndex }, mPrePresentCmdBuffer, new[] { mRenderCompleteSemaphore }); } void ViewChanged() { UpdateUniformBuffers(); } #region IDisposable Support private bool mIsDisposed = false; // To detect redundant calls private ITriangleDemoShaderPath mTrianglePath; protected virtual void Dispose(bool disposing) { if (mIsDisposed) { return; } ReleaseUnmanagedResources(); if (disposing) { ReleaseManagedResources(); } mIsDisposed = true; } private void ReleaseManagedResources() { } private void ReleaseUnmanagedResources() { var device = mConfiguration.Device; if (device != null) { if (mPipeline != null) mPipeline.DestroyPipeline(device, null); if (mPipelineLayout != null) mPipelineLayout.DestroyPipelineLayout(device, null); if (mDescriptorSetLayout != null) mDescriptorSetLayout.DestroyDescriptorSetLayout(device, null); if (vertices.buffer != null) vertices.buffer.DestroyBuffer(device, null); if (vertices.memory != null) vertices.memory.FreeMemory(device, null); if (indices.buffer != null) indices.buffer.DestroyBuffer(device, null); if (indices.memory != null) indices.memory.FreeMemory(device, null); if (uniformDataVS.buffer != null) uniformDataVS.buffer.DestroyBuffer(device, null); if (uniformDataVS.memory != null) uniformDataVS.memory.FreeMemory(device, null); if (mPresentCompleteSemaphore != null) mPresentCompleteSemaphore.DestroySemaphore(device, null); if (mRenderCompleteSemaphore != null) mRenderCompleteSemaphore.DestroySemaphore(device, null); foreach (var fence in mWaitFences) { fence.DestroyFence(device, null); } if (mDescriptorPool != null) mDescriptorPool.DestroyDescriptorPool(device, null); if (drawCmdBuffers != null) mConfiguration.Device.FreeCommandBuffers(mConfiguration.Partition.CommandPool, drawCmdBuffers); if (mPostPresentCmdBuffer != null) mConfiguration.Device.FreeCommandBuffers(mConfiguration.Partition.CommandPool, new[] { mPostPresentCmdBuffer }); if (mPrePresentCmdBuffer != null) mConfiguration.Device.FreeCommandBuffers(mConfiguration.Partition.CommandPool, new[] { mPrePresentCmdBuffer }); if (mGraphicsDevice != null) mGraphicsDevice.Dispose(); } } ~VulkanExample() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Models.Membership; using Umbraco.Core.Models.Rdbms; using Umbraco.Core.Persistence.DatabaseModelDefinitions; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.SqlSyntax; using Umbraco.Core.Persistence.UnitOfWork; namespace Umbraco.Core.Persistence.Repositories { internal class AuditRepository : PetaPocoRepositoryBase<int, IAuditItem>, IAuditRepository { public AuditRepository(IScopeUnitOfWork work, CacheHelper cache, ILogger logger, ISqlSyntaxProvider sqlSyntax) : base(work, cache, logger, sqlSyntax) { } /// <summary> /// Return the audit items as paged result /// </summary> /// <param name="query"> /// The query coming from the service /// </param> /// <param name="pageIndex"></param> /// <param name="pageSize"></param> /// <param name="totalRecords"></param> /// <param name="orderDirection"></param> /// <param name="auditTypeFilter"> /// Since we currently do not have enum support with our expression parser, we cannot query on AuditType in the query or the custom filter /// so we need to do that here /// </param> /// <param name="customFilter"> /// A user supplied custom filter /// </param> /// <returns></returns> public IEnumerable<IAuditItem> GetPagedResultsByQuery(IQuery<IAuditItem> query, long pageIndex, int pageSize, out long totalRecords, Direction orderDirection, AuditType[] auditTypeFilter, IQuery<IAuditItem> customFilter) { if (auditTypeFilter == null) auditTypeFilter = new AuditType[0]; var sql = GetBaseQuery(false); if (query == null) query = new Query<IAuditItem>(); var translatorIds = new SqlTranslator<IAuditItem>(sql, query); var translatedQuery = translatorIds.Translate(); var customFilterWheres = customFilter != null ? customFilter.GetWhereClauses().ToArray() : null; var hasCustomFilter = customFilterWheres != null && customFilterWheres.Length > 0; if (hasCustomFilter) { var filterSql = new Sql(); var first = true; foreach (var filterClaus in customFilterWheres) { if (first == false) { filterSql.Append(" AND "); } filterSql.Append(string.Format("({0})", filterClaus.Item1), filterClaus.Item2); first = false; } translatedQuery = GetFilteredSqlForPagedResults(translatedQuery, filterSql); } if (auditTypeFilter.Length > 0) { var filterSql = new Sql(); var first = true; foreach (var filterClaus in auditTypeFilter) { if (first == false || hasCustomFilter) { filterSql.Append(" AND "); } filterSql.Append("(logHeader = @logHeader)", new {logHeader = filterClaus.ToString() }); first = false; } translatedQuery = GetFilteredSqlForPagedResults(translatedQuery, filterSql); } if (orderDirection == Direction.Descending) translatedQuery.OrderByDescending("Datestamp"); else translatedQuery.OrderBy("Datestamp"); // Get page of results and total count var pagedResult = Database.Page<LogDto>(pageIndex + 1, pageSize, translatedQuery); totalRecords = pagedResult.TotalItems; var pages = pagedResult.Items.Select( dto => new AuditItem(dto.Id, dto.Comment, Enum<AuditType>.ParseOrNull(dto.Header) ?? AuditType.Custom, dto.UserId)).ToArray(); //Mapping the DateStamp for (int i = 0; i < pages.Length; i++) { pages[i].CreateDate = pagedResult.Items[i].Datestamp; } return pages; } protected override void PersistUpdatedItem(IAuditItem entity) { Database.Insert(new LogDto { Comment = entity.Comment, Datestamp = DateTime.Now, Header = entity.AuditType.ToString(), NodeId = entity.Id, UserId = entity.UserId }); } protected override Sql GetBaseQuery(bool isCount) { var sql = new Sql() .Select(isCount ? "COUNT(*)" : "umbracoLog.id, umbracoLog.userId, umbracoLog.NodeId, umbracoLog.Datestamp, umbracoLog.logHeader, umbracoLog.logComment, umbracoUser.userName, umbracoUser.avatar as userAvatar") .From<LogDto>(SqlSyntax); if (isCount == false) { sql = sql.LeftJoin<UserDto>(SqlSyntax).On<UserDto, LogDto>(SqlSyntax, dto => dto.Id, dto => dto.UserId); } return sql; } #region Not Implemented - not needed currently protected override void PersistNewItem(IAuditItem entity) { throw new NotImplementedException(); } protected override IAuditItem PerformGet(int id) { throw new NotImplementedException(); } protected override IEnumerable<IAuditItem> PerformGetAll(params int[] ids) { throw new NotImplementedException(); } protected override IEnumerable<IAuditItem> PerformGetByQuery(IQuery<IAuditItem> query) { throw new NotImplementedException(); } protected override string GetBaseWhereClause() { throw new NotImplementedException(); } protected override IEnumerable<string> GetDeleteClauses() { throw new NotImplementedException(); } protected override Guid NodeObjectTypeId { get { throw new NotImplementedException(); } } #endregion private Sql GetFilteredSqlForPagedResults(Sql sql, Sql filterSql) { Sql filteredSql; // Apply filter if (filterSql != null) { var sqlFilter = " WHERE " + filterSql.SQL.TrimStart("AND "); //NOTE: this is certainly strange - NPoco handles this much better but we need to re-create the sql // instance a couple of times to get the parameter order correct, for some reason the first // time the arguments don't show up correctly but the SQL argument parameter names are actually updated // accordingly - so we re-create it again. In v8 we don't need to do this and it's already taken care of. filteredSql = new Sql(sql.SQL, sql.Arguments); var args = filteredSql.Arguments.Concat(filterSql.Arguments).ToArray(); filteredSql = new Sql( string.Format("{0} {1}", filteredSql.SQL, sqlFilter), args); filteredSql = new Sql(filteredSql.SQL, args); } else { //copy to var so that the original isn't changed filteredSql = new Sql(sql.SQL, sql.Arguments); } return filteredSql; } } }
using System; using System.IO; using System.ComponentModel; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using ChargeBee.Internal; using ChargeBee.Api; using ChargeBee.Models.Enums; using ChargeBee.Filters.Enums; namespace ChargeBee.Models { public class DifferentialPrice : Resource { public DifferentialPrice() { } public DifferentialPrice(Stream stream) { using (StreamReader reader = new StreamReader(stream)) { JObj = JToken.Parse(reader.ReadToEnd()); apiVersionCheck (JObj); } } public DifferentialPrice(TextReader reader) { JObj = JToken.Parse(reader.ReadToEnd()); apiVersionCheck (JObj); } public DifferentialPrice(String jsonString) { JObj = JToken.Parse(jsonString); apiVersionCheck (JObj); } #region Methods public static CreateRequest Create(string id) { string url = ApiUtil.BuildUrl("item_prices", CheckNull(id), "differential_prices"); return new CreateRequest(url, HttpMethod.POST); } public static RetrieveRequest Retrieve(string id) { string url = ApiUtil.BuildUrl("differential_prices", CheckNull(id)); return new RetrieveRequest(url, HttpMethod.GET); } public static UpdateRequest Update(string id) { string url = ApiUtil.BuildUrl("differential_prices", CheckNull(id)); return new UpdateRequest(url, HttpMethod.POST); } public static DeleteRequest Delete(string id) { string url = ApiUtil.BuildUrl("differential_prices", CheckNull(id), "delete"); return new DeleteRequest(url, HttpMethod.POST); } public static DifferentialPriceListRequest List() { string url = ApiUtil.BuildUrl("differential_prices"); return new DifferentialPriceListRequest(url); } #endregion #region Properties public string Id { get { return GetValue<string>("id", true); } } public string ItemPriceId { get { return GetValue<string>("item_price_id", true); } } public string ParentItemId { get { return GetValue<string>("parent_item_id", true); } } public int? Price { get { return GetValue<int?>("price", false); } } public string PriceInDecimal { get { return GetValue<string>("price_in_decimal", false); } } public StatusEnum? Status { get { return GetEnum<StatusEnum>("status", false); } } public long? ResourceVersion { get { return GetValue<long?>("resource_version", false); } } public DateTime? UpdatedAt { get { return GetDateTime("updated_at", false); } } public DateTime CreatedAt { get { return (DateTime)GetDateTime("created_at", true); } } public DateTime ModifiedAt { get { return (DateTime)GetDateTime("modified_at", true); } } public List<DifferentialPriceTier> Tiers { get { return GetResourceList<DifferentialPriceTier>("tiers"); } } public string CurrencyCode { get { return GetValue<string>("currency_code", true); } } public List<DifferentialPriceParentPeriod> ParentPeriods { get { return GetResourceList<DifferentialPriceParentPeriod>("parent_periods"); } } #endregion #region Requests public class CreateRequest : EntityRequest<CreateRequest> { public CreateRequest(string url, HttpMethod method) : base(url, method) { } public CreateRequest ParentItemId(string parentItemId) { m_params.Add("parent_item_id", parentItemId); return this; } public CreateRequest Price(int price) { m_params.AddOpt("price", price); return this; } public CreateRequest PriceInDecimal(string priceInDecimal) { m_params.AddOpt("price_in_decimal", priceInDecimal); return this; } public CreateRequest ParentPeriodPeriodUnit(int index, DifferentialPriceParentPeriod.PeriodUnitEnum parentPeriodPeriodUnit) { m_params.Add("parent_periods[period_unit][" + index + "]", parentPeriodPeriodUnit); return this; } public CreateRequest ParentPeriodPeriod(int index, JArray parentPeriodPeriod) { m_params.AddOpt("parent_periods[period][" + index + "]", parentPeriodPeriod); return this; } public CreateRequest TierStartingUnit(int index, int tierStartingUnit) { m_params.AddOpt("tiers[starting_unit][" + index + "]", tierStartingUnit); return this; } public CreateRequest TierEndingUnit(int index, int tierEndingUnit) { m_params.AddOpt("tiers[ending_unit][" + index + "]", tierEndingUnit); return this; } public CreateRequest TierPrice(int index, int tierPrice) { m_params.AddOpt("tiers[price][" + index + "]", tierPrice); return this; } public CreateRequest TierStartingUnitInDecimal(int index, string tierStartingUnitInDecimal) { m_params.AddOpt("tiers[starting_unit_in_decimal][" + index + "]", tierStartingUnitInDecimal); return this; } public CreateRequest TierEndingUnitInDecimal(int index, string tierEndingUnitInDecimal) { m_params.AddOpt("tiers[ending_unit_in_decimal][" + index + "]", tierEndingUnitInDecimal); return this; } public CreateRequest TierPriceInDecimal(int index, string tierPriceInDecimal) { m_params.AddOpt("tiers[price_in_decimal][" + index + "]", tierPriceInDecimal); return this; } } public class RetrieveRequest : EntityRequest<RetrieveRequest> { public RetrieveRequest(string url, HttpMethod method) : base(url, method) { } public RetrieveRequest ItemPriceId(string itemPriceId) { m_params.Add("item_price_id", itemPriceId); return this; } } public class UpdateRequest : EntityRequest<UpdateRequest> { public UpdateRequest(string url, HttpMethod method) : base(url, method) { } public UpdateRequest ItemPriceId(string itemPriceId) { m_params.Add("item_price_id", itemPriceId); return this; } public UpdateRequest Price(int price) { m_params.AddOpt("price", price); return this; } public UpdateRequest PriceInDecimal(string priceInDecimal) { m_params.AddOpt("price_in_decimal", priceInDecimal); return this; } public UpdateRequest ParentPeriodPeriodUnit(int index, DifferentialPriceParentPeriod.PeriodUnitEnum parentPeriodPeriodUnit) { m_params.Add("parent_periods[period_unit][" + index + "]", parentPeriodPeriodUnit); return this; } public UpdateRequest ParentPeriodPeriod(int index, JArray parentPeriodPeriod) { m_params.AddOpt("parent_periods[period][" + index + "]", parentPeriodPeriod); return this; } public UpdateRequest TierStartingUnit(int index, int tierStartingUnit) { m_params.AddOpt("tiers[starting_unit][" + index + "]", tierStartingUnit); return this; } public UpdateRequest TierEndingUnit(int index, int tierEndingUnit) { m_params.AddOpt("tiers[ending_unit][" + index + "]", tierEndingUnit); return this; } public UpdateRequest TierPrice(int index, int tierPrice) { m_params.AddOpt("tiers[price][" + index + "]", tierPrice); return this; } public UpdateRequest TierStartingUnitInDecimal(int index, string tierStartingUnitInDecimal) { m_params.AddOpt("tiers[starting_unit_in_decimal][" + index + "]", tierStartingUnitInDecimal); return this; } public UpdateRequest TierEndingUnitInDecimal(int index, string tierEndingUnitInDecimal) { m_params.AddOpt("tiers[ending_unit_in_decimal][" + index + "]", tierEndingUnitInDecimal); return this; } public UpdateRequest TierPriceInDecimal(int index, string tierPriceInDecimal) { m_params.AddOpt("tiers[price_in_decimal][" + index + "]", tierPriceInDecimal); return this; } } public class DeleteRequest : EntityRequest<DeleteRequest> { public DeleteRequest(string url, HttpMethod method) : base(url, method) { } public DeleteRequest ItemPriceId(string itemPriceId) { m_params.Add("item_price_id", itemPriceId); return this; } } public class DifferentialPriceListRequest : ListRequestBase<DifferentialPriceListRequest> { public DifferentialPriceListRequest(string url) : base(url) { } public StringFilter<DifferentialPriceListRequest> ItemPriceId() { return new StringFilter<DifferentialPriceListRequest>("item_price_id", this).SupportsMultiOperators(true); } public StringFilter<DifferentialPriceListRequest> ItemId() { return new StringFilter<DifferentialPriceListRequest>("item_id", this).SupportsMultiOperators(true); } public StringFilter<DifferentialPriceListRequest> Id() { return new StringFilter<DifferentialPriceListRequest>("id", this).SupportsMultiOperators(true); } public StringFilter<DifferentialPriceListRequest> ParentItemId() { return new StringFilter<DifferentialPriceListRequest>("parent_item_id", this).SupportsMultiOperators(true); } } #endregion public enum StatusEnum { UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a dotnet-client version incompatibility. We suggest you to upgrade to the latest version */ [EnumMember(Value = "active")] Active, [EnumMember(Value = "deleted")] Deleted, } #region Subclasses public class DifferentialPriceTier : Resource { public int StartingUnit { get { return GetValue<int>("starting_unit", true); } } public int? EndingUnit { get { return GetValue<int?>("ending_unit", false); } } public int Price { get { return GetValue<int>("price", true); } } public string StartingUnitInDecimal { get { return GetValue<string>("starting_unit_in_decimal", false); } } public string EndingUnitInDecimal { get { return GetValue<string>("ending_unit_in_decimal", false); } } public string PriceInDecimal { get { return GetValue<string>("price_in_decimal", false); } } } public class DifferentialPriceParentPeriod : Resource { public enum PeriodUnitEnum { UnKnown, /*Indicates unexpected value for this enum. You can get this when there is a dotnet-client version incompatibility. We suggest you to upgrade to the latest version */ [EnumMember(Value = "day")] Day, [EnumMember(Value = "week")] Week, [EnumMember(Value = "month")] Month, [EnumMember(Value = "year")] Year, } public PeriodUnitEnum PeriodUnit { get { return GetEnum<PeriodUnitEnum>("period_unit", true); } } public JArray Period { get { return GetJArray("period", false); } } } #endregion } }
// // AudioscrobblerConnection.cs // // Author: // Chris Toshok <toshok@ximian.com> // Alexander Hixon <hixon.alexander@mediati.org> // Phil Trimble <philtrimble@gmail.com> // // Copyright (C) 2005-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.IO; using System.Net; using System.Text; using System.Timers; using System.Security.Cryptography; using System.Web; using Hyena; using Hyena.Json; using Mono.Unix; namespace Lastfm { public class AudioscrobblerConnection { private enum State { Idle, NeedTransmit, Transmitting, WaitingForResponse }; private const int TICK_INTERVAL = 2000; /* 2 seconds */ private const int RETRY_SECONDS = 60; /* 60 second delay for transmission retries */ private const int TIME_OUT = 10000; /* 10 seconds timeout for webrequests */ private bool connected = false; /* if we're connected to network or not */ public bool Connected { get { return connected; } } private bool started = false; /* engine has started and was/is connected to AS */ public bool Started { get { return started; } } private System.Timers.Timer timer; private DateTime next_interval; private IQueue queue; private int hard_failures = 0; private bool now_playing_started; private LastfmRequest current_now_playing_request; private LastfmRequest current_scrobble_request; private IAsyncResult current_async_result; private State state; internal AudioscrobblerConnection (IQueue queue) { LastfmCore.Account.Updated += AccountUpdated; state = State.Idle; this.queue = queue; } private void AccountUpdated (object o, EventArgs args) { Stop (); Start (); } public void UpdateNetworkState (bool connected) { Log.DebugFormat ("Audioscrobbler state: {0}", connected ? "connected" : "disconnected"); this.connected = connected; } public void Start () { if (started) { return; } started = true; hard_failures = 0; queue.TrackAdded += delegate(object o, EventArgs args) { StartTransitionHandler (); }; queue.Load (); StartTransitionHandler (); } private void StartTransitionHandler () { if (!started) { // Don't run if we're not actually started. return; } if (timer == null) { timer = new System.Timers.Timer (); timer.Interval = TICK_INTERVAL; timer.AutoReset = true; timer.Elapsed += new ElapsedEventHandler (StateTransitionHandler); timer.Start (); } else if (!timer.Enabled) { timer.Start (); } } public void Stop () { StopTransitionHandler (); queue.Save (); started = false; } private void StopTransitionHandler () { if (timer != null) { timer.Stop (); } } private void StateTransitionHandler (object o, ElapsedEventArgs e) { // if we're not connected, don't bother doing anything involving the network. if (!connected) { return; } if ((state == State.Idle || state == State.NeedTransmit) && hard_failures > 2) { hard_failures = 0; } // and address changes in our engine state switch (state) { case State.Idle: if (queue.Count > 0) { state = State.NeedTransmit; } else if (current_now_playing_request != null) { // Now playing info needs to be sent NowPlaying (current_now_playing_request); } else { StopTransitionHandler (); } break; case State.NeedTransmit: if (DateTime.Now > next_interval) { TransmitQueue (); } break; case State.Transmitting: case State.WaitingForResponse: // nothing here break; } } private void TransmitQueue () { // save here in case we're interrupted before we complete // the request. we save it again when we get an OK back // from the server queue.Save (); next_interval = DateTime.MinValue; if (!connected) { return; } current_scrobble_request = new LastfmRequest ("track.scrobble", RequestType.Write, ResponseFormat.Json); IList<IQueuedTrack> tracks = queue.GetTracks (); for (int i = 0; i < tracks.Count; i++) { IQueuedTrack track = tracks[i]; string str_track_number = String.Empty; if (track.TrackNumber != 0) { str_track_number = track.TrackNumber.ToString(); } bool chosen_by_user = (track.TrackAuth.Length == 0); current_scrobble_request.AddParameter (String.Format ("timestamp[{0}]", i), track.StartTime.ToString ()); current_scrobble_request.AddParameter (String.Format ("track[{0}]", i), track.Title); current_scrobble_request.AddParameter (String.Format ("artist[{0}]", i), track.Artist); current_scrobble_request.AddParameter (String.Format ("album[{0}]", i), track.Album); current_scrobble_request.AddParameter (String.Format ("trackNumber[{0}]", i), str_track_number); current_scrobble_request.AddParameter (String.Format ("duration[{0}]", i), track.Duration.ToString ()); current_scrobble_request.AddParameter (String.Format ("mbid[{0}]", i), track.MusicBrainzId); current_scrobble_request.AddParameter (String.Format ("chosenByUser[{0}]", i), chosen_by_user ? "1" : "0"); } Log.DebugFormat ("Last.fm scrobbler sending '{0}'", current_scrobble_request.ToString ()); state = State.Transmitting; current_async_result = current_scrobble_request.BeginSend (OnScrobbleResponse, tracks.Count); state = State.WaitingForResponse; if (!(current_async_result.AsyncWaitHandle.WaitOne (TIME_OUT, false))) { Log.Warning ("Audioscrobbler upload failed", "The request timed out and was aborted", false); next_interval = DateTime.Now + new TimeSpan (0, 0, RETRY_SECONDS); hard_failures++; state = State.Idle; } } private void OnScrobbleResponse (IAsyncResult ar) { int nb_tracks_scrobbled = 0; try { current_scrobble_request.EndSend (ar); nb_tracks_scrobbled = (int)ar.AsyncState; } catch (Exception e) { Log.Exception ("Failed to complete the scrobble request", e); state = State.Idle; return; } JsonObject response = null; try { response = current_scrobble_request.GetResponseObject (); } catch (Exception e) { Log.Exception ("Failed to process the scrobble response", e); state = State.Idle; return; } var error = current_scrobble_request.GetError (); if (error == StationError.ServiceOffline || error == StationError.TemporarilyUnavailable) { Log.WarningFormat ("Lastfm is temporarily unavailable: {0}", (string)response ["message"]); next_interval = DateTime.Now + new TimeSpan (0, 0, RETRY_SECONDS); hard_failures++; state = State.Idle; } else if (error != StationError.None) { // TODO: If error == StationError.InvalidSessionKey, // suggest to the user to (re)do the Last.fm authentication. hard_failures++; queue.RemoveInvalidTracks (); // if there are still valid tracks in the queue then retransmit on the next interval if (queue.Count > 0) { state = State.NeedTransmit; } else { state = State.Idle; } } else { try { var scrobbles = (JsonObject)response["scrobbles"]; var scrobbles_attr = (JsonObject)scrobbles["@attr"]; Log.InformationFormat ("Audioscrobbler upload succeeded: {0} accepted, {1} ignored", scrobbles_attr["accepted"], scrobbles_attr["ignored"]); if (nb_tracks_scrobbled > 1) { var scrobble_array = (JsonArray)scrobbles["scrobble"]; foreach (JsonObject scrobbled_track in scrobble_array) { LogIfIgnored (scrobbled_track); } } else { var scrobbled_track = (JsonObject)scrobbles["scrobble"]; LogIfIgnored (scrobbled_track); } } catch (Exception) { Log.Information ("Audioscrobbler upload succeeded but unknown response received"); Log.Debug ("Response received", response.ToString ()); } hard_failures = 0; // we succeeded, pop the elements off our queue queue.RemoveRange (0, nb_tracks_scrobbled); queue.Save (); state = State.Idle; } } private void LogIfIgnored (JsonObject scrobbled_track) { var ignoredMessage = (JsonObject)scrobbled_track["ignoredMessage"]; if (Convert.ToInt32 (ignoredMessage["code"]) == 0) { return; } var track = (JsonObject)scrobbled_track["track"]; var artist = (JsonObject)scrobbled_track["artist"]; var album = (JsonObject)scrobbled_track["album"]; Log.InformationFormat ("Track {0} - {1} (on {2}) ignored by Last.fm, reason: {3}", artist["#text"], track["#text"], album["#text"], ignoredMessage["#text"]); } public void NowPlaying (string artist, string title, string album, double duration, int tracknum) { NowPlaying (artist, title, album, duration, tracknum, ""); } public void NowPlaying (string artist, string title, string album, double duration, int tracknum, string mbrainzid) { if (String.IsNullOrEmpty (artist) || String.IsNullOrEmpty (title) || !connected) { return; } // FIXME: need a lock for this flag if (now_playing_started) { return; } now_playing_started = true; string str_track_number = String.Empty; if (tracknum != 0) { str_track_number = tracknum.ToString(); } LastfmRequest request = new LastfmRequest ("track.updateNowPlaying", RequestType.Write, ResponseFormat.Json); request.AddParameter ("track", title); request.AddParameter ("artist", artist); request.AddParameter ("album", album); request.AddParameter ("trackNumber", str_track_number); request.AddParameter ("duration", Math.Floor (duration).ToString ()); request.AddParameter ("mbid", mbrainzid); current_now_playing_request = request; NowPlaying (current_now_playing_request); } private void NowPlaying (LastfmRequest request) { try { request.BeginSend (OnNowPlayingResponse); } catch (Exception e) { Log.Warning ("Audioscrobbler NowPlaying failed", String.Format("Failed to post NowPlaying: {0}", e), false); } } private void OnNowPlayingResponse (IAsyncResult ar) { try { current_now_playing_request.EndSend (ar); } catch (Exception e) { Log.Exception ("Failed to complete the NowPlaying request", e); state = State.Idle; current_now_playing_request = null; return; } StationError error = current_now_playing_request.GetError (); // API docs say "Now Playing requests that fail should not be retried". if (error == StationError.InvalidSessionKey) { Log.Warning ("Audioscrobbler NowPlaying failed", "Session ID sent was invalid", false); // TODO: Suggest to the user to (re)do the Last.fm authentication ? } else if (error != StationError.None) { Log.WarningFormat ("Audioscrobbler NowPlaying failed: {0}", error.ToString ()); } else { Log.Debug ("Submitted NowPlaying track to Audioscrobbler"); now_playing_started = false; } current_now_playing_request = null; } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using QuantConnect.Algorithm.Selection; using QuantConnect.Data; using QuantConnect.Data.Fundamental; using QuantConnect.Data.Market; using QuantConnect.Data.UniverseSelection; using QuantConnect.Securities; using QuantConnect.Securities.Future; using QuantConnect.Util; namespace QuantConnect.Algorithm { public partial class QCAlgorithm { // save universe additions and apply at end of time step // this removes temporal dependencies from w/in initialize method // original motivation: adding equity/options to enforce equity raw data mode private readonly object _pendingUniverseAdditionsLock = new object(); private readonly List<UserDefinedUniverseAddition> _pendingUserDefinedUniverseSecurityAdditions = new List<UserDefinedUniverseAddition>(); private readonly List<Universe> _pendingUniverseAdditions = new List<Universe>(); // this is so that later during 'UniverseSelection.CreateUniverses' we wont remove these user universes from the UniverseManager private readonly HashSet<Symbol> _userAddedUniverses = new HashSet<Symbol>(); private ConcurrentSet<Symbol> _rawNormalizationWarningSymbols = new ConcurrentSet<Symbol>(); private readonly int _rawNormalizationWarningSymbolsMaxCount = 10; /// <summary> /// Gets universe manager which holds universes keyed by their symbol /// </summary> public UniverseManager UniverseManager { get; private set; } /// <summary> /// Gets the universe settings to be used when adding securities via universe selection /// </summary> public UniverseSettings UniverseSettings { get; private set; } /// <summary> /// Invoked at the end of every time step. This allows the algorithm /// to process events before advancing to the next time step. /// </summary> public void OnEndOfTimeStep() { if (_pendingUniverseAdditions.Count + _pendingUserDefinedUniverseSecurityAdditions.Count == 0) { // no point in looping through everything if there's no pending changes return; } var requiredHistoryRequests = new Dictionary<Security, Resolution>(); // rewrite securities w/ derivatives to be in raw mode lock (_pendingUniverseAdditionsLock) { foreach (var security in Securities.Select(kvp => kvp.Value).Union( _pendingUserDefinedUniverseSecurityAdditions.Select(x => x.Security))) { // check for any derivative securities and mark the underlying as raw if (Securities.Any(skvp => skvp.Key.SecurityType != SecurityType.Base && skvp.Key.HasUnderlyingSymbol(security.Symbol))) { // set data mode raw and default volatility model ConfigureUnderlyingSecurity(security); } var configs = SubscriptionManager.SubscriptionDataConfigService .GetSubscriptionDataConfigs(security.Symbol); if (security.Symbol.HasUnderlying && security.Symbol.SecurityType != SecurityType.Base) { Security underlyingSecurity; var underlyingSymbol = security.Symbol.Underlying; var resolution = configs.GetHighestResolution(); // create the underlying security object if it doesn't already exist if (!Securities.TryGetValue(underlyingSymbol, out underlyingSecurity)) { underlyingSecurity = AddSecurity(underlyingSymbol.SecurityType, underlyingSymbol.Value, resolution, underlyingSymbol.ID.Market, false, 0, configs.IsExtendedMarketHours()); } // set data mode raw and default volatility model ConfigureUnderlyingSecurity(underlyingSecurity); if (LiveMode && underlyingSecurity.GetLastData() == null) { if (requiredHistoryRequests.ContainsKey(underlyingSecurity)) { // lets request the higher resolution var currentResolutionRequest = requiredHistoryRequests[underlyingSecurity]; if (currentResolutionRequest != Resolution.Minute // Can not be less than Minute && resolution < currentResolutionRequest) { requiredHistoryRequests[underlyingSecurity] = (Resolution)Math.Max((int)resolution, (int)Resolution.Minute); } } else { requiredHistoryRequests.Add(underlyingSecurity, (Resolution)Math.Max((int)resolution, (int)Resolution.Minute)); } } // set the underlying security on the derivative -- we do this in two places since it's possible // to do AddOptionContract w/out the underlying already added and normalized properly var derivative = security as IDerivativeSecurity; if (derivative != null) { derivative.Underlying = underlyingSecurity; } } } if (!requiredHistoryRequests.IsNullOrEmpty()) { // Create requests var historyRequests = Enumerable.Empty<HistoryRequest>(); foreach (var byResolution in requiredHistoryRequests.GroupBy(x => x.Value)) { historyRequests = historyRequests.Concat( CreateBarCountHistoryRequests(byResolution.Select(x => x.Key.Symbol), 3, byResolution.Key)); } // Request data var historicLastData = History(historyRequests); historicLastData.PushThrough(x => { var security = requiredHistoryRequests.Keys.FirstOrDefault(y => y.Symbol == x.Symbol); security?.Cache.AddData(x); }); } // add subscriptionDataConfig to their respective user defined universes foreach (var userDefinedUniverseAddition in _pendingUserDefinedUniverseSecurityAdditions) { foreach (var subscriptionDataConfig in userDefinedUniverseAddition.SubscriptionDataConfigs) { userDefinedUniverseAddition.Universe.Add(subscriptionDataConfig); } } // finally add any pending universes, this will make them available to the data feed foreach (var universe in _pendingUniverseAdditions) { UniverseManager.Add(universe.Configuration.Symbol, universe); } _pendingUniverseAdditions.Clear(); _pendingUserDefinedUniverseSecurityAdditions.Clear(); } if (!_rawNormalizationWarningSymbols.IsNullOrEmpty()) { // Log our securities being set to raw price mode Debug($"Warning: The following securities were set to raw price normalization mode to work with options: " + $"{string.Join(", ", _rawNormalizationWarningSymbols.Take(_rawNormalizationWarningSymbolsMaxCount).Select(x => x.Value))}..."); // Set our warning list to null to stop emitting these warnings after its done once _rawNormalizationWarningSymbols = null; } } /// <summary> /// Gets a helper that provides pre-defined universe definitions, such as top dollar volume /// </summary> public UniverseDefinitions Universe { get; private set; } /// <summary> /// Adds the universe to the algorithm /// </summary> /// <param name="universe">The universe to be added</param> public Universe AddUniverse(Universe universe) { // The universe will be added at the end of time step, same as the AddData user defined universes. // This is required to be independent of the start and end date set during initialize _pendingUniverseAdditions.Add(universe); _userAddedUniverses.Add(universe.Configuration.Symbol); return universe; } /// <summary> /// Creates a new universe and adds it to the algorithm. This will use the default universe settings /// specified via the <see cref="UniverseSettings"/> property. This universe will use the defaults /// of SecurityType.Equity, Resolution.Daily, Market.USA, and UniverseSettings /// </summary> /// <typeparam name="T">The data type</typeparam> /// <param name="name">A unique name for this universe</param> /// <param name="selector">Function delegate that performs selection on the universe data</param> public Universe AddUniverse<T>(string name, Func<IEnumerable<T>, IEnumerable<Symbol>> selector) { return AddUniverse(SecurityType.Equity, name, Resolution.Daily, Market.USA, UniverseSettings, selector); } /// <summary> /// Creates a new universe and adds it to the algorithm. This will use the default universe settings /// specified via the <see cref="UniverseSettings"/> property. This universe will use the defaults /// of SecurityType.Equity, Resolution.Daily, Market.USA, and UniverseSettings /// </summary> /// <typeparam name="T">The data type</typeparam> /// <param name="name">A unique name for this universe</param> /// <param name="selector">Function delegate that performs selection on the universe data</param> public Universe AddUniverse<T>(string name, Func<IEnumerable<T>, IEnumerable<string>> selector) { return AddUniverse(SecurityType.Equity, name, Resolution.Daily, Market.USA, UniverseSettings, selector); } /// <summary> /// Creates a new universe and adds it to the algorithm. This will use the default universe settings /// specified via the <see cref="UniverseSettings"/> property. This universe will use the defaults /// of SecurityType.Equity, Resolution.Daily, and Market.USA /// </summary> /// <typeparam name="T">The data type</typeparam> /// <param name="name">A unique name for this universe</param> /// <param name="universeSettings">The settings used for securities added by this universe</param> /// <param name="selector">Function delegate that performs selection on the universe data</param> public Universe AddUniverse<T>(string name, UniverseSettings universeSettings, Func<IEnumerable<T>, IEnumerable<Symbol>> selector) { return AddUniverse(SecurityType.Equity, name, Resolution.Daily, Market.USA, universeSettings, selector); } /// <summary> /// Creates a new universe and adds it to the algorithm. This will use the default universe settings /// specified via the <see cref="UniverseSettings"/> property. This universe will use the defaults /// of SecurityType.Equity, Resolution.Daily, and Market.USA /// </summary> /// <typeparam name="T">The data type</typeparam> /// <param name="name">A unique name for this universe</param> /// <param name="universeSettings">The settings used for securities added by this universe</param> /// <param name="selector">Function delegate that performs selection on the universe data</param> public Universe AddUniverse<T>(string name, UniverseSettings universeSettings, Func<IEnumerable<T>, IEnumerable<string>> selector) { return AddUniverse(SecurityType.Equity, name, Resolution.Daily, Market.USA, universeSettings, selector); } /// <summary> /// Creates a new universe and adds it to the algorithm. This will use the default universe settings /// specified via the <see cref="UniverseSettings"/> property. This universe will use the defaults /// of SecurityType.Equity, Market.USA and UniverseSettings /// </summary> /// <typeparam name="T">The data type</typeparam> /// <param name="name">A unique name for this universe</param> /// <param name="resolution">The epected resolution of the universe data</param> /// <param name="selector">Function delegate that performs selection on the universe data</param> public Universe AddUniverse<T>(string name, Resolution resolution, Func<IEnumerable<T>, IEnumerable<Symbol>> selector) { return AddUniverse(SecurityType.Equity, name, resolution, Market.USA, UniverseSettings, selector); } /// <summary> /// Creates a new universe and adds it to the algorithm. This will use the default universe settings /// specified via the <see cref="UniverseSettings"/> property. This universe will use the defaults /// of SecurityType.Equity, Market.USA and UniverseSettings /// </summary> /// <typeparam name="T">The data type</typeparam> /// <param name="name">A unique name for this universe</param> /// <param name="resolution">The epected resolution of the universe data</param> /// <param name="selector">Function delegate that performs selection on the universe data</param> public Universe AddUniverse<T>(string name, Resolution resolution, Func<IEnumerable<T>, IEnumerable<string>> selector) { return AddUniverse(SecurityType.Equity, name, resolution, Market.USA, UniverseSettings, selector); } /// <summary> /// Creates a new universe and adds it to the algorithm. This will use the default universe settings /// specified via the <see cref="UniverseSettings"/> property. This universe will use the defaults /// of SecurityType.Equity, and Market.USA /// </summary> /// <typeparam name="T">The data type</typeparam> /// <param name="name">A unique name for this universe</param> /// <param name="resolution">The epected resolution of the universe data</param> /// <param name="universeSettings">The settings used for securities added by this universe</param> /// <param name="selector">Function delegate that performs selection on the universe data</param> public Universe AddUniverse<T>(string name, Resolution resolution, UniverseSettings universeSettings, Func<IEnumerable<T>, IEnumerable<Symbol>> selector) { return AddUniverse(SecurityType.Equity, name, resolution, Market.USA, universeSettings, selector); } /// <summary> /// Creates a new universe and adds it to the algorithm. This will use the default universe settings /// specified via the <see cref="UniverseSettings"/> property. This universe will use the defaults /// of SecurityType.Equity, and Market.USA /// </summary> /// <typeparam name="T">The data type</typeparam> /// <param name="name">A unique name for this universe</param> /// <param name="resolution">The epected resolution of the universe data</param> /// <param name="universeSettings">The settings used for securities added by this universe</param> /// <param name="selector">Function delegate that performs selection on the universe data</param> public Universe AddUniverse<T>(string name, Resolution resolution, UniverseSettings universeSettings, Func<IEnumerable<T>, IEnumerable<string>> selector) { return AddUniverse(SecurityType.Equity, name, resolution, Market.USA, universeSettings, selector); } /// <summary> /// Creates a new universe and adds it to the algorithm. This will use the default universe settings /// specified via the <see cref="UniverseSettings"/> property. /// </summary> /// <typeparam name="T">The data type</typeparam> /// <param name="securityType">The security type the universe produces</param> /// <param name="name">A unique name for this universe</param> /// <param name="resolution">The epected resolution of the universe data</param> /// <param name="market">The market for selected symbols</param> /// <param name="selector">Function delegate that performs selection on the universe data</param> public Universe AddUniverse<T>(SecurityType securityType, string name, Resolution resolution, string market, Func<IEnumerable<T>, IEnumerable<Symbol>> selector) { return AddUniverse(securityType, name, resolution, market, UniverseSettings, selector); } /// <summary> /// Creates a new universe and adds it to the algorithm. This will use the default universe settings /// specified via the <see cref="UniverseSettings"/> property. /// </summary> /// <typeparam name="T">The data type</typeparam> /// <param name="securityType">The security type the universe produces</param> /// <param name="name">A unique name for this universe</param> /// <param name="resolution">The epected resolution of the universe data</param> /// <param name="market">The market for selected symbols</param> /// <param name="selector">Function delegate that performs selection on the universe data</param> public Universe AddUniverse<T>(SecurityType securityType, string name, Resolution resolution, string market, Func<IEnumerable<T>, IEnumerable<string>> selector) { return AddUniverse(securityType, name, resolution, market, UniverseSettings, selector); } /// <summary> /// Creates a new universe and adds it to the algorithm /// </summary> /// <typeparam name="T">The data type</typeparam> /// <param name="securityType">The security type the universe produces</param> /// <param name="name">A unique name for this universe</param> /// <param name="resolution">The epected resolution of the universe data</param> /// <param name="market">The market for selected symbols</param> /// <param name="universeSettings">The subscription settings to use for newly created subscriptions</param> /// <param name="selector">Function delegate that performs selection on the universe data</param> public Universe AddUniverse<T>(SecurityType securityType, string name, Resolution resolution, string market, UniverseSettings universeSettings, Func<IEnumerable<T>, IEnumerable<Symbol>> selector) { var marketHoursDbEntry = MarketHoursDatabase.GetEntry(market, name, securityType); var dataTimeZone = marketHoursDbEntry.DataTimeZone; var exchangeTimeZone = marketHoursDbEntry.ExchangeHours.TimeZone; var symbol = QuantConnect.Symbol.Create(name, securityType, market, baseDataType: typeof(T)); var config = new SubscriptionDataConfig(typeof(T), symbol, resolution, dataTimeZone, exchangeTimeZone, false, false, true, true, isFilteredSubscription: false); return AddUniverse(new FuncUniverse(config, universeSettings, d => selector(d.OfType<T>()))); } /// <summary> /// Creates a new universe and adds it to the algorithm /// </summary> /// <typeparam name="T">The data type</typeparam> /// <param name="securityType">The security type the universe produces</param> /// <param name="name">A unique name for this universe</param> /// <param name="resolution">The epected resolution of the universe data</param> /// <param name="market">The market for selected symbols</param> /// <param name="universeSettings">The subscription settings to use for newly created subscriptions</param> /// <param name="selector">Function delegate that performs selection on the universe data</param> public Universe AddUniverse<T>(SecurityType securityType, string name, Resolution resolution, string market, UniverseSettings universeSettings, Func<IEnumerable<T>, IEnumerable<string>> selector) { var marketHoursDbEntry = MarketHoursDatabase.GetEntry(market, name, securityType); var dataTimeZone = marketHoursDbEntry.DataTimeZone; var exchangeTimeZone = marketHoursDbEntry.ExchangeHours.TimeZone; var symbol = QuantConnect.Symbol.Create(name, securityType, market, baseDataType: typeof(T)); var config = new SubscriptionDataConfig(typeof(T), symbol, resolution, dataTimeZone, exchangeTimeZone, false, false, true, true, isFilteredSubscription: false); return AddUniverse(new FuncUniverse(config, universeSettings, d => selector(d.OfType<T>()).Select(x => QuantConnect.Symbol.Create(x, securityType, market, baseDataType: typeof(T)))) ); } /// <summary> /// Creates a new universe and adds it to the algorithm. This is for coarse fundamental US Equity data and /// will be executed on day changes in the NewYork time zone (<see cref="TimeZones.NewYork"/> /// </summary> /// <param name="selector">Defines an initial coarse selection</param> public Universe AddUniverse(Func<IEnumerable<CoarseFundamental>, IEnumerable<Symbol>> selector) { return AddUniverse(new CoarseFundamentalUniverse(UniverseSettings, selector)); } /// <summary> /// Creates a new universe and adds it to the algorithm. This is for coarse and fine fundamental US Equity data and /// will be executed on day changes in the NewYork time zone (<see cref="TimeZones.NewYork"/> /// </summary> /// <param name="coarseSelector">Defines an initial coarse selection</param> /// <param name="fineSelector">Defines a more detailed selection with access to more data</param> public Universe AddUniverse(Func<IEnumerable<CoarseFundamental>, IEnumerable<Symbol>> coarseSelector, Func<IEnumerable<FineFundamental>, IEnumerable<Symbol>> fineSelector) { var coarse = new CoarseFundamentalUniverse(UniverseSettings, coarseSelector); return AddUniverse(new FineFundamentalFilteredUniverse(coarse, fineSelector)); } /// <summary> /// Creates a new universe and adds it to the algorithm. This is for fine fundamental US Equity data and /// will be executed on day changes in the NewYork time zone (<see cref="TimeZones.NewYork"/> /// </summary> /// <param name="universe">The universe to be filtered with fine fundamental selection</param> /// <param name="fineSelector">Defines a more detailed selection with access to more data</param> public Universe AddUniverse(Universe universe, Func<IEnumerable<FineFundamental>, IEnumerable<Symbol>> fineSelector) { return AddUniverse(new FineFundamentalFilteredUniverse(universe, fineSelector)); } /// <summary> /// Creates a new universe and adds it to the algorithm. This can be used to return a list of string /// symbols retrieved from anywhere and will loads those symbols under the US Equity market. /// </summary> /// <param name="name">A unique name for this universe</param> /// <param name="selector">Function delegate that accepts a DateTime and returns a collection of string symbols</param> public Universe AddUniverse(string name, Func<DateTime, IEnumerable<string>> selector) { return AddUniverse(SecurityType.Equity, name, Resolution.Daily, Market.USA, UniverseSettings, selector); } /// <summary> /// Creates a new universe and adds it to the algorithm. This can be used to return a list of string /// symbols retrieved from anywhere and will loads those symbols under the US Equity market. /// </summary> /// <param name="name">A unique name for this universe</param> /// <param name="resolution">The resolution this universe should be triggered on</param> /// <param name="selector">Function delegate that accepts a DateTime and returns a collection of string symbols</param> public Universe AddUniverse(string name, Resolution resolution, Func<DateTime, IEnumerable<string>> selector) { return AddUniverse(SecurityType.Equity, name, resolution, Market.USA, UniverseSettings, selector); } /// <summary> /// Creates a new user defined universe that will fire on the requested resolution during market hours. /// </summary> /// <param name="securityType">The security type of the universe</param> /// <param name="name">A unique name for this universe</param> /// <param name="resolution">The resolution this universe should be triggered on</param> /// <param name="market">The market of the universe</param> /// <param name="universeSettings">The subscription settings used for securities added from this universe</param> /// <param name="selector">Function delegate that accepts a DateTime and returns a collection of string symbols</param> public Universe AddUniverse(SecurityType securityType, string name, Resolution resolution, string market, UniverseSettings universeSettings, Func<DateTime, IEnumerable<string>> selector) { var marketHoursDbEntry = MarketHoursDatabase.GetEntry(market, name, securityType); var dataTimeZone = marketHoursDbEntry.DataTimeZone; var exchangeTimeZone = marketHoursDbEntry.ExchangeHours.TimeZone; var symbol = QuantConnect.Symbol.Create(name, securityType, market); var config = new SubscriptionDataConfig(typeof(CoarseFundamental), symbol, resolution, dataTimeZone, exchangeTimeZone, false, false, true, isFilteredSubscription: false); return AddUniverse(new UserDefinedUniverse(config, universeSettings, resolution.ToTimeSpan(), selector)); } /// <summary> /// Adds a new universe that creates options of the security by monitoring any changes in the Universe the provided security is in. /// Additionally, a filter can be applied to the options generated when the universe of the security changes. /// </summary> /// <param name="underlyingSymbol">Underlying Symbol to add as an option. For Futures, the option chain constructed will be per-contract, as long as a canonical Symbol is provided.</param> /// <param name="optionFilter">User-defined filter used to select the options we want out of the option chain provided.</param> /// <exception cref="InvalidOperationException">The underlying Symbol's universe is not found.</exception> public void AddUniverseOptions(Symbol underlyingSymbol, Func<OptionFilterUniverse, OptionFilterUniverse> optionFilter) { // We need to load the universe associated with the provided Symbol and provide that universe to the option filter universe. // The option filter universe will subscribe to any changes in the universe of the underlying Symbol, // ensuring that we load the option chain for every asset found in the underlying's Universe. Universe universe; if (!UniverseManager.TryGetValue(underlyingSymbol, out universe)) { // The universe might be already added, but not registered with the UniverseManager. universe = _pendingUniverseAdditions.SingleOrDefault(u => u.Configuration.Symbol == underlyingSymbol); if (universe == null) { underlyingSymbol = AddSecurity(underlyingSymbol).Symbol; } // Recheck again, we should have a universe addition pending for the provided Symbol universe = _pendingUniverseAdditions.SingleOrDefault(u => u.Configuration.Symbol == underlyingSymbol); if (universe == null) { // Should never happen, but it could be that the subscription // created with AddSecurity is not aligned with the Symbol we're using. throw new InvalidOperationException($"Universe not found for underlying Symbol: {underlyingSymbol}."); } } // Allow all option contracts through without filtering if we're provided a null filter. AddUniverseOptions(universe, optionFilter ?? (_ => _)); } /// <summary> /// Creates a new universe selection model and adds it to the algorithm. This universe selection model will chain to the security /// changes of a given <see cref="Universe"/> selection output and create a new <see cref="OptionChainUniverse"/> for each of them /// </summary> /// <param name="universe">The universe we want to chain an option universe selection model too</param> /// <param name="optionFilter">The option filter universe to use</param> public void AddUniverseOptions(Universe universe, Func<OptionFilterUniverse, OptionFilterUniverse> optionFilter) { AddUniverseSelection(new OptionChainedUniverseSelectionModel(universe, optionFilter)); } /// <summary> /// Adds the security to the user defined universe /// </summary> /// <param name="security">The security to add</param> /// <param name="configurations">The <see cref="SubscriptionDataConfig"/> instances we want to add</param> private void AddToUserDefinedUniverse( Security security, List<SubscriptionDataConfig> configurations) { var subscription = configurations.First(); // if we are adding a non-internal security which already has an internal feed, we remove it first Security existingSecurity; if (Securities.TryGetValue(security.Symbol, out existingSecurity)) { if (!subscription.IsInternalFeed && existingSecurity.IsInternalFeed()) { var securityUniverse = UniverseManager.Select(x => x.Value).OfType<UserDefinedUniverse>().FirstOrDefault(x => x.Members.ContainsKey(security.Symbol)); securityUniverse?.Remove(security.Symbol); Securities.Remove(security.Symbol); } } Securities.Add(security); // add this security to the user defined universe Universe universe; var universeSymbol = UserDefinedUniverse.CreateSymbol(security.Type, security.Symbol.ID.Market); lock (_pendingUniverseAdditionsLock) { if (!UniverseManager.TryGetValue(universeSymbol, out universe)) { universe = _pendingUniverseAdditions.FirstOrDefault(x => x.Configuration.Symbol == universeSymbol); if (universe == null) { // create a new universe, these subscription settings don't currently get used // since universe selection proper is never invoked on this type of universe var uconfig = new SubscriptionDataConfig(subscription, symbol: universeSymbol, isInternalFeed: true, fillForward: false); if (security.Type == SecurityType.Base) { // set entry in market hours database for the universe subscription to match the custom data var symbolString = MarketHoursDatabase.GetDatabaseSymbolKey(uconfig.Symbol); MarketHoursDatabase.SetEntry(uconfig.Market, symbolString, uconfig.SecurityType, security.Exchange.Hours, uconfig.DataTimeZone); } universe = new UserDefinedUniverse(uconfig, new UniverseSettings( subscription.Resolution, security.Leverage, subscription.FillDataForward, subscription.ExtendedMarketHours, TimeSpan.Zero), QuantConnect.Time.MaxTimeSpan, new List<Symbol>()); AddUniverse(universe); } } } var userDefinedUniverse = universe as UserDefinedUniverse; if (userDefinedUniverse != null) { lock (_pendingUniverseAdditionsLock) { _pendingUserDefinedUniverseSecurityAdditions.Add( new UserDefinedUniverseAddition(userDefinedUniverse, configurations, security)); } } else { // should never happen, someone would need to add a non-user defined universe with this symbol throw new Exception("Expected universe with symbol '" + universeSymbol.Value + "' to be of type UserDefinedUniverse."); } } /// <summary> /// Configures the security to be in raw data mode and ensures that a reasonable default volatility model is supplied /// </summary> /// <param name="security">The underlying security</param> private void ConfigureUnderlyingSecurity(Security security) { // force underlying securities to be raw data mode var configs = SubscriptionManager.SubscriptionDataConfigService .GetSubscriptionDataConfigs(security.Symbol); if (configs.DataNormalizationMode() != DataNormalizationMode.Raw) { // Add this symbol to our set of raw normalization warning symbols to alert the user at the end // Set a hard limit to avoid growing this collection unnecessarily large if (_rawNormalizationWarningSymbols != null && _rawNormalizationWarningSymbols.Count <= _rawNormalizationWarningSymbolsMaxCount) { _rawNormalizationWarningSymbols.Add(security.Symbol); } configs.SetDataNormalizationMode(DataNormalizationMode.Raw); // For backward compatibility we need to refresh the security DataNormalizationMode Property security.RefreshDataNormalizationModeProperty(); } // ensure a volatility model has been set on the underlying if (security.VolatilityModel == VolatilityModel.Null) { var config = configs.FirstOrDefault(); var bar = config?.Type.GetBaseDataInstance() ?? typeof(TradeBar).GetBaseDataInstance(); bar.Symbol = security.Symbol; var maxSupportedResolution = bar.SupportedResolutions().Max(); var updateFrequency = maxSupportedResolution.ToTimeSpan(); int periods; switch (maxSupportedResolution) { case Resolution.Tick: case Resolution.Second: periods = 600; break; case Resolution.Minute: periods = 60 * 24; break; case Resolution.Hour: periods = 24 * 30; break; default: periods = 30; break; } security.VolatilityModel = new StandardDeviationOfReturnsVolatilityModel(periods, maxSupportedResolution, updateFrequency); } } /// <summary> /// Helper class used to store <see cref="UserDefinedUniverse"/> additions. /// They will be consumed at <see cref="OnEndOfTimeStep"/> /// </summary> private class UserDefinedUniverseAddition { public Security Security { get; } public UserDefinedUniverse Universe { get; } public List<SubscriptionDataConfig> SubscriptionDataConfigs { get; } public UserDefinedUniverseAddition( UserDefinedUniverse universe, List<SubscriptionDataConfig> subscriptionDataConfigs, Security security) { Universe = universe; SubscriptionDataConfigs = subscriptionDataConfigs; Security = security; } } } }
#region license // Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // // DO NOT EDIT THIS FILE! // // This file was generated automatically by astgen.boo. // namespace Boo.Lang.Compiler.Ast { using System.Collections; using System.Runtime.Serialization; [System.Serializable] public partial class GenericReferenceExpression : Expression { protected Expression _target; protected TypeReferenceCollection _genericArguments; [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public GenericReferenceExpression CloneNode() { return (GenericReferenceExpression)Clone(); } /// <summary> /// <see cref="Node.CleanClone"/> /// </summary> [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] new public GenericReferenceExpression CleanClone() { return (GenericReferenceExpression)base.CleanClone(); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public NodeType NodeType { get { return NodeType.GenericReferenceExpression; } } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public void Accept(IAstVisitor visitor) { visitor.OnGenericReferenceExpression(this); } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Matches(Node node) { if (node == null) return false; if (NodeType != node.NodeType) return false; var other = ( GenericReferenceExpression)node; if (!Node.Matches(_target, other._target)) return NoMatch("GenericReferenceExpression._target"); if (!Node.AllMatch(_genericArguments, other._genericArguments)) return NoMatch("GenericReferenceExpression._genericArguments"); return true; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public bool Replace(Node existing, Node newNode) { if (base.Replace(existing, newNode)) { return true; } if (_target == existing) { this.Target = (Expression)newNode; return true; } if (_genericArguments != null) { TypeReference item = existing as TypeReference; if (null != item) { TypeReference newItem = (TypeReference)newNode; if (_genericArguments.Replace(item, newItem)) { return true; } } } return false; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override public object Clone() { GenericReferenceExpression clone = new GenericReferenceExpression(); clone._lexicalInfo = _lexicalInfo; clone._endSourceLocation = _endSourceLocation; clone._documentation = _documentation; clone._isSynthetic = _isSynthetic; clone._entity = _entity; if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone(); clone._expressionType = _expressionType; if (null != _target) { clone._target = _target.Clone() as Expression; clone._target.InitializeParent(clone); } if (null != _genericArguments) { clone._genericArguments = _genericArguments.Clone() as TypeReferenceCollection; clone._genericArguments.InitializeParent(clone); } return clone; } [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] override internal void ClearTypeSystemBindings() { _annotations = null; _entity = null; _expressionType = null; if (null != _target) { _target.ClearTypeSystemBindings(); } if (null != _genericArguments) { _genericArguments.ClearTypeSystemBindings(); } } [System.Xml.Serialization.XmlElement] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public Expression Target { get { return _target; } set { if (_target != value) { _target = value; if (null != _target) { _target.InitializeParent(this); } } } } [System.Xml.Serialization.XmlArray] [System.Xml.Serialization.XmlArrayItem(typeof(TypeReference))] [System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")] public TypeReferenceCollection GenericArguments { get { return _genericArguments ?? (_genericArguments = new TypeReferenceCollection(this)); } set { if (_genericArguments != value) { _genericArguments = value; if (null != _genericArguments) { _genericArguments.InitializeParent(this); } } } } } }
using UnityEngine; using System.Collections; public class SimpleEnemyAIBehavior : MonoBehaviour { //Inspector initiated variables. Defaults are set for ease of use. public bool on = true; //Is the AI active? this can be used to place pre-set enemies in you scene. public bool canFly = false; //Flying alters float behavior to ignore gravity. The enemy will fly up or down only to sustain floatHeight level. public float floatHeight = 0.0f; //If it can fly/hover, you need to let the AI know how high off the ground it should be. public bool runAway = false; //Is it the goal of this AI to keep it's distance? If so, it needs to have runaway active. public bool runTo = false; //Opposite to runaway, within a certain distance, the enemy will run toward the target. public float runDistance = 25.0f; //If the enemy should keep its distance, or charge in, at what point should they begin to run? public float runBufferDistance = 50.0f; //Smooth AI buffer. How far apart does AI/Target need to be before the run reason is ended. public int walkSpeed = 10; //Standard movement speed. public int runSpeed = 15; //Movement speed if it needs to run. public int randomSpeed = 10; //Movement speed if the AI is moving in random directions. public float rotationSpeed = 20.0f; //Rotation during movement modifier. If AI starts spinning at random, increase this value. (First check to make sure it's not due to visual radius limitations) public float visualRadius = 100.0f; //How close does the player need to be to be seen by the enemy? Set to 0 to remove this limitation. public float moveableRadius = 200.0f; //If the player is too far away, the AI will auto-matically shut down. Set to 0 to remove this limitation. public float attackRange = 10.0f; //How close does the enemy need to be in order to attack? public float attackTime = 0.50f; //How frequent or fast an enemy can attack (cool down time). public bool useWaypoints = false; //If true, the AI will make use of the waypoints assigned to it until over-ridden by another functionality. public bool reversePatrol = true; //if true, patrol units will walk forward and backward along their patrol. public Transform[] waypoints; //define a set path for them to follow. public bool pauseAtWaypoints = false; //if true, patrol units will pause momentarily at each waypoint as they reach them. public float pauseMin = 1.0f; //If pauseAtWaypoints is true, the unit will pause momentarily for minmum of this time. public float pauseMax = 3.0f; //If pauseAtWaypoints is true, the unit will pause momentarily formaximum of this time. public float huntingTimer = 5.0f; //Search for player timer in seconds. Minimum of 0.1 public bool estimateElevation = false; //This implements a pause between raycasts for heights and guestimates the need to move up/down in height based on the previous raycast. public float estRayTimer = 1.0f; //The amount of time in seconds between raycasts for gravity and elevation checks. public bool requireTarget = true; //Waypoint ONLY functionality (still can fly and hover). public Transform target; //The target, or whatever the AI is looking for. //private script handled variables private bool initialGo = false; //AI cannot function until it is initialized. private bool go = true; //An on/off override variable private Vector3 lastVisTargetPos; //Monitor target position if we lose sight of target. provides semi-intelligent AI. CharacterController characterController; //CC used for enemy movement and etc. private bool playerHasBeenSeen = false; //An enhancement to how the AI functions prior to visibly seeing the target. Brings AI to life when target is close, but not visible. private bool enemyCanAttack = false; //Used to determine if the enemy is within range to attack, regardless of moving or not. private bool enemyIsAttacking = false; //An attack interuption method. private bool executeBufferState = false; //Smooth AI buffer for runAway AI. Also used as a speed control variable. private bool walkInRandomDirection = false; //Speed control variable. private float lastShotFired; //Used in conjuction with attackTime to monitor attack durations. private float lostPlayerTimer; //Used for hunting down the player. private bool targetIsOutOfSight; //Player tracking overload prevention. Makes sure we do not call the same coroutines over and over. private Vector3 randomDirection; //Random movement behaviour setting. private float randomDirectionTimer; //Random movement behaviour tracking. private float gravity = 20.0f; //force of gravity pulling the enemy down. private float antigravity = 2.0f; //force at which floating/flying enemies repel private float estHeight = 0.0f; //floating/flying creatures using estimated elevation use this to estimate height necessities and gravity impacts. private float estGravityTimer = 0.0f; //floating/flying creatures using estimated elevation will use this to actually monitor time values. private int estCheckDirection = 0; //used to determine if AI is falling or not when estimating elevation. private bool wpCountdown = false; //used to determine if we're moving forward or backward through the waypoints. private bool monitorRunTo = false; //when AI is set to runTo, they will charge in, and then not charge again to after far enough away. private int wpPatrol = 0; //determines what waypoint we are heading toward. private bool pauseWpControl; //makes sure unit pauses appropriately. private bool smoothAttackRangeBuffer = false; //for runAway AI to not be so messed up by their visual radius and attack range. //---Starting/Initializing functions---// void Start() { StartCoroutine(Initialize()); //co-routine is used incase you need to interupt initiialization until something else is done. } IEnumerator Initialize() { if ((estimateElevation) && (floatHeight > 0.0f)) { estGravityTimer = Time.time; } characterController = gameObject.GetComponent<CharacterController>(); initialGo = true; yield return null; } //---Main Functionality---// void Update () { /* float range = 2.0f; Vector3 fwd = Vector3.forward; if(Physics.Raycast(transform.position, fwd, range)) { transform.Rotate (0,90,0); if(Physics.Raycast(transform.position, fwd, range)) { transform.Rotate (0,90,0); if(Physics.Raycast(transform.position, fwd, range)) { characterController.Move (fwd * 20 * Time.deltaTime); } } else { characterController.Move (fwd * 20 * Time.deltaTime); } }*/ if (!on || !initialGo) { return; } else { AIFunctionality(); } } void AIFunctionality() { if ((!target) && (requireTarget)) { return; //if no target was set and we require one, AI will not function. } //Functionality Updates lastVisTargetPos = target.position; //Target tracking method for semi-intelligent AI Vector3 moveToward = lastVisTargetPos - transform.position; //Used to face the AI in the direction of the target Vector3 moveAway = transform.position - lastVisTargetPos; //Used to face the AI away from the target when running away float distance = Vector3.Distance(transform.position, target.position); if (go) { MonitorGravity(); } if (!requireTarget) { //waypoint only functionality Patrol(); } else if (TargetIsInSight ()) { if (!go) { //useWaypoints is false and the player has exceeded moveableRadius, shutdown AI until player is near. return; } if ((distance > attackRange) && (!runAway) && (!runTo)) { enemyCanAttack = false; //the target is too far away to attack MoveTowards (moveToward); //move closer } else if ((smoothAttackRangeBuffer) && (distance > attackRange+5.0f)) { smoothAttackRangeBuffer = false; WalkNewPath(); }else if ((runAway || runTo) && (distance > runDistance) && (!executeBufferState)) { //move in random directions. if (monitorRunTo) { monitorRunTo = false; } if (runAway) { WalkNewPath (); } else { MoveTowards (moveToward); } } else if ((runAway || runTo) && (distance < runDistance) && (!executeBufferState)) { //make sure they do not get too close to the target //AHH! RUN AWAY!... or possibly charge :D enemyCanAttack = false; //can't attack, we're running! if (!monitorRunTo) { executeBufferState = true; //smooth buffer is now active! } walkInRandomDirection = false; //obviously we're no longer moving at random. if (runAway) { MoveTowards (moveAway); //move away } else { MoveTowards (moveToward); //move toward } } else if (executeBufferState && ((runAway) && (distance < runBufferDistance)) || ((runTo) && (distance > runBufferDistance))) { //continue to run! if (runAway) { MoveTowards (moveAway); //move away } else { MoveTowards (moveToward); //move toward } } else if ((executeBufferState) && (((runAway) && (distance > runBufferDistance)) || ((runTo) && (distance < runBufferDistance)))) { monitorRunTo = true; //make sure that when we have made it to our buffer distance (close to user) we stop the charge until far enough away. executeBufferState = false; //go back to normal activity } //start attacking if close enough if ((distance < attackRange) || ((!runAway && !runTo) && (distance < runDistance))) { if (runAway) { smoothAttackRangeBuffer = true; } if (Time.time > lastShotFired + attackTime) { StartCoroutine(Attack()); } } } else if ((playerHasBeenSeen) && (!targetIsOutOfSight) && (go)) { lostPlayerTimer = Time.time + huntingTimer; StartCoroutine(HuntDownTarget(lastVisTargetPos)); } else if (useWaypoints) { Patrol(); } else if (((!playerHasBeenSeen) && (go)) && ((moveableRadius == 0) || (distance < moveableRadius))){ //the idea here is that the enemy has not yet seen the player, but the player is fairly close while still not visible by the enemy //it will move in a random direction continuously altering its direction every 2 seconds until it does see the player. WalkNewPath(); } } //attack stuff... IEnumerator Attack() { enemyCanAttack = true; if (!enemyIsAttacking) { enemyIsAttacking = true; while (enemyCanAttack) { lastShotFired = Time.time; //implement attack variables here yield return new WaitForSeconds(attackTime); } } } //----Helper Functions---// //verify enemy can see the target bool TargetIsInSight () { //determine if the enemy should be doing anything other than standing still if ((moveableRadius > 0) && (Vector3.Distance(transform.position, target.position) > moveableRadius)) { go = false; } else { go = true; } //then lets make sure the target is within the vision radius we allowed our enemy //remember, 0 radius means to ignore this check if ((visualRadius > 0) && (Vector3.Distance(transform.position, target.position) > visualRadius)) { return false; } //Now check to make sure nothing is blocking the line of sight RaycastHit sight; if (Physics.Linecast(transform.position, target.position, out sight)) { if (!playerHasBeenSeen && sight.transform == target) { playerHasBeenSeen = true; } return sight.transform == target; } else { return false; } } //target tracking IEnumerator HuntDownTarget (Vector3 position) { //if this function is called, the enemy has lost sight of the target and must track him down! //assuming AI is not too intelligent, they will only move toward his last position, and hope they see him //this can be fixed later to update the lastVisTargetPos every couple of seconds to leave some kind of trail targetIsOutOfSight = true; while (targetIsOutOfSight) { Vector3 moveToward = position - transform.position; MoveTowards (moveToward); //check if we found the target yet if (TargetIsInSight ()) { targetIsOutOfSight = false; break; } //check to see if we should give up our search if (Time.time > lostPlayerTimer) { targetIsOutOfSight = false; playerHasBeenSeen = false; break; } yield return null; } } void Patrol () { if (pauseWpControl) { return; } Vector3 destination = CurrentPath(); Vector3 moveToward = destination - transform.position; float distance = Vector3.Distance(transform.position, destination); MoveTowards (moveToward); if (distance <= 1.5f+floatHeight) {// || (distance < floatHeight+1.5f)) { if (pauseAtWaypoints) { if (!pauseWpControl) { pauseWpControl = true; StartCoroutine(WaypointPause()); } } else { NewPath(); } } } IEnumerator WaypointPause () { yield return new WaitForSeconds(Random.Range(pauseMin, pauseMax)); NewPath(); pauseWpControl = false; } Vector3 CurrentPath () { return waypoints[wpPatrol].position; } void NewPath () { if (!wpCountdown) { wpPatrol++; if (wpPatrol >= waypoints.GetLength(0)) { if (reversePatrol) { wpCountdown = true; wpPatrol -= 2; } else { wpPatrol = 0; } } } else if (reversePatrol) { wpPatrol--; if (wpPatrol < 0) { wpCountdown = false; wpPatrol = 1; } } } //random movement behaviour void WalkNewPath () { RaycastHit hit; float range = Mathf.Infinity; if (!walkInRandomDirection) { walkInRandomDirection = true; if (!playerHasBeenSeen) { randomDirection = new Vector3(Random.Range(-0.15f,0.15f),0,Random.Range(-0.15f,0.15f)); } else { randomDirection = new Vector3(Random.Range(-0.5f,0.5f),0,Random.Range(-0.5f,0.5f)); } randomDirectionTimer = Time.time; } else if (walkInRandomDirection) { MoveTowards (randomDirection); } if ((Time.time - randomDirectionTimer) > 2) { //choose a new random direction after 2 seconds walkInRandomDirection = false; } } //standard movement behaviour void MoveTowards (Vector3 direction) { direction.y = 0; int speed = walkSpeed; if (walkInRandomDirection) { speed = randomSpeed; } if (executeBufferState) { speed = runSpeed; } //rotate toward or away from the target transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(direction), rotationSpeed * Time.deltaTime); transform.eulerAngles = new Vector3(0, transform.eulerAngles.y, 0); //slow down when we are not facing the target Vector3 forward = transform.TransformDirection(Vector3.forward); float speedModifier = Vector3.Dot(forward, direction.normalized); speedModifier = Mathf.Clamp01(speedModifier); //actually move toward or away from the target direction = forward * speed * speedModifier; if ((!canFly) && (floatHeight <= 0.0f)) { direction.y -= gravity; } characterController.Move(direction * Time.deltaTime); } //continuous gravity checks void MonitorGravity () { Vector3 direction = new Vector3(0, 0, 0); if ((!canFly) && (floatHeight > 0.0f)) { //we need to make sure our enemy is floating.. using evil raycasts! bwahahahah! if ((estimateElevation) && (estRayTimer > 0.0f)) { if (Time.time > estGravityTimer) { RaycastHit floatCheck; if (Physics.Raycast(transform.position, -Vector3.up, out floatCheck)) { if (floatCheck.distance < floatHeight-0.5f) { estCheckDirection = 1; estHeight = floatHeight - floatCheck.distance; } else if (floatCheck.distance > floatHeight+0.5f) { estCheckDirection = 2; estHeight = floatCheck.distance - floatHeight; } else { estCheckDirection = 3; } } else { estCheckDirection = 2; estHeight = floatHeight*2; } estGravityTimer = Time.time + estRayTimer; } switch(estCheckDirection) { case 1: direction.y += antigravity; estHeight -= direction.y * Time.deltaTime; break; case 2: direction.y -= gravity; estHeight -= direction.y * Time.deltaTime; break; default: //do nothing break; } } else { RaycastHit floatCheck; if (Physics.Raycast(transform.position, -Vector3.up, out floatCheck, floatHeight+1.0f)) { if (floatCheck.distance < floatHeight) { direction.y += antigravity; } } else { direction.y -= gravity; } } } else { //bird like creature! Again with the evil raycasts! :p if ((estimateElevation) && (estRayTimer > 0.0f)) { if (Time.time > estGravityTimer) { RaycastHit floatCheck; if (Physics.Raycast(transform.position, -Vector3.up, out floatCheck)) { if (floatCheck.distance < floatHeight-0.5f) { estCheckDirection = 1; estHeight = floatHeight - floatCheck.distance; } else if (floatCheck.distance > floatHeight+0.5f) { estCheckDirection = 2; estHeight = floatCheck.distance - floatHeight; } else { estCheckDirection = 3; } } estGravityTimer = Time.time + estRayTimer; } switch(estCheckDirection) { case 1: direction.y += antigravity; estHeight -= direction.y * Time.deltaTime; break; case 2: direction.y -= antigravity; estHeight -= direction.y * Time.deltaTime; break; default: //do nothing break; } } else { RaycastHit floatCheck; if (Physics.Raycast(transform.position, -Vector3.up, out floatCheck)) { if (floatCheck.distance < floatHeight-0.5f) { direction.y += antigravity; } else if (floatCheck.distance > floatHeight+0.5f) { direction.y -= antigravity; } } } } if ((!estimateElevation) || ((estimateElevation) && (estHeight >= 0.0f))) { characterController.Move(direction * Time.deltaTime); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Cloud.Dataproc.V1 { /// <summary>Resource name for the <c>Cluster</c> resource.</summary> public sealed partial class ClusterName : gax::IResourceName, sys::IEquatable<ClusterName> { /// <summary>The possible contents of <see cref="ClusterName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/clusters/{cluster}</c>. /// </summary> ProjectLocationCluster = 1, } private static gax::PathTemplate s_projectLocationCluster = new gax::PathTemplate("projects/{project}/locations/{location}/clusters/{cluster}"); /// <summary>Creates a <see cref="ClusterName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="ClusterName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static ClusterName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new ClusterName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="ClusterName"/> with the pattern /// <c>projects/{project}/locations/{location}/clusters/{cluster}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="clusterId">The <c>Cluster</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ClusterName"/> constructed from the provided ids.</returns> public static ClusterName FromProjectLocationCluster(string projectId, string locationId, string clusterId) => new ClusterName(ResourceNameType.ProjectLocationCluster, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), clusterId: gax::GaxPreconditions.CheckNotNullOrEmpty(clusterId, nameof(clusterId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ClusterName"/> with pattern /// <c>projects/{project}/locations/{location}/clusters/{cluster}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="clusterId">The <c>Cluster</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ClusterName"/> with pattern /// <c>projects/{project}/locations/{location}/clusters/{cluster}</c>. /// </returns> public static string Format(string projectId, string locationId, string clusterId) => FormatProjectLocationCluster(projectId, locationId, clusterId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ClusterName"/> with pattern /// <c>projects/{project}/locations/{location}/clusters/{cluster}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="clusterId">The <c>Cluster</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ClusterName"/> with pattern /// <c>projects/{project}/locations/{location}/clusters/{cluster}</c>. /// </returns> public static string FormatProjectLocationCluster(string projectId, string locationId, string clusterId) => s_projectLocationCluster.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(clusterId, nameof(clusterId))); /// <summary>Parses the given resource name string into a new <see cref="ClusterName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/clusters/{cluster}</c></description></item> /// </list> /// </remarks> /// <param name="clusterName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="ClusterName"/> if successful.</returns> public static ClusterName Parse(string clusterName) => Parse(clusterName, false); /// <summary> /// Parses the given resource name string into a new <see cref="ClusterName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/clusters/{cluster}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="clusterName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="ClusterName"/> if successful.</returns> public static ClusterName Parse(string clusterName, bool allowUnparsed) => TryParse(clusterName, allowUnparsed, out ClusterName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ClusterName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/clusters/{cluster}</c></description></item> /// </list> /// </remarks> /// <param name="clusterName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="ClusterName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string clusterName, out ClusterName result) => TryParse(clusterName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ClusterName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/clusters/{cluster}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="clusterName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="ClusterName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string clusterName, bool allowUnparsed, out ClusterName result) { gax::GaxPreconditions.CheckNotNull(clusterName, nameof(clusterName)); gax::TemplatedResourceName resourceName; if (s_projectLocationCluster.TryParseName(clusterName, out resourceName)) { result = FromProjectLocationCluster(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(clusterName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private ClusterName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string clusterId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; ClusterId = clusterId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="ClusterName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/clusters/{cluster}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="clusterId">The <c>Cluster</c> ID. Must not be <c>null</c> or empty.</param> public ClusterName(string projectId, string locationId, string clusterId) : this(ResourceNameType.ProjectLocationCluster, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), clusterId: gax::GaxPreconditions.CheckNotNullOrEmpty(clusterId, nameof(clusterId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Cluster</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ClusterId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationCluster: return s_projectLocationCluster.Expand(ProjectId, LocationId, ClusterId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as ClusterName); /// <inheritdoc/> public bool Equals(ClusterName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(ClusterName a, ClusterName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(ClusterName a, ClusterName b) => !(a == b); } /// <summary>Resource name for the <c>Service</c> resource.</summary> public sealed partial class ServiceName : gax::IResourceName, sys::IEquatable<ServiceName> { /// <summary>The possible contents of <see cref="ServiceName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/services/{service}</c>. /// </summary> ProjectLocationService = 1, } private static gax::PathTemplate s_projectLocationService = new gax::PathTemplate("projects/{project}/locations/{location}/services/{service}"); /// <summary>Creates a <see cref="ServiceName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="ServiceName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static ServiceName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new ServiceName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="ServiceName"/> with the pattern /// <c>projects/{project}/locations/{location}/services/{service}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="ServiceName"/> constructed from the provided ids.</returns> public static ServiceName FromProjectLocationService(string projectId, string locationId, string serviceId) => new ServiceName(ResourceNameType.ProjectLocationService, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), serviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="ServiceName"/> with pattern /// <c>projects/{project}/locations/{location}/services/{service}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ServiceName"/> with pattern /// <c>projects/{project}/locations/{location}/services/{service}</c>. /// </returns> public static string Format(string projectId, string locationId, string serviceId) => FormatProjectLocationService(projectId, locationId, serviceId); /// <summary> /// Formats the IDs into the string representation of this <see cref="ServiceName"/> with pattern /// <c>projects/{project}/locations/{location}/services/{service}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="ServiceName"/> with pattern /// <c>projects/{project}/locations/{location}/services/{service}</c>. /// </returns> public static string FormatProjectLocationService(string projectId, string locationId, string serviceId) => s_projectLocationService.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId))); /// <summary>Parses the given resource name string into a new <see cref="ServiceName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/services/{service}</c></description></item> /// </list> /// </remarks> /// <param name="serviceName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="ServiceName"/> if successful.</returns> public static ServiceName Parse(string serviceName) => Parse(serviceName, false); /// <summary> /// Parses the given resource name string into a new <see cref="ServiceName"/> instance; optionally allowing an /// unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/services/{service}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="serviceName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="ServiceName"/> if successful.</returns> public static ServiceName Parse(string serviceName, bool allowUnparsed) => TryParse(serviceName, allowUnparsed, out ServiceName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ServiceName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/services/{service}</c></description></item> /// </list> /// </remarks> /// <param name="serviceName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="ServiceName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string serviceName, out ServiceName result) => TryParse(serviceName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="ServiceName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/services/{service}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="serviceName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="ServiceName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string serviceName, bool allowUnparsed, out ServiceName result) { gax::GaxPreconditions.CheckNotNull(serviceName, nameof(serviceName)); gax::TemplatedResourceName resourceName; if (s_projectLocationService.TryParseName(serviceName, out resourceName)) { result = FromProjectLocationService(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(serviceName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private ServiceName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string locationId = null, string projectId = null, string serviceId = null) { Type = type; UnparsedResource = unparsedResourceName; LocationId = locationId; ProjectId = projectId; ServiceId = serviceId; } /// <summary> /// Constructs a new instance of a <see cref="ServiceName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/services/{service}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="serviceId">The <c>Service</c> ID. Must not be <c>null</c> or empty.</param> public ServiceName(string projectId, string locationId, string serviceId) : this(ResourceNameType.ProjectLocationService, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), serviceId: gax::GaxPreconditions.CheckNotNullOrEmpty(serviceId, nameof(serviceId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary> /// The <c>Service</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ServiceId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectLocationService: return s_projectLocationService.Expand(ProjectId, LocationId, ServiceId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as ServiceName); /// <inheritdoc/> public bool Equals(ServiceName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(ServiceName a, ServiceName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(ServiceName a, ServiceName b) => !(a == b); } public partial class MetastoreConfig { /// <summary> /// <see cref="ServiceName"/>-typed view over the <see cref="DataprocMetastoreService"/> resource name property. /// </summary> public ServiceName DataprocMetastoreServiceAsServiceName { get => string.IsNullOrEmpty(DataprocMetastoreService) ? null : ServiceName.Parse(DataprocMetastoreService, allowUnparsed: true); set => DataprocMetastoreService = value?.ToString() ?? ""; } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. namespace WebsitePanel.Installer.Controls { partial class ServiceControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ServiceControl)); this.grpConnectionSettings = new System.Windows.Forms.GroupBox(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.btnAdd = new System.Windows.Forms.Button(); this.btnTest = new System.Windows.Forms.Button(); this.lblStatus = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.textBox1 = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.textBox2 = new System.Windows.Forms.TextBox(); this.button2 = new System.Windows.Forms.Button(); this.textBox3 = new System.Windows.Forms.TextBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.textBox4 = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.grpConnectionSettings.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // grpConnectionSettings // this.grpConnectionSettings.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.grpConnectionSettings.Controls.Add(this.pictureBox1); this.grpConnectionSettings.Controls.Add(this.btnAdd); this.grpConnectionSettings.Controls.Add(this.btnTest); this.grpConnectionSettings.Controls.Add(this.lblStatus); this.grpConnectionSettings.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.grpConnectionSettings.Location = new System.Drawing.Point(14, 3); this.grpConnectionSettings.Name = "grpConnectionSettings"; this.grpConnectionSettings.Size = new System.Drawing.Size(379, 66); this.grpConnectionSettings.TabIndex = 0; this.grpConnectionSettings.TabStop = false; this.grpConnectionSettings.Text = "Status"; // // pictureBox1 // this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image"))); this.pictureBox1.Location = new System.Drawing.Point(13, 20); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(32, 32); this.pictureBox1.TabIndex = 12; this.pictureBox1.TabStop = false; // // btnAdd // this.btnAdd.Enabled = false; this.btnAdd.Image = ((System.Drawing.Image)(resources.GetObject("btnAdd.Image"))); this.btnAdd.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnAdd.Location = new System.Drawing.Point(258, 20); this.btnAdd.Name = "btnAdd"; this.btnAdd.Size = new System.Drawing.Size(83, 28); this.btnAdd.TabIndex = 11; this.btnAdd.Text = "Stop"; this.btnAdd.UseVisualStyleBackColor = true; // // btnTest // this.btnTest.Enabled = false; this.btnTest.Image = ((System.Drawing.Image)(resources.GetObject("btnTest.Image"))); this.btnTest.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.btnTest.Location = new System.Drawing.Point(169, 20); this.btnTest.Name = "btnTest"; this.btnTest.Size = new System.Drawing.Size(83, 28); this.btnTest.TabIndex = 10; this.btnTest.Text = "Start"; this.btnTest.UseVisualStyleBackColor = true; // // lblStatus // this.lblStatus.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.lblStatus.Location = new System.Drawing.Point(51, 26); this.lblStatus.Name = "lblStatus"; this.lblStatus.Size = new System.Drawing.Size(112, 21); this.lblStatus.TabIndex = 0; this.lblStatus.Text = "Not installed"; // // label1 // this.label1.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.label1.Location = new System.Drawing.Point(16, 82); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(100, 21); this.label1.TabIndex = 4; this.label1.Text = "Password"; // // label2 // this.label2.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.label2.Location = new System.Drawing.Point(16, 55); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(100, 21); this.label2.TabIndex = 2; this.label2.Text = "Port"; // // textBox1 // this.textBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBox1.Location = new System.Drawing.Point(122, 28); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(234, 21); this.textBox1.TabIndex = 1; // // label3 // this.label3.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.label3.Location = new System.Drawing.Point(16, 28); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(100, 21); this.label3.TabIndex = 0; this.label3.Text = "Server"; // // textBox2 // this.textBox2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBox2.Location = new System.Drawing.Point(122, 55); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(234, 21); this.textBox2.TabIndex = 3; // // button2 // this.button2.Image = ((System.Drawing.Image)(resources.GetObject("button2.Image"))); this.button2.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button2.Location = new System.Drawing.Point(14, 240); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(128, 28); this.button2.TabIndex = 11; this.button2.Text = "Update settings"; this.button2.UseVisualStyleBackColor = true; // // textBox3 // this.textBox3.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBox3.Location = new System.Drawing.Point(122, 82); this.textBox3.Name = "textBox3"; this.textBox3.PasswordChar = '*'; this.textBox3.Size = new System.Drawing.Size(234, 21); this.textBox3.TabIndex = 5; // // groupBox1 // this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.groupBox1.Controls.Add(this.textBox4); this.groupBox1.Controls.Add(this.label4); this.groupBox1.Controls.Add(this.textBox3); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Controls.Add(this.textBox2); this.groupBox1.Controls.Add(this.label2); this.groupBox1.Controls.Add(this.textBox1); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.groupBox1.Location = new System.Drawing.Point(14, 81); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(379, 150); this.groupBox1.TabIndex = 10; this.groupBox1.TabStop = false; this.groupBox1.Text = "Connection settings"; // // textBox4 // this.textBox4.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.textBox4.Location = new System.Drawing.Point(122, 109); this.textBox4.Name = "textBox4"; this.textBox4.PasswordChar = '*'; this.textBox4.Size = new System.Drawing.Size(234, 21); this.textBox4.TabIndex = 7; // // label4 // this.label4.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); this.label4.Location = new System.Drawing.Point(16, 109); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(100, 21); this.label4.TabIndex = 6; this.label4.Text = "Confirm password"; // // ServiceControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.button2); this.Controls.Add(this.groupBox1); this.Controls.Add(this.grpConnectionSettings); this.Name = "ServiceControl"; this.Size = new System.Drawing.Size(406, 327); this.grpConnectionSettings.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.GroupBox grpConnectionSettings; private System.Windows.Forms.Label lblStatus; private System.Windows.Forms.Button btnAdd; private System.Windows.Forms.Button btnTest; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.Button button2; private System.Windows.Forms.TextBox textBox3; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.TextBox textBox4; private System.Windows.Forms.Label label4; } }
// Copyright (c) 2012, Event Store LLP // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // Neither the name of the Event Store LLP nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Collections.Generic; using System.Runtime.Serialization; using EventStore.Projections.Core.Messages; namespace EventStore.Projections.Core.Services.Processing { public sealed class SourceDefinitionBuilder: IQuerySources // name it!! { private readonly QuerySourceOptions _options = new QuerySourceOptions(); private bool _allStreams; private List<string> _categories; private List<string> _streams; private string _catalogStream; private bool _allEvents; private List<string> _events; private bool _byStream; private bool _byCustomPartitions; private long? _limitingCommitPosotion; public SourceDefinitionBuilder() { _options.DefinesFold = true; } public void FromAll() { _allStreams = true; } public void FromCategory(string categoryName) { if (_categories == null) _categories = new List<string>(); _categories.Add(categoryName); } public void FromStream(string streamName) { if (_streams == null) _streams = new List<string>(); _streams.Add(streamName); } public void FromCatalogStream(string catalogStream) { _catalogStream = catalogStream; } public void AllEvents() { _allEvents = true; } public void SetIncludeLinks(bool includeLinks = true) { _options.IncludeLinks = includeLinks; } public void SetDisableParallelism(bool disableParallelism = true) { _options.DisableParallelism = disableParallelism; } public void IncludeEvent(string eventName) { if (_events == null) _events = new List<string>(); _events.Add(eventName); } public void SetByStream() { _byStream = true; } public void SetByCustomPartitions() { _byCustomPartitions = true; } public void SetDefinesStateTransform() { _options.DefinesStateTransform = true; _options.ProducesResults = true; } public void SetOutputState() { _options.ProducesResults = true; } public void NoWhen() { _options.DefinesFold = false; } public void SetResultStreamNameOption(string resultStreamName) { _options.ResultStreamName = String.IsNullOrWhiteSpace(resultStreamName) ? null : resultStreamName; } public void SetPartitionResultStreamNamePatternOption(string partitionResultStreamNamePattern) { _options.PartitionResultStreamNamePattern = String.IsNullOrWhiteSpace(partitionResultStreamNamePattern) ? null : partitionResultStreamNamePattern; } public void SetForceProjectionName(string forceProjectionName) { _options.ForceProjectionName = String.IsNullOrWhiteSpace(forceProjectionName) ? null : forceProjectionName; } public void SetReorderEvents(bool reorderEvents) { _options.ReorderEvents = reorderEvents; } public void SetProcessingLag(int processingLag) { _options.ProcessingLag = processingLag; } public void SetIsBiState(bool isBiState) { _options.IsBiState = isBiState; } public void SetHandlesStreamDeletedNotifications(bool value = true) { _options.HandlesDeletedNotifications = value; } public bool AllStreams { get { return _allStreams; } } public string[] Categories { get { return _categories != null ? _categories.ToArray() : null; } } public string[] Streams { get { return _streams != null ? _streams.ToArray() : null; } } public string CatalogStream { get { return _catalogStream; } } bool IQuerySources.AllEvents { get { return _allEvents; } } public string[] Events { get { return _events != null ? _events.ToArray() : null; } } public bool ByStreams { get { return _byStream; } } public bool ByCustomPartitions { get { return _byCustomPartitions; } } public long? LimitingCommitPosition { get { return _limitingCommitPosotion; } } public bool DefinesStateTransform { get { return _options.DefinesStateTransform; } } public bool DefinesCatalogTransform { get { return _options.DefinesCatalogTransform; } } public bool ProducesResults { get { return _options.ProducesResults; } } public bool DefinesFold { get { return _options.DefinesFold; } } public bool HandlesDeletedNotifications { get { return _options.HandlesDeletedNotifications; } } public bool IncludeLinksOption { get { return _options.IncludeLinks; } } public bool DisableParallelismOption { get { return _options.DisableParallelism; } } public string ResultStreamNameOption { get { return _options.ResultStreamName; } } public string PartitionResultStreamNamePatternOption { get { return _options.PartitionResultStreamNamePattern; } } public string ForceProjectionNameOption { get { return _options.ForceProjectionName; } } public bool ReorderEventsOption { get { return _options.ReorderEvents; } } public int? ProcessingLagOption { get { return _options.ProcessingLag; } } public bool IsBiState { get { return _options.IsBiState; } } public static IQuerySources From(Action<SourceDefinitionBuilder> configure) { var b = new SourceDefinitionBuilder(); configure(b); return b.Build(); } public IQuerySources Build() { return QuerySourcesDefinition.From(this); } public void SetLimitingCommitPosition(long limitingCommitPosition) { _limitingCommitPosotion = limitingCommitPosition; } } [DataContract] public class QuerySourceOptions { [DataMember] public string ResultStreamName { get; set; } [DataMember] public string PartitionResultStreamNamePattern { get; set; } [DataMember] public string ForceProjectionName { get; set; } [DataMember] public bool ReorderEvents { get; set; } [DataMember] public int ProcessingLag { get; set; } [DataMember] public bool IsBiState { get; set; } [DataMember] public bool DefinesStateTransform { get; set; } [DataMember] public bool DefinesCatalogTransform { get; set; } [DataMember] public bool ProducesResults { get; set; } [DataMember] public bool DefinesFold { get; set; } [DataMember] public bool HandlesDeletedNotifications { get; set; } [DataMember] public bool IncludeLinks { get; set; } [DataMember] public bool DisableParallelism { get; set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.CompilerServices; using System.Diagnostics; using System.Threading; using System.Runtime; using Xunit; namespace System.Tests { public static partial class GCTests { private static bool s_is32Bits = IntPtr.Size == 4; // Skip IntPtr tests on 32-bit platforms [Fact] public static void AddMemoryPressure_InvalidBytesAllocated_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("bytesAllocated", () => GC.AddMemoryPressure(-1)); // Bytes allocated < 0 if (s_is32Bits) { AssertExtensions.Throws<ArgumentOutOfRangeException>("pressure", () => GC.AddMemoryPressure((long)int.MaxValue + 1)); // Bytes allocated > int.MaxValue on 32 bit platforms } } [Fact] public static void Collect_Int() { for (int i = 0; i < GC.MaxGeneration + 10; i++) { GC.Collect(i); } } [Fact] public static void Collect_Int_NegativeGeneration_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("generation", () => GC.Collect(-1)); // Generation < 0 } [Theory] [InlineData(GCCollectionMode.Default)] [InlineData(GCCollectionMode.Forced)] public static void Collect_Int_GCCollectionMode(GCCollectionMode mode) { for (int gen = 0; gen <= 2; gen++) { var b = new byte[1024 * 1024 * 10]; int oldCollectionCount = GC.CollectionCount(gen); b = null; GC.Collect(gen, mode); Assert.True(GC.CollectionCount(gen) > oldCollectionCount); } } [Fact] public static void Collect_NegativeGenerationCount_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("generation", () => GC.Collect(-1, GCCollectionMode.Default)); AssertExtensions.Throws<ArgumentOutOfRangeException>("generation", () => GC.Collect(-1, GCCollectionMode.Default, false)); } [Theory] [InlineData(GCCollectionMode.Default - 1)] [InlineData(GCCollectionMode.Optimized + 1)] public static void Collection_InvalidCollectionMode_ThrowsArgumentOutOfRangeException(GCCollectionMode mode) { AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", null, () => GC.Collect(2, mode)); AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", null, () => GC.Collect(2, mode, false)); } [Fact] public static void Collect_CallsFinalizer() { FinalizerTest.Run(); } private class FinalizerTest { [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void MakeAndDropTest() { new TestObject(); } public static void Run() { MakeAndDropTest(); GC.Collect(); // Make sure Finalize() is called GC.WaitForPendingFinalizers(); Assert.True(TestObject.Finalized); } private class TestObject { public static bool Finalized { get; private set; } ~TestObject() { Finalized = true; } } } [Fact] public static void KeepAlive() { KeepAliveTest.Run(); } private class KeepAliveTest { [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void MakeAndDropDNKA() { new DoNotKeepAliveObject(); } public static void Run() { var keepAlive = new KeepAliveObject(); MakeAndDropDNKA(); GC.Collect(); GC.WaitForPendingFinalizers(); Assert.True(DoNotKeepAliveObject.Finalized); Assert.False(KeepAliveObject.Finalized); GC.KeepAlive(keepAlive); } private class KeepAliveObject { public static bool Finalized { get; private set; } ~KeepAliveObject() { Finalized = true; } } private class DoNotKeepAliveObject { public static bool Finalized { get; private set; } ~DoNotKeepAliveObject() { Finalized = true; } } } [Fact] public static void KeepAlive_Null() { KeepAliveNullTest.Run(); } private class KeepAliveNullTest { [System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void MakeAndNull() { var obj = new TestObject(); obj = null; } public static void Run() { MakeAndNull(); GC.Collect(); GC.WaitForPendingFinalizers(); Assert.True(TestObject.Finalized); } private class TestObject { public static bool Finalized { get; private set; } ~TestObject() { Finalized = true; } } } [Fact] public static void KeepAlive_Recursive() { KeepAliveRecursiveTest.Run(); } private class KeepAliveRecursiveTest { public static void Run() { int recursionCount = 0; RunWorker(new TestObject(), ref recursionCount); } private static void RunWorker(object obj, ref int recursionCount) { if (recursionCount++ == 10) return; GC.Collect(); GC.WaitForPendingFinalizers(); RunWorker(obj, ref recursionCount); Assert.False(TestObject.Finalized); GC.KeepAlive(obj); } private class TestObject { public static bool Finalized { get; private set; } ~TestObject() { Finalized = true; } } } [Fact] public static void SuppressFinalizer() { SuppressFinalizerTest.Run(); } private class SuppressFinalizerTest { public static void Run() { var obj = new TestObject(); GC.SuppressFinalize(obj); obj = null; GC.Collect(); GC.WaitForPendingFinalizers(); Assert.False(TestObject.Finalized); } private class TestObject { public static bool Finalized { get; private set; } ~TestObject() { Finalized = true; } } } [Fact] public static void SuppressFinalizer_NullObject_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("obj", () => GC.SuppressFinalize(null)); // Obj is null } [Fact] public static void ReRegisterForFinalize() { ReRegisterForFinalizeTest.Run(); } [Fact] public static void ReRegisterFoFinalize_NullObject_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("obj", () => GC.ReRegisterForFinalize(null)); // Obj is null } private class ReRegisterForFinalizeTest { public static void Run() { TestObject.Finalized = false; CreateObject(); GC.Collect(); GC.WaitForPendingFinalizers(); Assert.True(TestObject.Finalized); } private static void CreateObject() { using (var obj = new TestObject()) { GC.SuppressFinalize(obj); } } private class TestObject : IDisposable { public static bool Finalized { get; set; } ~TestObject() { Finalized = true; } public void Dispose() { GC.ReRegisterForFinalize(this); } } } [Fact] public static void CollectionCount_NegativeGeneration_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("generation", () => GC.CollectionCount(-1)); // Generation < 0 } [Fact] public static void RemoveMemoryPressure_InvalidBytesAllocated_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("bytesAllocated", () => GC.RemoveMemoryPressure(-1)); // Bytes allocated < 0 if (s_is32Bits) { AssertExtensions.Throws<ArgumentOutOfRangeException>("bytesAllocated", () => GC.RemoveMemoryPressure((long)int.MaxValue + 1)); // Bytes allocated > int.MaxValue on 32 bit platforms } } [Fact] public static void GetTotalMemoryTest_ForceCollection() { // We don't test GetTotalMemory(false) at all because a collection // could still occur even if not due to the GetTotalMemory call, // and as such there's no way to validate the behavior. We also // don't verify a tighter bound for the result of GetTotalMemory // because collections could cause significant fluctuations. GC.Collect(); int gen0 = GC.CollectionCount(0); int gen1 = GC.CollectionCount(1); int gen2 = GC.CollectionCount(2); Assert.InRange(GC.GetTotalMemory(true), 1, long.MaxValue); Assert.InRange(GC.CollectionCount(0), gen0 + 1, int.MaxValue); Assert.InRange(GC.CollectionCount(1), gen1 + 1, int.MaxValue); Assert.InRange(GC.CollectionCount(2), gen2 + 1, int.MaxValue); } [Fact] public static void GetGeneration() { // We don't test a tighter bound on GetGeneration as objects // can actually get demoted or stay in the same generation // across collections. GC.Collect(); var obj = new object(); for (int i = 0; i <= GC.MaxGeneration + 1; i++) { Assert.InRange(GC.GetGeneration(obj), 0, GC.MaxGeneration); GC.Collect(); } } [Theory] [InlineData(GCLargeObjectHeapCompactionMode.CompactOnce)] [InlineData(GCLargeObjectHeapCompactionMode.Default)] public static void LargeObjectHeapCompactionModeRoundTrips(GCLargeObjectHeapCompactionMode value) { GCLargeObjectHeapCompactionMode orig = GCSettings.LargeObjectHeapCompactionMode; try { GCSettings.LargeObjectHeapCompactionMode = value; Assert.Equal(value, GCSettings.LargeObjectHeapCompactionMode); } finally { GCSettings.LargeObjectHeapCompactionMode = orig; Assert.Equal(orig, GCSettings.LargeObjectHeapCompactionMode); } } [Theory] [InlineData(GCLatencyMode.Batch)] [InlineData(GCLatencyMode.Interactive)] public static void LatencyRoundtrips(GCLatencyMode value) { GCLatencyMode orig = GCSettings.LatencyMode; try { GCSettings.LatencyMode = value; Assert.Equal(value, GCSettings.LatencyMode); } finally { GCSettings.LatencyMode = orig; Assert.Equal(orig, GCSettings.LatencyMode); } } [Theory] [PlatformSpecific(TestPlatforms.Windows)] //Concurrent GC is not enabled on Unix. Recombine to TestLatencyRoundTrips once addressed. [InlineData(GCLatencyMode.LowLatency)] [InlineData(GCLatencyMode.SustainedLowLatency)] public static void LatencyRoundtrips_LowLatency(GCLatencyMode value) => LatencyRoundtrips(value); } public class GCExtendedTests : RemoteExecutorTestBase { private const int TimeoutMilliseconds = 10 * 30 * 1000; //if full GC is triggered it may take a while /// <summary> /// NoGC regions will be automatically exited if more than the requested budget /// is allocated while still in the region. In order to avoid this, the budget is set /// to be higher than what the test should be allocating. When running on CoreCLR/DesktopCLR, /// these tests generally do not allocate because they are implemented as fcalls into the runtime /// itself, but the CoreRT runtime is written in mostly managed code and tends to allocate more. /// /// This budget should be high enough to avoid exiting no-gc regions when doing normal unit /// tests, regardless of the runtime. /// </summary> private const int NoGCRequestedBudget = 8192; [Fact] [OuterLoop] public static void GetGeneration_WeakReference() { RemoteInvokeOptions options = new RemoteInvokeOptions(); options.TimeOut = TimeoutMilliseconds; RemoteInvoke(() => { Func<WeakReference> getweakref = delegate () { Version myobj = new Version(); var wkref = new WeakReference(myobj); Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget)); Assert.True(GC.GetGeneration(wkref) >= 0); Assert.Equal(GC.GetGeneration(wkref), GC.GetGeneration(myobj)); GC.EndNoGCRegion(); myobj = null; return wkref; }; WeakReference weakref = getweakref(); Assert.True(weakref != null); #if !DEBUG GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true, true); Assert.Throws<ArgumentNullException>(() => GC.GetGeneration(weakref)); #endif return SuccessExitCode; }, options).Dispose(); } [Fact] public static void GCNotificationNegTests() { Assert.Throws<ArgumentOutOfRangeException>(() => GC.RegisterForFullGCNotification(-1, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => GC.RegisterForFullGCNotification(100, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => GC.RegisterForFullGCNotification(-1, 100)); Assert.Throws<ArgumentOutOfRangeException>(() => GC.RegisterForFullGCNotification(10, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => GC.RegisterForFullGCNotification(-1, 10)); Assert.Throws<ArgumentOutOfRangeException>(() => GC.RegisterForFullGCNotification(100, 10)); Assert.Throws<ArgumentOutOfRangeException>(() => GC.RegisterForFullGCNotification(10, 100)); Assert.Throws<ArgumentOutOfRangeException>(() => GC.WaitForFullGCApproach(-2)); Assert.Throws<ArgumentOutOfRangeException>(() => GC.WaitForFullGCComplete(-2)); } [Theory] [InlineData(true, -1)] [InlineData(false, -1)] [InlineData(true, 0)] [InlineData(false, 0)] [InlineData(true, 100)] [InlineData(false, 100)] [InlineData(true, int.MaxValue)] [InlineData(false, int.MaxValue)] [OuterLoop] public static void GCNotificationTests(bool approach, int timeout) { RemoteInvokeOptions options = new RemoteInvokeOptions(); options.TimeOut = TimeoutMilliseconds; RemoteInvoke((approachString, timeoutString) => { TestWait(bool.Parse(approachString), int.Parse(timeoutString)); return SuccessExitCode; }, approach.ToString(), timeout.ToString(), options).Dispose(); } [Fact] [OuterLoop] public static void TryStartNoGCRegion_EndNoGCRegion_ThrowsInvalidOperationException() { RemoteInvokeOptions options = new RemoteInvokeOptions(); options.TimeOut = TimeoutMilliseconds; RemoteInvoke(() => { Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion()); return SuccessExitCode; }, options).Dispose(); } [MethodImpl(MethodImplOptions.NoOptimization)] private static void AllocateALot() { for (int i = 0; i < 10000; i++) { var array = new long[NoGCRequestedBudget]; GC.KeepAlive(array); } } [Fact] [OuterLoop] public static void TryStartNoGCRegion_ExitThroughAllocation() { RemoteInvokeOptions options = new RemoteInvokeOptions(); options.TimeOut = TimeoutMilliseconds; RemoteInvoke(() => { Assert.True(GC.TryStartNoGCRegion(1024)); AllocateALot(); // at this point, the GC should have booted us out of the no GC region // since we allocated too much. Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion()); return SuccessExitCode; }, options).Dispose(); } [Fact] [OuterLoop] public static void TryStartNoGCRegion_StartWhileInNoGCRegion() { RemoteInvokeOptions options = new RemoteInvokeOptions(); options.TimeOut = TimeoutMilliseconds; RemoteInvoke(() => { Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget)); Assert.Throws<InvalidOperationException>(() => GC.TryStartNoGCRegion(NoGCRequestedBudget)); Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion()); return SuccessExitCode; }, options).Dispose(); } [Fact] [OuterLoop] public static void TryStartNoGCRegion_StartWhileInNoGCRegion_BlockingCollection() { RemoteInvokeOptions options = new RemoteInvokeOptions(); options.TimeOut = TimeoutMilliseconds; RemoteInvoke(() => { Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget, true)); Assert.Throws<InvalidOperationException>(() => GC.TryStartNoGCRegion(NoGCRequestedBudget, true)); Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion()); return SuccessExitCode; }, options).Dispose(); } [Fact] [OuterLoop] public static void TryStartNoGCRegion_StartWhileInNoGCRegion_LargeObjectHeapSize() { RemoteInvokeOptions options = new RemoteInvokeOptions(); options.TimeOut = TimeoutMilliseconds; RemoteInvoke(() => { Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget, NoGCRequestedBudget)); Assert.Throws<InvalidOperationException>(() => GC.TryStartNoGCRegion(NoGCRequestedBudget, NoGCRequestedBudget)); Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion()); return SuccessExitCode; }, options).Dispose(); } [Fact] [OuterLoop] public static void TryStartNoGCRegion_StartWhileInNoGCRegion_BlockingCollectionAndLOH() { RemoteInvokeOptions options = new RemoteInvokeOptions(); options.TimeOut = TimeoutMilliseconds; RemoteInvoke(() => { Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget, NoGCRequestedBudget, true)); Assert.Throws<InvalidOperationException>(() => GC.TryStartNoGCRegion(NoGCRequestedBudget, NoGCRequestedBudget, true)); Assert.Throws<InvalidOperationException>(() => GC.EndNoGCRegion()); return SuccessExitCode; }, options).Dispose(); } [Fact] [OuterLoop] public static void TryStartNoGCRegion_SettingLatencyMode_ThrowsInvalidOperationException() { RemoteInvokeOptions options = new RemoteInvokeOptions(); options.TimeOut = TimeoutMilliseconds; RemoteInvoke(() => { // The budget for this test is 4mb, because the act of throwing an exception with a message // contained in a resource file has to potential to allocate a lot on CoreRT. In particular, when compiling // in multi-file mode, this will trigger a resource lookup in System.Private.CoreLib. // // In addition to this, the Assert.Throws xunit combinator tends to also allocate a lot. Assert.True(GC.TryStartNoGCRegion(4000 * 1024, true)); Assert.Equal(GCSettings.LatencyMode, GCLatencyMode.NoGCRegion); Assert.Throws<InvalidOperationException>(() => GCSettings.LatencyMode = GCLatencyMode.LowLatency); GC.EndNoGCRegion(); return SuccessExitCode; }, options).Dispose(); } [Fact] [OuterLoop] public static void TryStartNoGCRegion_SOHSize() { RemoteInvokeOptions options = new RemoteInvokeOptions(); options.TimeOut = TimeoutMilliseconds; RemoteInvoke(() => { Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget)); Assert.Equal(GCSettings.LatencyMode, GCLatencyMode.NoGCRegion); GC.EndNoGCRegion(); return SuccessExitCode; }, options).Dispose(); } [Fact] [OuterLoop] public static void TryStartNoGCRegion_SOHSize_BlockingCollection() { RemoteInvokeOptions options = new RemoteInvokeOptions(); options.TimeOut = TimeoutMilliseconds; RemoteInvoke(() => { Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget, true)); Assert.Equal(GCSettings.LatencyMode, GCLatencyMode.NoGCRegion); GC.EndNoGCRegion(); return SuccessExitCode; }, options).Dispose(); } [Fact] [OuterLoop] public static void TryStartNoGCRegion_SOHSize_LOHSize() { RemoteInvokeOptions options = new RemoteInvokeOptions(); options.TimeOut = TimeoutMilliseconds; RemoteInvoke(() => { Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget, NoGCRequestedBudget)); Assert.Equal(GCSettings.LatencyMode, GCLatencyMode.NoGCRegion); GC.EndNoGCRegion(); return SuccessExitCode; }, options).Dispose(); } [Fact] [OuterLoop] public static void TryStartNoGCRegion_SOHSize_LOHSize_BlockingCollection() { RemoteInvokeOptions options = new RemoteInvokeOptions(); options.TimeOut = TimeoutMilliseconds; RemoteInvoke(() => { Assert.True(GC.TryStartNoGCRegion(NoGCRequestedBudget, NoGCRequestedBudget, true)); Assert.Equal(GCSettings.LatencyMode, GCLatencyMode.NoGCRegion); GC.EndNoGCRegion(); return SuccessExitCode; }, options).Dispose(); } [Theory] [OuterLoop] [InlineData(0)] [InlineData(-1)] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Difference in behavior, full framework doesn't throw, fixed in .NET Core")] public static void TryStartNoGCRegion_TotalSizeOutOfRange(long size) { RemoteInvokeOptions options = new RemoteInvokeOptions(); options.TimeOut = TimeoutMilliseconds; RemoteInvoke(sizeString => { AssertExtensions.Throws<ArgumentOutOfRangeException>("totalSize", () => GC.TryStartNoGCRegion(long.Parse(sizeString))); return SuccessExitCode; }, size.ToString(), options).Dispose(); } [Theory] [OuterLoop] [InlineData(0)] // invalid because lohSize == [InlineData(-1)] // invalid because lohSize < 0 [InlineData(1152921504606846976)] // invalid because lohSize > totalSize [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Difference in behavior, full framework doesn't throw, fixed in .NET Core")] public static void TryStartNoGCRegion_LOHSizeInvalid(long size) { RemoteInvokeOptions options = new RemoteInvokeOptions(); options.TimeOut = TimeoutMilliseconds; RemoteInvoke(sizeString => { AssertExtensions.Throws<ArgumentOutOfRangeException>("lohSize", () => GC.TryStartNoGCRegion(1024, long.Parse(sizeString))); return SuccessExitCode; }, size.ToString(), options).Dispose(); } public static void TestWait(bool approach, int timeout) { GCNotificationStatus result = GCNotificationStatus.Failed; Thread cancelProc = null; // Since we need to test an infinite (or very large) wait but the API won't return, spawn off a thread which // will cancel the wait after a few seconds // bool cancelTimeout = (timeout == -1) || (timeout > 10000); GC.RegisterForFullGCNotification(20, 20); try { if (cancelTimeout) { cancelProc = new Thread(new ThreadStart(CancelProc)); cancelProc.Start(); } if (approach) result = GC.WaitForFullGCApproach(timeout); else result = GC.WaitForFullGCComplete(timeout); } catch (Exception e) { Assert.True(false, $"({approach}, {timeout}) Error - Unexpected exception received: {e.ToString()}"); } finally { if (cancelProc != null) cancelProc.Join(); } if (cancelTimeout) { Assert.True(result == GCNotificationStatus.Canceled, $"({approach}, {timeout}) Error - WaitForFullGCApproach result not Cancelled"); } else { Assert.True(result == GCNotificationStatus.Timeout, $"({approach}, {timeout}) Error - WaitForFullGCApproach result not Timeout"); } } public static void CancelProc() { Thread.Sleep(500); GC.CancelFullGCNotification(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using System.Xml.Linq; using DialogLogic; namespace DialogDesigner { public class DialogObjectManager { private Dialogs _dialogs; private readonly HashSet<string> _dialogsToRemove = new HashSet<string>(); private readonly Dictionary<string, DialogObject> _directoryDialogMapping = new Dictionary<string, DialogObject>(); private XElement _additionalData; private string _rootDirectory; public string RootDirectory { get { return _rootDirectory; } set { if (_rootDirectory == value) return; _rootDirectory = value; OnRootDirectoryChanged(); } } private string _currentXmlFile; public string XmlFile { get { return _currentXmlFile; } set { if(_currentXmlFile==value) return; _currentXmlFile = value; OnXmlFileChanged(); } } private bool _hasChanges; public bool HasChanges { get { return _hasChanges || (_dialogs != null && _dialogs.HasChanges); } set { _hasChanges = value; if (!_hasChanges) { if (_dialogs != null) _dialogs.HasChanges = false; foreach (var dlgObj in _directoryDialogMapping.Values.Where(dlg => dlg != null)) dlgObj.HasChanges = false; } } } public Dialogs Dialogs { get { return _dialogs; } } public event Action RootDirectoryChanged; public DialogObjectManager() { _dialogs = new Dialogs(); } public bool CheckDialogsForChanges() { return _directoryDialogMapping.Values.Any(val => val.HasChanges); } private void OnRootDirectoryChanged() { _directoryDialogMapping.Clear(); _dialogs = new Dialogs(); HasChanges = false; var action = RootDirectoryChanged; if (action != null) action(); } private void LoadCharacters() { if(_additionalData==null) return; var xCharacters = _additionalData.Element("characters"); if(xCharacters==null) return; var xCharProp = _additionalData.Element("characterProperties"); Dictionary<int, string> map = xCharProp == null ? null : _dialogs.AttributeCollection.ReadXml(xCharProp, new List<string> {"DisplayName", "Name", "Id"}); foreach(var xChar in xCharacters.Elements("character")) { string name; if(!xChar.TryGetAttribute("name",out name) || string.IsNullOrEmpty(name)) continue; var ch = _dialogs.GetOrCreateCharacter(name); ch.ReadProperties(xChar, id => map == null ? null : (map.ContainsKey(id) ? map[id] : null)); } } public DialogObject GetOrCreateDialogObject(string relativePath) { string relPath = relativePath.ToLower(); DialogObject result; if(_directoryDialogMapping.TryGetValue(relPath,out result)) return result; result=new DialogObject(); string fPath = null; if (RootDirectory != null) fPath = Path.Combine(RootDirectory, relPath + ".dlg"); var changed = _dialogs.HasChanges; var dlgInfo = new DialogInfo(_dialogs); result.Dialog = dlgInfo; if (File.Exists(fPath)) { var pref = new UserPreferences(result); var xDialog = GetDialogNode(relativePath); pref.PrepareForReading(xDialog ?? new XElement("dialog", new XAttribute("path", relativePath))); dlgInfo.LoadFromFile(fPath, pref); } result.RelativePath = relativePath; result.HasChanges = false; _dialogs.Add(dlgInfo); if(!changed) _dialogs.HasChanges = false; _directoryDialogMapping.Add(relPath, result); return result; } public void Reset() { XmlFile = null; RootDirectory = null; } public void SaveChanges(string newXmlFilePath, string rootDirectory, List<string> list) { if(_additionalData==null) _additionalData = new XElement("additionalData"); var xCfg = _additionalData.Element("configuration"); if(xCfg==null) { xCfg = new XElement("configuration"); _additionalData.Add(xCfg); } var xRootDir = xCfg.Element("rootDirectory"); if(xRootDir==null) { xRootDir=new XElement("rootDirectory"); xCfg.Add(xRootDir); } string rootDirRelative = string.Empty; if(!string.IsNullOrEmpty(RootDirectory)) { var newDir = Path.GetFullPath(Path.GetDirectoryName(newXmlFilePath)); rootDirRelative = PathHelper.GetRelativePath(newDir, RootDirectory); } xRootDir.Value = rootDirRelative; var xCharacters = _additionalData.Element("characters"); if(xCharacters!=null) xCharacters.Remove(); xCharacters = new XElement("characters"); var xProperties = new XElement("characterProperties"); var map = _dialogs.AttributeCollection.WriteXml(xProperties); xCharacters.Add(xProperties); var tmp = new XElement("characters"); xCharacters.Add(tmp); xCharacters = tmp; foreach (var ch in _dialogs.Characters.Values) { var xCh = new XElement("character"); xCh.Add(new XAttribute("name", ch.Name)); ch.WriteProperties(xCh, id => map[id]); xCharacters.Add(xCh); } _additionalData.Add(xCharacters); var xDialogs = _additionalData.Element("dialogs"); if(xDialogs==null) { xDialogs = new XElement("dialogs"); _additionalData.Add(xDialogs); } var dlgDict = (from xD in xDialogs.Elements("dialog") let path = xD.Attribute("path") where path != null && !string.IsNullOrEmpty(path.Value) select new {Key = path.Value, Value = xD}).ToDictionary(pair => pair.Key, pair => pair.Value); xDialogs.RemoveAll(); var ignoredDialogs = new HashSet<string>(); if (list != null) { foreach (var key in _directoryDialogMapping.Keys) ignoredDialogs.Add(key); foreach (var str in list.Select(s => s.ToLower())) ignoredDialogs.Remove(str); } foreach(var pair in _directoryDialogMapping) { if(ignoredDialogs.Contains(pair.Key)) continue; XElement xDlg; if (!dlgDict.TryGetValue(pair.Key, out xDlg)) xDlg = new XElement("dialog"); else dlgDict.Remove(pair.Key); var dlg = pair.Value; if(dlg.HasChanges) { xDlg.RemoveAll(); xDlg.Add(new XAttribute("path", pair.Key)); var pref = new UserPreferences(dlg); var fPath = Path.Combine(rootDirectory, dlg.RelativePath + ".dlg"); var dirPath = Path.GetDirectoryName(fPath); if (!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath); pref.PrepareForWriting(xDlg, dlg); dlg.Dialog.SaveToFile(fPath, pref); } xDialogs.Add(xDlg); } foreach(var pair in dlgDict) { string fullPath = Path.Combine(xRootDir.Value, pair.Key + ".dlg"); if(File.Exists(fullPath)) { if (_dialogsToRemove.Contains(pair.Key)) { try { File.Delete(fullPath); _dialogsToRemove.Remove(pair.Key); } catch { //Nobody cares Console.WriteLine(@"Unable to delete file '{0}'", fullPath); } } else xDialogs.Add(pair.Value); } } foreach(var dlgToRemove in _dialogsToRemove) { string path = Path.Combine(xRootDir.Value, dlgToRemove + ".dlg"); if(!File.Exists(path)) continue; try { File.Delete(path); } catch { //Nobody cares Console.WriteLine(@"Unable to delete file '{0}'", path); } } _dialogsToRemove.Clear(); using (var fStream=new FileStream(newXmlFilePath,FileMode.Create,FileAccess.Write)) { using(var writer=XmlWriter.Create(fStream,new XmlWriterSettings{Indent=true})) { var xDoc = new XDocument(_additionalData); xDoc.WriteTo(writer); } } XmlFile = newXmlFilePath; RootDirectory = rootDirectory; HasChanges = false; } private XElement GetDialogNode(string path) { if(_additionalData!=null) { var xDialogs = _additionalData.Element("dialogs"); if (xDialogs != null) return xDialogs.Elements("dialog").FirstOrDefault(xDlg => { string p; return xDlg.TryGetAttribute("path", out p) && p == path; }); } return null; } private void OnXmlFileChanged() { if (XmlFile == null || !File.Exists(XmlFile)) { RootDirectory = null; _additionalData = null; } else { var doc = XDocument.Load(XmlFile); _additionalData = doc.Element("additionalData"); if (_additionalData != null) { LoadCharacters(); var xCfg = _additionalData.Element("configuration"); if (xCfg != null) { var xRootDir = xCfg.Element("rootDirectory"); if (xRootDir != null && !string.IsNullOrEmpty(xRootDir.Value)) { var rootDir = xRootDir.Value; if(!Path.IsPathRooted(rootDir)) { var baseDir = Path.GetFullPath(Path.GetDirectoryName(XmlFile)); rootDir = Path.GetFullPath(Path.Combine(baseDir, rootDir)); } RootDirectory = Directory.Exists(rootDir) ? rootDir : null; } else RootDirectory = null; } } } } public void RenameFolder(string relativePath, string newFolderName) { var path = relativePath.ToLower() + '\\'; List<string> toRename = _directoryDialogMapping.Where(pair => pair.Key.StartsWith(path)).Select(pair => pair.Key).ToList(); int lastBackslash = relativePath.LastIndexOf('\\'); string left = (lastBackslash > 0 ? relativePath.Substring(0, lastBackslash + 1) : string.Empty) + newFolderName; foreach(var dlgPath in toRename) { var dObj = _directoryDialogMapping[dlgPath]; string right = dObj.RelativePath.Substring(path.Length - 1); dObj.RelativePath = left + right; _directoryDialogMapping.Remove(dlgPath); _directoryDialogMapping.Add(dObj.RelativePath.ToLower(), dObj); } string fullPath = Path.Combine(RootDirectory, relativePath), newFullPath = Path.Combine(RootDirectory, left); RenameRealFolder(fullPath, newFullPath); _hasChanges = true; } private static void RenameRealFolder(string folderPath, string newFolderPath) { if(!Directory.Exists(folderPath)) return; Directory.Move(folderPath, newFolderPath); } public void RenameDialog(string relativePath, string newDialogName) { var path = relativePath.ToLower(); DialogObject info; if(!_directoryDialogMapping.TryGetValue(path,out info)) return; int lastBackslash = relativePath.LastIndexOf('\\'); string newPath = (lastBackslash > 0 ? relativePath.Substring(0, lastBackslash + 1) : string.Empty) + newDialogName; info.RelativePath = newPath; _directoryDialogMapping.Remove(path); path = newPath.ToLower(); _directoryDialogMapping.Add(path, info); _hasChanges = true; } public void RemoveFolder(string relativePath) { var path = relativePath.ToLower() + '\\'; List<string> toRemove = _directoryDialogMapping.Keys.Where(key => key.StartsWith(path)).ToList(); foreach (var key in toRemove) RemoveDialogInternal(key); var fullPath = Path.Combine(RootDirectory, relativePath); RemoveRealFolder(fullPath); _hasChanges = true; } private static void RemoveRealFolder(string fullPath) { if(Directory.Exists(fullPath)) { var info = new DirectoryInfo(fullPath); if (ContainsOnlyDialogs(info)) Directory.Delete(fullPath, true); } } private static bool ContainsOnlyDialogs(DirectoryInfo info) { foreach(var fInfo in info.GetFiles()) { if(fInfo.Extension!=".dlg") return false; } foreach(var dirInfo in info.GetDirectories()) { // ignore svn folder if((dirInfo.Attributes & FileAttributes.Hidden)!=0) continue; if(!ContainsOnlyDialogs(dirInfo)) return false; } return true; } public void RemoveDialog(string relativePath) { var path = relativePath.ToLower(); RemoveDialogInternal(path); _hasChanges = true; } private void RemoveDialogInternal(string key) { DialogObject dlg; _directoryDialogMapping.TryGetValue(key, out dlg); _dialogsToRemove.Add(key); if(dlg==null) return; _dialogs.Remove(dlg.Dialog); _directoryDialogMapping.Remove(key); return; } public List<string> GetChangedFiles() { return (from dlgObj in _directoryDialogMapping.Values where dlgObj.HasChanges select dlgObj.RelativePath). ToList(); } } }
using System; using System.Windows.Forms; using System.IO; using System.Collections; using System.Xml; using GenLib; namespace PrimerProObjects { /// <summary> /// /// </summary> public class SightWords { private Settings m_Settings; private string m_FileName; private ArrayList m_Words; private const string cTagSightWords = "sightwords"; private const string cTagWord = "word"; public SightWords(Settings s) { m_Settings = s; m_FileName = ""; m_Words = new ArrayList(); } public string FileName { get {return m_FileName;} set {m_FileName = value;} } public ArrayList Words { get {return m_Words;} set {m_Words = value;} } public void AddWord(string strWord) { m_Words.Add(strWord); } public void DelWord(int n) { m_Words.RemoveAt(n); } public string GetWord(int n) { if (n < this.Count()) return (string) m_Words[n]; else return null; } public string GetWordInLowerCase(int n) { if (n < this.Count()) { string str = (string) m_Words[n]; return str; } else return null; } public int Count() { if (m_Words == null ) return 0; else return m_Words.Count; } public bool IsSightWord(string strWord) { bool flag = false; for (int i = 0; i < this.Count(); i++) { if (this.GetWord(i) == strWord) { flag = true; break; } } return flag; } public bool LoadFromFile(string strFileName) { bool flag = false; m_Words = new ArrayList(); if (File.Exists(strFileName)) { XmlTextReader reader = null; try { // Load the reader with the data file and ignore all white space nodes. reader = new XmlTextReader(strFileName); reader.WhitespaceHandling = WhitespaceHandling.None; // Parse the file string nam = ""; string val = ""; while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: nam = reader.Name; val = ""; break; case XmlNodeType.Text: val = reader.Value; if (nam == SightWords.cTagWord) { this.AddWord(val); } break; case XmlNodeType.CDATA: break; case XmlNodeType.ProcessingInstruction: break; case XmlNodeType.Comment: break; case XmlNodeType.XmlDeclaration: break; case XmlNodeType.Document: break; case XmlNodeType.DocumentType: break; case XmlNodeType.EntityReference: break; case XmlNodeType.EndElement: nam = reader.Name; break; } } flag = true; } catch { flag = false; } finally { if (reader!=null) { m_FileName = strFileName; reader.Close(); } } } return flag; } public void SaveToFile(string strFileName) { string strPath = ""; string strText = ""; if (m_Settings.OptionSettings.SightWordsFile != "") { m_FileName = strFileName; strPath = Funct.GetFolder(m_FileName); if (!Directory.Exists(strPath)) { m_FileName = m_Settings.PrimerProFolder + Constants.Backslash + Funct.ShortFileNameWithExt(m_FileName); m_Settings.OptionSettings.SightWordsFile = m_FileName; } if (!File.Exists(m_FileName)) { StreamWriter sw = File.CreateText(m_FileName); sw.Close(); } XmlTextWriter writer = new XmlTextWriter(m_FileName, System.Text.Encoding.UTF8); writer.Formatting = Formatting.Indented; writer.WriteStartElement(cTagSightWords); string strWord = ""; for (int i = 0; i < m_Words.Count; i++) { strWord = (string)m_Words[i]; writer.WriteElementString(cTagWord, strWord); } writer.WriteEndElement(); writer.Close(); } //else MessageBox.Show("Sight Words file not specified"); else { strText = m_Settings.LocalizationTable.GetMessage("SightWords1"); if (strText == "") strText = "Sight Words file not specified"; MessageBox.Show(strText); } } public string RetrieveSortedTable() { string strText = ""; string strKey = ""; string strLine = ""; SortedList sl = new SortedList(StringComparer.OrdinalIgnoreCase); if (this != null) { for (int i = 0; i < this.Count(); i++) { strLine = this.GetWord(i); strKey = strLine; sl.Add(strKey, strLine); } for ( int i = 0; i < sl.Count; i++) { strLine = (string) sl.GetByIndex(i); strText += strLine + Environment.NewLine; } } //else MessageBox.Show("Sight Word List is missing"); else { strText = m_Settings.LocalizationTable.GetMessage("SightWords2"); if (strText == "") strText = "Sight Word List is missing"; MessageBox.Show(strText); } return strText; } public string GetMissingWords() { string strText = ""; ArrayList alMissingWords = new ArrayList(); string strWord = ""; for (int i = 0; i < this.Count(); i++) { strWord = (string) this.Words[i]; if ( !m_Settings.WordList.IsWordInList(strWord) ) { if ( !alMissingWords.Contains(strWord) ) { alMissingWords.Add(strWord); strText += strWord + Environment.NewLine; } } } return strText; } } }
using System; using System.Drawing; using System.Windows.Forms; using PrimerProForms; using PrimerProObjects; using GenLib; namespace PrimerProSearch { /// <summary> /// Word Search /// </summary> public class WordSearch : Search { //Search parameters private string m_Target; //Word or Root to be searched private bool m_Words; //Search words private bool m_Roots; //Search roots private bool m_ParaFormat; //How to display the results private bool m_IgnoreTone; //Ignore Tone private string m_Title; //Title private Settings m_Settings; //Application Settings private WordList m_Wordlist; private bool m_ViewParaSentWord; //Flag for viewing ParaSentWord number //search definition tags private const string kTarget = "target"; private const string kWords = "searchwords"; private const string kRoots = "searchroots"; private const string kParaFormat = "paraformat"; private const string kIgnoreTone = "ignoretone"; //private const string kTitle = "Word Search"; //private const string kSearch = "Processing Grapheme Search"; private const string kSeparator = Constants.Tab; public WordSearch(int number, Settings s) : base(number, SearchDefinition.kWord) { m_Target = ""; m_Words = true; m_Roots = false; m_ParaFormat = false; m_IgnoreTone = false; m_Settings = s; //m_Title = WordSearch.kTitle; m_Title = m_Settings.LocalizationTable.GetMessage("WordSearchT"); if (m_Title == "") m_Title = "Word Search"; m_Wordlist = m_Settings.WordList; m_ViewParaSentWord = m_Settings.OptionSettings.ViewParaSentWord; } public WordSearch(string wrd, Settings s) : base(0, SearchDefinition.kWord) { m_Target = wrd; m_Words = true; m_Roots = false; m_ParaFormat = false; m_IgnoreTone = false; m_Title = ""; m_Settings = s; m_Wordlist = m_Settings.WordList; m_ViewParaSentWord = m_Settings.OptionSettings.ViewParaSentWord; } public string Target { get {return m_Target;} set {m_Target = value;} } public bool Words { get {return m_Words;} set {m_Words = value;} } public bool Roots { get {return m_Roots;} set {m_Roots = value;} } public bool ParaFormat { get {return m_ParaFormat;} set {m_ParaFormat = value;} } public bool IgnoreTone { get { return m_IgnoreTone; } set { m_IgnoreTone = value; } } public string Title { get {return m_Title;} } public WordList Wordlist { get { return m_Wordlist; } } public bool ViewParaSentWord { get { return m_ViewParaSentWord; } } public bool SetupSearch() { bool flag = false; //FormWord fpb = new FormWord(m_Settings.OptionSettings.GetDefaultFont()); FormWord form = new FormWord(m_Settings.OptionSettings.GetDefaultFont(), m_Settings.LocalizationTable); DialogResult dr = form.ShowDialog(); if (dr == DialogResult.OK) { this.Target = form.Target; this.Words = false; this.Roots = false; if (form.Type == FormWord.TargetType.Root) this.Roots = true; if (form.Type == FormWord.TargetType.Word) this.Words = true; this.ParaFormat = form.ParaFormat; this.IgnoreTone = form.IgnoreTone; SearchDefinition sd = new SearchDefinition(SearchDefinition.kWord); SearchDefinitionParm sdp = null; this.SearchDefinition = sd; if (form.Target != "") { string strText = ""; sdp = new SearchDefinitionParm(WordSearch.kTarget, this.Target); sd.AddSearchParm(sdp); m_Title = m_Title + " - [" + this.Target + "]"; if (form.Type == FormWord.TargetType.Word) { sdp = new SearchDefinitionParm(WordSearch.kWords); sd.AddSearchParm(sdp); } else if (form.Type == FormWord.TargetType.Root) { sdp = new SearchDefinitionParm(WordSearch.kRoots); sd.AddSearchParm(sdp); strText = m_Settings.LocalizationTable.GetMessage("WordSearch2"); if (strText == "") strText = "Word Search for Root"; m_Title = strText + " [" + this.Target + "]"; } if (form.ParaFormat) { sdp = new SearchDefinitionParm(WordSearch.kParaFormat); sd.AddSearchParm(sdp); } if (form.IgnoreTone) { sdp = new SearchDefinitionParm(WordSearch.kIgnoreTone); sd.AddSearchParm(sdp); } this.SearchDefinition = sd; flag = true; } else { string strMsg = m_Settings.LocalizationTable.GetMessage("WordSearch3"); if (strMsg == "") strMsg = "Word or Root must be specified"; MessageBox.Show(strMsg); } } return flag; } public bool SetupSearch(SearchDefinition sd) { bool flag = false; string strTag = ""; string strText = ""; for (int i = 0; i < sd.SearchParmsCount(); i++) { strTag = sd.GetSearchParmAt(i).GetTag(); if (strTag == WordSearch.kTarget) { this.Target = sd.GetSearchParmContent(strTag); m_Title = m_Title + " - [" + this.Target + "]"; flag = true; } if (strTag == WordSearch.kWords) { this.Words = true; this.Roots = false; flag = true; } if (strTag == WordSearch.kRoots) { this.Roots = true; this.Words = false; strText = m_Settings.LocalizationTable.GetMessage("WordSearch2"); if (strText == "") strText = "Word Search for Root"; m_Title = strText + " [" + this.Target + "]"; flag = true; } if (strTag == WordSearch.kParaFormat) this.ParaFormat = true; if (strTag == WordSearch.kIgnoreTone) this.IgnoreTone = true; } this.SearchDefinition = sd; return flag; } public string BuildResults() { string strText = ""; string str = ""; string strSN = Search.TagSN + this.SearchNumber.ToString().Trim(); strText += Search.TagOpener + strSN + Search.TagCloser + Environment.NewLine; strText += this.Title + Environment.NewLine + Environment.NewLine; strText += this.SearchResults; strText += Environment.NewLine; strText += this.SearchCount.ToString(); //strText += " entries found" + Environment.NewLine; str = m_Settings.LocalizationTable.GetMessage("Search2"); if (str == "") str = "entries found"; strText += Constants.Space + str + Environment.NewLine; strText += Search.TagOpener + Search.TagForwardSlash + strSN + Search.TagCloser; return strText; } public WordSearch ExecuteWordSearch(TextData td) { if (this.ParaFormat) ExecuteWordSearchP(td); else ExecuteWordSearchL(td); return this; } private WordSearch ExecuteWordSearchP(TextData td) { string strTarget = this.Target; bool fWords = this.Words; bool fRoots = this.Roots; bool fIgnoreTone = this.IgnoreTone; int nCount = 0; string strRslt = ""; string strWord = ""; string strRoot = ""; string str = ""; Paragraph para = null; Sentence sent = null; Word wrd = null; Word wrd2 = null; int nPara = td.ParagraphCount(); //FormProgressBar form = new FormProgressBar("Processing Word Search"); str = m_Settings.LocalizationTable.GetMessage("WordSearch1"); if (str == "") str = "Processing Word Search"; FormProgressBar form = new FormProgressBar(str); form.PB_Init(0, nPara); for (int i = 0; i < nPara; i++) { form.PB_Update(i); para = td.GetParagraph(i); int nSent = para.SentenceCount(); for (int j = 0; j < nSent; j++) { sent = para.GetSentence(j); int nWord = sent.WordCount(); for (int k = 0; k < nWord; k++) { wrd = sent.GetWord(k); if (fWords) { if (fIgnoreTone) strWord = wrd.GetWordWithoutTone(); else strWord = wrd.DisplayWord; if (strWord == strTarget) { nCount++; strRslt += Constants.kHCOn + wrd.DisplayWord + Constants.kHCOff + Constants.Space; } else strRslt += wrd.DisplayWord + Constants.Space; } if (fRoots) { if (fIgnoreTone) strWord = wrd.GetWordWithoutTone(); else strWord = wrd.DisplayWord; wrd2 = this.Wordlist.GetWord(strWord); if (wrd2 != null) { if (wrd2.Root != null) { if (fIgnoreTone) strRoot = wrd2.Root.GetRootWithoutTone(); else strRoot = wrd2.Root.DisplayRoot; if (strRoot == strTarget) { nCount++; strRslt += Constants.kHCOn + wrd.DisplayWord + Constants.kHCOff + Constants.Space; } else strRslt += wrd.DisplayWord + Constants.Space; } else strRslt += wrd.DisplayWord + Constants.Space; } else strRslt += wrd.DisplayWord + Constants.Space; } } strRslt = strRslt.Substring(0, strRslt.Length - 1); strRslt += sent.EndingPunctuation; strRslt += Constants.Space; } strRslt += Environment.NewLine + Environment.NewLine; } form.Close(); this.SearchResults = strRslt; this.SearchCount = nCount; return this; } private WordSearch ExecuteWordSearchL(TextData td) { string strTarget = this.Target; bool fWords = this.Words; bool fRoots = this.Roots; bool fIgnoreTone = this.IgnoreTone; int nCount = 0; string strRslt = ""; string strWord = ""; string strRoot = ""; string str = ""; Paragraph para = null; Sentence sent = null; Word wrd = null; Word wrd2 = null; int nTmp = 0; int nPara = td.ParagraphCount(); //FormProgressBar form = new FormProgressBar("Processing Word Search"); str = m_Settings.LocalizationTable.GetMessage("WordSearch1"); if (str == "") str = "Processing Word Search"; FormProgressBar form = new FormProgressBar(str); form.PB_Init(0, td.ParagraphCount()); for (int i = 0; i < nPara; i++) { form.PB_Update(i); para = td.GetParagraph(i); int nSent = para.SentenceCount(); for (int j = 0; j < nSent; j++) { sent = para.GetSentence(j); int nWord = sent.WordCount(); for (int k = 0; k < nWord; k++) { wrd = sent.GetWord(k); if (fIgnoreTone) strWord = wrd.GetWordWithoutTone(); else strWord = wrd.DisplayWord; if (fWords) { if (strWord == strTarget) { nCount++; if (this.ViewParaSentWord) { nTmp = i + 1; strRslt += TextData.kPara + Search.Colon + nTmp.ToString().PadLeft(4); strRslt += WordSearch.kSeparator; nTmp = j + 1; strRslt += TextData.kSent + Search.Colon + nTmp.ToString().PadLeft(4); strRslt += WordSearch.kSeparator; nTmp = k + 1; strRslt += TextData.kWord + Search.Colon + nTmp.ToString().PadLeft(4); strRslt += WordSearch.kSeparator; } strRslt += wrd.DisplayWord; strRslt += Environment.NewLine; } } if (fRoots) { if (fIgnoreTone) strWord = wrd.GetWordWithoutTone(); else strWord = wrd.DisplayWord; wrd2 = this.Wordlist.GetWord(strWord); if (wrd2 != null) { if (wrd2.Root != null) { if (fIgnoreTone) strRoot = wrd2.Root.GetRootWithoutTone(); else strRoot = wrd2.Root.DisplayRoot; if (strRoot == strTarget) { nCount++; if (this.ViewParaSentWord) { nTmp = i + 1; strRslt += TextData.kPara + Search.Colon + nTmp.ToString().PadLeft(4); strRslt += WordSearch.kSeparator; nTmp = j + 1; strRslt += TextData.kSent + Search.Colon + nTmp.ToString().PadLeft(4); strRslt += WordSearch.kSeparator; nTmp = k + 1; strRslt += TextData.kWord + Search.Colon + nTmp.ToString().PadLeft(4); strRslt += WordSearch.kSeparator; } strRslt += wrd.DisplayWord; strRslt += Environment.NewLine; } } } } } } } form.Close(); this.SearchResults = strRslt; this.SearchCount = nCount; return this; } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Globalization; using System.Threading; using System.Threading.Tasks; using System.Web; using Microsoft.Owin.Host.SystemWeb.CallEnvironment; using Microsoft.Owin.Host.SystemWeb.Infrastructure; namespace Microsoft.Owin.Host.SystemWeb.IntegratedPipeline { internal class IntegratedPipelineContext { // Ordered list of supported stage names private static readonly IList<string> StageNames = new[] { Constants.StageAuthenticate, Constants.StagePostAuthenticate, Constants.StageAuthorize, Constants.StagePostAuthorize, Constants.StageResolveCache, Constants.StagePostResolveCache, Constants.StageMapHandler, Constants.StagePostMapHandler, Constants.StageAcquireState, Constants.StagePostAcquireState, Constants.StagePreHandlerExecute, }; private readonly IntegratedPipelineBlueprint _blueprint; private State _state; public IntegratedPipelineContext(IntegratedPipelineBlueprint blueprint) { _blueprint = blueprint; } public bool PreventNextStage { get { return _state.PreventNextStage; } set { _state.PreventNextStage = value; } } public void Initialize(HttpApplication application) { for (IntegratedPipelineBlueprintStage stage = _blueprint.FirstStage; stage != null; stage = stage.NextStage) { var segment = new IntegratedPipelineContextStage(this, stage); switch (stage.Name) { case Constants.StageAuthenticate: application.AddOnAuthenticateRequestAsync(segment.BeginEvent, segment.EndEvent); break; case Constants.StagePostAuthenticate: application.AddOnPostAuthenticateRequestAsync(segment.BeginEvent, segment.EndEvent); break; case Constants.StageAuthorize: application.AddOnAuthorizeRequestAsync(segment.BeginEvent, segment.EndEvent); break; case Constants.StagePostAuthorize: application.AddOnPostAuthorizeRequestAsync(segment.BeginEvent, segment.EndEvent); break; case Constants.StageResolveCache: application.AddOnResolveRequestCacheAsync(segment.BeginEvent, segment.EndEvent); break; case Constants.StagePostResolveCache: application.AddOnPostResolveRequestCacheAsync(segment.BeginEvent, segment.EndEvent); break; case Constants.StageMapHandler: application.AddOnMapRequestHandlerAsync(segment.BeginEvent, segment.EndEvent); break; case Constants.StagePostMapHandler: application.AddOnPostMapRequestHandlerAsync(segment.BeginEvent, segment.EndEvent); break; case Constants.StageAcquireState: application.AddOnAcquireRequestStateAsync(segment.BeginEvent, segment.EndEvent); break; case Constants.StagePostAcquireState: application.AddOnPostAcquireRequestStateAsync(segment.BeginEvent, segment.EndEvent); break; case Constants.StagePreHandlerExecute: application.AddOnPreRequestHandlerExecuteAsync(segment.BeginEvent, segment.EndEvent); break; default: throw new NotSupportedException( string.Format(CultureInfo.InvariantCulture, Resources.Exception_UnsupportedPipelineStage, stage.Name)); } } // application.PreSendRequestHeaders += PreSendRequestHeaders; // Null refs for async un-buffered requests with bodies. application.AddOnEndRequestAsync(BeginFinalWork, EndFinalWork); } private void Reset() { PushExecutingStage(null); _state = new State(); } public static Task DefaultAppInvoked(IDictionary<string, object> env) { object value; if (env.TryGetValue(Constants.IntegratedPipelineContext, out value)) { var self = (IntegratedPipelineContext)value; return self._state.ExecutingStage.DefaultAppInvoked(env); } throw new InvalidOperationException(); } public static Task ExitPointInvoked(IDictionary<string, object> env) { object value; if (env.TryGetValue(Constants.IntegratedPipelineContext, out value)) { var self = (IntegratedPipelineContext)value; return self._state.ExecutingStage.ExitPointInvoked(env); } throw new InvalidOperationException(); } private IAsyncResult BeginFinalWork(object sender, EventArgs e, AsyncCallback cb, object extradata) { var result = new StageAsyncResult(cb, extradata, () => { }); TaskCompletionSource<object> tcs = TakeLastCompletionSource(); if (tcs != null) { tcs.TrySetResult(null); } if (_state.OriginalTask != null) { // System.Web does not allow us to use async void methods to complete the IAsyncResult due to the special sync context. #pragma warning disable 4014 DoFinalWork(result); #pragma warning restore 4014 } else { result.TryComplete(); } result.InitialThreadReturning(); return result; } private async Task DoFinalWork(StageAsyncResult result) { try { await _state.OriginalTask; _state.CallContext.OnEnd(); CallContextAsyncResult.End(_state.CallContext.AsyncResult); result.TryComplete(); } catch (Exception ex) { _state.CallContext.AbortIfHeaderSent(); result.Fail(ErrorState.Capture(ex)); } } private void EndFinalWork(IAsyncResult ar) { Reset(); StageAsyncResult.End(ar); } public Func<IDictionary<string, object>, Task> PrepareInitialContext(HttpApplication application) { IDictionary<string, object> environment = GetInitialEnvironment(application); var originalCompletionSource = new TaskCompletionSource<object>(); _state.OriginalTask = originalCompletionSource.Task; PushLastObjects(environment, originalCompletionSource); return _blueprint.AppContext.AppFunc; } public IDictionary<string, object> GetInitialEnvironment(HttpApplication application) { if (_state.CallContext != null) { return _state.CallContext.Environment; } string pathBase = application.Request.Path.Substring(0, _blueprint.PathBase.Length); // Preserve client casing string requestPath = application.Request.AppRelativeCurrentExecutionFilePath.Substring(1) + application.Request.PathInfo; _state.CallContext = _blueprint.AppContext.CreateCallContext( application.Request.RequestContext, pathBase, requestPath, null, null); _state.CallContext.CreateEnvironment(); AspNetDictionary environment = _state.CallContext.Environment; environment.IntegratedPipelineContext = this; return environment; } public void PushExecutingStage(IntegratedPipelineContextStage stage) { IntegratedPipelineContextStage prior = Interlocked.Exchange(ref _state.ExecutingStage, stage); if (prior != null) { prior.Reset(); } } public void PushLastObjects(IDictionary<string, object> environment, TaskCompletionSource<object> completionSource) { IDictionary<string, object> priorEnvironment = Interlocked.CompareExchange(ref _state.LastEnvironment, environment, null); TaskCompletionSource<object> priorCompletionSource = Interlocked.CompareExchange(ref _state.LastCompletionSource, completionSource, null); if (priorEnvironment != null || priorCompletionSource != null) { // TODO: trace fatal condition throw new InvalidOperationException(); } } public IDictionary<string, object> TakeLastEnvironment() { return Interlocked.Exchange(ref _state.LastEnvironment, null); } public TaskCompletionSource<object> TakeLastCompletionSource() { return Interlocked.Exchange(ref _state.LastCompletionSource, null); } // Does stage1 come before stage2? // Returns false for unknown stages, or equal stages. internal static bool VerifyStageOrder(string stage1, string stage2) { int stage1Index = StageNames.IndexOf(stage1); int stage2Index = StageNames.IndexOf(stage2); if (stage1Index == -1 || stage2Index == -1) { return false; } return stage1Index < stage2Index; } private struct State { public IDictionary<string, object> LastEnvironment; public TaskCompletionSource<object> LastCompletionSource; public Task OriginalTask; public OwinCallContext CallContext; public bool PreventNextStage; public IntegratedPipelineContextStage ExecutingStage; } } }